package cn.quantgroup.customer.config.http.mvc.filter;

import cn.quantgroup.customer.config.container.UserThreadLocal;
import cn.quantgroup.customer.entity.OpUser;
import cn.quantgroup.customer.enums.ErrorCodeEnum;
import cn.quantgroup.customer.exception.ValidTokenException;
import cn.quantgroup.customer.rest.vo.JsonResult;
import cn.quantgroup.customer.service.IOpSystemService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * @author yangjun
 * @Date 2020/4/17 16:02
 * @Desc 鉴权过滤器
 * @Update
 */
@WebFilter(filterName = "operatePermitFilter",urlPatterns = {"/operate/sys/*","/repay/earlySettleOperate","/vcc/*"})
@Slf4j
public class ValidOperatePermitFilter implements Filter {
    @Autowired
    private IOpSystemService IOpSystemService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            log.info("OPTIONS请求，放行");
            return;
        }

        String token = request.getHeader("x-auth-token");
        //String system = request.getHeader("x-auth-system");
        if (StringUtils.isBlank(token)) {
            log.error("根据token信息查询用户信息,当前 requestUrl={}",request.getRequestURL());
            renderErrorMsg(servletResponse,ErrorCodeEnum.NO_TOKEN);
            return;
        }

        JsonResult<OpUser> opUserResult = IOpSystemService.findUserByToken(token, null);
        if (Objects.isNull(opUserResult) || !opUserResult.isSuccess()) {
            log.error("根据token查询不到用户信息 token:{}", token);
            renderErrorMsg(servletResponse,ErrorCodeEnum.ILLEGAL_TOKEN);
            return;
        } else {
            OpUser opUser = opUserResult.getData();
            UserThreadLocal.set(opUser);
        }

        //执行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * 处理返回json格式数据
     * @param servletResponse
     * @param codeEnum
     */
    private void renderErrorMsg(ServletResponse servletResponse, ErrorCodeEnum codeEnum) {
        servletResponse.setCharacterEncoding("utf-8");
        PrintWriter out = null;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",codeEnum.getCode());
        jsonObject.put("msg",codeEnum.getMessage());
        try {
            out = servletResponse.getWriter();
            servletResponse.setContentType("application/json; charset=utf-8");
            out.print(jsonObject);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("处理转换信息异常:{}",e.getMessage());
        }

    }

    @Override
    public void destroy() {

    }
}
