package com.engine.htsc.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.htsc.payment.pojo.ContractInfoVo;
import com.engine.htsc.payment.pojo.ContractRequestParam;
import com.engine.htsc.payment.pojo.TripPaymentRequest;
import com.engine.htsc.payment.service.PaymentService;
import com.engine.htsc.payment.service.PaymentWorkflowService;
import com.engine.htsc.payment.util.PayUtil;
import com.engine.htsc.payment.util.WorkflowCreateUtil;
import com.google.common.collect.Lists;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.runtime.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.setup.ModeRightInfo;
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.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;
import weaver.interfaces.htsc.payment.BTSUpdateAccountDetail;
import weaver.interfaces.htsc.payment.PaymentWorkflowInvoke;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

public class PaymentWorkflowServiceImpl extends Service implements PaymentWorkflowService {

  private Log log = LogFactory.getLog(this.getClass());
  private static final String IsNextFlow = "1";
  //部门表
  private static final String TABLE_DEPARTMENT = "hrmdepartment";
  //员工信息表
  private static final String TABLE_RESOURCE = "hrmresource";

  private List<List> budgetItems = new ArrayList<>();


  @Override
  public Map<String, Object> getVirtualDept() {
    Map<String, Object> datas = new HashMap<>();

    try {
      RecordSet rs = new RecordSet();
      rs.executeQuery("select t.id,t.departmentname from hrmdepartment t " +
          " left join HRMDEPARTMENTDEFINED tf on t.id = tf.deptid" +
          " where t.canceled = 1" +
          " and (tf.sfycgxnbm <> '1' or tf.sfycgxnbm is null) " +
          " and t.id >= 1000 ");
      List<Map> dataList = new ArrayList<>();
      while (rs.next()) {
        Map<String, Object> dataMap = new HashMap<>();
        //Map<String,Object> displayKeys = new HashMap<>();
        List<String> displayKeys = new ArrayList<>();
        displayKeys.add("departmentname");
        String id = Util.null2String(rs.getString("id"));
        String departmentname = Util.null2String(rs.getString("departmentname"));
        dataMap.put("allVersionIds", "");
        dataMap.put("canClick", true);
        dataMap.put("checkStrictly", false);
        dataMap.put("departmentname", departmentname);
        dataMap.put("displayKeys", displayKeys);
        dataMap.put("icon", "icon-coms-Branch");
        dataMap.put("id", id);
        dataMap.put("isImgIcon", false);
        dataMap.put("isParent", false);
        dataMap.put("isVirtual", "1");
        dataMap.put("name", departmentname);
        dataMap.put("orgWholePathspan", departmentname);
        dataMap.put("pid", "728");
        dataMap.put("psubcompanyid", "");
        dataMap.put("selected", false);
        dataMap.put("shadowInfo", departmentname + "/华泰证券股份有限公司/华泰集团/华泰集团组织架构");
        dataMap.put("supdepid", "华泰证券股份有限公司");
        dataMap.put("type", "2");
        dataList.add(dataMap);
      }
      datas.put("datas", dataList);

    } catch (Exception e) {
      e.printStackTrace();
    }
    return datas;
  }


  @Override
  public Map<String, Object> createBusinessTravelWorkflow(TripPaymentRequest request) {
    Map<String, Object> datas = new HashMap<>();
    ResourceComInfo resourceComInfo = null;
    RecordSet rs = new RecordSet();
    RecordSet rsdetail = new RecordSet();
    try {
      resourceComInfo = new ResourceComInfo();
      String loginid = request.getEmpCode();//拟稿人工号
      String deptCode = request.getDeptCode();//拟稿人部门编码
      String account = "";
      Integer deptid = -1;
      //是否为分支机构
      boolean isSub=!("010803".equals(request.getEmpCode())&&"ZZ001".equals(request.getDeptCode()));
      //是否兼岗账号 岗位
      boolean isSecondPosition=loginid.contains("@");
      //如果为分支机构获取到他的次账号
      if (isSecondPosition) {//次账号处理
        //根据部门编码获取部门id
        rsdetail.executeQuery("select id from hrmdepartment where departmentcode = ?", deptCode);
        if (rsdetail.next()) {
          deptid = Util.getIntValue(rsdetail.getString("id"));
        }
        log.info("根据部门编码获取部门id==" + deptid);
        //截取@符之前数字--loginid
        String mainLogind = loginid.substring(0, loginid.indexOf("@"));
        log.info("主账号id==" + mainLogind);
        rs.executeQuery("select id from hrmresource where loginid = ?", mainLogind);
        if (rs.next()) {
          account = Util.null2String(rs.getString("id"));//主账号id
          rsdetail.executeQuery("select id from hrmresource where belongto = ?", account);
          while (rsdetail.next()) {
            String userid = Util.null2String(rsdetail.getString("id"));
            log.info("账号" + account + "==存在次账号==" + userid);
            //获取部门进行比较
            String departmentID = resourceComInfo.getDepartmentID(userid);
            log.info("==次账号部门id==" + departmentID);
            if (deptid == Integer.parseInt(departmentID)) {
              account = userid;
              break;
            }
          }
        } else {
          datas.put("info", "系统查无此人");
          return datas;
        }
      } else {
        //1.验真工号准确性////
        rs.executeQuery("select id from hrmresource where loginid = ?", loginid);
        if (rs.next()) {
          account = Util.null2String(rs.getString("id"));
        } else {
          datas.put("info", "系统查无此人");
          return datas;
        }
      }

      datas.put("account", account);
      log.info("==account==" + account);
      //2.自动创建OA商旅付款流程
      PropBean pb = new PropBean();
      String workflowId;
      String requestName;
      if(isSub){
        workflowId = pb.getPropName("FZJGJSFK_WORKFLOWID");
      }else{
        workflowId = pb.getPropName("SLJSFK_WORKFLOWID");
      }
      Map<String, String> requestMainMap = new HashMap<String, String>();
      String timeTempStr = request.getBeginTime().substring(0, 7);
      String[] tempArr = timeTempStr.split("-");
      if(isSub){
        requestName = "分支机构智能商旅" + tempArr[0] + "年" + tempArr[1] + "月费用月结";
        //分支机构流程为下一节点指定处理人
        int bmbm = getDeptId(request.getDeptCode());
        rs.executeQuery("select kj,kjjl from uf_fzjgfkgwpp  where bm = ?",bmbm);
        while(rs.next()){
          String kj = rs.getString("kj");
          String kjjl = rs.getString("kjjl");
          if(StringUtils.isNotBlank(kj) && StringUtils.isNotBlank(kjjl)){
            requestMainMap.put("ngfgsfyhjsh",kj);
            requestMainMap.put("fgscwjlsh", kjjl);
          }
        }
      }else{
        requestName = "智能商旅" + tempArr[0] + "年" + tempArr[1] + "月费用月结";
      }
      String lcbh = getLcbh(Integer.parseInt(workflowId));
      String ngsj = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
      requestMainMap.put("lcbh", lcbh);
      requestMainMap.put("ngsj", ngsj);
      requestMainMap.put("fkxx", "0");
      requestMainMap.put("ngr",account);
      String bm = getDeptId(request.getDeptCode()) + "";
      requestMainMap.put("szbm", bm);
      //分支机构需要赋值对应的出纳人
      if (isSub) {
        Map<String,String> cnMap = getCNRYInfo(bm);
        String cnry = cnMap.get("cnry");
        String cnrygh = cnMap.get("cnrygh");
        if (StringUtils.isNotBlank(cnry)) {
          requestMainMap.put("cnry", cnry);
        } else {
          log.warn("分支机构商旅结算付款流程创建失败，未配置对应出纳! ngr:" + account + ", bm:" + bm);
          datas.put("info", "分支机构商旅结算付款流程创建失败，未配置对应出纳");
          return datas;
        }
        if(StringUtils.isNotBlank(cnrygh)){
          requestMainMap.put("cnrygh", cnrygh);
        }else{
          log.warn("分支机构商旅结算付款流程创建失败，获取出纳人员工号失败! ngr:" + account + ", bm:" + bm);
          datas.put("info", "分支机构商旅结算付款流程创建失败，获取出纳人员工号失败");
          return datas;
        }
      }
      //分支机构指定人员拟稿时，走指定内部审核
      if(request.getEmpCode().equals("006628@ZZ323305_2703")){
        requestMainMap.put("nbshr","25151");
      }
      Integer requestid = Util.getIntValue(WorkflowCreateUtil
          .workflowCreateByRequestMap(account, workflowId, requestName, IsNextFlow,
              requestMainMap));
      if (requestid > 0) {
        log.info("商旅付款流程编号:" + requestid);
        log.info(String.format("do update requestmark where requestid = %s", requestid));
        rs.executeUpdate("update workflow_requestbase set requestmark = ? where requestid = ?",
            lcbh, requestid);
        request.setRequestId(requestid);
        saveDetailInfo(request);
        datas.put("info", "商旅付款流程自动创建成功");
        datas.put("requestid",requestid);
      } else {
        datas.put("info", "商旅付款流程自动创建失败");
      }
    } catch (Exception e) {
      log.error("商旅付款流程创建或明细信息存储出错!", e);
      datas.put("info", "商旅付款流程创建或明细信息存储出错");
    }
    return datas;
  }

  @Override
  public void saveDetailInfo(TripPaymentRequest request)
      throws Exception {
    RecordSet rs = new RecordSet();
    Integer requestid = request.getRequestId();
    //查询主表名
    String tablename = "formtable_main_";
    String tableSql = "select formid from workflow_base where id = " +
                      "(select workflowid from workflow_requestbase where requestid = " +
                      requestid + ")";
    rs.execute(tableSql);
    if (rs.next()) {
      int formid = Math.abs(Util.getIntValue(rs.getString("formid")));
      tablename = tablename + formid;
    }
    //查询主表id
    int mainId = -1;
    rs.executeQuery(String.format("select id from %s where requestid = ?", tablename), requestid);
    while (rs.next()) {
      mainId = Util.getIntValue(rs.getString("id"));
    }
    Assert.isTrue(mainId > 0, "mainId <= 0 ");
    //更新合同信息
    List<Object> updateHTParams = new ArrayList<>();
    PaymentService paymentServiceImpl = new PaymentServiceImpl();
    //合同名称
    String contractCode = "";
    //合同编码
    String processCode = "";
    ContractRequestParam param = new ContractRequestParam();
    param.setUserCode(request.getEmpCode());
    if(request.getEmpCode().equals("007070@ZZ323429_2703") || request.getEmpCode().equals("006628@ZZ323305_2703")){
      contractCode = "智能商旅服务的补充协议";
      processCode = "合计(2020)26806";
      updateHTParams.add(mainId);
      updateHTParams.add(processCode);
      updateHTParams.add(contractCode);
      rs.executeUpdate(String.format("update %s set htxx = ? where id = ?",tablename),"合计(2020)26806",mainId);
      param.setCode(processCode);
      param.setName(contractCode);
      setContractInfoIntoParam(updateHTParams, paymentServiceImpl, contractCode, processCode,
          param);
      updateHTParams.add(processCode);
    }else if (!("010803".equals(request.getEmpCode())&&"ZZ001".equals(request.getDeptCode()))){
      contractCode = "携程商旅出行服务补充协议";
      processCode = "合计(2020)14579";
      updateHTParams.add(mainId);
      updateHTParams.add(processCode);
      updateHTParams.add(contractCode);
      rs.executeUpdate(String.format("update %s set htxx = ? where id = ?",tablename),"合计(2020)14579",mainId);
      param.setCode(processCode);
      param.setName(contractCode);
      setContractInfoIntoParam(updateHTParams, paymentServiceImpl, contractCode, processCode,
          param);
      updateHTParams.add(processCode);
    }else{
      contractCode = "集中采购转合同审批(商务旅行服务协议）";
      processCode = "合计(2019)18564";
      updateHTParams.add(mainId);
      updateHTParams.add(processCode);
      updateHTParams.add(contractCode);
      //总部流程更新主表
      rs.executeUpdate(String.format("update %s set htxx = ? where id = ?",tablename),"合计(2019)18564",mainId);
      param.setCode(processCode);
      param.setName(contractCode);
      setContractInfoIntoParam(updateHTParams, paymentServiceImpl, contractCode, processCode,
          param);
      updateHTParams.add(processCode);
    }
    //更新分支机构 总部通用的合同明细信息
    rs.executeUpdate(String.format("insert into %s (mainid,htbh,htmc,yfjebhbq," +
                                   "htze,ckhtxx,bqzfje,wfjebhbq,bz) " +
                                   "values(?,?,?,?,?,?,0,0,5)",
        tablename  + "_dt4"),updateHTParams);

    //更新主表支付类型字段
    ExecutorService executorService = Executors.newCachedThreadPool();
    CompletionService<Map<String, String>> cs = new ExecutorCompletionService<>(executorService);
    Callable compareCallable = () -> getCompareInfo(request);

    Callable getDeptInfoCallable = () -> getDeptInfo(request);

    Callable getPaymentDetailInfoCallable = () -> getPaymentDetailInfo(request);

    Callable getAllowanceDetailCallable = () -> getAllowanceDetail(request);
    //构建futureTask任务，控制返回顺序
    FutureTask<Map<String, String>> futureTask1 = new FutureTask<Map<String, String>>(
        compareCallable);
    FutureTask<Map<String, String>> futureTask2 = new FutureTask<Map<String, String>>(
        getDeptInfoCallable);
    FutureTask<Map<String, String>> futureTask3 = new FutureTask<Map<String, String>>(
        getPaymentDetailInfoCallable);
    FutureTask<Map<String, String>> futureTask4 = new FutureTask<Map<String, String>>(
        getAllowanceDetailCallable);
    StopWatch sw = new StopWatch("差旅对账接口调用耗时");
    sw.start("对比信息");
    executorService.submit(futureTask1);
    sw.stop();
    sw.start("账单汇总");
    executorService.submit(futureTask2);
    sw.stop();
    sw.start("账单明细");
    executorService.submit(futureTask3);
    sw.stop();
    sw.start("差补明细");
    executorService.submit(futureTask4);
    sw.stop();
    log.info("差旅对账接口调用耗时汇总" + sw.prettyPrint());
    String compareResult = (futureTask1.get()).get("compareResult");
    String orderSettlementDetailJson = (futureTask3.get()).get("orderSettlementDetailJson");
    String allowanceDetailJson = (futureTask4.get()).get("allowanceDetailJson");
    Map<String, String> temp = futureTask2.get();
    String allowanceSummaryRes = temp.get("allowanceSummaryRes");
    String snapshotInfoRes = temp.get("snapshotInfoRes");

    //保存月结账单对比数据(对比信息)
    saveCompareInfoToDB(compareResult, mainId, tablename);

    //保存部门账单费用汇总(账单汇总)
    savePaymentSummaryPerDeptToDB(allowanceSummaryRes, snapshotInfoRes, mainId, tablename, request);

    //保存机票 火车 酒店 用车 订单订单明细(账单明细)
    savePaymentDetailToDB(orderSettlementDetailJson, mainId, tablename);

    //总部需要写入携程合阿里的费用明细,以及对应的订单明细
    if (("010803".equals(request.getEmpCode())&&"ZZ001".equals(request.getDeptCode()))){
      TripPaymentRequest ctripRequest=new TripPaymentRequest();
      BeanUtils.copyProperties(request,ctripRequest);
      ctripRequest.setPlatformType("CTRIP");
      //携程部门明细汇总
      String ctripSnapshotInfoRes = getSnapshotInfo(ctripRequest).get("snapshotInfoRes");
      saveCostPerDeptAndSupplierToDB(ctripSnapshotInfoRes, mainId, tablename,"dt20");

      TripPaymentRequest alitripRequest=new TripPaymentRequest();
      BeanUtils.copyProperties(request,alitripRequest);
      alitripRequest.setPlatformType("ALITRIP");
      //阿里部门明细汇总
      String alitripSnapshotInfoRes = getSnapshotInfo(alitripRequest).get("snapshotInfoRes");
      saveCostPerDeptAndSupplierToDB(alitripSnapshotInfoRes, mainId, tablename,"dt26");

      //重新设置支付明细
      saveZFMXToDB(allowanceSummaryRes,ctripSnapshotInfoRes,alitripSnapshotInfoRes,mainId,tablename);
    }

    //保存差补明细(差补明细)
    saveAllowanceDetailToDB(allowanceDetailJson, mainId, tablename);

    //K1810012 拆分税金,hto-5468
    splitTaxesSaveToMainDB(mainId, tablename);

    //发起费用预占
    doBudgetCommit(tablename, request.getRequestId());

    //生成会计科目
    updateAccountDetail(requestid, tablename);

  }

  private void setContractInfoIntoParam(List<Object> updateHTParams,
      PaymentService paymentServiceImpl, String contractCode, String processCode,
      ContractRequestParam param) throws Exception {
    //接口获取已付金额 合同金额
    String yfjeRes = paymentServiceImpl.queryContractPaidMoney(contractCode,processCode);
    ContractInfoVo contractInfoVo = paymentServiceImpl.queryContractPagination(param);
    //设置已付金额参数
    if(StringUtils.isNotBlank(yfjeRes)){
      JSONObject yfObject = JSONObject.parseObject(yfjeRes);
      String isSuccess = yfObject.getString("isSuccess");
      //已付接口请求失败
      if(!isSuccess.equalsIgnoreCase("true")){
        updateHTParams.add("0");
      }else{
        updateHTParams.add(yfObject.getString("data"));
      }
    }else{
      updateHTParams.add("0");
    }
    //设置合同金额参数
    if(contractInfoVo == null){
      updateHTParams.add("0");
    }else{
      JSONObject contractObject = (JSONObject) JSONObject.toJSON(contractInfoVo);
      String isSuccess = contractObject.getString("isSuccess");
      //合同接口请求失败
      if(!isSuccess.equalsIgnoreCase("true")){
        updateHTParams.add("0");
      }else{
        if(CollectionUtils.isEmpty(contractObject.getJSONArray("data"))){
          updateHTParams.add("0");
        }else{
          JSONObject contract = (JSONObject) contractObject.getJSONArray("data").get(0);
          String htje = contract.getString("ttl");
          updateHTParams.add(htje);
        }
      }
    }
  }

  private String updateAccountDetail(Integer requestid, String tablename) {
    BTSUpdateAccountDetail ac = new BTSUpdateAccountDetail();
    try {
      RequestInfo ri = new RequestInfo();
      ri.setRequestid(String.valueOf(requestid));
      RequestManager rm = new RequestManager();
      rm.setBilltablename(tablename);
      ri.setRequestManager(rm);
      return ac.execute(ri);
    } catch (Exception e) {
      log.error("商旅结算付款生成会计科目失败");
      return BTSUpdateAccountDetail.FAILURE_AND_CONTINUE;
    }
  }

  private void splitTaxesSaveToMainDB(int mainId, String tableName) {
    log.info("商旅结算付款执行费用分摊逻辑");
    if (!CollectionUtils.isEmpty(budgetItems)) {
      RecordSetTrans rst = new RecordSetTrans();
      rst.setAutoCommit(false);
      try {
        List<BigDecimal> deductionTaxList = new ArrayList<>();
        List<BigDecimal> inputTaxList = new ArrayList<>();

        budgetItems.forEach(row -> {
          Integer sy = (Integer) row.get(7);
          String sj = (String) row.get(4);
          //机票 火车
          if (sy == 0 || sy == 1) {
            deductionTaxList.add(new BigDecimal(sj));
          }
          //用车 酒店 服务费
          if (sy == 2 || sy == 3 || sy == 5) {
            inputTaxList.add(new BigDecimal(sj));
          }
        });
        BigDecimal deductionTax = deductionTaxList.stream().reduce(BigDecimal.ZERO, BigDecimal::add); //计算抵扣进项小计
        BigDecimal inputTax = inputTaxList.stream().reduce(BigDecimal.ZERO, BigDecimal::add); //进项税小计

        log.info(String.format("分摊后数据, deductionTax:%s, inputTax:%s", deductionTax, inputTax));
        rst.executeUpdate("update " + tableName +
                          " set jsdksjxj=?,jxsxj=? where ID=?", deductionTax, inputTax, mainId);
        rst.commit();
      } catch (Exception e) {
        rst.rollback();
        log.error("拆分税金小计异常");
      }

    }


  }


  private void saveCompareInfoToDB(String compareResult, int mainId, String tablename) {
    //获取月结账单对比信息，并更新对应表中数据
    RecordSet rs = new RecordSet();
    Map<String, Object> hasDiff = new HashMap<>();
    Map<String, Object> noDiff = new HashMap<>();
    //存在差异数据时存入差异明细，不存在时存入对比结果
    JSONObject jsonDuiBi = JSONObject.parseObject(compareResult);
    if (jsonDuiBi == null) {
      log.warn("compare info is null!");
      return;
    }
    JSONArray jsonArraymoth = jsonDuiBi.getJSONArray("compareResultModelList");
    if (jsonArraymoth != null) {
      //对比接口返回,该数组实际只有一个元素(仅返回一个月的数据)
      for (int i = 0; i < jsonArraymoth.size(); i++) {
        JSONObject jsonObject = jsonArraymoth.getJSONObject(i);
        String compareMonth = jsonObject.getJSONObject("compareHistoryDetail")
            .getString("compareMonth");
        String comparisonre = jsonObject.getJSONObject("compareHistoryDetail")
            .getString("compareResult");
        if (StringUtils.isNotEmpty(comparisonre)) {
          if ("CORRECT".equals(comparisonre)) {
            //无差异
            if (StringUtils.isNotEmpty(compareMonth)) {
              //对比月份
              noDiff.put("dbyf", compareMonth);
            } else {
              log.warn("compare month in response is empty!");
            }
            noDiff.put("dbjg", "无差异");
          } else {
            String detailJson = jsonObject.getString("orderCompareResultDetails");
            //有差异
            if (StringUtils.isNotEmpty(compareMonth)) {
              //对比月份
              hasDiff.put("dbyf", compareMonth);
            } else {
              log.warn("compare month in response is empty!");
            }
            hasDiff.put("dbjg", detailJson);
          }
        } else {
          log.warn("compare result is empty!");
        }
      }
      if (mainId != -1) {
        //无差异数据，只更新主表，若存在差异数据，则需要同时更新主表与明细表
        if (!CollectionUtils.isEmpty(noDiff)) {
          //update maintable only
          String dbyf = (String) noDiff.get("dbyf");
          String dbjg = (String) noDiff.get("dbjg");
          rs.executeUpdate(String.format("update %s set dbyf = ?,dbjg = ? where id = ?", tablename),
              dbyf, dbjg, mainId);
        }
        //update maintable and detail table together
        if (!CollectionUtils.isEmpty(hasDiff)) {
          String dbyf = (String) hasDiff.get("dbyf");
          String dbjg = (String) hasDiff.get("dbjg");
          rs.executeUpdate(String.format("update %s set dbyf = ?,dbjg = ? where id = ?", tablename),
              dbyf, dbjg, mainId);
          saveMonthlyCompareDetailToDB(hasDiff, mainId, tablename);
        }
      }
    }
  }

  private void saveMonthlyCompareDetailToDB(Map<String, Object> param, int mainId,
      String tablename) {
    RecordSet rs = new RecordSet();
    List<List> updateParams = new ArrayList<>();
    String detailJsonStr = (String) param.get("dbjg");
    JSONArray jsonArray = null;
    if (StringUtils.isNotBlank(detailJsonStr)) {
      jsonArray = JSON.parseArray(detailJsonStr);
    }
    if (jsonArray != null) {
      for (int i = 0; i < jsonArray.size(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        List<Object> list = new ArrayList<>();
        list.add(mainId);
        String ddh = jsonObject.getString("orderId");
        list.add(ddh);
        String ddlx = jsonObject.getString("orderType");
        list.add(ddlx);
        String cylx = jsonObject.getString("orderErrorType");
        list.add(cylx);
        //金额接口返回即为保留2位
        String htmxjeStr = jsonObject.getString("orderAmount");
        list.add(htmxjeStr);
        String xcmxje = jsonObject.getString("batchAmount");
        list.add(xcmxje);
        String glxch = jsonObject.getString("journeyId");
        list.add(glxch);
        String yggh = jsonObject.getString("employeeId");
        list.add(yggh);
        String ygxm = jsonObject.getString("employeeName");
        list.add(ygxm);
        String zffs = jsonObject.getString("payType");
        list.add(zffs);
        int bmbm = getDeptId(jsonObject.getString("empDeptCode"));
        int ygbm = getEmpId(jsonObject.getString("employeeId"));
        list.add(bmbm);
        list.add(ygbm);
        updateParams.add(list);
      }
    }
    rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt13"), mainId);
    rs.executeBatchSql(String.format(
        "insert into %s (mainid,ddh,ddlx,cylx,htmxje,xcmxje,glxch,yggh,ygxm,zffs,bmbm,ygbm" +
        ") values(?,?,?,?,?,?,?,?,?,?,?,?) ", tablename + "_dt13"), updateParams);
  }

  private void savePaymentSummaryPerDeptToDB(String allowanceSummaryRes, String snapshotInfoRes,
      int mainId, String tablename, TripPaymentRequest request) {
    RecordSet rs = new RecordSet();
    List<List> updateParams = new ArrayList<>();
    List<List> bbzfUpdateParams = new ArrayList<>();
    List<List> zfmxUpdateParams = new ArrayList<>();
    Set<String> chaibuDeptSet;
    Set<String> paymentDeptSet = new HashSet<>();
    //处理差补汇总信息，按照部门分组
    Map<String, Object> allowanceSummaryMap = new HashMap<>();
    JSONObject allowanceJson = JSONObject.parseObject(allowanceSummaryRes);
    JSONArray allowanceJsonArray = allowanceJson.getJSONArray("travelAllowanceCollectDetails");
    if (allowanceJsonArray != null) {
      for (int i = 0; i < allowanceJsonArray.size(); i++) {
        JSONObject jsonObject = allowanceJsonArray.getJSONObject(i);
        String deptCode = jsonObject.getString("deptCode");
        // String allowanceAmount = jsonObject.getString("allowanceAmount");
        if (StringUtils.isNotEmpty(deptCode)) {
          allowanceSummaryMap.put(deptCode, jsonObject);
        }
      }
    } else {
      log.warn("get allowance summary failed!");
    }
    JSONObject snapshotInfoJson = JSONObject.parseObject(snapshotInfoRes);
    JSONArray snapshotInfoJsonArray = snapshotInfoJson.getJSONArray("deptOrderResultModels");
    DepartmentComInfo dc = new DepartmentComInfo();
    //存储汇总信息
    String jpze = snapshotInfoJson.getString("flightAmount");
    String hcpze = snapshotInfoJson.getString("trainAmount");
    String jdze = snapshotInfoJson.getString("hotelAmount");
    String ycze = snapshotInfoJson.getString("carAmount");
    String fwfze = snapshotInfoJson.getString("serviceFeeAmount");
    String xcfyze = snapshotInfoJson.getString("totalAmount");
    String cbze = allowanceJson.getString("totalAllowanceAmount");
    List<List> hzUpdateParams = new ArrayList<>();
    List<Object> hzList = new ArrayList<>();
    hzList.add(mainId);
    hzList.add(jpze);
    hzList.add(hcpze);
    hzList.add(jdze);
    hzList.add(ycze);
    hzList.add(fwfze);
    hzList.add(xcfyze);
    hzList.add(cbze);
    hzUpdateParams.add(hzList);
    //录入汇总信息
    rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt14"), mainId);
    rs.executeBatchSql(String.format(
        "insert into %s (mainid,jpze,hcpze,jdze,ycze,fwfze,xcfyze,cbze) values(?,?,?,?,?,?,?,?)",
        tablename + "_dt14"), hzUpdateParams);
    Map<String, Object> getCysParams = new HashMap<>();
    String idPrefix = Util.null2String(new PropBean().getPropName("YSaccountTreeId_yskm"));

    if (snapshotInfoJsonArray != null) {
      for (int i = 0; i < snapshotInfoJsonArray.size(); i++) {
        JSONObject jsonObject = snapshotInfoJsonArray.getJSONObject(i);
        List<Object> list = new ArrayList<>();
        String bm;
        String jp;
        String hcp;
        String jd;
        String yc;
        String fwfhj;
        String xcfyhj;
        String cbTemp;
        //若该部门差补信息为空，则默认为0
        String cb;
        int bmbm;
        String kdksze;
        String tpf;
        BigDecimal bhsje;
        int cys;
        BigDecimal jpje;
        BigDecimal kdkseje;
        BigDecimal temp1;
        BigDecimal temp2;
        BigDecimal temp3;
        BigDecimal temp4;
        BigDecimal cbje;
        BigDecimal cysje;
        paymentDeptSet.add(jsonObject.getString("deptCode"));
        //差补的部门信息中包含该部门信息
        if (allowanceSummaryMap.containsKey(jsonObject.getString("deptCode"))) {
          bm = jsonObject.getString("deptName");
          jp = jsonObject.getString("flightAmount");
          hcp = jsonObject.getString("trainAmount");
          jd = jsonObject.getString("hotelAmount");
          yc = jsonObject.getString("carAmount");
          fwfhj = jsonObject.getString("serviceFeeAmount");
          xcfyhj = jsonObject.getString("totalAmount");
          cbTemp = ((JSONObject) allowanceSummaryMap.get(jsonObject.getString("deptCode")))
              .getString("allowanceAmount");
          //若该部门差补信息为空，则默认为0
          cb = StringUtils.isEmpty(cbTemp) ? "0.00" : cbTemp;
          bmbm = getDeptId(jsonObject.getString("deptCode"));
          kdksze = jsonObject.getString("flightDeductibleTaxAmount");
          tpf = jsonObject.getString("trainCancelFeeAmount");
          //计算不含税金额及超预算
          jpje = new BigDecimal(jp);
          kdkseje = new BigDecimal(kdksze);
          temp1 = new BigDecimal(hcp).subtract(new BigDecimal(tpf));
          temp2 = temp1.divide(new BigDecimal("1.09"), 2, BigDecimal.ROUND_HALF_UP);
          temp3 = new BigDecimal(jd).add(new BigDecimal(yc));
          temp4 = temp3.divide(new BigDecimal("1.06"), 2, BigDecimal.ROUND_HALF_UP);
          cbje = new BigDecimal(cb == null ? "0" : cb);
          //不含税金额=机票 - 可抵扣税额+ (火车-退票费)/1.09+ 火车退票费 + (酒店+用车)/1.06 + 补贴
          bhsje = (jpje.subtract(kdkseje)).add(temp2).add(new BigDecimal(tpf)).add(temp4).add(cbje);
          String bmCode = dc.getDepartmentCode(bmbm + "");
          getCysParams.put("deptNum", bmCode);
          getCysParams.put("deptType", getDeptTypeCode(bmbm + ""));
          getCysParams.put("Bgitem", "8601050301");
          cysje = getBigDecimalCys(getCysParams);
          //超预算标识 0 未超预算 1 超预算 2未处理数据
          cys = getCys(bhsje, cysje);
        } else {
          bm = jsonObject.getString("deptName");
          jp = jsonObject.getString("flightAmount");
          hcp = jsonObject.getString("trainAmount");
          jd = jsonObject.getString("hotelAmount");
          yc = jsonObject.getString("carAmount");
          fwfhj = jsonObject.getString("serviceFeeAmount");
          xcfyhj = jsonObject.getString("totalAmount");
          //差补中不包含该部门，取0
          cb = "0.00";
          bmbm = getDeptId(jsonObject.getString("deptCode"));
          kdksze = jsonObject.getString("flightDeductibleTaxAmount");
          tpf = jsonObject.getString("trainCancelFeeAmount");
          //计算不含税金额及超预算
          jpje = new BigDecimal(jp);
          kdkseje = new BigDecimal(kdksze);
          temp1 = new BigDecimal(hcp).subtract(new BigDecimal(tpf));
          temp2 = temp1.divide(new BigDecimal("1.09"), 2, BigDecimal.ROUND_HALF_UP);
          temp3 = new BigDecimal(jd).add(new BigDecimal(yc));
          temp4 = temp3.divide(new BigDecimal("1.06"), 2, BigDecimal.ROUND_HALF_UP);
          cbje = new BigDecimal(cb == null ? "0" : cb);
          //不含税金额=机票 - 可抵扣税额+ (火车-退票费)/1.09+ 火车退票费 + (酒店+用车)/1.06 + 补贴
          bhsje = (jpje.subtract(kdkseje)).add(temp2).add(new BigDecimal(tpf)).add(temp4).add(cbje);
          String bmCode = dc.getDepartmentCode(bmbm + "");
          getCysParams.put("deptNum", bmCode);
          getCysParams.put("deptType", getDeptTypeCode(bmbm + ""));
          getCysParams.put("Bgitem", "8601050301");
          cysje = getBigDecimalCys(getCysParams);
          //超预算标识 0 未超预算 1 超预算 2未处理数据
          cys = getCys(bhsje, cysje);
        }
        list.add(mainId);
        list.add(bm);
        list.add(jp);
        list.add(hcp);
        list.add(jd);
        list.add(yc);
        list.add(fwfhj);
        list.add(xcfyhj);
        list.add(cb);
        list.add(bmbm);
        list.add(kdksze);
        list.add(tpf);
        list.add(bhsje.toString());
        list.add(cys);
        updateParams.add(list);
        List<Object> bbzfList1 = new ArrayList<>();
        List<Object> bbzfList2 = new ArrayList<>();
        List<Object> bbzfList3 = new ArrayList<>();
        List<Object> bbzfList4 = new ArrayList<>();
        List<Object> bbzfList5 = new ArrayList<>();
        //mainid,fysjcdbm,,yskm,bhsje,sj,jshjje,cys
        //交通费类型使用相同会计科目的预算接口返回
        getCysParams.put("Bgitem", "8601050301");
        cysje = getBigDecimalCys(getCysParams);
        //mainid
        bbzfList1.add(mainId);
        //fysjcdbm
        bbzfList1.add(bmbm);
        //yskm
        bbzfList1.add("8601050301");
        //bhsje  = 合计 - 税金
        BigDecimal bhsje1 = jpje.subtract(kdkseje);
        bbzfList1.add(bhsje1.toString());
        //sj
        bbzfList1.add(kdkseje.toString());
        //jshjje = 不含税金额  + 税金
        bbzfList1.add(bhsje1.add(kdkseje).toString());
        //cys
        bbzfList1.add(getCys(bhsje1, cysje));
        //sy
        bbzfList1.add(0);
        //sl
        bbzfList1.add(10);
        //yskmid
        bbzfList1.add(idPrefix + "_" + "8601050301");

        bbzfList2.add(mainId);
        bbzfList2.add(bmbm);
        bbzfList2.add("8601050301");
        BigDecimal sj2 = temp2.multiply(new BigDecimal("0.09")).setScale(2, BigDecimal.ROUND_HALF_UP);
        //合计 - 税金
        BigDecimal bhsje2 = new BigDecimal(hcp).subtract(sj2);
        bbzfList2.add(bhsje2.toString());
        bbzfList2.add(sj2.toString());
        bbzfList2.add(bhsje2.add(sj2).toString());
        bbzfList2.add(getCys(bhsje2, cysje));
        bbzfList2.add(1);
        bbzfList2.add(10);
        bbzfList2.add(idPrefix + "_" + "8601050301");

        bbzfList3.add(mainId);
        bbzfList3.add(bmbm);
        bbzfList3.add("8601050301");
        BigDecimal sj3 = new BigDecimal(yc)
            .divide(new BigDecimal("1.06"), 2, BigDecimal.ROUND_HALF_UP)
            .multiply(new BigDecimal("0.06")).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal bhsje3 = new BigDecimal(yc).subtract(sj3);
        bbzfList3.add(bhsje3.toString());
        bbzfList3.add(sj3.toString());
        bbzfList3.add(bhsje3.add(sj3).toString());
        bbzfList3.add(getCys(bhsje3, cysje));
        bbzfList3.add(2);
        bbzfList3.add(10);
        bbzfList3.add(idPrefix + "_" + "8601050301");

        getCysParams.put("Bgitem", "8601050303");
        cysje = getBigDecimalCys(getCysParams);
        bbzfList4.add(mainId);
        bbzfList4.add(bmbm);
        bbzfList4.add("8601050303");
        BigDecimal sj4 = new BigDecimal(jd)
            .divide(new BigDecimal("1.06"), 2, BigDecimal.ROUND_HALF_UP)
            .multiply(new BigDecimal("0.06")).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal bhsje4 = new BigDecimal(jd).subtract(sj4);
        bbzfList4.add(bhsje4.toString());
        bbzfList4.add(sj4.toString());
        bbzfList4.add(bhsje4.add(sj4).toString());
        bbzfList4.add(getCys(bhsje4, cysje));
        bbzfList4.add(3);
        bbzfList4.add(10);
        bbzfList4.add(idPrefix + "_" + "8601050303");

        getCysParams.put("Bgitem", "8601050302");
        cysje = getBigDecimalCys(getCysParams);
        bbzfList5.add(mainId);
        bbzfList5.add(bmbm);
        bbzfList5.add("8601050302");
        BigDecimal bhsje5 = cbje;
        bbzfList5.add(cbje.toString());
        BigDecimal sj5 = new BigDecimal("0");
        bbzfList5.add(sj5.toString());
        bbzfList5.add(cbje.add(sj5).toString());
        bbzfList5.add(getCys(bhsje5, cysje));
        bbzfList5.add(4);
        bbzfList5.add(10);
        bbzfList5.add(idPrefix + "_" + "8601050302");
        bbzfUpdateParams.add(bbzfList1);
        bbzfUpdateParams.add(bbzfList2);
        bbzfUpdateParams.add(bbzfList3);
        bbzfUpdateParams.add(bbzfList4);
        bbzfUpdateParams.add(bbzfList5);
      }
      //部门汇总信息中，差补返回的部门多余账单汇总中的部门,则该部门只包含差补信息和部门信息
      chaibuDeptSet = allowanceSummaryMap.keySet();
      chaibuDeptSet.removeAll(paymentDeptSet);
      if (!CollectionUtils.isEmpty(chaibuDeptSet)) {
        for (String deptCode : chaibuDeptSet) {
          List<Object> tempList = new ArrayList<>();
          String bm = ((JSONObject) allowanceSummaryMap.get(deptCode)).getString("deptName");
          String jp = "0.00";
          String hcp = "0.00";
          String jd = "0.00";
          String yc = "0.00";
          String fwfhj = "0.00";
          String xcfyhj = "0.00";
          String cbTemp = ((JSONObject) allowanceSummaryMap.get(deptCode))
              .getString("allowanceAmount");
          //若该部门差补信息为空，则默认为0
          String cb = StringUtils.isEmpty(cbTemp) ? "0.00" : cbTemp;
          int bmbm = getDeptId(
              ((JSONObject) allowanceSummaryMap.get(deptCode)).getString("deptCode"));
          String kdksze = "0.00";
          String tpf = "0.00";
          //超预算标识 0 未超预算 1 超预算 2未处理数据
          String bhsje = "0.00";
          int cys = 0;
          tempList.add(mainId);
          tempList.add(bm);
          tempList.add(jp);
          tempList.add(hcp);
          tempList.add(jd);
          tempList.add(yc);
          tempList.add(fwfhj);
          tempList.add(xcfyhj);
          tempList.add(cb);
          tempList.add(bmbm);
          tempList.add(kdksze);
          tempList.add(tpf);
          tempList.add(bhsje);
          tempList.add(cys);
          updateParams.add(tempList);

          //本币支付模块在差补 部门信息多余 账单部门信息时
          List<Object> bbzfList1 = new ArrayList<>();
          List<Object> bbzfList2 = new ArrayList<>();
          List<Object> bbzfList3 = new ArrayList<>();
          List<Object> bbzfList4 = new ArrayList<>();
          List<Object> bbzfList5 = new ArrayList<>();
          //mainid,fysjcdbm,,yskm,bhsje,sj,jshjje,cys
          //交通费类型使用相同会计科目的预算接口返回
          BigDecimal cysje = BigDecimal.ZERO;
          //mainid
          bbzfList1.add(mainId);
          //fysjcdbm
          bbzfList1.add(bmbm);
          //yskm
          bbzfList1.add("8601050301");
          //bhsje  = 机票-可抵扣税额
          BigDecimal bhsje1 = BigDecimal.ZERO;
          bbzfList1.add(bhsje1.toString());
          //sj
          bbzfList1.add(BigDecimal.ZERO.toString());
          //jshjje = 不含税金额  + 税金
          bbzfList1.add(bhsje1.add(BigDecimal.ZERO).toString());
          //cys
          bbzfList1.add(0);
          //sy
          bbzfList1.add(0);
          //sl
          bbzfList1.add(10);
          //yskmid
          bbzfList1.add(idPrefix + "_" + "8601050301");

          bbzfList2.add(mainId);
          bbzfList2.add(bmbm);
          bbzfList2.add("8601050301");
          BigDecimal bhsje2 = BigDecimal.ZERO;
          bbzfList2.add(bhsje2.toString());
          BigDecimal sj2 = BigDecimal.ZERO;
          bbzfList2.add(sj2.toString());
          bbzfList2.add(bhsje2.add(sj2).toString());
          bbzfList2.add(0);
          bbzfList2.add(1);
          bbzfList2.add(10);
          bbzfList2.add(idPrefix + "_" + "8601050301");

          bbzfList3.add(mainId);
          bbzfList3.add(bmbm);
          bbzfList3.add("8601050301");
          BigDecimal bhsje3 = BigDecimal.ZERO;
          bbzfList3.add(bhsje3.toString());
          BigDecimal sj3 = BigDecimal.ZERO;
          bbzfList3.add(sj3.toString());
          bbzfList3.add(bhsje3.add(sj3).toString());
          bbzfList3.add(0);
          bbzfList3.add(2);
          bbzfList3.add(10);
          bbzfList3.add(idPrefix + "_" + "8601050301");

          bbzfList4.add(mainId);
          bbzfList4.add(bmbm);
          bbzfList4.add("8601050303");
          BigDecimal bhsje4 = BigDecimal.ZERO;
          bbzfList4.add(bhsje4.toString());
          BigDecimal sj4 = BigDecimal.ZERO;
          bbzfList4.add(sj4.toString());
          bbzfList4.add(bhsje4.add(sj4).toString());
          bbzfList4.add(0);
          bbzfList4.add(3);
          bbzfList4.add(10);
          bbzfList4.add(idPrefix + "_" + "8601050303");

          Map<String, Object> tempCysParams = new HashMap<>();
          tempCysParams.put("deptNum", deptCode);
          tempCysParams.put("deptType", getDeptTypeCode(bmbm + ""));
          tempCysParams.put("Bgitem", "8601050302");
          cysje = getBigDecimalCys(tempCysParams);
          bbzfList5.add(mainId);
          bbzfList5.add(bmbm);
          bbzfList5.add("8601050302");
          BigDecimal bhsje5 = new BigDecimal(cb);
          bbzfList5.add(cb);
          BigDecimal sj5 = new BigDecimal("0");
          bbzfList5.add(sj5.toString());
          bbzfList5.add(new BigDecimal(cb).add(sj5).toString());
          bbzfList5.add(getCys(bhsje5, cysje));
          bbzfList5.add(4);
          bbzfList5.add(10);
          bbzfList5.add(idPrefix + "_" + "8601050302");
          bbzfUpdateParams.add(bbzfList1);
          bbzfUpdateParams.add(bbzfList2);
          bbzfUpdateParams.add(bbzfList3);
          bbzfUpdateParams.add(bbzfList4);
          bbzfUpdateParams.add(bbzfList5);
        }
      }


      //分支机构费用不分摊计财部，而是到请求对应部门
      if(!("010803".equals(request.getEmpCode())&&"ZZ001".equals(request.getDeptCode()))){
        String fzCode = request.getDeptCode();
        getCysParams.put("deptNum", fzCode);
        int deptId = getDeptId(fzCode);
        String deptTypeCode = getDeptTypeCode(deptId + "");
        getCysParams.put("deptType", deptTypeCode);
        getCysParams.put("Bgitem", "8601050302");
        BigDecimal cysje;
        cysje = getBigDecimalCys(getCysParams);
        List<Object> fzList = new ArrayList<>();
        fzList.add(mainId);
        fzList.add(deptId);
        fzList.add("8601050302");
        BigDecimal fzsj = new BigDecimal(snapshotInfoJson.getString("serviceFeeAmount"))
            .divide(new BigDecimal("1.06"), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("0.06"))
            .setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal fzbhsje = new BigDecimal(snapshotInfoJson.getString("serviceFeeAmount"))
            .subtract(fzsj);
        fzList.add(fzbhsje.toString());
        fzList.add(fzsj.toString());
        fzList.add(fzbhsje.add(fzsj).toString());
        fzList.add(getCys(fzbhsje, cysje));
        fzList.add(5);
        fzList.add(10);
        fzList.add(idPrefix + "_" + "8601050302");
        bbzfUpdateParams.add(fzList);

      }else{
        //总部流程，费用分摊至计财部
        String jcbCode = dc.getDepartmentCode(16 + "");
        getCysParams.put("deptNum", jcbCode);
        getCysParams.put("deptType", getDeptTypeCode(16 + ""));
        getCysParams.put("Bgitem", "8601050302");
        BigDecimal cysje;
        cysje = getBigDecimalCys(getCysParams);
        List<Object> jcbList1 = new ArrayList<>();
        jcbList1.add(mainId);
        jcbList1.add(16);
        jcbList1.add("8601050302");
        BigDecimal jcbsj = new BigDecimal(snapshotInfoJson.getString("serviceFeeAmount"))
            .divide(new BigDecimal("1.06"), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("0.06"))
            .setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal jcbbhsje = new BigDecimal(snapshotInfoJson.getString("serviceFeeAmount"))
            .subtract(jcbsj);
        jcbList1.add(jcbbhsje.toString());
        jcbList1.add(jcbsj.toString());
        jcbList1.add(jcbbhsje.add(jcbsj).toString());
        jcbList1.add(getCys(jcbbhsje, cysje));
        jcbList1.add(5);
        jcbList1.add(10);
        jcbList1.add(idPrefix + "_" + "8601050302");
        bbzfUpdateParams.add(jcbList1);
      }
      List<Object> zfmxList1 = new ArrayList<>();
      List<Object> zfmxList2 = new ArrayList<>();
      //银行支付金额yxzfje = 四项费用+服务费
      BigDecimal totalFee = new BigDecimal(snapshotInfoJson.getString("flightAmount"))
          .add(new BigDecimal(snapshotInfoJson.getString("trainAmount")))
          .add(new BigDecimal(snapshotInfoJson.getString("hotelAmount")))
          .add(new BigDecimal(snapshotInfoJson.getString("carAmount")));
      BigDecimal totalServiceFee = new BigDecimal(snapshotInfoJson.getString("serviceFeeAmount"));
      zfmxList1.add(mainId);
      //skdw
      zfmxList1.add("上海携程宏睿国际旅行社有限公司");
      //yxzh
      zfmxList1.add("1001014819000001515");
      //ss
      zfmxList1.add("31,3101");
      zfmxList1.add(totalFee.add(totalServiceFee).toString());
      //现金支付金额xjzfje
      zfmxList1.add(new BigDecimal("0.00").toString());
      //开户行 khx
      zfmxList1.add("102290001487");
      //开户行名称 khxmc
      zfmxList1.add(getKHXMC("102290001487"));
      //dfkje
      zfmxList1.add(new BigDecimal("0.00").toString());
      //zpzfje
      zfmxList1.add(new BigDecimal("0.00").toString());
      zfmxUpdateParams.add(zfmxList1);

      zfmxList2.add(mainId);
      zfmxList2.add("发放员工差旅补贴");
      zfmxList2.add(null);
      zfmxList2.add(null);
      zfmxList2.add(new BigDecimal("0.00").toString());
      BigDecimal totalAllowance = new BigDecimal(allowanceJson.getString("totalAllowanceAmount"));
      zfmxList2.add(totalAllowance.toString());
      zfmxList2.add("");
      zfmxList2.add("");
      zfmxList2.add(new BigDecimal("0.00").toString());
      zfmxList2.add(new BigDecimal("0.00").toString());
      zfmxUpdateParams.add(zfmxList2);
      //支付明细信息
      rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt11"),
          mainId);
      rs.executeBatchSql(String.format(
          "insert into %s (mainid,skdw,yxzh,ss,yxzfje,xjzfje,khx,khxmc,dfkje,zpzfje) values(?,?,?,?,?,?,?,?,?,?)",
          tablename + "_dt11"), zfmxUpdateParams);
      //本币支付信息
      rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt8"),
          mainId);
      rs.executeBatchSql(String.format(
          "insert into %s (mainid,fysjcdbm,yskm,bhsje,sj,jshjje,cys,sy,sl,yskmid) values(?,?,?,?,?,?,?,?,?,?)",
          tablename + "_dt8"), bbzfUpdateParams);

      //保存是由信息
      budgetItems = bbzfUpdateParams;

      //部门汇总信息
      rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt14"),
          mainId);
      rs.executeBatchSql(String.format(
          "insert into %s (mainid,bm,jp,hcp,jd,yc,fwfhj,xcfyhj,cb,bmbm,kdksze,tpf,bhsje,cys) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
          tablename + "_dt14"), updateParams);
    } else {
      log.warn("get cost summary per dept failed!");
    }

  }



  private void saveCostPerDeptAndSupplierToDB(String snapshotInfoRes,
      int mainId, String tablename,String detailTable) {
    RecordSet rs = new RecordSet();
    List<List> updateParams = new ArrayList<>();
    JSONObject snapshotInfoJson = JSONObject.parseObject(snapshotInfoRes);
    JSONArray snapshotInfoJsonArray = snapshotInfoJson.getJSONArray("deptOrderResultModels");
    //存储汇总信息
    String jpze = snapshotInfoJson.getString("flightAmount");
    String hcpze = snapshotInfoJson.getString("trainAmount");
    String jdze = snapshotInfoJson.getString("hotelAmount");
    String ycze = snapshotInfoJson.getString("carAmount");
    String fwfze = snapshotInfoJson.getString("serviceFeeAmount");
    String xcfyze = snapshotInfoJson.getString("totalAmount");
    List<List> hzUpdateParams = new ArrayList<>();
    List<Object> hzList = new ArrayList<>();
    hzList.add(mainId);
    hzList.add(jpze);
    hzList.add(hcpze);
    hzList.add(jdze);
    hzList.add(ycze);
    hzList.add(fwfze);
    hzList.add(xcfyze);
    hzUpdateParams.add(hzList);
    //录入汇总信息
    rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_"+detailTable), mainId);
    rs.executeBatchSql(String.format(
        "insert into %s (mainid,jpze,hcpze,jdze,ycze,fwfze,xcfyze) values(?,?,?,?,?,?,?)",
        tablename + "_"+detailTable), hzUpdateParams);

    if (snapshotInfoJsonArray != null) {
      for (int i = 0; i < snapshotInfoJsonArray.size(); i++) {
        JSONObject jsonObject = snapshotInfoJsonArray.getJSONObject(i);
        List<Object> list = new ArrayList<>();
        String bm= jsonObject.getString("deptName");
        String jp= jsonObject.getString("flightAmount");
        String hcp= jsonObject.getString("trainAmount");
        String jd= jsonObject.getString("hotelAmount");
        String yc= jsonObject.getString("carAmount");
        String fwfhj= jsonObject.getString("serviceFeeAmount");
        String xcfyhj= jsonObject.getString("totalAmount");
        int bmbm = getDeptId(jsonObject.getString("deptCode"));
        list.add(mainId);
        list.add(bm);
        list.add(jp);
        list.add(hcp);
        list.add(jd);
        list.add(yc);
        list.add(fwfhj);
        list.add(xcfyhj);
        list.add(bmbm);
        updateParams.add(list);
      }
      //部门汇总信息
      rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_"+detailTable),
          mainId);
      rs.executeBatchSql(String.format(
          "insert into %s (mainid,bm,jp,hcp,jd,yc,fwfhj,xcfyhj,bmbm) values(?,?,?,?,?,?,?,?,?)",
          tablename + "_"+detailTable), updateParams);
    } else {
      log.warn("get cost summary per dept failed!");
    }

  }

  private void saveZFMXToDB(String allowanceRes,String ctripSnapshotInfoRes,String alitripSnapshotInfoRes,
      int mainId, String tablename) {
    RecordSet rs = new RecordSet();
    List<List> zfmxUpdateParams = new ArrayList<>();
    if (StringUtils.isNotBlank(ctripSnapshotInfoRes)){
      JSONObject ctripSnapshotInfoJson = JSONObject.parseObject(ctripSnapshotInfoRes);
      List<Object> ctripzfmxList = new ArrayList<>();
      //银行支付金额yxzfje = 四项费用+服务费
      BigDecimal ctripTotalFee = new BigDecimal(ctripSnapshotInfoJson.getString("flightAmount"))
          .add(new BigDecimal(ctripSnapshotInfoJson.getString("trainAmount")))
          .add(new BigDecimal(ctripSnapshotInfoJson.getString("hotelAmount")))
          .add(new BigDecimal(ctripSnapshotInfoJson.getString("carAmount")));
      BigDecimal ctripTotalServiceFee = new BigDecimal(ctripSnapshotInfoJson.getString("serviceFeeAmount"));
      ctripzfmxList.add(mainId);
      //skdw
      ctripzfmxList.add("上海携程宏睿国际旅行社有限公司");
      //yxzh
      ctripzfmxList.add("1001014819000001515");
      //ss
      ctripzfmxList.add("31,3101");
      ctripzfmxList.add(ctripTotalFee.add(ctripTotalServiceFee).toString());
      //现金支付金额xjzfje
      ctripzfmxList.add(new BigDecimal("0.00").toString());
      //开户行 khx
      ctripzfmxList.add("102290001487");
      //开户行名称 khxmc
      ctripzfmxList.add(getKHXMC("102290001487"));
      //dfkje
      ctripzfmxList.add(new BigDecimal("0.00").toString());
      //zpzfje
      ctripzfmxList.add(new BigDecimal("0.00").toString());
      zfmxUpdateParams.add(ctripzfmxList);
    }

    if (StringUtils.isNotBlank(alitripSnapshotInfoRes)){
      JSONObject alitripSnapshotInfoJson = JSONObject.parseObject(alitripSnapshotInfoRes);
      List<Object> alitripzfmxList = new ArrayList<>();
      //银行支付金额yxzfje = 四项费用+服务费
      BigDecimal alitripTotalFee = new BigDecimal(alitripSnapshotInfoJson.getString("flightAmount"))
          .add(new BigDecimal(alitripSnapshotInfoJson.getString("trainAmount")))
          .add(new BigDecimal(alitripSnapshotInfoJson.getString("hotelAmount")))
          .add(new BigDecimal(alitripSnapshotInfoJson.getString("carAmount")));
      BigDecimal alitripTotalServiceFee = new BigDecimal(alitripSnapshotInfoJson.getString("serviceFeeAmount"));
      alitripzfmxList.add(mainId);
      //skdw
      alitripzfmxList.add("浙江阿里商旅旅行社有限公司");
      //yxzh
      alitripzfmxList.add("571910226010502002360302");
      //ss
      alitripzfmxList.add("33,3302");
      alitripzfmxList.add(alitripTotalFee.add(alitripTotalServiceFee).toString());
      //现金支付金额xjzfje
      alitripzfmxList.add(new BigDecimal("0.00").toString());
      //开户行 khx
      alitripzfmxList.add("308331012079");
      //开户行名称 khxmc
      alitripzfmxList.add(getKHXMC("308331012079"));
      //dfkje
      alitripzfmxList.add(new BigDecimal("0.00").toString());
      //zpzfje
      alitripzfmxList.add(new BigDecimal("0.00").toString());
      zfmxUpdateParams.add(alitripzfmxList);
    }

    if (StringUtils.isNotBlank(allowanceRes)){
      JSONObject allowanceJson = JSONObject.parseObject(allowanceRes);
      List<Object> cbzfmxList = new ArrayList<>();
      cbzfmxList.add(mainId);
      cbzfmxList.add("发放员工差旅补贴");
      cbzfmxList.add(null);
      cbzfmxList.add(null);
      cbzfmxList.add(new BigDecimal("0.00").toString());
      BigDecimal totalAllowance = new BigDecimal(allowanceJson.getString("totalAllowanceAmount"));
      cbzfmxList.add(totalAllowance.toString());
      cbzfmxList.add("");
      cbzfmxList.add("");
      cbzfmxList.add(new BigDecimal("0.00").toString());
      cbzfmxList.add(new BigDecimal("0.00").toString());
      zfmxUpdateParams.add(cbzfmxList);
    }

    //支付明细信息
    rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt11"),
        mainId);
    rs.executeBatchSql(String.format(
        "insert into %s (mainid,skdw,yxzh,ss,yxzfje,xjzfje,khx,khxmc,dfkje,zpzfje) values(?,?,?,?,?,?,?,?,?,?)",
        tablename + "_dt11"), zfmxUpdateParams);

  }

  private String getKHXMC(String khx){
    String name = "";
    RecordSet rs = new RecordSet();
    String sql = String.format("select yxmc from %s where lxh = ?", "uf_khh");
    rs.executeQuery(sql, khx);
    while (rs.next()) {
      name = rs.getString("yxmc");
      break;
    }
    return name;
  }

  private Map<String,String> getCNRYInfo(String bm) {
    Map<String,String> result = new HashMap<>();
    String name = "";
    String workCode = "";
    RecordSet rs = new RecordSet();
    String sql = String.format("select cn from %s where bm = ?", "uf_fzjgfkgwpp");
    rs.executeQuery(sql, bm);
    while (rs.next()) {
      name = rs.getString("cn");
      break;
    }
    //出纳可能为多个
    String[] cnArray = name.split(",");
    String getGhSql = String.format("select workcode from %s where id = ?","hrmresource");
    for(int i = 0; i < cnArray.length; i++){
      String tempworkCode = "";
      rs.executeQuery(getGhSql, cnArray[i]);
      while (rs.next()) {
        tempworkCode = rs.getString("workcode");
        break;
      }
      if(cnArray.length == 1){
        workCode = tempworkCode;
        break;
      }else{
        if(i != cnArray.length -1){
          workCode = workCode + tempworkCode + ",";
        }else{
          workCode = workCode + tempworkCode;
        }
      }
    }
    result.put("cnry",name);
    result.put("cnrygh",workCode);
    return result;
  }

  private BigDecimal getBigDecimalCys(Map<String, Object> getCysParams) {
    HTUtil htUtil = new HTUtil();
    //默认返回为null
    BigDecimal cysje = null;
    String cysRes = htUtil.getBudget(getCysParams);
    JSONObject budgetObject = null;
    if (StringUtils.isNotBlank(cysRes)) {
      budgetObject = JSONObject.parseObject(cysRes);
    }
    if (budgetObject != null) {
      JSONObject levelObject = null;
      if (budgetObject.getJSONObject("BudgetData") != null) {
        levelObject = budgetObject.getJSONObject("BudgetData").getJSONObject("Level");
      }
      if (levelObject != null && StringUtils.isNotBlank(levelObject.getString("FBgbanlance"))) {
        try {
          cysje = new BigDecimal(levelObject.getString("FBgbanlance"));
        } catch (Exception e) {
          log.warn("FBgbanlance can not convert to number. FBgbanlance:"+levelObject.getString("FBgbanlance"));
        }
      }
    }
    return cysje;
  }

  private int getCys(BigDecimal bhsje, BigDecimal cysje) {
    int cys;
    //超预算接口返回空返回为维护
    if (cysje==null) {
      return 2;
    }
    int cysFlag = bhsje.compareTo(cysje);
    //小于等于预算金额，则不超预算
    if (cysFlag <= 0) {
      cys = 0;
    } else {
      cys = 1;
    }
    return cys;
  }

  private void savePaymentDetailToDB(String orderSettlementDetailJson, int mainId,
      String tablename) {
    JSONObject orderSettlementDetailObject = JSON.parseObject(orderSettlementDetailJson);
    JSONArray jsonArrayfilgh = orderSettlementDetailObject
        .getJSONArray("flightOrderSettlementModels");
    JSONArray jsonArraytrain = orderSettlementDetailObject
        .getJSONArray("trainOrderSettlementModels");
    JSONArray jsonArrayhotel = orderSettlementDetailObject
        .getJSONArray("hotelOrderSettlementModels");
    JSONArray jsonArraycar = orderSettlementDetailObject.getJSONArray("carOrderSettlementModels");
    //机票明细
    if (jsonArrayfilgh == null || jsonArrayfilgh.size() <= 0) {
      log.warn("flight order settlement info is empty!");
    } else {
      log.info("start to save flight order settlement info to DB");
      savePlaneOrderSettlementDetailToDB(jsonArrayfilgh, mainId,tablename);
      log.info("save flight order settlement info to DB end");
    }
    //火车明细
    if (jsonArraytrain == null || jsonArraytrain.size() <= 0) {
      log.warn("train order settlement info is empty!");
    } else {
      log.info("start to save flight order settlement info to DB");
      saveTrainOrderSettlementDetailToDB(jsonArraytrain, mainId,tablename);
      log.info("save flight order settlement info to DB end");
    }
    //打车明细
    if (jsonArraycar == null || jsonArraycar.size() <= 0) {
      log.warn("car order settlement info is empty!");
    } else {
      log.info("start to save car order settlement info to DB");
      saveCarOrderSettlementDetailToDB(jsonArraycar, mainId,tablename);
      log.info("save car order settlement info to DB end");
    }
    //酒店明细
    if (jsonArrayhotel == null || jsonArrayhotel.size() <= 0) {
      log.warn("hotel order settlement info is empty!");
    } else {
      log.info("start to save car order settlement info to DB");
      saveHotelOrderSettlementDetailToDB(jsonArrayhotel, mainId,tablename);
      log.info("save car order settlement info to DB end");
    }

  }

  private void savePlaneOrderSettlementDetailToDB(JSONArray jsonArrayFlight, int mainId,
      String tablename) {
    RecordSet rs = new RecordSet();
    List<List> updateParams = new ArrayList<>();
    for (int i = 0; i < jsonArrayFlight.size(); i++) {
      List<Object> list = new ArrayList<>();
      JSONObject jsonObjectFlight = jsonArrayFlight.getJSONObject(i);
      String fycdbm = jsonObjectFlight.getString("empDeptCode");
      String yggh = jsonObjectFlight.getString("employeeId");
      String cjr = jsonObjectFlight.getString("employeeName");
      String ccsqbh = jsonObjectFlight.getString("journeyId");
      String cjjj = jsonObjectFlight.getString("price");
      String ry = jsonObjectFlight.getString("oilFee");
      String pmje = jsonObjectFlight.getString("ticketPrice");
      String tpf = jsonObjectFlight.getString("refundFee");
      String gqf = jsonObjectFlight.getString("rebookQueryFee");
      String fwf = jsonObjectFlight.getString("serviceFeeSum");
      String kdkse = jsonObjectFlight.getString("deductibleTax");
      String bkdkse = jsonObjectFlight.getString("nonDeductibleTax");
      String spf = jsonObjectFlight.getString("sendTicketFee");
      String bxf = jsonObjectFlight.getString("insuranceFee");
      String gqcj = jsonObjectFlight.getString("priceDifferential");
      String hj = jsonObjectFlight.getString("amountSum");
      String cfsj = jsonObjectFlight.getString("takeOffTime");
      //去掉时间字符串的后4位.000,存在部分数据缺少时间字段值，避免NPE
      cfsj = getProperTimeFormat(cfsj);
      String cfcs = jsonObjectFlight.getString("departureCityName");
      String cfjc = jsonObjectFlight.getString("departurePortName");
      String ddsj = jsonObjectFlight.getString("arrivalTime");
      ddsj = getProperTimeFormat(ddsj);
      String ddcs = jsonObjectFlight.getString("arrivalCityName");
      String ddjc = jsonObjectFlight.getString("arrivalPortName");
      String hbh = jsonObjectFlight.getString("flight");
      String fxsc = jsonObjectFlight.getString("flightTime");
      String ddh = jsonObjectFlight.getString("orderId");
      String ddlx = jsonObjectFlight.getString("orderDetailType");
      String zkl = jsonObjectFlight.getString("priceRate");
      String djhbjg = jsonObjectFlight.getString("lowPrice");
      String wxdjhbyy = jsonObjectFlight.getString("lowPriceReason");
      int bmbm = getDeptId(jsonObjectFlight.getString("empDeptCode"));
      int ygbm = getEmpId(jsonObjectFlight.getString("employeeId"));
      String slptly = getPlatformName(jsonObjectFlight.getString("platformType"));
      list.add(mainId);
      list.add(fycdbm);
      list.add(yggh);
      list.add(cjr);
      list.add(ccsqbh);
      list.add(cjjj);
      list.add(ry);
      list.add(pmje);
      list.add(tpf);
      list.add(gqf);
      list.add(fwf);
      list.add(kdkse);
      list.add(bkdkse);
      list.add(spf);
      list.add(bxf);
      list.add(gqcj);
      list.add(hj);
      list.add(cfsj);
      list.add(cfcs);
      list.add(cfjc);
      list.add(ddsj);
      list.add(ddcs);
      list.add(ddjc);
      list.add(hbh);
      list.add(fxsc);
      list.add(ddh);
      list.add(ddlx);
      list.add(zkl);
      list.add(djhbjg);
      list.add(wxdjhbyy);
      list.add(bmbm);
      list.add(ygbm);
      list.add(slptly);
      updateParams.add(list);
    }
    rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt15"), mainId);
    rs.executeBatchSql(String.format("insert into %s (mainid,fycdbm,yggh,cjr,ccsqbh,cjjj,ry,pmje," +
                                     "tpf,gqf,fwf,kdkse,bkdkse,spf,bxf,gqcj,hj,cfsj,cfcs,cfjc,ddsj,ddcs,ddjc,hbh,fxsc," +
                                     "ddh,ddlx,zkl,djhbjg,wxdjhbyy,bmbm,ygbm,slptly) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
        tablename + "_dt15"), updateParams);
  }

  private void saveTrainOrderSettlementDetailToDB(JSONArray jsonArrayTrain, int mainId,
      String tablename) {
    RecordSet rs = new RecordSet();
    List<List> updateParams = new ArrayList<>();
    for (int i = 0; i < jsonArrayTrain.size(); i++) {
      List<Object> list = new ArrayList<>();
      JSONObject jsonObjecTrain = jsonArrayTrain.getJSONObject(i);
      String fycdbm = jsonObjecTrain.getString("empDeptCode");
      String yggh = jsonObjecTrain.getString("employeeId");
      String ccr = jsonObjecTrain.getString("employeeName");
      String ccsqbh = jsonObjecTrain.getString("journeyId");
      String pmje = jsonObjecTrain.getString("ticketPrice");
      String fwf = jsonObjecTrain.getString("serviceFee");
      String hhzfwfje = jsonObjecTrain.getString("amountSum");
      String tpfy = jsonObjecTrain.getString("cancelFee");
      String hj = jsonObjecTrain.getString("amountSum");
      String cfsj = jsonObjecTrain.getString("departureDate");
      cfsj = getProperTimeFormat(cfsj);
      String cfcs = jsonObjecTrain.getString("departureCityName");
      String cfcz = jsonObjecTrain.getString("departureStationName");
      String ddsj = jsonObjecTrain.getString("arrivalDate");
      ddsj = getProperTimeFormat(ddsj);
      String ddcs = jsonObjecTrain.getString("arrivalCityName");
      String ddcz = jsonObjecTrain.getString("arrivalStationName");
      String cc = jsonObjecTrain.getString("trainName");
      String xb = jsonObjecTrain.getString("seatTypeName");
      String ddh = jsonObjecTrain.getString("orderId");
      String ddlx = getOrderStatusName(jsonObjecTrain.getString("detailType"));
      int bmbm = getDeptId(jsonObjecTrain.getString("empDeptCode"));
      int ygbm = getEmpId(jsonObjecTrain.getString("employeeId"));
      String slptly = getPlatformName(jsonObjecTrain.getString("platformType"));
      list.add(mainId);
      list.add(fycdbm);
      list.add(yggh);
      list.add(ccr);
      list.add(ccsqbh);
      list.add(pmje);
      list.add(fwf);
      list.add(hhzfwfje);
      list.add(tpfy);
      list.add(hj);
      list.add(cfsj);
      list.add(cfcs);
      list.add(cfcz);
      list.add(ddsj);
      list.add(ddcs);
      list.add(ddcz);
      list.add(cc);
      list.add(xb);
      list.add(ddh);
      list.add(ddlx);
      list.add(bmbm);
      list.add(ygbm);
      list.add(slptly);
      updateParams.add(list);
    }
    rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt16"), mainId);
    rs.executeBatchSql(String.format("insert into %s (mainid,fycdbm,yggh,ccr,ccsqbh,pmje,fwf," +
                                     "hhzfwfje,tpfy,hj,cfsj,cfcs,cfcz,ddsj,ddcs,ddcz,cc,xb,ddh,ddlx,bmbm,ygbm,slptly)" +
                                     " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
        tablename + "_dt16"), updateParams);
  }

  private void saveCarOrderSettlementDetailToDB(JSONArray jsonArrayCar, int mainId,
      String tablename) {
    RecordSet rs = new RecordSet();
    List<List> updateParams = new ArrayList<>();
    for (int i = 0; i < jsonArrayCar.size(); i++) {
      List<Object> list = new ArrayList<>();
      JSONObject jsonObjectCar = jsonArrayCar.getJSONObject(i);
      String fycdbm = jsonObjectCar.getString("empDeptCode");
      String yggh = jsonObjectCar.getString("employeeId");
      String ccr = jsonObjectCar.getString("employeeName");
      String ccsqbh = jsonObjectCar.getString("journeyId");
      String jj = jsonObjectCar.getString("ticketPrice");
      String fwf = jsonObjectCar.getString("serviceFee");
      String jsse = jsonObjectCar.getString("carAddTaxAmount");
      String hj = jsonObjectCar.getString("amountSum");
      String cfsj = jsonObjectCar.getString("serviceBeginTime");
      cfsj = getProperTimeFormat(cfsj);
      String ddsj = jsonObjectCar.getString("serviceEndTime");
      ddsj = getProperTimeFormat(ddsj);
      String cfcs = jsonObjectCar.getString("departureCityName");
      String ddcs = jsonObjectCar.getString("arrivalCityName");
      String cfdz = jsonObjectCar.getString("departureAddressDetail");
      String dddz = jsonObjectCar.getString("arrivalAddressDetail");
      String jl = jsonObjectCar.getString("actualDistance");
      String sc = jsonObjectCar.getString("actualTime");
      String ddh = jsonObjectCar.getString("orderId");
      String ddzt = getOrderStatusName(jsonObjectCar.getString("detailType"));
      String jcfymx = jsonObjectCar.getString("carBasicFeeDetail");
      String zzfy = jsonObjectCar.getString("carValueAddFee");
      String wyj = jsonObjectCar.getString("penaltyFee");
      String kdfy = jsonObjectCar.getString("expressFee");
      int bmbm = getDeptId(jsonObjectCar.getString("empDeptCode"));
      int ygbm = getEmpId(jsonObjectCar.getString("employeeId"));
      String slptly = getPlatformName(jsonObjectCar.getString("platformType"));
      list.add(mainId);
      list.add(fycdbm);
      list.add(yggh);
      list.add(ccr);
      list.add(ccsqbh);
      list.add(jj);
      list.add(fwf);
      list.add(jsse);
      list.add(hj);
      list.add(cfsj);
      list.add(ddsj);
      list.add(cfcs);
      list.add(ddcs);
      list.add(cfdz);
      list.add(dddz);
      list.add(jl);
      list.add(sc);
      list.add(ddh);
      list.add(ddzt);
      list.add(jcfymx);
      list.add(zzfy);
      list.add(wyj);
      list.add(kdfy);
      list.add(bmbm);
      list.add(ygbm);
      list.add(slptly);
      updateParams.add(list);
    }
    rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt18"), mainId);
    rs.executeBatchSql(String.format("insert into %s (mainid,fycdbm,yggh,ccr,ccsqbh,jj,fwf,jsse," +
                                     "hj,cfsj,ddsj,cfcs,ddcs,cfdz,dddz,jl,sc,ddh,ddzt,jcfymx,zzfy,wyj," +
                                     "kdfy,bmbm,ygbm,slptly) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
        tablename + "_dt18"), updateParams);

  }

  private void saveHotelOrderSettlementDetailToDB(JSONArray jsonArrayHotel, int mainId,
      String tablename) {
    RecordSet rs = new RecordSet();
    List<List> updateParams = new ArrayList<>();
    for (int i = 0; i < jsonArrayHotel.size(); i++) {
      List<Object> list = new ArrayList<>();
      JSONObject jsonObjectHotel = jsonArrayHotel.getJSONObject(i);
      String fycdbm = jsonObjectHotel.getString("empDeptCode");
      String yggh = jsonObjectHotel.getString("employeeId");
      String rzr = jsonObjectHotel.getString("clientName");
      String ccsqbh = jsonObjectHotel.getString("journeyId");
      String zszje = jsonObjectHotel.getString("amountSum");
      String dj = jsonObjectHotel.getString("price");
      String jys = jsonObjectHotel.getString("quantity");
      String sfkzp = jsonObjectHotel.getString("isHasSpecialInvoice");
      String kzpsxf = jsonObjectHotel.getString("extraCharge");
      String fwf = jsonObjectHotel.getString("servicefee");
      String hj = jsonObjectHotel.getString("amountSum");
      String fjm = jsonObjectHotel.getString("roomQuantity");
      String rzsj = jsonObjectHotel.getString("startTime");
      rzsj = getProperTimeFormat(rzsj);
      String ldsj = jsonObjectHotel.getString("endTime");
      ldsj = getProperTimeFormat(ldsj);
      String cs = jsonObjectHotel.getString("cityName");
      String jdm = jsonObjectHotel.getString("hotelName");
      String ddh = jsonObjectHotel.getString("orderId");
      int bmbm = getDeptId(jsonObjectHotel.getString("empDeptCode"));
      int ygbm = getEmpId(jsonObjectHotel.getString("employeeId"));
      String slptly = getPlatformName(jsonObjectHotel.getString("platformType"));
      list.add(mainId);
      list.add(fycdbm);
      list.add(yggh);
      list.add(rzr);
      list.add(ccsqbh);
      list.add(zszje);
      list.add(dj);
      list.add(jys);
      list.add(sfkzp);
      list.add(kzpsxf);
      list.add(fwf);
      list.add(hj);
      list.add(fjm);
      list.add(rzsj);
      list.add(ldsj);
      list.add(cs);
      list.add(jdm);
      list.add(ddh);
      list.add(bmbm);
      list.add(ygbm);
      list.add(slptly);
      updateParams.add(list);
    }
    rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt17"), mainId);
    rs.executeBatchSql(String.format(
        "insert into %s (mainid,fycdbm,yggh,rzr," + "ccsqbh,zszje,dj,jys,sfkzp,kzpsxf,fwf,hj,fjm," +
        "rzsj,ldsj,cs,jdm,ddh,bmbm,ygbm,slptly) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
        tablename + "_dt17"), updateParams);
  }

  private void saveAllowanceDetailToDB(String allowanceDetailJson, int mainId, String tablename) {
    RecordSet rs = new RecordSet();
    JSONObject allowanceDetailObject = JSONObject.parseObject(allowanceDetailJson);
    JSONArray allowanceFetailJsonArray = allowanceDetailObject
        .getJSONArray("travelAllowanceDetailModels");
    if (allowanceFetailJsonArray == null || allowanceFetailJsonArray.size() <= 0) {
      log.info("allowance detail info is empty!");
    } else {
      // log.info("allowance detail info is:" + JSON.toJSONString(allowanceFetailJsonArray));
      List<List> updateParams = new ArrayList<>();
      for (int i = 0; i < allowanceFetailJsonArray.size(); i++) {
        List<Object> list = new ArrayList<>();
        JSONObject jsonObject = allowanceFetailJsonArray.getJSONObject(i);
        String cbje = jsonObject.getString("realAllowance");
        String gh = jsonObject.getString("empCode");
        String xm = jsonObject.getString("empName");
        String ccrbm = jsonObject.getString("empDeptName");
        String lcbh = jsonObject.getString("workFlowNum");
        String lcbt = jsonObject.getString("workFlowSubject");
        String khx = jsonObject.getString("bankName");
        String kh = jsonObject.getString("cardNo");
        int bmbm = getDeptId(jsonObject.getString("empDeptCode"));
        int ygbm = getEmpId(jsonObject.getString("empCode"));
        list.add(mainId);
        list.add(cbje);
        list.add(gh);
        list.add(xm);
        list.add(ccrbm);
        list.add(lcbh);
        list.add(lcbt);
        list.add(khx);
        list.add(kh);
        list.add(bmbm);
        list.add(ygbm);
        updateParams.add(list);
      }
      rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt19"),
          mainId);
      rs.executeBatchSql(String.format(
          "insert into %s (mainid,cbje,gh,xm,ccrbm,lcbh,lcbt,khx,kh,bmbm,ygbm)" +
          " values (?,?,?,?,?,?,?,?,?,?,?)", tablename + "_dt19"), updateParams);
    }
  }

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

  /**
   * 根据部门编号获取泛微部门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 = "select depttypecode from hrmdepartmentdefined where deptid=?";
    RecordSet rs = new RecordSet();
    rs.executeQuery(sql, deptId);
    while (rs.next()) {
      code = rs.getString("depttypecode");
      break;
    }
    return code;
  }

  private String getProperTimeFormat(String stringOrigin) {
    if (StringUtils.isBlank(stringOrigin) || StringUtils.isEmpty(stringOrigin)) {
      return stringOrigin;
    } else {
      return stringOrigin = stringOrigin.substring(0, stringOrigin.length() - 4);
    }
  }

  private String getLcbh(int workFlowId) {
    int formModeId = PayUtil.getFormModeIdByCubeName("uf_fklcbh");
    StringBuilder mark = new StringBuilder(); //流程编码
    RecordSet rs = new RecordSet();
    String sql = "select WORKFLOWNAME,UNNUMBER from workflow_base where ID=?";
    rs.executeQuery(sql, workFlowId);
    String name = "";
    if (rs.next()) {
      name = rs.getString("WORKFLOWNAME");
    }
    String unNumber = PayUtil.getUnNumberByWorkFlowId(workFlowId);
    String modeUuid = "";
    LocalDateTime now = LocalDateTime.now();
    String yM = now.format(DateTimeFormatter.ofPattern("yyyyMM"));

    rs.executeQuery(
        "select id,lsh,MODEUUID from uf_fklcbh where ny = '" + yM + "' and LCLX='" + unNumber +
        "'");
    if (rs.next()) {
      //更新
      int num = Util.getIntValue(rs.getString("lsh")) + 1;
      int id = Util.getIntValue(rs.getString("id"));
      modeUuid = Util.null2String(rs.getString("MODEUUID"));
      String updateSql = "update uf_fklcbh set lsh=? where id=?";
      rs.executeUpdate(updateSql, num, id);
      mark = new StringBuilder(num + "");
      while (mark.length() < 6) {
        mark.insert(0, "0");
      }
      mark = new StringBuilder(name + now.format(DateTimeFormatter.ofPattern("yyyyMM")) + mark);
    } else {
      String userId = Util.null2String("");
      String userType = Util.null2String("0");
      String createDate = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
      String createTime = now.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
      //插入
      String insertSql = "insert into uf_fklcbh" +
                         "(FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME,MODEUUID,LSH,NY,LCLX) \n" +
                         "values(?,?,?,?,?,?,?,?,?)";
      String uuid = UUID.randomUUID().toString();
      modeUuid = uuid;
      rs.executeUpdate(insertSql, formModeId, userId, userType, createDate, createTime, uuid, "1",
          yM, unNumber);
      mark = new StringBuilder(name + now.format(DateTimeFormatter.ofPattern("yyyyMM")) + "000001");
    }

    //权限重构
    int dataId = PayUtil.getDataIdByUUID(modeUuid);
    ModeRightInfo modeRightInfo = new ModeRightInfo();
    modeRightInfo.editModeDataShare(1, formModeId, dataId);
    return mark.toString();
  }

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

  private String getPlatformName(String platform) {
    String name = "";
    if (StringUtils.isNotBlank(platform)) {
      if ("ctrip".equalsIgnoreCase(platform)){
        name="携程";
      }
      if ("alitrip".equalsIgnoreCase(platform)){
        name="阿里";
      }
    }
    return name;
  }

  private String getOrderStatusName(String orderStatus) {
    String name = "";
    if (StringUtils.isNotBlank(orderStatus)) {
      if ("o".equalsIgnoreCase(orderStatus)){
        name="出票";
      }
      if ("a".equalsIgnoreCase(orderStatus)){
        name="改签";
      }
      if ("r".equalsIgnoreCase(orderStatus)){
        name="退票";
      }
    }
    return name;
  }

  private void doBudgetCommit(String tableName, int requestId) {
    PaymentWorkflowInvoke paymentWorkflowInvoke = new PaymentWorkflowInvoke();
    paymentWorkflowInvoke.setBillStatus("3");
    RequestInfo requestInfo = new RequestInfo();
    requestInfo.setRequestid(requestId + "");
    RequestManager requestManager = new RequestManager();
    requestManager.setBilltablename(tableName);
    requestInfo.setRequestManager(requestManager);
    paymentWorkflowInvoke.execute(requestInfo);
  }

  //调用对比接口
  private Map<String, String> getCompareInfo(TripPaymentRequest request) {
    Map<String, String> result = new HashMap<>();
    HTUtil htUtil = new HTUtil();
    Map<String, Object> monthlyCompareParams = new HashMap<>();
    monthlyCompareParams.put("beginTime", request.getBeginTime());
    monthlyCompareParams.put("endTime", request.getEndTime());
    monthlyCompareParams.put("realBatchNoList", request.getRealBatchNoList());
    monthlyCompareParams.put("ngr", request.getEmpCode().contains("@")?request.getEmpCode().substring(0,request.getEmpCode().indexOf("@")):request.getEmpCode());
    String compareResult = htUtil.getCompareResults(monthlyCompareParams);
    result.put("compareResult", compareResult);
    return result;
  }

  //调用差补汇总和部门汇总
  private Map<String, String> getDeptInfo(TripPaymentRequest request) {
    Map<String, String> result = new HashMap<>();
    HTUtil htUtil = new HTUtil();

    Map<String, Object> getAllowanceInfoParams = new HashMap<>();

    //先查询差补汇总信息
    getAllowanceInfoParams.put("beginTime", request.getBeginTime());
    getAllowanceInfoParams.put("endTime", request.getEndTime());
    getAllowanceInfoParams.put("payType", "MONTHLY");
    getAllowanceInfoParams.put("accountIdList", Collections.singletonList(request.getAccountId()));
    getAllowanceInfoParams.put("ngr", request.getEmpCode().contains("@")?request.getEmpCode().substring(0,request.getEmpCode().indexOf("@")):request.getEmpCode());
    String allowanceSummaryRes = htUtil
        .getTravelAllowanceCollectInformation(getAllowanceInfoParams);
    Map<String, Object> getSnapshotInfoParams = new HashMap<>();
    getSnapshotInfoParams.put("beginTime", request.getBeginTime());
    getSnapshotInfoParams.put("endTime", request.getEndTime());
    getSnapshotInfoParams.put("payType", "MONTHLY");
    getSnapshotInfoParams.put("realBatchNoList", request.getRealBatchNoList());
    getSnapshotInfoParams.put("ngr", request.getEmpCode().contains("@")?request.getEmpCode().substring(0,request.getEmpCode().indexOf("@")):request.getEmpCode());
    String snapshotInfoRes = htUtil.getOrderSnapshotInfo(getSnapshotInfoParams);
    result.put("allowanceSummaryRes", allowanceSummaryRes);
    result.put("snapshotInfoRes", snapshotInfoRes);
    return result;
  }

  private Map<String, String> getSnapshotInfo(TripPaymentRequest request) {
    Map<String, String> result = new HashMap<>();
    HTUtil htUtil = new HTUtil();
    Map<String, Object> getSnapshotInfoParams = new HashMap<>();
    getSnapshotInfoParams.put("beginTime", request.getBeginTime());
    getSnapshotInfoParams.put("endTime", request.getEndTime());
    getSnapshotInfoParams.put("payType", "MONTHLY");
    getSnapshotInfoParams.put("realBatchNoList", request.getRealBatchNoList());
    getSnapshotInfoParams.put("ngr", request.getEmpCode().contains("@")?request.getEmpCode().substring(0,request.getEmpCode().indexOf("@")):request.getEmpCode());
    getSnapshotInfoParams.put("platformType", request.getPlatformType());
    String snapshotInfoRes = htUtil.getOrderSnapshotInfo(getSnapshotInfoParams);
    result.put("snapshotInfoRes", snapshotInfoRes);
    return result;
  }

  private Map<String, String> getPaymentDetailInfo(TripPaymentRequest request) {
    Map<String, String> result = new HashMap<>();
    HTUtil htUtil = new HTUtil();
    Map<String, Object> getSnapshotDetailInfoParams = new HashMap<>();
    getSnapshotDetailInfoParams.put("beginTime", request.getBeginTime());
    getSnapshotDetailInfoParams.put("endTime", request.getEndTime());
    getSnapshotDetailInfoParams.put("payType","MONTHLY");
    getSnapshotDetailInfoParams
        .put("realBatchNoList", request.getRealBatchNoList());
    getSnapshotDetailInfoParams.put("ngr", request.getEmpCode().contains("@")?request.getEmpCode().substring(0,request.getEmpCode().indexOf("@")):request.getEmpCode());
    String orderSettlementDetailJson = htUtil
        .queryOrderSnapshotDetails(getSnapshotDetailInfoParams);
    result.put("orderSettlementDetailJson", orderSettlementDetailJson);
    return result;
  }

  private Map<String, String> getAllowanceDetail(TripPaymentRequest request) {
    Map<String, String> result = new HashMap<>();
    HTUtil htUtil = new HTUtil();
    Map<String, Object> getAllowanceDetailParams = new HashMap<>();
    getAllowanceDetailParams.put("beginTime", request.getBeginTime());
    getAllowanceDetailParams.put("endTime", request.getEndTime());
    getAllowanceDetailParams.put("payType", "MONTHLY");
    getAllowanceDetailParams.put("accountIdList", Collections.singletonList(request.getAccountId()));
    getAllowanceDetailParams.put("ngr", request.getEmpCode().contains("@")?request.getEmpCode().substring(0,request.getEmpCode().indexOf("@")):request.getEmpCode());
    String allowanceDetailJson = htUtil.getAllowanceCollectDetail(getAllowanceDetailParams);
    result.put("allowanceDetailJson", allowanceDetailJson);
    return result;
  }

  //本地debug时，修改HTutil中接口url，以及获取token的url
  public static void main(String[] args) throws Exception {
    GCONST.setRootPath("");
    GCONST.setServerName("ecology");
    TripPaymentRequest request=new TripPaymentRequest();
    request.setBeginTime("2020-10-01T00:00:00");
    request.setEndTime("2020-10-31T23:59:59.999999999");
    request.setAccountId("378074");
    request.setRealBatchNoList(Lists.newArrayList("htsc_378074_20201001","htsc_dingd391290d34082fd3bc961a6cb783455b_20201001"));
    request.setDeptCode("ZZ001");
    request.setEmpCode("010803");
    PaymentWorkflowServiceImpl paymentWorkflowService = new PaymentWorkflowServiceImpl();
    paymentWorkflowService.createBusinessTravelWorkflow(request);
    // PaymentService paymentService = new PaymentServiceImpl();
    // String contractCode = "集中采购转合同审批(商务旅行服务协议）";
    // String processCode = "合计(2019)18564";
    // ContractRequestParam param = new ContractRequestParam();
    // param.setUserCode("010803");
    // String yfje = paymentService.queryContractPaidMoney(contractCode,processCode);
    // ContractInfoVo contractInfoVo = paymentService.queryContractPagination(param);
    // System.out.println("已付金额"  + yfje);
    // System.out.println("合同金额" + JSON.toJSONString(contractInfoVo));
    System.out.println("1111");
  }

  @Override
  public Map<String, Object> getLevelDept(String deptid) {
    Map<String, Object> datas = new HashMap<>();
    try {
      RecordSet rs = new RecordSet();
      BaseBean bb = new BaseBean();
      DepartmentComInfo departmentComInfo = new DepartmentComInfo();
      String departmentName = departmentComInfo.getDepartmentName(deptid);
      rs.executeQuery("select supdepid from hrmdepartment where id = ? and tlevel = 4",deptid);
      if (rs.next() && ! "682".equals(deptid)) {//总部二级部门存在一级部门,默认费用承担部门为一级部 除报价融资部682
        String supdepid = Util.null2String(rs.getString("supdepid"));
        deptid = supdepid;
        departmentName = departmentComInfo.getDepartmentname(supdepid);
      }
      datas.put("deptid",deptid);
      datas.put("departmentName",departmentName);
      //bb.infoLog("info",JSONObject.toJSONString(datas));

    }catch (Exception e){
      e.printStackTrace();
    }
    return datas;
  }
}
