package com.mortals.xhx.busiz.security.filter;

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.service.IAuthTokenService;
import com.mortals.framework.service.IUser;
import com.mortals.framework.web.interceptor.BaseInterceptor;
import com.mortals.xhx.base.framework.annotation.ApiUserAuth;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import com.mortals.xhx.module.device.model.DeviceEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * api接口权限验证
 *
 * @author: zxfei
 * @date: 2022/4/11 15:50
 */
@Component
public class ApiSubmitInterceptor extends BaseInterceptor {

    @Autowired
    private IAuthTokenService authTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            ApiUserAuth annotation = method.getAnnotation(ApiUserAuth.class);
            if (annotation != null) {
                //校验
                if (!this.verifyApiUser(request)) {
                    JSONObject ret = new JSONObject();
                    ret.put("code", ApiRespCodeEnum.TOKEN_FAILED.getValue());
                    ret.put("msg", ApiRespCodeEnum.TOKEN_FAILED.getLabel());
                    super.writeJsonResponse(response, 200, JSONObject.toJSONString(ret));
                    return false;
                }
            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }

    public boolean verifyApiUser(HttpServletRequest request) {
        IUser apiUser = authTokenService.getLoginUser(request);
        if (!ObjectUtils.isEmpty(apiUser) ) {
          //  authTokenService.verifyToken(apiUser);
            return true;
        }
        return false;

    }
}
