package com.ruoyi.web.controller.system;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Result;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.framework.jwt.utils.JwtUtils;
import com.ruoyi.system.domain.TokenRequest;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.tool.RsaUtil;
import com.ruoyi.web.controller.tool.SecretKeyBo;
import com.ruoyi.web.controller.tool.StringUtils;
import com.ruoyi.common.redis.RedisService;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;

import java.security.NoSuchAlgorithmException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;



@RestController
@RequestMapping("/auth")
public class SecurityController {

    @Resource
    private RedisService redisService;
    @Autowired
    private ISysUserService userService;

    /**
     * 获取秘钥接口
     * 前端请求后该方法会生成一对秘钥，分别为公钥和私钥
     * 将公钥返回给前端用于加密，私钥存入缓存（60s）用于后台解密
     */
    @PostMapping("/getRemoteSecretKey")
    @ResponseBody
    public Result<?> getRemoteSecretKey() {
        String publicKey;
        try {
            SecretKeyBo bo = RsaUtil.genKeyPair();
            redisService.setCacheObject("remoteSecretKey", bo.getPrivateKey(), 60L, TimeUnit.SECONDS);
            publicKey = bo.getPublicKey();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        if (StringUtils.isNotEmpty(publicKey)) {
            return Result.ok(publicKey, "操作成功");
        }
        return Result.fail("操作失败");
    }


    /**
     * 获取token
     */
    @PostMapping("/getToken")
    @ResponseBody
    public AjaxResult getToken(@RequestBody TokenRequest form) {
        //解密密码字符串
//        String privateKey = redisService.getCacheObject("remoteSecretKey");
//        try {
//            RsaUtil.decrypt(form.getUsername(), privateKey);
//        } catch (Exception e) {
//            return AjaxResult.error("获取token失败").put("data", null).put("code",40002);
//        }
        SysUser user = userService.selectUserByLoginName(form.getUsername());
        String token = JwtUtils.createToken(form.getUsername(), user.getPassword());
        try {
            return Objects.requireNonNull(AjaxResult.success("获取成功").put("data", token)).put("code",200);
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (com.ruoyi.common.utils.StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return AjaxResult.error(msg).put("data", null).put("code",40000);
        }
    }



}
