package weaver.interfaces.htsc.cus;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.cus.entity.trip.CcrEntity;
import weaver.interfaces.htsc.cus.entity.trip.ClspEntity;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TripReimbursementAction extends BaseBean implements Action {

  //基础表
  private static final String TABLE_CLSP = "uf_clsp";
  //费用会计表
  private static final String TABLE_FYKJJD = "uf_fykjjd";
  //部门表
  private static final String TABLE_DEPARTMENT = "hrmdepartment";
  //部门自定义表
  private static final String TABLE_DEPARTMENT_DEFINED = "hrmdepartmentdefined";
  //员工信息表
  private static final String TABLE_RESOURCE = "hrmresource";
  //联合协管领导
  private static final String TABLE_LH_XGLD = "uf_htlhbmxgld";


  @Override
  public String execute(RequestInfo requestInfo) {
    try {
      ResourceComInfo rc = new ResourceComInfo();
      DepartmentComInfo dc = new DepartmentComInfo();
      //流程请求ID
      String requestId = Util.null2String(requestInfo.getRequestid());
      //主表
      String mainTable = Util.null2String(requestInfo.getRequestManager().getBillTableName());
      //明细表12
      String dt12Table = mainTable + "_dt12";
      //明细表9
      String dt9Table = mainTable + "_dt9";
      //查询主表数据
      String sql = String
          .format("select id,lcbh,ngr,szjg,szbm,cclxzxx,ngrq from %s where requestid = ?",
              mainTable);
      RecordSet rs = new RecordSet();
      rs.executeQuery(sql, requestId);
      while (rs.next()) {
        //主表ID
        int mainId = Util.getIntValue(rs.getInt("id"));
        //流程编号
        String lcbh = Util.null2String(rs.getString("lcbh"));
        //拟稿人
        String ngr = Util.null2String(rs.getString("ngr"));
        // 拟稿人工号
        String ngrgh = Util.null2String(rc.getWorkcode(ngr));
        // 拟稿日期
        String ngrq = Util.null2String(rs.getString("ngrq"));
        String paramTag = String
            .format(" prams:requestId:%s, mainId:%s, lcbh:%s, ngrgh:%s", requestId, mainId, lcbh,
                ngrgh);
        Map<String, Object> param = new HashMap<>();
        Map<String, Set<String>> ccrParam = new HashMap<>();
        //获取出差人信息
        List<CcrEntity> ccrDataList = getCCRData(mainId, dt9Table, dt12Table, ngrq, mainTable);
        writeLog("get ccr info, result:" + JSONArray.toJSONString(ccrDataList) + paramTag);
        for (CcrEntity ccrEntity : ccrDataList) {
          String ccr = ccrEntity.getCcr();
          // 出差人机构
          String jg = ccrEntity.getCcrszjg();
          // 出差人部门
          String bm = ccrEntity.getCcrszbm();
          // 查询基础表获取审批链
          List<ClspEntity> clspDataList = getClspData(jg, bm);
          writeLog("get spl, result:" + JSONArray.toJSONString(clspDataList) + paramTag +
              String.format(", ccr:%s, jg:%s, bm:%s", ccr, jg, bm));
          if (!CollectionUtils.isEmpty(clspDataList)) {
            ClspEntity clspData = combineClspData(ccrEntity, clspDataList);
            if (clspData != null) {
              writeLog("get combine spl, result:" + JSON.toJSONString(clspData) + paramTag +
                  String.format(", ccr:%s, jg:%s, bm:%s", ccr, jg, bm));
              convertCCRApproveMap(ccr, ngr, rc, dc, clspData, ccrParam);
            }
          }
        }
        if (ccrParam.size() > 0) {
          if (!CollectionUtils.isEmpty(ccrParam.get("yjbmfzr"))) {
            param.put("yjbmfzr", String.join(",", ccrParam.get("yjbmfzr")));
          }
          if (!CollectionUtils.isEmpty(ccrParam.get("ejbmfzr"))) {
            param.put("ejbmfzr", String.join(",", ccrParam.get("ejbmfzr")));
          }
          if (!CollectionUtils.isEmpty(ccrParam.get("thqyfzrsp"))) {
            param.put("txqyfzrsp", String.join(",", ccrParam.get("thqyfzrsp")));
          }
          if (!CollectionUtils.isEmpty(ccrParam.get("fgld"))) {
            param.put("fgld", String.join(",", ccrParam.get("fgld")));
          }
          if (!CollectionUtils.isEmpty(ccrParam.get("zc"))) {
            param.put("zc", String.join(",", ccrParam.get("zc")));
          }
          if (!CollectionUtils.isEmpty(ccrParam.get("dsc"))) {
            param.put("dsc", String.join(",", ccrParam.get("dsc")));
          }
          if (!CollectionUtils.isEmpty(ccrParam.get("xgld"))) {
            param.put("xgld", String.join(",", ccrParam.get("xgld")));
          }
        } else {
          writeLog("not found effective cpl" + paramTag);
        }
        //会签部门领导
        String hqbm = Util.null2String(rs.getString("hqbm"));
        Map<String, Object> hqbmLeaderMap = getDeptLeader(hqbm);
        if (!StringUtils.isBlank((String) hqbmLeaderMap.get("bmfzrid"))) {
          param.put("hqbmfzr", hqbmLeaderMap.get("bmfzrid"));
        }
        //出差类型子选项
        String cclxzxx = getCclxzxx(mainId, dt12Table);
        String thxmfzr = "";
        String xmssbmfzr = "";
        if ("0".equals(cclxzxx)) {
          //投行负责人与项目所属负责人调用接口实时获取
          Map<String, String> project = getProject(mainId, dt12Table, dt9Table);
          thxmfzr = project.get("thxmfzr");
          xmssbmfzr = project.get("xmfzbmfzr");
          writeLog("invoke th interface, result:" + JSON.toJSONString(project) + paramTag);
        }
        //投行负责人
        if (!StringUtils.isBlank(thxmfzr)) {
          param.put("thxmfzr", thxmfzr);
        }
        //项目所属部门负责人
        if (!StringUtils.isBlank(xmssbmfzr)) {
          param.put("xmfzbmfzr", xmssbmfzr);
        }
        //一级部门负责人 项目负责人 以及项目所属部门负责人
        String yjbmfzrStr = Util.null2String(param.get("yjbmfzr"));
        String thxmfzrStr = Util.null2String(param.get("thxmfzr"));
        String xmfzbmfzrStr = Util.null2String(param.get("xmfzbmfzr"));
        Set<String> yjbmfzrSetTemp = new HashSet<>(Arrays.asList(yjbmfzrStr.split(",")));
        Set<String> thxmfzrSetTemp = new HashSet<>(Arrays.asList(thxmfzrStr.split(",")));
        Set<String> xmfzbmfzrSetTemp = new HashSet<>(Arrays.asList(xmfzbmfzrStr.split(",")));
        //处理项目负责人，节点优先度 项目负责人 > 一级负责人 > 项目所属部门负责人
        yjbmfzrSetTemp.removeAll(thxmfzrSetTemp);
        xmfzbmfzrSetTemp.removeAll(thxmfzrSetTemp);
        param.put("thxmfzr", String.join(",", thxmfzrSetTemp));
        param.put("yjbmfzr", String.join(",", yjbmfzrSetTemp));
        //处理项目负责人
        xmfzbmfzrSetTemp.removeAll(yjbmfzrSetTemp);
        param.put("xmfzbmfzr", String.join(",", xmfzbmfzrSetTemp));
        //当项目负责人与二级部门负责人有重复时，跳过项目负责人节点
        String temp1 = Util.null2String(param.get("xmfzbmfzr"));
        String temp2 = Util.null2String(param.get("ejbmfzr"));
        if (temp1 != null && temp2 != null) {
          Set<String> xmfzbmfzrSet = new HashSet<>(Arrays.asList(temp1.split(",")));
          Set<String> ejbmfzrSet = new HashSet<>(Arrays.asList(temp2.split(",")));
          if (!CollectionUtils.isEmpty(xmfzbmfzrSet) && !CollectionUtils.isEmpty(ejbmfzrSet)) {
            xmfzbmfzrSet.removeAll(ejbmfzrSet);
            param.put("xmfzbmfzr", String.join(",", xmfzbmfzrSet));
          }
        }
        /**
         * 分管领导与总裁去重
         */
        Object fgldObj = param.get("fgld");
        Object zcObj = param.get("zc");
        Object dszObj = param.get("dsc");
        if(Objects.nonNull(fgldObj)){
          List<String> fgldList = Arrays.asList(fgldObj.toString().split(","));
          if(Objects.nonNull(zcObj)){
            List<String> zcList = Arrays.asList(zcObj.toString().split(","));
            List<String> zcEmpCodeList = zcList.stream().map(this::getWorkCode).collect(Collectors.toList());
            fgldList = fgldList.stream().filter(t -> !zcEmpCodeList.contains(getWorkCode(t))).collect(Collectors.toList());
          }
          if(Objects.nonNull(dszObj)){
            List<String> dszList = Arrays.asList(dszObj.toString().split(","));
            List<String> dszEmpCodeList = dszList.stream().map(this::getWorkCode).collect(Collectors.toList());
            fgldList = fgldList.stream().filter(t -> !dszEmpCodeList.contains(getWorkCode(t))).collect(Collectors.toList());
          }
          String fgld = String.join(",", fgldList);
          param.put("fgld", fgld);
        }

        if (param.size() > 0) {
          //更新mainTable
          updateMainTable(mainTable, mainId, param);
          writeLog("update main table, update:" + JSON.toJSONString(param) + paramTag);
        }
      }
    } catch (Exception e) {
      writeLog("invoke error", e);
      requestInfo.getRequestManager().setMessageid("11111111");
      requestInfo.getRequestManager().setMessagecontent("接口捕获异常，请联系管理员处理！");
      return Action.FAILURE_AND_CONTINUE;
    }
    return Action.SUCCESS;
  }

  private ClspEntity combineClspData(CcrEntity ccrData, List<ClspEntity> clspData) {
    ClspEntity result = null;
    double splje = NumberUtils.toDouble(ccrData.getSplje(), 0);
    int aqdj = NumberUtils.toInt(ccrData.getAqdj(), 0);
    String ccr = ccrData.getCcr();
    List<ClspEntity> tempList = clspData;
    List<ClspEntity> ryList = clspData.stream().filter(ce -> ce.getRy().equals(ccr))
        .collect(Collectors.toList());
    if (!CollectionUtils.isEmpty(ryList)) {
      //有特殊人员
      tempList = ryList;
    } else {
      //无特殊人员，匹配安全级别
      if (aqdj == 50) {
        tempList = tempList.stream().filter(ce -> "50".equals(ce.getAqdj()))
            .collect(Collectors.toList());
      }
      if (aqdj < 50) {
        tempList = tempList.stream().filter(ce -> Integer.parseInt(ce.getAqdj()) < 50)
            .collect(Collectors.toList());
      }
      if (aqdj > 50) {
        tempList = tempList.stream().filter(ce -> Integer.parseInt(ce.getAqdj()) > 50)
            .collect(Collectors.toList());
      }
    }

    List<ClspEntity> amountList = new ArrayList<>();
    //匹配金额
    //先判断临界情况
    for (int i = 0; i < tempList.size(); i++) {
      ClspEntity tempEntity = tempList.get(i);
      //最小预算等于合计,且存在区间取值
      if (StringUtils.isNotBlank(tempEntity.getZjfyhj()) &&
          StringUtils.isNotBlank(tempEntity.getZdfyhj()) &&
          Double.parseDouble(tempEntity.getZjfyhj()) == splje) {
        if (Double.parseDouble(tempEntity.getZdfyhj()) > splje) {
          amountList.add(tempEntity);
          break;
        }
      }
      //最大预算等于合计,且符合取值条件
      if ((StringUtils.isBlank(tempEntity.getZjfyhj()) ||
          Double.parseDouble(tempEntity.getZjfyhj()) == 0.0) &&
          Double.parseDouble(tempEntity.getZdfyhj()) == splje) {
        amountList.add(tempEntity);
        break;
      }
    }
    if (CollectionUtils.isEmpty(amountList)) {
      amountList = tempList.stream().filter(ce ->
              (StringUtils.isBlank(ce.getZdfyhj()) || Double.parseDouble(ce.getZdfyhj()) == 0.0) &&
                  !StringUtils.isBlank(ce.getZjfyhj()) && Double.parseDouble(ce.getZjfyhj()) > splje)
          .collect(Collectors.toList());
    }
    if (CollectionUtils.isEmpty(amountList)) {
      amountList = tempList.stream().filter(ce ->
              (StringUtils.isBlank(ce.getZjfyhj()) || Double.parseDouble(ce.getZjfyhj()) == 0.0) &&
                  !StringUtils.isBlank(ce.getZdfyhj()) && Double.parseDouble(ce.getZdfyhj()) < splje)
          .collect(Collectors.toList());
    }
    if (CollectionUtils.isEmpty(amountList)) {
      amountList = tempList.stream().filter(
          ce -> !StringUtils.isBlank(ce.getZjfyhj()) && !StringUtils.isBlank(ce.getZdfyhj()) &&
              Double.parseDouble(ce.getZjfyhj()) < splje &&
              Double.parseDouble(ce.getZdfyhj()) > splje).collect(Collectors.toList());
    }
    tempList = amountList;
    if (!CollectionUtils.isEmpty(tempList)) {
      result = tempList.get(0);
    } else {
      writeLog("not found spl");
    }
    return result;
  }

  private void convertCCRApproveMap(String ccr, String ngr, ResourceComInfo rc,
      DepartmentComInfo dc, ClspEntity combineClspData, Map<String, Set<String>> param) {
    String ccrDeptId = rc.getDepartmentID(ccr);
    String supCcrDeptId = dc.getAllSupDepId(Integer.parseInt(ccrDeptId));
    if (!StringUtils.isBlank(supCcrDeptId) && supCcrDeptId.contains(",")) {
      supCcrDeptId = supCcrDeptId.substring(0, supCcrDeptId.indexOf(","));
    }
    Map<String, Object> deptLeaderMap = getDeptLeader(ccrDeptId);
    //一级部门负责人
    String yjbmfzr = combineClspData.getYjbmfzr();
    String yjbmfzrId = "";
    if ("0".equals(yjbmfzr)) {
      yjbmfzrId = (String) deptLeaderMap.get("bmfzrid");
    } else if ("1".equals(yjbmfzr)) {
      yjbmfzrId = String.valueOf(getEmpId("009169"));
    } else if ("2".equals(yjbmfzr)) {
      yjbmfzrId = String.valueOf(getEmpId("009254"));
    } else if ("3".equals(yjbmfzr)) {
      yjbmfzrId = String.valueOf(getEmpId("009400"));
    } else if ("4".equals(yjbmfzr)) {
      yjbmfzrId = (String) deptLeaderMap.get("bmfgldid");
    } else if ("5".equals(yjbmfzr)) {
      Map<String, Object> supDeptLeaderMap = getDeptLeader(supCcrDeptId);
      yjbmfzrId = (String) supDeptLeaderMap.get("bmfzrid");
    }
    if (!param.containsKey("yjbmfzr")) {
      param.put("yjbmfzr", new HashSet<>());
    }
    param.get("yjbmfzr").add(yjbmfzrId);
    //二级部门负责人
    String ejbmfzr = combineClspData.getEjbmfzr();
    String ejbmfzrId = "";
    if ("0".equals(ejbmfzr)) {
      ejbmfzrId = (String) deptLeaderMap.get("bmfzrid");
    }
    if (!param.containsKey("ejbmfzr")) {
      param.put("ejbmfzr", new HashSet<>());
    }
    param.get("ejbmfzr").add(ejbmfzrId);
    //投行区域负责人审批(拟稿人部门ID)
    String thqyfzrsp = combineClspData.getTxqyfzrsp();
    if ("0".equals(thqyfzrsp)) {
      if (!param.containsKey("thqyfzrsp")) {
        param.put("thqyfzrsp", new HashSet<>());
      }
      String departmentID = rc.getDepartmentID(ccr);
      param.get("thqyfzrsp").add(getThfzr(departmentID));
    }
    //分管领导
    String fgld = combineClspData.getFgld();
    String fgldId = "";
    if ("0".equals(fgld)) {
      fgldId = (String) deptLeaderMap.get("bmfgldid");
    } else if ("1".equals(fgld)) {
      fgldId = String.valueOf(getEmpId("001781"));
    }
    if (!param.containsKey("fgld")) {
      param.put("fgld", new HashSet<>());
    }
    param.get("fgld").add(fgldId);
    // 总裁
    String zc = combineClspData.getZc();
    String zcId = "";
    if ("0".equals(zc)) {
      zcId = String.valueOf(getEmpId("009400"));
    }
    if (!param.containsKey("zc")) {
      param.put("zc", new HashSet<>());
    }
    param.get("zc").add(zcId);
    //董事长
    String dsc = combineClspData.getDsc();
    String dscId = "";
    if ("0".equals(dsc)) {
      dscId = String.valueOf(getEmpId("009169"));
    }
    if (!param.containsKey("dsc")) {
      param.put("dsc", new HashSet<>());
    }
    param.get("dsc").add(dscId);
    //协管领导
    if ("1".equals(combineClspData.getXgld())) {
      String bm = combineClspData.getBm();
      if (!param.containsKey("xgld")) {
        param.put("xgld", new HashSet<>());
      }
      param.get("xgld").add(getXgldByBm(bm));
    }
    //如果投行区域负责人和协管领导重复则去掉投行区域负责人重复的人员
    if (param.containsKey("thqyfzrsp") && param.get("thqyfzrsp").size() > 0 && param.containsKey(
        "xgld") && param.get("xgld").size() > 0) {
      Set<String> thqyfzrSet = param.get("thqyfzrsp");
      Set<String> xgldSet = param.get("xgld");
      thqyfzrSet.removeAll(xgldSet);
      param.put("thqyfzrsp", thqyfzrSet);
    }
  }


  /**
   * 获取出差人信息
   *
   * @param mainId
   * @return
   */
  private List<CcrEntity> getCCRData(int mainId, String dt9Table, String dt12Table, String ngrq,
      String mainTable)
      throws Exception {
    RecordSet rs = new RecordSet();
    List<CcrEntity> result = new ArrayList<>();
    List<CcrEntity> list = new ArrayList<>();
    //流程是否代领导报销
    boolean flag = isActLeader(rs, mainId, mainTable);
    String sql;
    //代领导报销时，ccsqlc字段不存在
    if (flag) {
      writeLog("lh spl isActLeader");
      sql = String.format(
          "select dd.ccrszjg,dd.ccrszbm,dd.aqdj,dd.ccr,tt.splje from %s dd left join %s tt on dd.mainid=tt.mainid where dd.mainid=?",
          dt12Table, dt9Table);
    } else {
      sql = String.format(
          "select dd.ccrszjg,dd.ccrszbm,dd.aqdj,dd.ccr,tt.splje from %s dd left join %s tt on dd.mainid=tt.mainid and dd.ccsqlc=tt.ccsqlc where dd.mainid=?",
          dt12Table, dt9Table);
    }

    rs.executeQuery(sql, mainId);
    while (rs.next()) {
      CcrEntity entity = new CcrEntity();
      entity.setCcrszjg(rs.getString("ccrszjg"));
      entity.setCcrszbm(rs.getString("ccrszbm"));
      entity.setAqdj(rs.getString("aqdj"));
      entity.setSplje(rs.getString("splje"));
      entity.setCcr(rs.getString("ccr"));
      list.add(entity);
    }
    //聚合数据合并同一个出差人
    Map<String, List<CcrEntity>> groupByCcr = list.stream()
        .collect(Collectors.groupingBy(CcrEntity::getCcr));
    for (Entry<String, List<CcrEntity>> entry : groupByCcr.entrySet()) {
      String ccr = entry.getKey();
      CcrEntity entity = entry.getValue().get(0);
      double ys = entry.getValue().stream().mapToDouble(a -> Double.parseDouble(Util.null2String(a.getSplje()) == "" ? "0.00" : Util.null2String(a.getSplje())))
          .sum();
      CcrEntity ccrEntity = new CcrEntity();
      BeanUtils.copyProperties(entity, ccrEntity);
      ccrEntity.setSplje(String.valueOf(ys));
      result.add(ccrEntity);
    }
    //计税合计金额为0，则不匹配审批链
    List<CcrEntity> resultHaveJe = result.stream().filter(
            ccr -> StringUtils.isNotBlank(ccr.getSplje()) &&
                new BigDecimal(ccr.getSplje()).compareTo(BigDecimal.ZERO) != 0)
        .collect(Collectors.toList());
    return resultHaveJe;
  }


  private String getSfcys(String bm, String ngrq, double ys) throws Exception {
    HTUtil ht = new HTUtil();
    Map<String, Object> param = new HashMap<>();
    DepartmentComInfo dc = new DepartmentComInfo();
    String bmCode = dc.getDepartmentCode(bm);
    param.put("deptNum", bmCode);
    param.put("deptType", getDeptTypeCode(bm));
    param.put("Bgitem", "8601050301");
    param.put("BgPeriod", ngrq.substring(0, ngrq.indexOf(" ")));
    String response = ht.getBudget(param);
    String budget = "";
    if (StringUtils.isNotBlank(response)) {
      JSONObject jsonObject = JSONObject.parseObject(response);
      if (jsonObject != null && jsonObject.size() > 0) {
        if (JSONPath.contains(jsonObject, "$.BudgetData.Level.FBgbanlance")) {
          budget = String.valueOf(JSONPath.eval(jsonObject, "$.BudgetData.Level.FBgbanlance"));
        }
      }
    } else {
      throw new Exception("get budget exception");
    }
    if (StringUtils.isNotBlank(budget)) {
      double v = Double.parseDouble(budget);
      if (ys > v) {
        return "1";
      } else {
        return "0";
      }
    } else {
      return "0";
    }
  }

  /**
   * 获取审批链
   *
   * @param jg
   * @param bm
   * @return
   */
  private List<ClspEntity> getClspData(String jg, String bm) {
    List<ClspEntity> list = new ArrayList<>();
    String sql = String.format(
        "select id,jg,bm,aqdj,ry,zjfyhj,zdfyhj,jeqk,yjbmfzr,ejbmfzr,txqyfzrsp,fgld,zc,dsc,xgld from %s where 1=1 and jg=? and bm=?",
        TABLE_CLSP);
    RecordSet rs = new RecordSet();
    rs.executeQuery(sql, jg, bm);
    while (rs.next()) {
      ClspEntity entity = new ClspEntity();
      entity.setId(rs.getString("id"));
      entity.setJg(rs.getString("jg"));
      entity.setBm(rs.getString("bm"));
      entity.setAqdj(rs.getString("aqdj"));
      entity.setRy(rs.getString("ry"));
      entity.setZjfyhj(rs.getString("zjfyhj"));
      entity.setZdfyhj(rs.getString("zdfyhj"));
      entity.setJeqk(rs.getString("jeqk"));
      entity.setYjbmfzr(rs.getString("yjbmfzr"));
      entity.setEjbmfzr(rs.getString("ejbmfzr"));
      entity.setTxqyfzrsp(rs.getString("txqyfzrsp"));
      entity.setFgld(rs.getString("fgld"));
      entity.setZc(rs.getString("zc"));
      entity.setDsc(rs.getString("dsc"));
      entity.setXgld(rs.getString("xgld"));
      list.add(entity);
    }
    return list;
  }

  /**
   * 更新主表字段
   *
   * @param tableName
   * @param mainId
   * @param param
   */
  private void updateMainTable(String tableName, int mainId, Map<String, Object> param) {
    RecordSetTrans rts = new RecordSetTrans();
    rts.setAutoCommit(false);
    String updateSql = " update " + tableName + " set ";
    String sqlWhere = " where id=" + mainId;
    Object[] valueArr = new Object[param.size()];
    int i = 0;
    for (Entry<String, Object> entry : param.entrySet()) {
      String key = entry.getKey();
      if (i == 0) {
        updateSql = String.format("%s%s=?", updateSql, key);
      } else {
        updateSql = String.format("%s, %s=?", updateSql, key);
      }
      valueArr[i] = entry.getValue();
      i++;
    }
    updateSql += sqlWhere;
    try {
      boolean result = rts.executeUpdate(updateSql, valueArr);
      if (result) {
        rts.commit();
      } else {
        writeLog("update main table failed");
      }
    } catch (Exception e) {
      rts.rollback();
      writeLog("update main table exception", e);
    }
  }

  private Map<String, String> getProject(int mainId, String dt12Name, String dt9Name) {
    Map<String, String> result = new HashMap<>();
    Map<Integer, String> projectIdMap = getProjectIdMapByMainId(mainId, dt12Name);
    Map<Integer, String> bmMap = getFycdbmAndSzbmMapByMainId(mainId, dt9Name);
    Set<String> thxmfzrSet = new HashSet<>();
    Set<String> xmfzbmfzrSet = new HashSet<>();
    for (Entry<Integer, String> entry :
        projectIdMap.entrySet()) {
      Integer ccsqlc = entry.getKey();
      String projectIdAndBxr = entry.getValue();
      String[] arr = projectIdAndBxr.split("_");
      Integer projectId = NumberUtils.toInt(arr[0]);
      String bxr = arr[1];
      boolean isLxfzr = isLxfzr(bxr);
      String[] bmArr = bmMap.get(ccsqlc).split("_");
      Integer deptId = NumberUtils.toInt(bmArr[0]);
      Integer ccrDeptId = NumberUtils.toInt(bmArr[1]);

      HTUtil ht = new HTUtil();
      Map<String, Object> paras = new HashMap<>();
      paras.put("projectId", String.valueOf(projectId));
      String projectInfo = ht.getProjectById(paras);

      if (StringUtils.isNotBlank(projectInfo)) {
        JSONObject jsonObject = JSON.parseObject(projectInfo);
        //项目负责人
        String userCodes = (String) jsonObject.get("userIds1");
        if (!StringUtils.isBlank(userCodes)) {
          String[] userCodesArr = userCodes.split(",");
          Set<String> tempSet = Arrays.stream(userCodesArr).filter(StringUtils::isNotBlank)
              .collect(Collectors.toSet());
          for (String empCode : tempSet) {
            thxmfzrSet.add(getEmpId(empCode) + "");
          }
        }
        if (deptId > 0) {
          //费用承担部门与出差人所在部门一致，则跳过费用承担部门负责人
          if (isLxfzr && deptId.equals(ccrDeptId)) {
            writeLog(
                "skip xmfzbmfzr. bxr: " + bxr + ", fycdbm: " + deptId + ", ccrszbm: " + ccrDeptId);
          } else {
            Map<String, Object> deptLeader = getDeptLeader(String.valueOf(deptId));
            String bmfzrid = (String) deptLeader.get("bmfzrid");
            if (!StringUtils.isBlank(bmfzrid)) {
              xmfzbmfzrSet.add(bmfzrid);
            }
          }
        }
      }

    }
    //投行负责人
    if (thxmfzrSet.size() > 0) {
      result.put("thxmfzr", String.join(",", thxmfzrSet));
    }
    //项目所属部门负责人
    if (xmfzbmfzrSet.size() > 0) {
      result.put("xmfzbmfzr", String.join(",", xmfzbmfzrSet));
    }
    return result;
  }

  private Map<Integer, String> getProjectIdMapByMainId(int mainId, String tableName) {
    Map<Integer, String> result = new HashMap<>();
    int ccsqlc = 0;
    int projectId = 0;
    int bxr = 0;
    RecordSet rs = new RecordSet();
    String sql = String.format("select ccsqlc,txbm,ccr from %s where mainid = ?", tableName);
    rs.executeQuery(sql, mainId);
    while (rs.next()) {
      ccsqlc = rs.getInt("ccsqlc");
      projectId = rs.getInt("txbm");
      bxr = rs.getInt("ccr");
      if (projectId > 0) {
        result.put(ccsqlc, String.format("%s_%s", projectId, bxr));
      }
    }
    return result;
  }

  private Map<Integer, String> getFycdbmAndSzbmMapByMainId(int mainId, String tableName) {
    Map<Integer, String> result = new HashMap<>();
    int ccsqlc = 0;
    int fycdbm = 0;
    int ccrssbm = 0;
    RecordSet rs = new RecordSet();
    String sql = String.format("select ccsqlc,fycdbm,ccrssbm from %s where mainid = ?", tableName);
    rs.executeQuery(sql, mainId);
    while (rs.next()) {
      ccsqlc = rs.getInt("ccsqlc");
      fycdbm = rs.getInt("fycdbm");
      ccrssbm = rs.getInt("ccrssbm");
      result.put(ccsqlc, String.format("%s_%s", fycdbm, ccrssbm));
    }
    return result;
  }

  /**
   * 根据员工号获取泛微ID
   *
   * @param empCode
   * @return
   */
  private int getEmpId(String empCode) {
    int id = 0;
    String sql = String.format("select id,workcode from %s where workcode=? and belongto is null", TABLE_RESOURCE);
    RecordSet rs = new RecordSet();
    rs.executeQuery(sql, empCode);
    while (rs.next()) {
      id = rs.getInt("id");
      break;
    }
    return id;
  }

  /**
   * 根据泛微第获取工号
   * @param id
   * @return
   */
  private String getWorkCode(String id){
    String sql = String.format("select workcode from %s where id=?", TABLE_RESOURCE);
    RecordSet rs = new RecordSet();
    rs.executeQuery(sql, id);
    if (rs.next()){
      return rs.getString("workcode");
    }
    return "";
  }

  /**
   * 获取部门负责人已经分管领导
   *
   * @param deptId
   * @return
   */
  private Map<String, Object> getDeptLeader(String deptId) {
    Map<String, Object> result = new HashMap<>();
    String sql = String.format("select deptdirectors,deptleaders,cohead from %s where deptid=?",
        TABLE_DEPARTMENT_DEFINED);
    RecordSet rs = new RecordSet();
    rs.executeQuery(sql, deptId);
    while (rs.next()) {
      result.put("bmfgldid", rs.getString("deptleaders"));
      String lxfzr = rs.getString("cohead");
      Set<String> lxfzrSet = new HashSet<>();
      if (StringUtils.isNotBlank(lxfzr)) {
        lxfzrSet = Stream.of(lxfzr.split(",")).filter(StringUtils::isNotBlank)
            .collect(Collectors.toSet());
      }
      String bmfzr = rs.getString("deptdirectors");
      Set<String> bmfzrSet = new HashSet<>();
      if (StringUtils.isNotBlank(bmfzr)) {
        bmfzrSet = Stream.of(bmfzr.split(",")).filter(StringUtils::isNotBlank)
            .collect(Collectors.toSet());
      }
      bmfzrSet.removeAll(lxfzrSet);
      result.put("bmfzrid", String.join(",", bmfzrSet));
      break;
    }
    return result;
  }


  /**
   * 根据部门编号获取泛微部门ID
   *
   * @param deptCode
   * @return
   */
  private int getDeptId(String deptCode) {
    int id = 0;
    String sql = String.format("select id from %s where departmentcode=?", TABLE_DEPARTMENT);
    RecordSet rs = new RecordSet();
    rs.executeQuery(sql, deptCode);
    while (rs.next()) {
      id = rs.getInt("id");
      break;
    }
    return id;
  }

  private String getDeptTypeCode(String deptId) {
    String code = "";
    String sql = String
        .format("select depttypecode from %s where deptid=?", TABLE_DEPARTMENT_DEFINED);
    RecordSet rs = new RecordSet();
    rs.executeQuery(sql, deptId);
    while (rs.next()) {
      code = rs.getString("depttypecode");
      break;
    }
    return code;
  }

  private String getDeptName(Integer deptId) {
    String name = "";
    String sql = String
        .format("select departmentname from %s where id=?", TABLE_DEPARTMENT);
    RecordSet rs = new RecordSet();
    rs.executeQuery(sql, deptId);
    while (rs.next()) {
      name = rs.getString("departmentname");
      break;
    }
    return name;
  }

  /**
   * 获取投行负责人
   *
   * @param departmentID
   */
  private String getThfzr(String departmentID) {
    String result = "";
    RecordSet rs = new RecordSet();
    String sql = String.format("select txqyfzr from %s where deptid = ?", TABLE_DEPARTMENT_DEFINED);
    rs.executeQuery(sql, departmentID);
    while (rs.next()) {
      result = rs.getString("txqyfzr");
      break;
    }
    return result;
  }

  /**
   * 是否超预算
   *
   * @param mainId
   * @param ccr
   * @return
   */
  private String getSfcb(int mainId, String ccr, String tableName) {
    String result = "";
    RecordSet rs = new RecordSet();
    String sql = String.format("select fysfcb from %s where mainid = ? and ccr = ?", tableName);
    rs.executeQuery(sql, mainId, ccr);
    while (rs.next()) {
      result = rs.getString("fysfcb");
      break;
    }
    return result;
  }

  private String getCclxzxx(int mainId, String tableName) {
    String result = "";
    RecordSet rs = new RecordSet();
    String sql = String.format("select cclxzxx from %s where mainid = ?", tableName);
    rs.executeQuery(sql, mainId);
    while (rs.next()) {
      result = rs.getString("cclxzxx");
      break;
    }
    return result;
  }

  private void compareAndSetFzr(String fzrStr1, String fzrStr2, String putNullFzr,
      Map<String, Object> param) {
    List<String> tempList1 = Arrays.asList(fzrStr1.split(","));
    List<String> tempList2 = Arrays.asList(fzrStr2.split(","));
    tempList1.sort(Comparator.comparing(String::hashCode));
    tempList2.sort(Comparator.comparing(String::hashCode));
    if (tempList1.toString().equals(tempList2.toString())) {
      param.put(putNullFzr, null);
    }
  }

  //判断报销人是否为联席负责人
  private boolean isLxfzr(String bxr) {
    boolean result = false;
    RecordSet rs = new RecordSet();
    String sql = "select cohead from " + TABLE_DEPARTMENT_DEFINED
        + " where deptcodepath like '100-%' and cohead is not null";
    rs.executeQuery(sql);
    while (rs.next()) {
      String cohead = rs.getString("cohead");
      if (StringUtils.isNotBlank(cohead)) {
        List<String> coheadList = Arrays.asList(cohead.split(","));
        if (StringUtils.isNotBlank(bxr) && coheadList.contains(bxr)) {
          result = true;
          break;
        }
      }
    }
    return result;
  }

  private String getXgldByBm(String bm) {
    String xgld = "";
    RecordSet rs = new RecordSet();
    String sql = String.format("select spr from %s where bm = ?", TABLE_LH_XGLD);
    rs.executeQuery(sql, bm);
    while (rs.next()) {
      xgld = rs.getString("spr");
    }
    return xgld;
  }

  private boolean isActLeader(RecordSet rs, int mainid, String mainTable) {
    String sfldbx = "";
    String sql = String.format("select sfldbx from %s " +
        " where id = ?", mainTable);
    rs.executeQuery(sql, mainid);
    while (rs.next()) {
      sfldbx = rs.getString("sfldbx");
      break;
    }
    if ("0".equals(sfldbx)) {
      return true;
    } else {
      return false;
    }
  }

  public static void main(String[] args) {
    GCONST.setRootPath("WEB-INF/");
    GCONST.setServerName("ecology");

    TripReimbursementAction action = new TripReimbursementAction();
    RequestInfo requestInfo = new RequestInfo();
    requestInfo.setRequestid("5137150");
    RequestManager requestManager = new RequestManager();
    // 注意表名 每个测试环境不一样 169 为main_51 171为main_132
    requestManager.setBilltablename("formtable_main_132");
    requestInfo.setRequestManager(requestManager);
    action.execute(requestInfo);
    System.out.println("111");
  }
}
