package com.customization.htsc.payment;

import com.alibaba.fastjson.JSONObject;
import com.engine.core.cfg.annotation.CommandDynamicProxy;
import com.engine.core.interceptor.AbstractCommandProxy;
import com.engine.core.interceptor.Command;
import com.engine.htsc.payment.enums.ReiState;
import com.engine.htsc.trip.util.WeaverUtil;
import com.engine.workflow.cmd.requestForm.RequestSubmitCmd;
import com.engine.workflow.entity.requestForm.RequestOperationResultBean;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * k1810012
 * 总部差旅报销,保存或删除时行程时同步行程状态
 * DRAFT: 保存
 * TERMINATION: 终止
 */
@CommandDynamicProxy(target = RequestSubmitCmd.class, desc = "总部报销保存时提交行程信息")
public class SaveTableSendTravelReiData2HT extends AbstractCommandProxy<Map<String, Object>> {

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

  @Override
  public Map<String, Object> execute(Command<Map<String, Object>> targetCommand) {
    RequestSubmitCmd requestSubmitCmd = (RequestSubmitCmd) targetCommand;
    HttpServletRequest request = requestSubmitCmd.getRequest();
    PropBean pp = new PropBean();
    //资金业务付款 workflowid
    String headTravelWorkflowId = pp.getPropName("HeadTravelWorkflowId");
    //获取代理对象
    String requestid = Util.null2String(request.getParameter("requestid"));
    String workflowid = Util.null2String(request.getParameter("workflowid"));
    String nodetype = Util.null2String(request.getParameter("nodetype"));
    String src = Util.null2String(request.getParameter("src")); //状态
    //执行标准的业务处理
    Map<String, Object> result = nextExecute(targetCommand);
    RequestOperationResultBean resultBean = (RequestOperationResultBean) result.get("data");
    //流程处理结果
    String type = Util.null2String(resultBean.getType());

    if (StringUtils.isNotBlank(headTravelWorkflowId)
            && workflowid.equals(headTravelWorkflowId)
            && "0".equals(nodetype)) { // 总部报销创建节点
      if ("SUCCESS".equalsIgnoreCase(type)) { //成功
        if ("save".equalsIgnoreCase(src) || "dostopc".equalsIgnoreCase(src)) { //保存 终止
          String code = "";
          log.info(String.format("总部差旅拦截保存或删除事件:workflowid:%s;src:%s;nodetype:%s", workflowid, src, nodetype));
          //状态
          if ("save".equalsIgnoreCase(src)) {
            code = "DRAFT"; //保存
          } else {
            code = "TERMINATION"; //终止
          }
          //保存的requestid未生成
          Map<String, Object> submitParams = resultBean.getSubmitParams();
          if ("-1".equals(requestid)) {
            requestid = Util.null2String(submitParams.get("requestid"));
          }
          //流程id
          HTUtil ht = new HTUtil();
          String tableName = ht.getTableNameByWfid(Integer.parseInt(workflowid));
          Map<String, Object> reiReq = getDataToUpdate(tableName, requestid, code);
          log.info("总部差旅报销流程,同步给华泰差旅报销信息,入参" + JSONObject.toJSONString(reiReq));
          String resp = ht.updateReimbursement(reiReq);
          log.info("总部差旅报销流程,同步给华泰差旅报销信息,返回值" + resp);

        }
      }
    }
    return result;
  }

  /**
   * 生成数据
   *
   * @return map
   */
  private Map<String, Object> getDataToUpdate(String tableName, String requestId, String code) {

    RecordSet rs = new RecordSet();

    String sql = "select t1.lcbh,t1.ngrgh,t1.ngsj,t1.glcclc,t1.zfmxhj,t2.lastname,t3.REQUESTNAME\n" +
            "from " + tableName + " t1\n" +
            "left join hrmresource t2\n" +
            "on t1.ngr = t2.id\n" +
            "left join workflow_requestbase t3\n" +
            "on t1.REQUESTID=t3.REQUESTID\n" +
            "where t1.requestid =?";
    rs.executeQuery(sql, requestId);

    Map<String, Object> para = new HashMap<>();
    if (rs.next()) {
      para.put("draftTime", Util.null2String(rs.getString("ngsj")));
      para.put("drafterId", Util.null2String(rs.getString("ngrgh")));
      para.put("reimbursementBizNo", Util.null2String(rs.getString("lcbh")));
      para.put("drafterName", Util.null2String(rs.getString("lastname")));
      para.put("totalAmount", Util.null2String(rs.getString("zfmxhj")));
      para.put("title", Util.null2String(rs.getString("REQUESTNAME")));
      para.put("processId", requestId);
      para.put("travelApplicationBizNo", splitTravelBizNo(rs.getString("glcclc")));
      para.put("status", code);
    }

    return para;
  }

  private List<String> splitTravelBizNo(String glcclc) {
    List<String> bizNos = new ArrayList<>();
    if (StringUtils.isNotBlank(glcclc)) {
      bizNos = Arrays.stream(glcclc.split(",")).map(
              i -> "出差申请" + i
      ).collect(Collectors.toList());
    }
    return bizNos;
  }
}
