package com.engine.htsc.mall.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.htsc.mall.pojo.MallConfirmVo;
import com.engine.htsc.mall.pojo.MallExoenseConfirmationRequest;
import com.engine.htsc.mall.service.MallExpenseConfirmationService;
import com.engine.htsc.payment.enums.Sequences;
import com.engine.htsc.payment.service.SettlePaymentFlowService;
import com.engine.htsc.payment.service.impl.SettlePaymentFlowServiceImpl;
import com.engine.htsc.payment.util.CoWfUtil;
import com.engine.htsc.payment.util.WorkflowCreateUtil;
import com.engine.htsc.payment.web.SettlePaymentFlowAction;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

/**
 * 商城订单费用确认流程
 */
public class MallExpenseConfirmationServiceImpl extends Service implements
    MallExpenseConfirmationService {
  
  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 static final String TABLE_FLOW_BASE = "workflow_requestbase";
  
  @Override
  public Map<String, Object> createMallExpenseConfirmationWorkflow(
      MallExoenseConfirmationRequest request) {
    Map<String, Object> datas = new HashMap<>();

    try {
      RecordSet rs = new RecordSet();
      String loginid = request.getEmpCode();
      String mobile = "";
      String account = "";
      rs.executeQuery("select id,mobile from hrmresource where loginid = ?", loginid);
      if (rs.next()) {
        //员工对应泛微ID
        account = Util.null2String(rs.getString("id"));
        mobile = Util.null2String(rs.getString("mobile"));
      } else {
        datas.put("info", "系统查无此人");
        return datas;
      }
      datas.put("account", account);
      log.info("create expense confirmation workflow ,account :" + account);
      String workflowId;
      String requestName;
      Map<String, String> requestMainMap = new HashMap<String, String>();
      String timeTempStr = request.getDate();
      String[] tempArr = timeTempStr.split("-");
      requestName = "采购商城" + tempArr[0] + "年" + tempArr[1] + "月费用确认";
      PropBean pb = new PropBean();
      workflowId = pb.getPropName("SCFYQR_WORKFLOWID");
      String unNumber = pb.getPropName("SCFYQR_UNNUMBER");
      String lcbh = CoWfUtil.getRequestMarkByUnNumber(unNumber, Sequences.NET_REI_WORKFLOW_SEQ_ZB);
      String ngsj = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
      SettlePaymentFlowService settlePaymentFlowService = ServiceUtil.getService(SettlePaymentFlowServiceImpl.class);
      requestMainMap.put("lcbh", lcbh);
      requestMainMap.put("ngsj", ngsj);
      requestMainMap.put("fkxx", "0");
      requestMainMap.put("ngr", account);
      requestMainMap.put("jjcd","0");
      //获取审批链下一节点处理人员方法，入参 ：流程类型， 组织编码
      String ngr = settlePaymentFlowService.getSplNgr(request.getFlowType(), request.getOrgCode());
      requestMainMap.put("ysgly", ngr);
      requestMainMap.put("lxfs",mobile);
      requestMainMap.put("szbm", getSzbmByUserId(account));
      requestMainMap.put("szjg", getSzjgByUserId(account));
      if ("zb".equals(request.getFlowType())){
        requestMainMap.put("scglysh", ngr);//总部下一节点为商城管理员审核 现为郭逸凡
      }else {
        requestMainMap.put("fgscwjlsh",ngr);//分支为各分公司财务经理
      }
      Integer requestid = Util.getIntValue(WorkflowCreateUtil
          .workflowCreateByRequestMap(account, workflowId, requestName, IsNextFlow,
              requestMainMap));
      if (requestid > 0) {
        log.info("采购商城费用确认编号:" + requestid);
        request.setRequestId(requestid);
        saveOrderInfo(request,lcbh,datas);
        //审批链
        log.info("start to save spl for mall expense confirmation");

        HashMap<String,String> reqMap = settlePaymentFlowService.getSplParam(requestid + "");
        reqMap.put("requestid",requestid + "");
        log.info("save spl input params :" + JSON.toJSONString(reqMap));
        settlePaymentFlowService.saveSubCompanySpl(reqMap);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return datas;
  }
  
  
  public void saveOrderInfo(MallExoenseConfirmationRequest request,String lcbh,Map<String,Object> datas) {
    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"));
    }
    //更新流程类型: zb 总部 ,fzjg 分支机构
    String updateFlowTypeSql = String.format("update %s set fyly = ? where id = ?",tablename);
    //更新流程编号信息
    String updateFlowNumSql = String.format("update %s set requestmark = ? where requestid = ?",TABLE_FLOW_BASE);
    rs.executeUpdate(updateFlowTypeSql,request.getFlowType(),mainId);
    rs.executeUpdate(updateFlowNumSql,lcbh,request.getRequestId());
    //获取token,拉取数据
    HTUtil htUtil = new HTUtil();
    String token = htUtil.getToken(request.getEmpCode());
    String statisticsRes = getStatistics(request, token);
    //返回查询到的订单号和费用确认流程编号，用于xp维护支付状态
    MallConfirmVo mallConfirmVo = buildMallConfirmVo(statisticsRes,lcbh);
    datas.put("datas",mallConfirmVo);
    saveStatisticsToDB(statisticsRes, tablename, mainId);
    //查询，保存全部明细信息
    JSONArray array = ((JSONObject) JSON.parse(statisticsRes)).getJSONObject("data").getJSONArray("mallGetStatisticsVos");
    List<String> deptCodes = new ArrayList<>();
    if(!CollectionUtils.isEmpty(array)){
      for (int i = 0; i < array.size(); i++){
        JSONObject orderObject = (JSONObject) array.get(i);
        String deptCode = orderObject.getString("deptCode");
        deptCodes.add(deptCode);
      }
    }
    if(!CollectionUtils.isEmpty(deptCodes)){
      //清理mainid对应多余旧数据
      rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt4"),
          mainId);
      for(String deptCode : deptCodes){
        String detailRes = getDetails(request, token, deptCode);
        saveDetailToDB(detailRes, tablename, mainId);
      }
    }
    //获取保存对比信息
      String compareRes = getCompareInfo(request, token);
      saveCompareInfoToDB(compareRes, tablename, mainId);


  }
  
  public String getStatistics(MallExoenseConfirmationRequest request, String token) {
    String result = "";
    if (Objects.isNull(request)) {
      log.warn("get mall order statistics input parmas null!");
      return result;
    }
    Map<String, Object> params = new HashMap<>();
    params.put("date", request.getDate());
    params.put("orgCode", request.getOrgCode());
    params.put("mtrTypeCodes", request.getMtrTypeCodes());
    Map<String, String> headers = getHeader(token);
    String reqStr = JSON.toJSONString(params);
    String url = Util.null2String(new PropBean().getPropName("query_mall_order_statistics"));
    log.info(String.format("query mall order statistics input params" + reqStr));
    HTUtil htUtil = new HTUtil();
    String res = Util.null2String(htUtil.httpPostRaw(url, reqStr, headers, null));
    if ("1".equals(Util.null2String(new PropBean().getPropName("show.debug.log")))) {
      log.info("query mall order statistics response：" + res);
    }
    if (StringUtils.isNotEmpty(res)) {
      result = res;
    } else {
      log.info("query mall order statistics response null!");
    }
    return result;
  }
  
  public String getDetails(MallExoenseConfirmationRequest request, String token, String deptCode) {
    String result = "";
    if (Objects.isNull(request)) {
      log.warn("get mall order details input parmas null!");
      return result;
    }
    Map<String, Object> params = new HashMap<>();
    params.put("deptCode", deptCode);
    params.put("date", request.getDate());
    params.put("orderStatus", request.getOrderStatus());
    Map<String, String> headers = getHeader(token);
    String reqStr = JSON.toJSONString(params);
    String url = Util.null2String(new PropBean().getPropName("query_mall_order_detail"));
    log.info(String.format("query mall order detail input params" + reqStr));
    HTUtil htUtil = new HTUtil();
    String res = Util.null2String(htUtil.httpPostRaw(url, reqStr, headers, null));
    if ("1".equals(Util.null2String(new PropBean().getPropName("show.debug.log")))) {
      log.info("query mall order detail response：" + res);
    }
    if (StringUtils.isNotEmpty(res)) {
      result = res;
    } else {
      log.info("query mall order detail response null!");
    }
    return result;
  }
  
  public String getCompareInfo(MallExoenseConfirmationRequest request, String token){
    String result = "";
    if (Objects.isNull(request)) {
      log.warn("input parmas null!");
      return result;
    }
    Map<String, Object> params = new HashMap<>();
    params.put("orderTime", request.getDate());
    params.put("orgCode", request.getOrgCode());
    Map<String, String> headers = getHeader(token);
    String reqStr = JSON.toJSONString(params);
    String url = Util.null2String(new PropBean().getPropName("query_mall_order_compare_info"));
    log.info(String.format("query mall order statistics input params", reqStr));
    HTUtil htUtil = new HTUtil();
    String res = Util.null2String(htUtil.httpPostRaw(url, reqStr, headers, null));
    if ("1".equals(Util.null2String(new PropBean().getPropName("show.debug.log")))) {
      log.info("query mall order compare info response：" + res);
    }
    if (StringUtils.isNotEmpty(res)) {
      result = res;
    } else {
      log.info("query mall order compare info response null!");
    }
    return result;
  }
  
  private Map<String, String> getHeader(String token) {
    Map<String, String> headers = new HashMap<>();
    headers.put("JTXT-AUTH-TOKEN", token);
    headers.put("JTXT-AUTH-TYPE", "USER");
    return headers;
  }
  
  public void saveStatisticsToDB(String statisticsRes, String tablename, int mainId) {
    RecordSet rs = new RecordSet();
    List<List> updateParams = new ArrayList<>();
    List<List> updateDt5Params = new ArrayList<>();
    JSONArray array = ((JSONObject) JSON.parse(statisticsRes)).getJSONObject("data").getJSONArray("mallGetStatisticsVos");
    //合计金额与不含税合计金额
    String hj = ((JSONObject) JSON.parse(statisticsRes)).getJSONObject("data").getString("amount");
    String bhshj = ((JSONObject) JSON.parse(statisticsRes)).getJSONObject("data").getString("noTaxAmount");
    String sj = new BigDecimal(hj).subtract(new BigDecimal(bhshj)).toString();
    //维护总计金额
    String hjSql = String.format("update %s set hj = ?,bhsje = ?,sj = ? where id = ?",tablename);
    rs.executeUpdate(hjSql,hj,bhshj,sj,mainId);
    if (CollectionUtils.isEmpty(array)) {
      log.warn("get mall order statistics failed!,mainid:" + mainId);
    }
    for (int i = 0; i < array.size(); i++) {
      List<Object> list = new ArrayList<>();
      JSONObject orderObject = (JSONObject) array.get(i);
      list.add(mainId);
      //部门金额
      String amount = orderObject.getString("amount");
      list.add(amount);
      //部门不含税金额
      String noTaxDeptAmount = orderObject.getString("noTaxAmount");
      String deptTax = new BigDecimal(amount).subtract(new BigDecimal(noTaxDeptAmount)).toString();
      list.add(noTaxDeptAmount);
      list.add(deptTax);
      //部门编号
      String deptCode = orderObject.getString("deptCode");
      list.add(deptCode);
      String deptName = orderObject.getString("deptName");
      list.add(deptName);
      //泛微部门编码
      int bmbm = getbmbm(orderObject.getString("deptCode"));
      list.add(bmbm);
      //11-24增加分管领导录入
      list.add(getFgldByBmbm(bmbm));
      JSONArray statsticsArray = orderObject.getJSONArray("statstics");
      List<JSONObject> temList = new ArrayList<>();
      for (int j = 0; j < statsticsArray.size(); j++) {
        JSONObject statsticsObject = (JSONObject) statsticsArray.get(j);
        temList.add(statsticsObject);
        JSONArray channelArray = statsticsObject.getJSONArray("channelList");
        for (int k = 0; k < channelArray.size(); k++) {
          JSONObject channelObject = (JSONObject) channelArray.get(k);
          List<Object> dt5List = new ArrayList<>();
          dt5List.add(mainId);
          dt5List.add(deptCode);
          dt5List.add(statsticsObject.getString("mtrTypeId"));
          String channelAmount = channelObject.getString("amount");
          String channelNoTaxAmount = channelObject.getString("noTaxAmount");
          String channeltax = new BigDecimal(channelAmount).subtract(new BigDecimal(channelNoTaxAmount)).toString();
          dt5List.add(channelAmount);
          //供应商不含税金额
          dt5List.add(channelNoTaxAmount);
          dt5List.add(channeltax);
          dt5List.add(channelObject.getString("code"));
          dt5List.add(channelObject.getString("name"));
          updateDt5Params.add(dt5List);
        }
      }
      //办公品
      List<JSONObject> bgOptional = temList.stream()
          .filter(item -> item.getString("mtrTypeId").equals("C1018681"))
          .collect(Collectors.toList());
      if (!CollectionUtils.isEmpty(bgOptional)) {
        String bgAmount = bgOptional.get(0).getString("amount");
        String bgNoTaxAmount = bgOptional.get(0).getString("noTaxAmount");
        String bgTax = new BigDecimal(bgAmount).subtract(new BigDecimal(bgNoTaxAmount)).toString();
        list.add(bgAmount);
        list.add(bgNoTaxAmount);
        list.add(bgTax);
      } else {
        list.add("0");
        list.add("0");
        list.add("0");
      }
      list.add("C1018681");
      list.add("办公用品");
      //耗材
      List<JSONObject> hcOptional = temList.stream()
          .filter(item -> item.getString("mtrTypeId").equals("C1018682"))
          .collect(Collectors.toList());
      if (!CollectionUtils.isEmpty(hcOptional)) {
        String hcAmount = hcOptional.get(0).getString("amount");
        String hcNoTaxAmount = hcOptional.get(0).getString("noTaxAmount");
        String hcTax = new BigDecimal(hcAmount).subtract(new BigDecimal(hcNoTaxAmount)).toString();
        list.add(hcAmount);
        list.add(hcNoTaxAmount);
        list.add(hcTax);
      } else {
        list.add("0");
        list.add("0");
        list.add("0");
      }
      list.add("C1018682");
      list.add("耗材");
      //IT标准硬件
      List<JSONObject> itOptioncal = temList.stream()
          .filter(item -> item.getString("mtrTypeId").equals("ITBZYJ"))
          .collect(Collectors.toList());
      if (!CollectionUtils.isEmpty(itOptioncal)) {
        String itAmount = itOptioncal.get(0).getString("amount");
        String itNoTaxAmount = itOptioncal.get(0).getString("noTaxAmount");
        String itTax = new BigDecimal(itAmount).subtract(new BigDecimal(itNoTaxAmount)).toString();
        list.add(itAmount);
        list.add(itNoTaxAmount);
        list.add(itTax);
      } else {
        list.add("0");
        list.add("0");
        list.add("0");
      }
      list.add("ITBZYJ");
      list.add("IT标准硬件");
      //宣传品
      List<JSONObject> xcpOptional = temList.stream()
          .filter(item -> item.getString("mtrTypeId").equals("C1018684"))
          .collect(Collectors.toList());
      if (!CollectionUtils.isEmpty(xcpOptional)) {
        String xcpAmount = xcpOptional.get(0).getString("amount");
        String xcpNoTaxAmount = xcpOptional.get(0).getString("noTaxAmount");
        String xcpTax = new BigDecimal(xcpAmount).subtract(new BigDecimal(xcpNoTaxAmount)).toString();
        list.add(xcpAmount);
        list.add(xcpNoTaxAmount);
        list.add(xcpTax);
      } else {
        list.add("0");
        list.add("0");
        list.add("0");
      }
      list.add("C1018684");
      list.add("宣传品");
      //电子设备
      List<JSONObject> dzsbOptional = temList.stream()
          .filter(item -> item.getString("mtrTypeId").equals("C1018683"))
          .collect(Collectors.toList());
      if (!CollectionUtils.isEmpty(dzsbOptional)) {
        String dzsbAmount = dzsbOptional.get(0).getString("amount");
        String dzsbNoTaxAmount = dzsbOptional.get(0).getString("noTaxAmount");
        String dzsbTax = new BigDecimal(dzsbAmount).subtract(new BigDecimal(dzsbNoTaxAmount)).toString();
        list.add(dzsbAmount);
        list.add(dzsbNoTaxAmount);
        list.add(dzsbTax);
      } else {
        list.add("0");
        list.add("0");
        list.add("0");
      }
      list.add("C1018683");
      list.add("电子设备");
      updateParams.add(list);
    }
    if (!CollectionUtils.isEmpty(updateParams)) {
      rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt3"),
          mainId);
      rs.executeBatchSql(String
          .format("insert into %s (mainid,dzje,hjbhsje,hjsj,htbmbm,htbm,bm,fgldgh,bgypfyamount,bgypfybhsje,bgypfysj," +
                  "bgypfymtrtypeid,bgypfymtrtypename,hcfyamount,hcfybhsje,hcfysj,hcfymtrtypeid," +
                  "hcfymtrtypename,itbzyjfyamount,itbzyjfybhsje,itbzyjfysj,itbzyjfymtrtypeid,itbzyjfymtrtypename," +
                  "xcpfyamount,xcpfybhsje,xcpfysj,xcpfymtrtypeid,xcpfymtrtypename,dzsbfyamount,dzsbfybhsje,dzsbfysj," +
                  "dzsbfymtrtypeid,dzsbfymtrtypename) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
              tablename + "_dt3"), updateParams);
    }
    if (!CollectionUtils.isEmpty(updateDt5Params)) {
      rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt5"),
          mainId);

      log.info("updateDt5Params ele: " + updateDt5Params);
      rs.executeBatchSql(String
          .format("insert into %s (mainid,deptcode,mtrtypeid,amount,bhsje,sj,cod,name) values(?,?,?,?,?,?,?,?)",
              tablename + "_dt5"), updateDt5Params);
    }
  }
  
  private void saveDetailToDB(String detailRes, String tablename, int mainid) {
    List<List> updateParams = new ArrayList<>();
    JSONArray jsonArray = ((JSONObject) JSON.parse(detailRes)).getJSONArray("data");
    for (int i = 0; i < jsonArray.size(); i++) {
      JSONObject object = (JSONObject) jsonArray.get(i);
      String billNo = object.getString("billNo");
      String channelCode = object.getString("channelCode");
      String channelName = object.getString("channelName");
      String deptCode = object.getString("deptCode");
      String deptName = object.getString("deptName");
      String effectiveOrderTime = object.getString("effectiveOrderTime");
      String empName = object.getString("empName");
      String empNo = object.getString("empNo");
      JSONArray detailArray = object.getJSONArray("mallOrderDetailsVos");
      for (int j = 0; j < detailArray.size(); j++) {
        List<Object> list = new ArrayList<>();
        JSONObject detailObject = (JSONObject) detailArray.get(j);
        String amount = detailObject.getString("amount");
        String brandName = detailObject.getString("brandName");
        String chanGoodsId = detailObject.getString("chanGoodsId");
        String cmmdtyName = detailObject.getString("cmmdtyName");
        String goodsNum = detailObject.getString("goodsNum");
        String mtrTypeCode = detailObject.getString("mtrTypeCode");
        String mtrTypeName = detailObject.getString("mtrTypeName");
        String mtrValue = detailObject.getString("mtrValue");
        String mtrValueCode = detailObject.getString("mtrValueCode");
        String noTaxAmount = detailObject.getString("noTaxAmount");
        String noTaxPrice = detailObject.getString("noTaxPrice");
        String saleUnit = detailObject.getString("saleUnit");
        String taxRate = detailObject.getString("taxRate");
        String unitPrice = detailObject.getString("unitPrice");
        String mtrModel = detailObject.getString("model");
        String contractCode = detailObject.getString("contractCode");
        String budgetItemCode = detailObject.getString("budgetItemCode");
        String demandNo = detailObject.getString("demandNo");
        String orderPersonNo = detailObject.getString("orderPersonNo");
        String orderPerson = detailObject.getString("orderPerson");
        list.add(mainid);
        list.add(billNo);
        list.add(mtrTypeCode);
        list.add(mtrTypeName);
        list.add(mtrValueCode);
        list.add(mtrValue);
        list.add(chanGoodsId);
        list.add(cmmdtyName);
        list.add(brandName);
        list.add(mtrModel);
        //channelCode
        list.add(channelCode);
        //channelName
        list.add(channelName);
        //effectiveOrderTime
        list.add(effectiveOrderTime);
        //empNo
        list.add(empNo);
        //spdw
        list.add(saleUnit);
        //bhsdj
        list.add(noTaxPrice);
        //shuil
        list.add(taxRate);
        //hsdj
        list.add(unitPrice);
        //bmcode
        list.add(deptCode);
        //sl
        list.add(goodsNum);
        //hszj
        list.add(amount);
        //bhszj
        list.add(noTaxAmount);
        //dwmc
        list.add(deptName);
        //dwbh
        list.add(deptCode);
        //xdrxm
        list.add(empName);
        list.add(contractCode);
        list.add(budgetItemCode);
        list.add(demandNo);
        list.add(orderPersonNo);
        list.add(orderPerson);
        updateParams.add(list);
      }
      
    }
    RecordSet rs = new RecordSet();
    if (!CollectionUtils.isEmpty(updateParams)) {

      rs.executeBatchSql(String.format(
          "insert into %s (mainid,billno,mtrtypecode,mtrtypename,mtrvaluecode,mtrvalue," +
          "changoodsid,cmmdtyname,brandname,model,channelcode,channelname,effectiveordertime," +
          "empno,spdw,bhsdj,shuil,hsdj,bmcode,sl,hszj,bhszj,dwmc,dwbh,xdrxm,contractcode,budgetitemcode" +
          ",grcgxqh,grcgxqyggh,grcgxqygxm) " +
          "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
          tablename + "_dt4"), updateParams);
    }
  }
  
  private void saveCompareInfoToDB(String compareRes, String tablename, int mainid) {
    JSONObject dataObject = JSON.parseObject(compareRes).getJSONObject("data");
    List<List> updateParams = new ArrayList<>();
    if (Objects.nonNull(dataObject)) {
      String hasDiff = dataObject.getString("hasDiff");
      if("NO".equals(hasDiff)){
      
      }else{
        JSONArray diffArray = dataObject.getJSONArray("diffInfo");
        if(!CollectionUtils.isEmpty(diffArray)){
          for(int j =0; j < diffArray.size(); j ++){
            List<Object> list = new ArrayList<>();
            JSONObject diffObject = (JSONObject)diffArray.get(j);
            //差异类型
            String diffType = diffObject.getString("diffType");
            //本地金额
            String htDetailAmount = diffObject.getString("htDetailAmount");
            //供应商金额
            String channelDetailAmount = diffObject.getString("channelDetailAmount");
            //供应商名称
            String channelName = diffObject.getString("channelName");
            //申请单编号
            String biiNo = diffObject.getString("biiNo");
            //机构名称
            String orgName = diffObject.getString("orgName");
            //类别名称
            String mtrTypeName = diffObject.getString("mtrTypeName");
            //商品名称
            String cmmdtyName = diffObject.getString("cmmdtyName");
            //品牌名称
            String brandName = diffObject.getString("brandName");
            //型号
            String model = diffObject.getString("model");
            //单位
            String saleUnit = diffObject.getString("saleUnit");
            //数量
            String goodsNum = diffObject.getString("goodsNum");
            //工号
            String empNo = diffObject.getString("empNo");
            //员工名
            String empName = diffObject.getString("empName");
            list.add(mainid);//mainid
            list.add(diffType);//cylx
            list.add(htDetailAmount);//htmxje
            list.add(channelDetailAmount);//gysmxje
            list.add(channelName);//gysmc
            list.add(biiNo);//sqdbh
            list.add(orgName);//dwmc
            list.add(mtrTypeName);//spflmc
            list.add(cmmdtyName);//spmc
            list.add(brandName);//pp
            list.add(model);//xh
            list.add(saleUnit);//spdw
            list.add(goodsNum);//sl
            list.add(empNo);//xdrgh
            list.add(empName);//xdrxm
            updateParams.add(list);
          }
        }
      }
    
  }
    RecordSet rs = new RecordSet();
    if(!CollectionUtils.isEmpty(updateParams)){
      rs.executeUpdate(String.format("delete from %s where mainid = ?", tablename + "_dt2"),
          mainid);
      rs.executeBatchSql(String.format(
          "insert into %s (mainid,cylx,htmxje,gysmxje,gysmc,sqdbh,dwmc," +
          "spflmc,spmc,pp,xh,spdw,sl,xdrgh,xdrxm) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
          tablename + "_dt2"), updateParams);
      rs.executeUpdate(String.format("update %s set bdjg = ? where id = ?", tablename), "有差异", mainid);
    }else{
      rs.executeUpdate(String.format("update %s set bdjg = ? where id = ?", tablename), "无差异", mainid);
    }
  }
  
  private String getFgldByBmbm(int bmbm){
    RecordSet rs = new RecordSet();
    String fgld = "";
    rs.executeQuery("select f.deptleaders " + "  from hrmdepartmentdefined f" +
                    " where f.deptid = ?", bmbm);
    while (rs.next()){
      fgld = rs.getString("deptleaders");
    }
    return fgld;
  }
  private int getbmbm(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 getSzbmByUserId(String userId){
    String szbm = "";
    RecordSet rs = new RecordSet();
    rs.executeQuery("select s.departmentid from hrmresource s where id = ?", userId);
    while (rs.next()){
      szbm = rs.getString("departmentid");
      break;
    }
    return szbm;
  }
  
  private String getSzjgByUserId(String userId){
    String szjg = "";
    RecordSet rs = new RecordSet();
    rs.executeQuery("select id from ( select t.* from HrmDepartment t \n" +
                    "start with t.id=( select a.id from HRMDEPARTMENT a,HRMRESOURCE b \n" +
                    "where a.id=b.DEPARTMENTID and b.id= ?)\n" +
                    " connect by prior t.supdepid=t.id) where SUPDEPID is null or SUPDEPID=0", userId);
    while (rs.next()){
      szjg = rs.getString("id");
      break;
    }
    return szjg;
  }
  
  private MallConfirmVo buildMallConfirmVo(String statisticsRes, String lcbh){
    MallConfirmVo mallConfirmVo = new MallConfirmVo();
    JSONArray array = ((JSONObject) JSON.parse(statisticsRes)).getJSONObject("data").getJSONArray("orderNos");
    mallConfirmVo.setMallConfirmBizNo(lcbh);
    if(!CollectionUtils.isEmpty(array)){
      mallConfirmVo.setOrderNos(array.toJavaList(String.class));
      log.info(String.format("query mall order statistics return orderNo list %s," +
                             "expense confirm workflow lcbh %s",JSON.toJSONString(mallConfirmVo.getOrderNos()),lcbh));
    }else{
      log.info(String.format("query mall order statistics return empty orderNo list! res %s," +
                             "expense confirm workflow lcbh %s",statisticsRes,lcbh));
      mallConfirmVo.setOrderNos(new ArrayList<>());
    }
    return mallConfirmVo;
  }
  
  public static void main(String[] args) {
    GCONST.setRootPath("");
    GCONST.setServerName("ecology");
    MallExpenseConfirmationServiceImpl mallExpenseConfirmationService = new MallExpenseConfirmationServiceImpl();
    MallExoenseConfirmationRequest request = new MallExoenseConfirmationRequest();
    request.setOrgCode("ZZ001");
    // request.setDate("2021-11-20");
    // request.setOrderStatus("2");
    request.setEmpCode("006007");
    request.setCompareDate("2021-10-31");
    // request.setDeptCode("ZZ001112");
    // request.setDate("2021-10-20");
    // request.setOrderStatus("3");
    // request.setMtrTypeCode("C1018684");
    // request.setEmpCode("016328");
    // request.setChannelCodes(Arrays.asList("S000006"));
    HTUtil htUtil = new HTUtil();
    String token = htUtil.getToken(request.getEmpCode());
    String compareRes = mallExpenseConfirmationService.getCompareInfo(request, token);
    mallExpenseConfirmationService.saveCompareInfoToDB(compareRes, "formtable_main_392", 207);



    System.out.println("1111111111111");
  }
}
