package com.winsun.intercept;

import com.alibaba.fastjson.JSONObject;
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.util.LoginUtils;
import com.winsun.mapper.SysUserMapper;
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.concurrent.TimeUnit;

/**
 *
 * @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 String AUTH_REDIS_SECURITY = "authRedisSecurity:";

    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;
            }

            String key = AUTH_REDIS_PREFIX + StringUtils.join(roleList.toArray(), ",");

            String securityKey = AUTH_REDIS_SECURITY + security;
            Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(securityKey, "1");
            if (!aBoolean) {
                return false;
            }else {
                stringRedisTemplate.opsForValue().set(securityKey, "1", 1, TimeUnit.DAYS);
            }

            ResponseData<String> stringResponseData = LoginUtils.pwdDecrypt(security);
            if (!stringResponseData.isSuccess()) {
                log.error("鉴权失败");
                return false;
            }
            String data = stringResponseData.getData();
            String s = stringRedisTemplate.opsForValue().get(key);
            List<Menu> roleMenu = null;
            if (StringUtils.isNotBlank(s)) {
                roleMenu = JSONObject.parseArray(s, Menu.class);
            }else {
                roleMenu = sysUserMapper.getRoleMenu(roleList);
                stringRedisTemplate.opsForValue().set(key,
                                JSONObject.toJSONString(roleMenu),
                                CACHE_TIME, TimeUnit.SECONDS);
            }

            if (roleMenu == null || roleMenu.isEmpty()) {
                return false;
            }

            log.info("data: {}", data);
            for (Menu menu : roleMenu) {


                if (menu == null || StringUtils.isBlank(menu.getUrl())) {
                    continue;
                }
                log.info(menu.getUrl());
                if (StringUtils.equals(menu.getUrl(), data)) {
                    log.info("获取到相同的菜单");
                    return true;
                }
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

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

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