package com.engine.htsc.payment.util;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.engine.htsc.payment.enums.ThirdInterfaceEnum;
import com.engine.htsc.payment.pojo.InterfaceLogDTO;
import com.engine.htsc.payment.service.impl.HeadPaymentBudgetCommand;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public final class InterfaceLogUtil {

  private static final Log log = LogFactory.getLog(InterfaceLogUtil.class);

  private static final BizUtils bz = new BizUtils();

  /**
   * aop替换方式,直接传入参数实现日志存库
   * @param paras 方法入参
   */
  public static void saveLogWithMapParams(Map<String, Object> paras, Object response, String methodName) {
    try {
      log.info(String.format("平台调用第三方日志记录,方法名称:%s; 方法参数:%s; 方法返回值:%s",
              methodName, paras, response));
      InterfaceLogDTO interfaceLog = new InterfaceLogDTO();
      //预算接口
      if ("budgetCommit".equals(methodName)) {
        String requestId = JSONUtil.parseObj(paras.get("data")).getStr("billnum");
        interfaceLog = InterfaceLogUtil.collectLog(requestId);
        interfaceLog.setJkmc("");
        interfaceLog.setDydfdz(String.format("%s/cwbase/JTGL/BudgetProcess.asmx?wsdl",
                Util.null2String(new PropBean().getPropName("budgetIp"))));
        interfaceLog.setDyff(methodName);
        interfaceLog.setJklb(ThirdInterfaceEnum.YS.toString());
        interfaceLog.setFwywjg("预算失败");
        if ("F1001".equals(response)) {
          interfaceLog.setFwywjg("预算成功");
        }
      }

      //核算接口
      if ("saveFydj".equals(methodName)) {
        String requestMark = (String) paras.get("fkdh");
        String requestId = JAVATools.getRequestidByRequestMark(requestMark);
        interfaceLog = InterfaceLogUtil.collectLog(requestId);
        interfaceLog.setJkmc("");
        interfaceLog.setDydfdz(String
                .format("%s/cwbase/service/jtgl/zqfyjk.asmx?wsdl + %s/cwbase/JTGL/ZQFYJK.asmx",
                        Util.null2String(new PropBean().getPropName("LangChaoSlaveIp")),
                        Util.null2String(new PropBean().getPropName("LangChaoMasterIp"))));
        interfaceLog.setDyff(methodName);
        interfaceLog.setJklb(ThirdInterfaceEnum.HS.toString());
        interfaceLog.setFwywjg("核算失败");
        if ("F1001".equals(response)) {
          interfaceLog.setFwywjg("核算成功");
        }
      }

      //云票夹关联
      if ("connectInvAndBill".equals(methodName)) {
        String requestMark = (String) paras.get("BillID");
        String requestId = JAVATools.getRequestidByRequestMark(requestMark);
        interfaceLog = InterfaceLogUtil.collectLog(requestId);
        interfaceLog.setJkmc("");
        interfaceLog.setDydfdz(String
                .format("%s/cwbase/sg/v1/ERP/JTCW/HTZQ/API_JTCW_IMAGESYS/ConnectInvAndBill",
                        Util.null2String(new PropBean().getPropName("langChaoIp"))
                                .replace("\"", "")));
        interfaceLog.setDyff(methodName);
        interfaceLog.setJklb(ThirdInterfaceEnum.YPJ_GL.toString());
        interfaceLog.setFwywjg("发票关联失败");
        if (StringUtils.isNotBlank((String) response) && ((String) response).contains("成功")) {
          interfaceLog.setFwywjg("发票关联成功");
        }
      }

      //云票夹取消关联
      if ("resetImageAndBill".equals(methodName)) {
        String requestMark = (String) paras.get("BillID");
        String requestId = JAVATools.getRequestidByRequestMark(requestMark);
        interfaceLog = InterfaceLogUtil.collectLog(requestId);
        interfaceLog.setJkmc("");
        interfaceLog.setDydfdz(String
                .format("%s/cwbase/sg/v1/ERP/JTCW/HTZQ/API_JTCW_IMAGESYS/ResetImageAndBill",
                        Util.null2String(new PropBean().getPropName("langChaoIp"))
                                .replace("\"", "")));
        interfaceLog.setDyff(methodName);
        interfaceLog.setJklb(ThirdInterfaceEnum.YPJ_RESET_GL.toString());
        interfaceLog.setFwywjg("发票取消关联失败");
        if (StringUtils.isNotBlank((String) response) && ((String) response).contains("成功")) {
          interfaceLog.setFwywjg("发票取消关联成功");
        }
      }

      if (StringUtils.isNotBlank(interfaceLog.getRequestId())) {
        interfaceLog.setRc(JSON.toJSONString(paras));
        interfaceLog.setCc((String) response);
        interfaceLog.setDysj(TimeUtil.getCurrentTimeString());
        interfaceLog.setFwjqip(IpUtils.getHostIp());

        InterfaceLogUtil.saveLog(interfaceLog);
      }

    } catch (Exception e) {
      log.error("saveLogWithMapParams catch error:" + e);
    }

  }

  /**
   * 从表单中收集日志
   */
  public static InterfaceLogDTO collectLog(String requestId) throws Exception {
    InterfaceLogDTO ifl = new InterfaceLogDTO();
    ResourceComInfo rc = new ResourceComInfo();
    RecordSet rs = new RecordSet();
    String sql = String.format(
            "SELECT LCBH,NGR FROM %s WHERE REQUESTID = ?",
            bz.getTableNameByRequestId(requestId));
    rs.executeQuery(sql, requestId);
    if (rs.next()) {
      String ngr = Util.null2String(rs.getString("NGR"));
      ifl.setRequestId(requestId);
      ifl.setDyrgh(rc.getWorkcode(ngr));
      ifl.setDyrmc(rc.getLastname(ngr));
      ifl.setLcbh(Util.null2String(rs.getString("LCBH")));
    }
    return ifl;
  }

  /**
   * 保存调用第三方日志
   * @param interfaceLogDTO 收集后的日志数据
   */
  public static void saveLog(InterfaceLogDTO interfaceLogDTO) {
    List<List<Object>> updateParams = new ArrayList<>();
    List<Object> record = new ArrayList<>();
    record.add(Util.null2String(interfaceLogDTO.getRequestId()));
    record.add(Util.null2String(interfaceLogDTO.getLcbh()));
    record.add(Util.null2String(interfaceLogDTO.getRqsj()));
    record.add(Util.null2String(interfaceLogDTO.getJkmc()));
    record.add(Util.null2String(interfaceLogDTO.getRc()));
    record.add(Util.null2String(interfaceLogDTO.getCc()));
    record.add(Util.null2String(interfaceLogDTO.getDyrgh()));
    record.add(Util.null2String(interfaceLogDTO.getDyrmc()));
    record.add(Util.null2String(interfaceLogDTO.getDysj()));
    record.add(Util.null2String(interfaceLogDTO.getFwjqip()));
    record.add(Util.null2String(interfaceLogDTO.getDydfdz()));
    record.add(Util.null2String(interfaceLogDTO.getDyff()));
    record.add(Util.null2String(interfaceLogDTO.getFwywjg()));
    record.add(Util.null2String(interfaceLogDTO.getJklb()));
    updateParams.add(record);
    log.info("日志数据: " + JSON.toJSONString(interfaceLogDTO));
    String insertSql = "INSERT INTO UF_INTERFACELOG " +
            "(REQUESTID,LCBH,RQSJ,JKMC,RC,CC,DYRGH,DYRMC,DYSJ,FWJQIP,DYDFDZ,DYFF,FWYWJG,JKLB) \n" +
            "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    RecordSetTrans rst = new RecordSetTrans();
    try {
      rst.setAutoCommit(false);
      rst.executeBatchSql(insertSql, updateParams);
      rst.commit();
    } catch (Exception e) {
      rst.rollback();
      rst.writeLog("保存调用第三方日志失败,catch error:" + e);
    }
  }
}
