package com.propertyManagement.business.support.interceptor;

import com.alibaba.fastjson2.JSON;
import com.propertyManagement.business.domain.vo.LoginWxUser;
import com.propertyManagement.business.service.WxUserTokenService;
import com.propertyManagement.common.annotation.Anonymous;
import com.propertyManagement.common.constant.Constants;
import com.propertyManagement.common.core.domain.AjaxResult;
import com.siashan.toolkit.core.thread.threadlocal.ThreadLocalMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * 小程序登录拦截器
 *
 * @author liushuai
 * @date 2025/05/13
 */
@Slf4j
@Component
public class WxUserLoginInterceptor implements HandlerInterceptor {

    private String URL_PRE = "/api/";

    @Autowired
    protected WxUserTokenService wxUserTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Anonymous annotation = method.getAnnotation(Anonymous.class);
            if (null != annotation) {
                return true;
            } else {
                String requestURI = request.getRequestURI();
                boolean targetURI = requestURI.startsWith(URL_PRE);
                if (targetURI) {
                    LoginWxUser wxLogin = wxUserTokenService.getWxLogin(request);
                    if (null == wxLogin) {
                        sendResponse(response);
                        return false;
                    }
                    wxUserTokenService.verifyToken(wxLogin);
                    ThreadLocalMap.put(Constants.USER_AUTH, wxLogin);
                    return true;
                } else {
                    return true;
                }
            }
        } else {
            return true;
        }
    }


    private void sendResponse(HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        try (OutputStream out = response.getOutputStream();
             PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"))) {
            // 返回json格式的提示
            pw.println(JSON.toJSONString(AjaxResult.error(401, "请先登录后才能操作！")));
        } catch (IOException ex) {
            log.warn("", ex);
        }
    }
}
