package com.ruoyi.app.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.JWTUtil;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisCache redisCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED);
        //获取请求头里的token
        String token = request.getHeader(Constants.TOKEN);


        //eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb21wYW55Q29kZSI6IlFZMDAwMSIsInBjVXNlcklkIjoiMSIsImlkIjoiMTEiLCJ1c2VyVHlwZSI6IjEiLCJ1c2VyTmFtZSI6ImFkbWluIiwiZXhwIjoxNjk0ODI4NTg5fQ.q_RGTy1j9tv0kRVRorrQ3ioDOKBDFzoooWeoHoxZ4qk
        log.info("【APPToken】请求头中的Token：{} leader:{} URI：{}", token, JWTUtil.isLeader(), request.getContextPath());
        log.info("【APPToken】是否领导:{}", JWTUtil.isLeader());

        if (token == null || token.equals("") || token.toUpperCase().equals("NULL")) {
            map.put("msg", "未授权");
        } else {
            //验证
            String companyCode = JWTUtil.getCompanyCode();
            String userId = JWTUtil.getUserId();
            //userId：11 companyCode：QY0001
//            log.info("【APPToken】userId：{} companyCode：{}", userId, companyCode);
            if (StringUtils.isNull(userId) || StringUtils.isNull(companyCode)) {
                map.put("code", HttpStatus.FORBIDDEN);
                map.put("msg", "无效签名");
            } else {
                try {
                    String secretKey = redisCache.getSecretKey(userId, companyCode);
                    //YsUhLqQo
//                    log.info("【APPToken】Redis中取出用户密钥：{}", secretKey);
                    log.info("【APPToken】userId：{} companyCode：{} Redis中取出用户密钥：{} URI：{}", userId, companyCode, secretKey, request.getContextPath());
                    JWTUtil.verify(token, secretKey); //验证令牌
                    return true;
                    //签名异常
                } catch (SignatureVerificationException e) {
//                    e.printStackTrace();
                    map.put("code", HttpStatus.FORBIDDEN);
                    map.put("msg", "无效签名");
                    //过期异常
                } catch (TokenExpiredException e) {
//                    e.printStackTrace();
                    map.put("code", HttpStatus.FORBIDDEN);
                    map.put("msg", "token过期");
                    //算法不匹配
                } catch (AlgorithmMismatchException e) {
//                    e.printStackTrace();
                    map.put("code", HttpStatus.FORBIDDEN);
                    map.put("msg", "token算法不一致");
                    //总异常
                } catch (Exception e) {
//                    e.printStackTrace();
                    map.put("code", HttpStatus.FORBIDDEN);
                    map.put("msg", "token无效");
                }
            }
        }

        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
