package com.ruoyi.framework.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.CSMemberUserLoginToken;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.securityContext.CsOrderMemberUser;
import com.ruoyi.common.securityContext.CsOrderMemberUserSecurityContext;
import com.ruoyi.common.utils.RSAUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.cs.service.ICsOrderMemberUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * 企业用户校验拦截
 */
@Component
public class CSOrderMemberUserInterceptor implements HandlerInterceptor {

    @Resource
    private ICsOrderMemberUserService csUserInfoService;

    @Resource
    private RedisCache redisCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            CSMemberUserLoginToken annotation = method.getAnnotation(CSMemberUserLoginToken.class);
            if (annotation != null){

                // 错误消息
                int code = 403;
                String errorMsg = "";
                String loginToken = "";
                try{
                    // 获取头部信息M-Authorization
                    String companyUserToken = request.getHeader("M-Authorization");
                    if (StringUtils.isBlank(companyUserToken)){
                        errorMsg = "请先登录平台";
                    }else {
                        // RSA私钥解密
                        loginToken = RSAUtils.privateDecrypt(companyUserToken);

                        if (redisCache.hasKey(CacheConstants.CS_MEMBER_LOGIN_TOKEN_KEY+loginToken)){
                            String encryptUserId = redisCache.getCacheObject(CacheConstants.CS_MEMBER_LOGIN_TOKEN_KEY+loginToken).toString();
                            String csUserId = RSAUtils.privateDecrypt(encryptUserId);
                            // 校验用户id
                            if (StringUtils.isNotBlank(csUserId)){
                                JSONObject companyUserMsg = this.getCompanyUserMsg(csUserId, method);
                                code = companyUserMsg.getInteger("code");
                                errorMsg = companyUserMsg.getString("errorMsg");
                            }else {
                                errorMsg = "参数错误，缺少用户标识。";
                            }
                        }else {
                            errorMsg = "登录状态已过期，请重新登录。";
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    errorMsg = "登陆失效，请重新登录。";
                }

                // 如果消息不为空，则拦截并返回消息
                if (StringUtils.isNotBlank(errorMsg)){
                    AjaxResult ajaxResult = AjaxResult.error(code, errorMsg);
                    ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
                    return false;
                }else {
                    // 请求成功，刷新token有效期
                    long expire = redisCache.getExpire(CacheConstants.CS_MEMBER_LOGIN_TOKEN_KEY + loginToken);
                    if (expire >= 0){
                        redisCache.expire(CacheConstants.CS_MEMBER_LOGIN_TOKEN_KEY+loginToken, 3, TimeUnit.DAYS);
                    }

                    return true;
                }
            }
        }
        return true;
    }

    /**
     * 查询超算用户信息
     * @param memberUserId 超算用户ID
     */
    public JSONObject getCompanyUserMsg(String memberUserId, Method method){
        JSONObject jsonObject = new JSONObject();
        // 错误消息
        int code = 403;
        String errorMsg = "";
        com.ruoyi.cs.domain.CsOrderMemberUser csUser = csUserInfoService.selectCsUserInfoByMemberUserId(memberUserId);
        if (ObjectUtils.isEmpty(csUser) || csUser.getDelFlag().equals('1')){
            errorMsg = "用户信息异常";
        }else {
            if (csUser.getStatus().equals('1')){
                errorMsg = "此账号被冻结";
            }

            CsOrderMemberUser companyUserInfo = BeanUtil.copyProperties(csUser, CsOrderMemberUser.class);
            CsOrderMemberUserSecurityContext.set(companyUserInfo);
        }
        jsonObject.put("code", code);
        jsonObject.put("errorMsg", errorMsg);
        return jsonObject;
    }

}
