package com.skr.mdm.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.skr.mdm.dto.TokenDTO;
import com.skr.mdm.enums.ResultCodeEnum;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.bean.vo.VerifyCodeVO;
import com.skr.mdm.service.AdminTokenService;
import com.skr.mdm.util.RedisGetKeyUtil;
import com.skr.mdm.util.RedisUtils;
import com.skr.mdm.util.VerifyCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;


/**
 * @author nfq
 * @date 2020/6/29 10:35
 */
@RestController
@Slf4j
@Api( tags = "登录认证")
public class AdminAuthenticationController {

    @Autowired
    private AdminTokenService tokenService;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 获取验证码
     *
     * @param request
     * @return
     */
    @ApiOperation("获取验证码")
    @PostMapping("verifyCode")
    public ResponseResult verifyCode(HttpServletRequest request) throws IOException {
        String verifyCode = VerifyCodeUtil.generateVerifyCode(4);
//        String encode = VerifyCodeUtil.verifyCode(100, 30, verifyCode);

        CircleCaptcha shearCaptcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 4);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        shearCaptcha.write(outputStream);
        String encode = Base64.encode(outputStream.toByteArray());
//        String ipAddr = IpUtil.getIpAddr(request);
        String uuid = IdUtil.simpleUUID();
        redisUtils.set(RedisGetKeyUtil.getVerifyCodeKey(uuid), shearCaptcha.getCode(), 5 * 60);
        VerifyCodeVO verifyCodeVO = VerifyCodeVO.builder()
                .verifyCode(encode)
                .uuid(uuid)
                .build();
        return ResponseResult.success(verifyCodeVO);
    }


    /**
     * 刷新token
     *
     * @param jwt_token
     * @param refresh_token
     * @return
     */
    @ApiOperation("刷新token")
    @PostMapping("refresh/token")
    public ResponseResult refreshToken(@ApiParam(value = "访问令牌", required = true) String jwt_token, @ApiParam(required = true, value = "刷新令牌") String refresh_token) {

        TokenDTO tokenDTO = tokenService.refreshToken(jwt_token, refresh_token);
        if (tokenDTO == null) {
            return ResponseResult.failure(ResultCodeEnum.REFRESH_TOKEN_EXPIRE);
        }
        return ResponseResult.success(tokenDTO);

    }

}
