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

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.util.StringUtils;
import com.mortals.framework.web.interceptor.BaseInterceptor;
import com.mortals.xhx.base.DeviceAuth;
import com.mortals.xhx.busiz.security.SecurityUtils;
import com.mortals.xhx.busiz.security.DeviceTokenService;
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;

/**
 * 设备上报验证
 *
 * @author: zxfei
 * @date: 2022/4/11 15:50
 */
@Component
public class DeviceSubmitInterceptor extends BaseInterceptor {

    @Autowired
    private DeviceTokenService deviceTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            DeviceAuth annotation = method.getAnnotation(DeviceAuth.class);
            if (annotation != null) {
                //校验
                if (this.verifyDevice(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 verifyDevice(HttpServletRequest request) {
        DeviceEntity device = deviceTokenService.getLoginDevice(request);
        if (!ObjectUtils.isEmpty(device) ) {
            deviceTokenService.verifyToken(device);
            return true;
        }
        return false;

    }
}
