package ink.wgink.login.oauth2.server.controller.apis;

import ink.wgink.annotation.CheckRequestBodyAnnotation;
import ink.wgink.common.base.DefaultBaseController;
import ink.wgink.exceptions.*;
import ink.wgink.interfaces.consts.ISystemConstant;
import ink.wgink.login.oauth2.server.pojo.dtos.OAuth2ClientDTO;
import ink.wgink.login.oauth2.server.pojo.vos.OAuth2ClientVO;
import ink.wgink.login.oauth2.server.service.IOAuth2ClientService;
import ink.wgink.pojo.ListPage;
import ink.wgink.pojo.result.ErrorResult;
import ink.wgink.pojo.result.SuccessResult;
import ink.wgink.pojo.result.SuccessResultList;
import ink.wgink.util.AesUtil;
import io.swagger.annotations.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: OauthClientController
 * @Description: Oauth客户端
 * @Author: WangGeng
 * @Date: 2019/3/12 11:15 AM
 * @Version: 1.0
 **/
@Api(tags = ISystemConstant.API_TAGS_SYSTEM_PREFIX + "Oauth客户端")
@RestController
@RequestMapping(ISystemConstant.API_PREFIX + "/oauth2client")
public class OAuth2ClientController extends DefaultBaseController {

    @Autowired
    private IOAuth2ClientService oAuth2ClientService;

    @ApiOperation(value = "Oauth客户端新增", notes = "Oauth客户端新增接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("save")
    @CheckRequestBodyAnnotation
    public SuccessResult saveOauthClient(@RequestBody OAuth2ClientVO oAuth2ClientVO) throws Exception {
        if (!StringUtils.equals(oAuth2ClientVO.getClientSecret(),
                Base64.encodeBase64String(
                        AesUtil.aesEncoder(
                                IOAuth2ClientService.OAUTH_CLIENT_RULE, oAuth2ClientVO.getClientId()
                        ).getBytes("UTF-8")
                ))) {
            throw new ParamsException("clientId与clientSecret不匹配");
        }
        checkParams(oAuth2ClientVO);
        oAuth2ClientService.save(oAuth2ClientVO);
        return new SuccessResult();
    }

    @ApiOperation(value = "Oauth客户端删除", notes = "Oauth客户端删除接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "Oauth客户端ID列表，用下划线分隔", paramType = "path", example = "1_2_3")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @DeleteMapping("remove/{ids}")
    public SuccessResult remove(@PathVariable("ids") String ids) throws RemoveException {
        oAuth2ClientService.remove(Arrays.asList(ids.split("\\_")));
        return new SuccessResult();
    }

    @ApiOperation(value = "Oauth客户端修改", notes = "Oauth客户端修改接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "clientId", value = "Oauth客户端ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("update/{clientId}")
    public SuccessResult updateOauthClient(@PathVariable("clientId") String clientId,
                                           @RequestBody OAuth2ClientVO oAuth2ClientVO) throws Exception {
        checkParams(oAuth2ClientVO);
        oAuth2ClientService.update(clientId, oAuth2ClientVO);
        return new SuccessResult();
    }

    /**
     * 校验参数
     *
     * @param oAuth2ClientVO
     * @throws ParamsException
     */
    private void checkParams(OAuth2ClientVO oAuth2ClientVO) throws ParamsException {
        if (StringUtils.equals(oAuth2ClientVO.getSystemType(), IOAuth2ClientService.OAUTH_CLIENT_SYSTEM_TYPE_THIRD)) {
            if (StringUtils.isBlank(oAuth2ClientVO.getSystemState())) {
                throw new ParamsException("系统状态不能为空");
            }
            if (StringUtils.isBlank(oAuth2ClientVO.getExpireTime())) {
                throw new ParamsException("系统到期时间不能为空");
            }
        }
    }

    @ApiOperation(value = "easyui Oauth客户端列表", notes = "easyui Oauth客户端列表列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "rows", value = "显示数量", paramType = "query", dataType = "int", defaultValue = "20"),
            @ApiImplicitParam(name = "keywords", value = "关键字", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listpage")
    public SuccessResultList<List<OAuth2ClientDTO>> listPage(ListPage page) throws SearchException {
        Map<String, Object> params = requestParams();
        page.setParams(params);
        return oAuth2ClientService.listPage(page);
    }

    @ApiOperation(value = "Oauth客户端列表", notes = "Oauth客户端列表列表接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("list")
    public List<OAuth2ClientDTO> listOauthClient() throws SearchException {
        Map<String, Object> params = requestParams();
        return oAuth2ClientService.list(params);
    }

    @ApiOperation(value = "Oauth客户端详情", notes = "Oauth客户端详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "clientId", value = "Oauth客户端ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("get/{clientId}")
    public OAuth2ClientDTO getOauthClient(@PathVariable("clientId") String clientId) throws Exception {
        return oAuth2ClientService.get(clientId);
    }

    @ApiOperation(value = "Oauth客户端绑定菜单", notes = "Oauth客户端绑定菜单接口，自动创建根节点菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "clientId", value = "Oauth客户端ID", paramType = "path"),
            @ApiImplicitParam(name = "menuId", value = "菜单ID", paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("update-menu-init/{clientId}")
    public SuccessResult updateMenuInit(@PathVariable("clientId") String clientId, @RequestParam(name = "menuId", required = false) String menuId) {
        oAuth2ClientService.updateMenuInit(clientId, menuId);
        return new SuccessResult();
    }

    @ApiOperation(value = "清除客户端菜单", notes = "清除客户端菜单菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "clientId", value = "Oauth客户端ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("update-menu-empty/{clientId}")
    public SuccessResult updateMenuEmpty(@PathVariable("clientId") String clientId) {
        oAuth2ClientService.updateMenuEmpty(clientId);
        return new SuccessResult();
    }

    @ApiOperation(value = "Oauth客户端初始化数据", notes = "Oauth客户端初始化数据接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("get-init")
    public OAuth2ClientDTO getInitClient() throws Exception {
        return oAuth2ClientService.getInit();
    }


}
