package com.uas.platform.b2b.listener;

import com.alibaba.fastjson.JSON;
import com.uas.platform.b2b.core.util.ContextUtils;
import com.uas.platform.b2b.dao.ErrorLogDao;
import com.uas.platform.b2b.dao.ErrorLogDetailDao;
import com.uas.platform.b2b.model.ErrorLog;
import com.uas.platform.b2b.model.ErrorLogDetail;
import com.uas.platform.b2b.support.SysConf;
import com.uas.platform.b2b.temporary.model.ExceptionMsg;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.util.AgentUtils;
import com.uas.platform.core.util.serializer.FlexJsonUtils;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 全局异常监听
 *
 * Created by hejq on 2018-06-20.
 */
@ControllerAdvice
@Component
public class GlobalExceptionHandler {

    @Autowired
    private ErrorLogDao logDao;

    @Autowired
    private ErrorLogDetailDao detailDao;

    /**
     * B2B接口地址
     */
    private final String B2B_URL = ContextUtils.getBean(SysConf.class).getB2b();

    /**
     * accessID uu号
     */
    private final static String idParam = "access_id";

    /**
     * 加密串
     */
    private final static String signatureParam = "_signature";

    /**
     * data数据
     */
    private final static String dataParam = "data";

    /**
     * 监控异常，存储方便查看
     *
     * @param request 请求
     * @param e 异常
     * @param response 响应
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public HttpServletResponse defaultErrorHandler(HttpServletRequest request, Exception e, HttpServletResponse response) throws UnsupportedEncodingException {
        String jsonStr = JSON.toJSONString(e.getStackTrace());
        List<ExceptionMsg> msgList = FlexJsonUtils.fromJsonArray(jsonStr, ExceptionMsg.class);
        List<ExceptionMsg> msgs = new ArrayList<>();
        for (ExceptionMsg msg : msgList) {
            if (msg.getClassName().contains(ExceptionMsg.B2BPROGRAMNAME)) {
                msgs.add(msg);
            }
        }
        String url = B2B_URL + request.getServletPath();
        Short needRead = Constant.NO;
        if (url.contains(ExceptionMsg.ERPACCESSURL)) {
            needRead = Constant.YES;
        }
        String access = request.getParameter(signatureParam);
        String data = request.getParameter(dataParam);
        ErrorLog log = logDao.save(new ErrorLog(JSON.toJSONString(msgs), e.toString(), url, e.getCause().getMessage()));
        if (!StringUtils.isEmpty(log.getId())) {
            detailDao.save(new ErrorLogDetail(log.getId(), AgentUtils.getIp(request), needRead, StringUtils.isEmpty(data) ? "" : URLDecoder.decode(data, HTTP.UTF_8), access));
        }
        return response;
    }
}
