package com.tykj.workflowcore.user.config;

import com.tykj.workflowcore.user.dao.StorageKeyDao;
import com.tykj.workflowcore.user.pojo.StorageKey;
import com.tykj.workflowcore.user.pojo.User;
import com.tykj.workflowcore.user.pojo.UserDetail;
import com.tykj.workflowcore.user.pojo.vo.uservo.CurrentUserVo;
import com.tykj.workflowcore.user.util.AuthenticationUtils;
import com.tykj.workflowcore.user.util.CipherUtil;
import com.tykj.workflowcore.user.util.SpringContextHolder;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author huangjiafu
 * @version V1.0
 * @data 2021/8/19 10:52
 **/
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StorageKeyDao storageKeyDao;
    @Autowired
    AuthenticationUtils authenticationUtils;


    //存当前用户
    static HashMap<String, CurrentUserVo> map = new HashMap<>();


    public TokenInterceptor() {
    }

    public static HashMap<String, CurrentUserVo> getMap() {
        return map;
    }

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        System.out.println("拦截。。。。。。。。。。。。。。");
        String token = request.getHeader("token");
       // JSONObject jsonObject = JSONObject.fromObject(token);

        UserDetail authentication = authenticationUtils.getAuthentication();

        StorageKeyDao storageKeyDao= SpringContextHolder.getBean(StorageKeyDao.class);
        List<StorageKey> storageKeys = storageKeyDao.findAll();
        System.out.println("11111:"+storageKeys.get(0));

        String decrypt = CipherUtil.decrypt(token, CipherUtil.string2PrivateKey(storageKeys.get(0).getRsaPrivateKey()));
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(CipherUtil.string2PublicKey(storageKeys.get(0).getSignPublicKey())).parseClaimsJws(decrypt);
        Claims body = claimsJws.getBody();
        System.out.println("77777777:"+body);
        Object username = body.get("username");
        String username1 = username.toString();
        User user = authentication.toUser();
        if (! user.equals(username1)){
            PrintWriter writer = response.getWriter();
            writer.print("token中的用户与当前登录用户不符");
            return false;
        }

        Date loginTime = UserMap.userMap.get(username1);
        if (loginTime == null){
            PrintWriter writer = response.getWriter();
            writer.print("用户未登录");
            return false;
        }
        long time = (System.currentTimeMillis()-loginTime.getTime())/(1000);
        if (time > 30){
            PrintWriter writer = response.getWriter();
            writer.print("用户登录已过期");
            return false;
        }
        UserMap.userMap.put(username1,new Date());
        return true;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

//        System.out.println("拦截器1 postHandle： ");
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        System.out.println("拦截器1 afterCompletion： ");
    }
}
