package com.winsun.intercept;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.netflix.discovery.converters.Auto;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.auth.model.common.Menu;
import com.winsun.item.core.shiro.ShiroKit;
import com.winsun.item.modular.system.dao.RelationMapper;
import com.winsun.item.util.LoginUtils;
import com.winsun.mapper.SysUserMapper;
import com.winsun.tenpay.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author chengfengluo
 * @date 2022-03-15 14:47
 */
@Slf4j
@Component
public class AuthIntercept extends HandlerInterceptorAdapter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final static String AUTH_REDIS_PREFIX = "authRedis:";

    private final static Integer CACHE_TIME =  60;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            ShiroUser user = ShiroKit.getUser();
            if (user == null) {
                log.error("错误");
                return false;
            }

            String security = request.getHeader("security").trim();

            if (StringUtils.isBlank(security)) {
                log.error("校验权限失败！");
                return false;
            }

            List<Integer> roleList = user.getRoleList();
            if (roleList.size() == 0) {
                log.error("无权限");
                return false;
            }
            ResponseData<String> stringResponseData = LoginUtils.pwdDecrypt(security);
            if (!stringResponseData.isSuccess()) {
                log.error("鉴权失败");
                return false;
            }
            String data = stringResponseData.getData();
            String s = stringRedisTemplate.opsForValue().get(AUTH_REDIS_PREFIX + user.getRoleId());
            List<Menu> roleMenu = null;
            if (StringUtils.isNotBlank(s)) {
                roleMenu = JSONObject.parseArray(s, Menu.class);
            }else {
                roleMenu = sysUserMapper.getRoleMenu(roleList);
                stringRedisTemplate.opsForValue().set(AUTH_REDIS_PREFIX + user.getRoleId(),
                                JSONObject.toJSONString(roleMenu),
                                CACHE_TIME, TimeUnit.SECONDS);
            }
            if (roleMenu == null || roleMenu.isEmpty()) {
                return false;
            }
            log.info("data: {}", data);
            for (Menu menu : roleMenu) {
                log.info(menu.getUrl());
                if (StringUtils.equals(menu.getUrl(), data)) {
                    log.info("获取到相同的菜单");
                    return true;
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        Map<String, Object> model = modelAndView.getModel();
        log.info("结束信息: {}", JSONObject.toJSONString(model));

        super.postHandle(request, response, handler, modelAndView);
    }
}
