package com.bohuikeji.delivery.backstage.lnterceptor;

import com.bohuikeji.delivery.backstage.service.ITOpenService;
import com.bohuikeji.frame.module.admin.base.SuperBase;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.utils.IpUtil;
import com.bohuikeji.frame.module.admin.utils.JsonUtil;
import com.bohuikeji.frame.module.admin.utils.JwtTokenUtil;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 开放平台拦截器
 * @author Admin
 */
@Slf4j
@RequiredArgsConstructor
public class OpenApiLnterceptor extends SuperBase implements HandlerInterceptor {
    @Autowired
    ITOpenService openService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            log.error("token为空，错误Code：410，来自IP：[{}]，接口地址：[{}]", IpUtil.getIpAddr(request),request.getRequestURL());
            returnJson(APIEntity.fail("token为空，请重新登陆。", 410), response);
            return false;
        }
        int verifyCode = JwtTokenUtil.verify(token);
        if (verifyCode == -1) {
            log.error("token=[{}]无效或已过期，错误Code：411，来自IP：[{}]，接口地址：[{}]",token,IpUtil.getIpAddr(request),request.getRequestURL());
            returnJson(APIEntity.fail("token无效或已过期", 411), response);
            return false;
        }
        if(!("开放平台".equals(JwtTokenUtil.getType(token)))){
            returnJson(APIEntity.fail("token无效！", 411), response);
            return false;
        }
        if(!openService.isExist(verifyCode)){
            returnJson(APIEntity.fail("无法找到您的账号信息，请重新申请token再试！", 411), response);
            return false;
        }
        request.setAttribute("JwtOpenId", verifyCode);
        return true;
    }
    /**
     * Response 返回处理
     *
     * @param result
     * @param response
     */
    private void returnJson(APIEntity result, HttpServletResponse response) {
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.print(JsonUtil.objToJson(result).toJSONString());
        writer.close();
        try {
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
