package com.yiqi.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yiqi.app.domain.AppUser;
import com.yiqi.app.service.IAppUserService;
import com.yiqi.app.service.IWeAppTokenService;
import com.yiqi.common.core.domain.AuthHolder;
import com.yiqi.common.core.domain.AuthInfoDO;
import com.yiqi.common.enums.StatusType;
import com.yiqi.common.exception.user.SessionFailException;
import com.yiqi.common.utils.StringUtils;
import com.yiqi.system.domain.SysSessionRecord;
import com.yiqi.system.service.ISysSessionRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.Map;

/**
 * @author xiaohei
 * @date 2023/10/3
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
    private final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);
    @Autowired
    private IWeAppTokenService weAppTokenService;
    @Autowired
    private ISysSessionRecordService sysSessionRecordService;
    @Autowired
    private IAppUserService appUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String url = request.getScheme() + "://" +
                request.getServerName() +
                ("http".equals(request.getScheme()) && request.getServerPort() == 80 || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? "" : ":" + request.getServerPort()) +
                request.getRequestURI() +
                (request.getQueryString() != null ? "?" + request.getQueryString() : "");
        logger.info("收到请求:" + url);
        if (request.getMethod().equals("POST")) {

            Map<String, String[]> parameterMap = request.getParameterMap();
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                try {
                    logger.info("参数：" + entry.getKey() + "=" + org.apache.commons.lang.StringUtils.join(entry.getValue()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        logger.info("=========================================");
        AuthInfoDO authInfoDO = weAppTokenService.getLoginUser(request);
        if (StringUtils.isNull(authInfoDO))
        {
            //先判断库里是否有这个token
            SysSessionRecord sysSessionRecord = sysSessionRecordService
                    .getOne(new QueryWrapper<SysSessionRecord>().lambda().eq(SysSessionRecord::getToken,weAppTokenService.getToken(request)));
            if(sysSessionRecord == null){
                throw new SessionFailException();
            }
            AppUser user = appUserService.getOne(new QueryWrapper<AppUser>().lambda()
                    .eq(AppUser::getId,sysSessionRecord.getAppUserId()));
            if(user == null || user.getStatus().equals(StatusType.DELETED.getCode())){
                throw new SessionFailException();
            }
            authInfoDO = new AuthInfoDO(user);
            weAppTokenService.refreshToken(authInfoDO);
        }else{
            weAppTokenService.verifyToken(authInfoDO);
        }
        AuthHolder.setInfo(authInfoDO);
        return super.preHandle(request, response, handler);
    }

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