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

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.htsc.ReimbursementFlow.model.NewUser;
import com.engine.htsc.branch.approvalChain.tools.ServiceTools;
import com.engine.htsc.branchpayment.enums.OperateMsg;
import com.engine.htsc.branchpayment.pojo.UfCash;
import com.engine.htsc.branchpayment.service.impl.BranchCostDTOFactory;
import com.engine.htsc.branchpayment.utils.BranchBizUtil;
import com.engine.htsc.payment.dao.BudgetDao;
import com.engine.htsc.payment.dao.UfCgsplDao;
import com.engine.htsc.payment.enums.Sequences;
import com.engine.htsc.payment.pojo.*;
import com.engine.htsc.payment.service.SettlePaymentFlowService;
import com.engine.htsc.payment.util.BizUtils;
import com.engine.htsc.payment.util.CoWfUtil;
import com.engine.htsc.payment.util.HttpUtil;
import com.engine.htsc.payment.util.PayUtil;
import com.engine.htsc.subcompany.model.ZgsDept;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;
import weaver.interfaces.htsc.payment.SettlePaymentInvoke;
import weaver.soa.workflow.request.*;
import weaver.workflow.request.RequestManager;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class SettlePaymentFlowServiceImpl  extends Service implements SettlePaymentFlowService {

    private static final String IsNextFlow = "1";
    //办公品,耗材
    private static final String bgphcType = "'C1018681','C1018682'";
    //宣传品     C1018684
    private static final String xcpType = "'C1018684'";
    //电子设备    C1018683 和 IT标准硬件    ITBZYJ
    private static final String dzsbType = "'C1018683','ITBZYJ'";

    protected UfCgsplDao ufCgsplDao = new UfCgsplDao();

    protected ServiceTools serviceTools = new ServiceTools();

    private final PropBean pp = new PropBean();

    private final BudgetDao budgetDao = new BudgetDao();

    @Override
    public List<SettlePayAutoRequestParam> getParam(String requestid) throws Exception {
        List<SettlePayAutoRequestParam> result = new ArrayList<>();
        JAVATools.writelog("requestid:"+requestid+" 根据商城费用确认自动创建采购商城结算付款流程开始");
        String ngsj = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        String[] tempArr = ngsj.split("-");
        RecordSet rs = new RecordSet();
        PropBean propBean = new PropBean();
        //费用确认流程id
        String workflowId = propBean.getPropName("SCFYQR_WORKFLOWID");//46021
        //结算付款流程id
        String workflowIdNew = propBean.getPropName("CGSCJSFK_WORKFLOWID");//47021

        String sql = "select t.WORKFLOWNAME,t.UNNUMBER,abs(t.formid) as formid from workflow_base t where ID=?";
        rs.executeQuery(sql, workflowId);
        String oldTbaleName = "formtable_main_";
        if (rs.next()) {
            oldTbaleName = oldTbaleName + Util.getIntValues(rs.getString("formid"));
        }
        String mainSelectSQL = "select * from "+oldTbaleName+" where requestid = '"+requestid+"'";
        JAVATools.writelog("商城费用确认requestid: "+requestid+" 获取费用确认主表内容 "+mainSelectSQL);
        rs.execute(mainSelectSQL);
        if (rs.next()) {
            String mainid = Util.null2String(rs.getString("id"));//主表id
            String szbm = Util.null2String(rs.getString("szbm"));//所属部门
            String szjg = Util.null2String(rs.getString("szjg"));//所属机构
            String lxfs = Util.null2String(rs.getString("lxfs"));//联系方式
            String jjyy = Util.null2String(rs.getString("jjyy"));//加急原因
            String tzyddxhz = Util.null2String(rs.getString("tzyddxhz"));//已添加通知阅读对象
            String tzydyy = Util.null2String(rs.getString("tzydyy"));//通知阅读原因
            String qttzyddx = Util.null2String(rs.getString("qttzyddx"));//通知阅读对象
            String tybty = Util.null2String(rs.getString("tybty"));//同意不同意
//            String shfs = Util.null2String(rs.getString("shfs"));//审核方式
            String bz = Util.null2String(rs.getString("bz"));//备注
            String gllc = Util.null2String(rs.getString("requestid"));//关联流程,requestid
            String hj = Util.null2String(rs.getString("hj"));//合计
            String jjcd = Util.null2String(rs.getString("jjcd"));//紧急程度
            String fyly = Util.null2String(rs.getString("fyly"));//区分总部还是分支
            String ngr = "";
            String scglysh = Util.null2String(rs.getString("scglysh"));//商城管理员
            String fgscwjlsh = Util.null2String(rs.getString("fgscwjlsh"));//分公司部门负责人
            if("zb".equals(fyly)){
                ngr = scglysh;
            } else if("fzjg".equals(fyly)){
                ngr = fgscwjlsh;
            }
            String dbjg = Util.null2String(rs.getString("bdjg"));//对比结果
            if("".equals(dbjg)){
                dbjg = "0.00";
            }
            String ngsj1 =  Util.null2String(rs.getString("ngsj"));//商城费用确认拟稿时间
            String[] tempArrngsj1 = ngsj1.split("-");
            String dbyf = tempArrngsj1[1];//对比月份

            Map<String, String> mapDt5 = ufCgsplDao.getDt5(mainid,oldTbaleName);
            //办公品   C1018681
            Double bgp = 0.0;
            if (!"".equals(Util.null2String(mapDt5.get("C1018681")))){
                bgp = Util.getDoubleValue(mapDt5.get("C1018681"));
            }
            //耗材   C1018682
            Double hc = 0.0;
            if (!"".equals(Util.null2String(mapDt5.get("C1018682")))){
                hc = Util.getDoubleValue(mapDt5.get("C1018682"));
            }
            //办公品,耗材 mtrTypeId=1
            Double bgyphc = bgp + hc;
            if (!"".equals(Util.null2String(mapDt5.get("C1018681")))||!"".equals(Util.null2String(mapDt5.get("C1018682")))){
                //获取流程编号
                String requestMark = "";
                requestMark = CoWfUtil.getRequestMarkByUnNumber("cgscjsfk", Sequences.NET_REI_WORKFLOW_SEQ_ZB);
                //办公品,耗材   主表
                Map<String, String> mainMap = new HashMap<>();
                mainMap.put("splb","1");
                mainMap.put("ngsj",ngsj);//拟稿时间
                mainMap.put("fj","");//附件
                mainMap.put("ngr",ngr);//拟稿人
                mainMap.put("szbm",szbm);//所属部门
                mainMap.put("dbjg",dbjg);//对比结果
                mainMap.put("dbyf",dbyf);//对比月份
                if (!"".equals(szjg)){
                    mainMap.put("szjg",szjg);//所属机构
                }
                mainMap.put("lxfs",lxfs);//联系方式
                mainMap.put("jjyy",jjyy);//加急原因
                mainMap.put("tzyddxhz",tzyddxhz);//已添加通知阅读对象
                mainMap.put("tzydyy",tzydyy);//通知阅读原因
                mainMap.put("qttzyddx",qttzyddx);//通知阅读对象
                mainMap.put("tybty",tybty);//同意不同意
                mainMap.put("djzs","0");//单据张数默认为0
                mainMap.put("sfxfkhtgfp","1");//x先付款后提供发票默认为1
                mainMap.put("bz",bz);//备注
                mainMap.put("gllc",gllc);//关联流程
                mainMap.put("glfyqrlc",gllc);//关联的费用确认流程
                mainMap.put("hjxxjeitxmf",bgyphc.toString());//合计
                mainMap.put("jjcd",jjcd);//紧急程度
                mainMap.put("lcbh",requestMark);//流程编号
                mainMap.put("jszfmx","点我计算");
                mainMap.put("ngrgh",JAVATools.gethrmidtoworkcode(ngr));//拟稿人工号
                mainMap.put("ngrq",ngsj);//拟稿时间
                mainMap.put("fyly",fyly);//区分分支或总部
                if("zb".equals(fyly)){
                    mainMap.put("scglysh",scglysh);
                } else if("fzjg".equals(fyly)){
                    mainMap.put("fgscwjlsh",fgscwjlsh);
                }
                SettlePayAutoRequestParam param = new SettlePayAutoRequestParam();
                param.setRelateStaffRid(gllc);
                param.setCreatorUid(ngr);
                param.setWorkflowId(workflowIdNew);
                param.setIsNextFlow(IsNextFlow);
                String requestName = "采购商城结算付款" + tempArr[0] + "年" + tempArr[1] + "月费用月结-办公用品、耗材";
                param.setRequestName(requestName);
                param.setMain(mainMap);
                Map<String,List<Map<String, String>>> map = getDt4AndDt11(mainid,oldTbaleName,bgphcType);
                List<Map<String, String>> dt11rows = map.get("dt11");
                List<Map<String, String>> dt4rows = map.get("dt4");
                List<Map<String, String>> dt8rows = getDt8(mainid,oldTbaleName,bgphcType);
                List<Map<String, String>> dt9rows = getDt9(mainid,oldTbaleName,bgphcType);
                List<Map<String, String>> dt10rows = getDt10(mainid,oldTbaleName,bgphcType);
                List<Map<String, String>> dt12rows = getDt12(dt8rows);
                param.setDt4(dt4rows);
                param.setDt8(dt8rows);
                param.setDt9(dt9rows);
                param.setDt10(dt10rows);
                param.setDt11(dt11rows);
                param.setDt12(dt12rows);
                JAVATools.writelog(String.format("自动触发采购商城结算付款流程, 构造参数:%s", JSONObject.toJSONString(param)));
                result.add(param);
            }
            //宣传品   C1018684 mtrTypeId=2
            Double xcp = 0.0;
            if (!"".equals(Util.null2String(mapDt5.get("C1018684")))){
                //获取流程编号
                String requestMark = "";
                requestMark = CoWfUtil.getRequestMarkByUnNumber("cgscjsfk", Sequences.NET_REI_WORKFLOW_SEQ_ZB);
                xcp = Util.getDoubleValue(mapDt5.get("C1018684"));
                Map<String, String> mainMap = new HashMap<>();
                mainMap.put("splb","2");
                mainMap.put("ngsj",ngsj);//拟稿时间
                mainMap.put("fj","");//附件
                mainMap.put("ngr",ngr);//拟稿人
                mainMap.put("szbm",szbm);//所属部门
                mainMap.put("dbjg",dbjg);//对比结果
                mainMap.put("dbyf",dbyf);//对比月份
                if (!"".equals(szjg)){
                    mainMap.put("szjg",szjg);//所属机构
                }
                mainMap.put("lxfs",lxfs);//联系方式
                mainMap.put("jjyy",jjyy);//加急原因
                mainMap.put("tzyddxhz",tzyddxhz);//已添加通知阅读对象
                mainMap.put("tzydyy",tzydyy);//通知阅读原因
                mainMap.put("qttzyddx",qttzyddx);//通知阅读对象
                mainMap.put("tybty",tybty);//同意不同意
                mainMap.put("djzs","0");//单据张数默认为0
                mainMap.put("sfxfkhtgfp","1");//x先付款后提供发票默认为1
                mainMap.put("bz",bz);//备注
                mainMap.put("gllc",gllc);//关联流程
                mainMap.put("glfyqrlc",gllc);//关联的费用确认流程
                mainMap.put("hjxxjeitxmf",xcp.toString());//合计
                mainMap.put("jjcd",jjcd);//紧急程度
                mainMap.put("lcbh",requestMark);//流程编号
                mainMap.put("jszfmx",xcp.toString());//计算（支付明细
                mainMap.put("ngrgh",JAVATools.gethrmidtoworkcode(ngr));//拟稿人工号
                mainMap.put("ngrq",ngsj);//拟稿时间
                mainMap.put("fyly",fyly);//区分分支或总部
                if("zb".equals(fyly)){
                    mainMap.put("scglysh",scglysh);
                } else if("fzjg".equals(fyly)){
                    mainMap.put("fgscwjlsh",fgscwjlsh);
                }
                SettlePayAutoRequestParam param = new SettlePayAutoRequestParam();
                param.setRelateStaffRid(gllc);
                param.setCreatorUid(ngr);
                param.setWorkflowId(workflowIdNew);
                param.setIsNextFlow(IsNextFlow);
                String requestName = "采购商城结算付款" + tempArr[0] + "年" + tempArr[1] + "月费用月结-宣传品";
                param.setRequestName(requestName);
                param.setMain(mainMap);
                Map<String,List<Map<String, String>>> map = getDt4AndDt11(mainid,oldTbaleName,xcpType);
                List<Map<String, String>> dt11rows = map.get("dt11");
                List<Map<String, String>> dt4rows = map.get("dt4");
                List<Map<String, String>> dt8rows = getDt8(mainid,oldTbaleName,xcpType);
                List<Map<String, String>> dt9rows = getDt9(mainid,oldTbaleName,xcpType);
                List<Map<String, String>> dt10rows = getDt10(mainid,oldTbaleName,xcpType);
                List<Map<String, String>> dt12rows = getDt12(dt8rows);
                param.setDt4(dt4rows);
                param.setDt8(dt8rows);
                param.setDt9(dt9rows);
                param.setDt10(dt10rows);
                param.setDt11(dt11rows);
                param.setDt12(dt12rows);
                JAVATools.writelog(String.format("自动触发采购商城结算付款流程, 构造参数:%s", JSONObject.toJSONString(param)));
                result.add(param);
            }
            //电子设备   C1018683 mtrTypeId=3
            Double dzsb = 0.0;
            if (!"".equals(Util.null2String(mapDt5.get("C1018683")))){
                dzsb = Util.getDoubleValue(mapDt5.get("C1018683"));
            }
            //IT标准硬件    ITBZYJ mtrTypeId=4
            Double ityj = 0.0;
            if (!"".equals(Util.null2String(mapDt5.get("ITBZYJ")))){
                ityj = Util.getDoubleValue(mapDt5.get("ITBZYJ"));
            }
            Double dzit = dzsb+ityj;
            if (!"".equals(Util.null2String(mapDt5.get("C1018683")))||!"".equals(Util.null2String(mapDt5.get("ITBZYJ")))){
                //获取流程编号
                String requestMark = "";
                requestMark = CoWfUtil.getRequestMarkByUnNumber("cgscjsfk", Sequences.NET_REI_WORKFLOW_SEQ_ZB);
                Map<String, String> mainMap = new HashMap<>();
                mainMap.put("splb","3");
                mainMap.put("ngsj",ngsj);//拟稿时间
                mainMap.put("fj","");//附件
                mainMap.put("ngr",ngr);//拟稿人
                mainMap.put("szbm",szbm);//所属部门
                mainMap.put("dbjg",dbjg);//对比结果
                mainMap.put("dbyf",dbyf);//对比月份
                if (!"".equals(szjg)){
                    mainMap.put("szjg",szjg);//所属机构
                }
                mainMap.put("lxfs",lxfs);//联系方式
                mainMap.put("jjyy",jjyy);//加急原因
                mainMap.put("tzyddxhz",tzyddxhz);//已添加通知阅读对象
                mainMap.put("tzydyy",tzydyy);//通知阅读原因
                mainMap.put("qttzyddx",qttzyddx);//通知阅读对象
                mainMap.put("tybty",tybty);//同意不同意
                mainMap.put("djzs","0");//单据张数默认为0
                mainMap.put("sfxfkhtgfp","1");//x先付款后提供发票默认为1
                mainMap.put("bz",bz);//备注
                mainMap.put("gllc",gllc);//关联流程
                mainMap.put("glfyqrlc",gllc);//关联的费用确认流程
                mainMap.put("hjxxjeitxmf",dzit.toString());//合计
                mainMap.put("jjcd",jjcd);//紧急程度
                mainMap.put("lcbh",requestMark);//流程编号
                mainMap.put("jszfmx",dzit.toString());//计算（支付明细
                mainMap.put("ngrgh",JAVATools.gethrmidtoworkcode(ngr));//拟稿人工号
                mainMap.put("ngrq",ngsj);//拟稿时间
                mainMap.put("fyly",fyly);//区分分支或总部
                if("zb".equals(fyly)){
                    mainMap.put("scglysh",scglysh);
                } else if("fzjg".equals(fyly)){
                    mainMap.put("fgscwjlsh",fgscwjlsh);
                }
                SettlePayAutoRequestParam param = new SettlePayAutoRequestParam();
                param.setRelateStaffRid(gllc);
                param.setCreatorUid(ngr);
                param.setWorkflowId(workflowIdNew);
                param.setIsNextFlow(IsNextFlow);
                String requestName = "采购商城结算付款" + tempArr[0] + "年" + tempArr[1] + "月费用月结-电子设备、IT标准硬件";
                param.setRequestName(requestName);
                param.setMain(mainMap);
                Map<String,List<Map<String, String>>> map = getDt4AndDt11(mainid,oldTbaleName,dzsbType);
                List<Map<String, String>> dt11rows = map.get("dt11");
                List<Map<String, String>> dt4rows = map.get("dt4");
                List<Map<String, String>> dt8rows = getDt8(mainid,oldTbaleName,dzsbType);
                List<Map<String, String>> dt9rows = getDt9(mainid,oldTbaleName,dzsbType);
                List<Map<String, String>> dt10rows = getDt10(mainid,oldTbaleName,dzsbType);
                List<Map<String, String>> dt12rows = getDt12(dt8rows);
                param.setDt4(dt4rows);
                param.setDt8(dt8rows);
                param.setDt9(dt9rows);
                param.setDt10(dt10rows);
                param.setDt11(dt11rows);
                param.setDt12(dt12rows);
                JAVATools.writelog(String.format("自动触发采购商城结算付款流程, 构造参数:%s", JSONObject.toJSONString(param)));
                result.add(param);
            }
        }
        return result;
    }

    private List<Map<String, String>> getDt12(List<Map<String, String>> dt8rows) {
        PaymentServiceImpl paymentService = new PaymentServiceImpl();
        String accountTreeId = pp.getPropName("accountTreeId");
        //获取进项税
        String jxs = ufCgsplDao.getkjkm("进项税");
        String jxsid = "";
        if (!"".equals(Util.null2String(jxs))){
            jxsid = accountTreeId+"_"+jxs;
        }
        List<Map<String, String>> dt12List = new ArrayList<>();
        if (null!=dt8rows&&dt8rows.size()>0){
            for (Map<String, String> map:dt8rows){
                String hlStr = ufCgsplDao.getHl("0");
                Double hl = Util.getDoubleValue(hlStr);
                String yskm = map.get("yskm");
                String yskmid = map.get("yskmid");
                Double jshjje = Util.getDoubleValue(map.get("jshjje"));
                Double sj = Util.getDoubleValue(map.get("sj"));
                Double bhsje = Util.getDoubleValue(map.get("bhsje"));
                String fysjcdbm = map.get("fysjcdbm");
                Double sjrmb = sj*hl;
                Double bhsrmb = bhsje*hl;
                Double hsrmb = jshjje*hl;
                String kjkm = "";
                String kjkmid = "";
                String kjkmValue = paymentService.getAccountCode(yskm);
                if (!"".equals(kjkmValue)){
                    kjkm = kjkmValue.split("_")[1].split("@")[0];
                    kjkmid = kjkmValue.split("@")[0];
                }
                if (sj>0){
                    Map<String, String> dt8sj = new LinkedHashMap<>();
                    dt8sj.put("fysjcdbm",fysjcdbm);
                    dt8sj.put("yskm",yskm);
                    dt8sj.put("je",sj.toString());
                    dt8sj.put("sjbz","0");
                    dt8sj.put("hl",hlStr);
                    dt8sj.put("zhrmb",sjrmb.toString());
                    dt8sj.put("hjkmid",jxsid);
                    dt8sj.put("hjkm",jxs);
                    dt12List.add(dt8sj);
                    Map<String, String> dt8 = new LinkedHashMap<>();
                    dt8.put("fysjcdbm",fysjcdbm);
                    dt8.put("yskm",yskm);
                    dt8.put("je",bhsje.toString());
                    dt8.put("sjbz","0");
                    dt8.put("hl",hlStr);
                    dt8.put("zhrmb",bhsrmb.toString());
                    dt8.put("hjkmid",kjkmid);
                    dt8.put("hjkm",kjkm);
                    dt12List.add(dt8);
                }else {
                    Map<String, String> dt8 = new LinkedHashMap<>();
                    dt8.put("fysjcdbm",fysjcdbm);
                    dt8.put("yskm",yskm);
                    dt8.put("je",jshjje.toString());
                    dt8.put("sjbz","0");
                    dt8.put("hl",hlStr);
                    dt8.put("zhrmb",hsrmb.toString());
                    dt8.put("hjkmid",kjkmid);
                    dt8.put("hjkm",kjkm);
                    dt12List.add(dt8);
                }
            }
        }
        return dt12List;
    }

    @Override
    public String createWorkflowMain(List<SettlePayAutoRequestParam> paramList) throws Exception {
        String result = "";
        String fyqr = "";
        String jsfk = "";
        for (SettlePayAutoRequestParam param:paramList){
            RequestInfo requestInfo = new RequestInfo();
            requestInfo.setCreatorid(param.getCreatorUid());
            requestInfo.setWorkflowid(param.getWorkflowId());
            requestInfo.setDescription(param.getRequestName());
            requestInfo.setIsNextFlow(param.getIsNextFlow());
            Map<String, String> main = param.getMain();
            //主表数据
            MainTableInfo mainTableInfo = new MainTableInfo();
            Property[] propertyArray = new Property[main.size()];
            int p = 0;
            for (Map.Entry<String, String> entry : main.entrySet()) {
                propertyArray[p] = new Property();
                propertyArray[p].setName(Util.null2String(entry.getKey()));
                propertyArray[p].setValue(Util.null2String(entry.getValue()));
                p++;
            }
            mainTableInfo.setProperty(propertyArray);
            requestInfo.setMainTableInfo(mainTableInfo);

            //工会主表名
            String tableName = PayUtil.getTableNameByUnNumber("cgscjsfk");

            //从表字段
            DetailTableInfo detailTableInfo = new DetailTableInfo();
            //表4
            List<Map<String, String>> dt4 = param.getDt4();
            if (CollectionUtils.isNotEmpty(dt4)) {
                DetailTable detailTable4 = addDtRow(dt4);
                detailTable4.setId("4");
                detailTable4.setTableDBName(tableName + "_dt4");
                detailTableInfo.addDetailTable(detailTable4);
            }
            //表8
            List<Map<String, String>> dt8 = param.getDt8();
            if (CollectionUtils.isNotEmpty(dt8)) {
                DetailTable detailTable8= addDtRow(dt8);
                detailTable8.setId("8");
                detailTable8.setTableDBName(tableName + "_dt8");
                detailTableInfo.addDetailTable(detailTable8);
            }
            //表9
            List<Map<String, String>> dt9 = param.getDt9();
            if (CollectionUtils.isNotEmpty(dt9)) {
                DetailTable detailTable9 = addDtRow(dt9);
                detailTable9.setId("9");
                detailTable9.setTableDBName(tableName + "_dt9");
                detailTableInfo.addDetailTable(detailTable9);
            }
            //表10
            List<Map<String, String>> dt10 = param.getDt10();
            if (CollectionUtils.isNotEmpty(dt10)) {
                DetailTable detailTable10 = addDtRow(dt10);
                detailTable10.setId("10");
                detailTable10.setTableDBName(tableName + "_dt10");
                detailTableInfo.addDetailTable(detailTable10);
            }
            //表11
            List<Map<String, String>> dt11 = param.getDt11();
            if (CollectionUtils.isNotEmpty(dt11)) {
                DetailTable detailTable11 = addDtRow(dt11);
                detailTable11.setId("11");
                detailTable11.setTableDBName(tableName + "_dt11");
                detailTableInfo.addDetailTable(detailTable11);
            }
            //表12
            List<Map<String, String>> dt12 = param.getDt12();
            if (CollectionUtils.isNotEmpty(dt12)) {
                DetailTable detailTable12 = addDtRow(dt12);
                detailTable12.setId("12");
                detailTable12.setTableDBName(tableName + "_dt12");
                detailTableInfo.addDetailTable(detailTable12);
            }

            requestInfo.setDetailTableInfo(detailTableInfo);
            RequestService service = new RequestService();
            String requestId = service.createRequest(requestInfo);
            if(!requestId.contains("-")){
                //更新uf_ShoppingMalPool
                ufCgsplDao.updateShoppingMalPool(main.get("gllc"));
                //更新workflow_requestbase
                ufCgsplDao.updateRequestbase(requestId,main.get("lcbh"));
                result+=result==""?requestId:","+requestId;
                //调用审批链
                HashMap<String,String> reqMap = getSplParam(requestId);
                reqMap.put("requestid",requestId);
                saveSubCompanySpl(reqMap);
                //预占
                RequestInfo requestInfoReq = new RequestInfo();
                RequestManager requestManager = new RequestManager();
                requestManager.setSrc("");
                requestInfoReq.setRequestManager(requestManager);
                requestInfoReq.setRequestid(requestId);
                SettlePaymentInvoke settlePaymentInvoke = new SettlePaymentInvoke();
                settlePaymentInvoke.setBillStatus("3");
                settlePaymentInvoke.execute(requestInfoReq);
                fyqr = main.get("gllc");
                jsfk += jsfk==""?requestId:","+requestId;
            }
//        //生成requestId后单独插入明细8和明细13的数据
//        boolean flag = batchInsertDetails(requestId, tableName, param);
        }
        //调用updatepayStatus接口，采购商城订单付款状态同步
        updatepayStatus(fyqr,jsfk,"2");
        return result;
    }

    private List<Map<String, String>> getDt9(String id, String oldTbaleName,String type ) {
        RecordSet rs = new RecordSet();
        List<Map<String, String>> dt9List = new ArrayList<>();
        //获取费用确认明细表3的数据
        String olddt3SelectSQL = "select * from "+oldTbaleName+"_dt3 where mainid = '"+id+"'";
        rs.execute(olddt3SelectSQL);
        while (rs.next()){
            if (bgphcType.equals(type)){
                Map<String, String> dt9 = new LinkedHashMap<>();
                dt9.put("bm",Util.null2String(rs.getString("bm")));//华泰部门编码
                dt9.put("htbmbm",Util.null2String(rs.getString("htbmbm")));//华泰部门编码
                dt9.put("htbmmc",new ZgsDept(Util.null2String(rs.getString("bm"))).getDepName());//华泰部门名称
                dt9.put("bgyp",Util.null2String(rs.getString("bgypfyamount")));//办公用品费用amount
                dt9.put("bgypmtrtypeid",Util.null2String(rs.getString("bgypfymtrtypeid")));//办公用品费用mtrTypeId
                dt9.put("hcmtrtypeid",Util.null2String(rs.getString("hcfymtrtypeid")));//耗材费用mtrTypeId
                dt9.put("hc",Util.null2String(rs.getString("hcfyamount")));//耗材费用amount
                Double bgypfyamount = 0.0;
                if (!"".equals(Util.null2String(rs.getString("bgypfyamount")))){
                    bgypfyamount = Double.parseDouble(Util.null2String(rs.getString("bgypfyamount")));
                }
                Double hcfyamount = 0.0;
                if (!"".equals(Util.null2String(rs.getString("hcfyamount")))){
                    hcfyamount = Double.parseDouble(Util.null2String(rs.getString("hcfyamount")));
                }
                Double hjje = 0.0;
                if (bgypfyamount>0){
                    hjje = hjje+bgypfyamount;
                }
                if (hcfyamount>0){
                    hjje = hjje+hcfyamount;
                }
                if (hjje>0){
                    dt9.put("hjje",hjje.toString());//合计金额
                    dt9List.add(dt9);
                }
                dt9.put("itbzyj","0.0");//IT标准硬件费用amount
                dt9.put("xcp","0.0");//宣传品费用amount
                dt9.put("dzsb","0.0");//电子设备费用amount
            }
            if (xcpType.equals(type)){
                Map<String, String> dt9 = new LinkedHashMap<>();
                dt9.put("bm",Util.null2String(rs.getString("bm")));//华泰部门编码
                dt9.put("htbmbm",Util.null2String(rs.getString("htbmbm")));//华泰部门编码
                dt9.put("htbmmc",new ZgsDept(Util.null2String(rs.getString("bm"))).getDepName());//华泰部门名称
                dt9.put("xcpmtrtypeid",Util.null2String(rs.getString("xcpfymtrtypeid")));//宣传品费用mtrTypeId
                dt9.put("xcp",Util.null2String(rs.getString("xcpfyamount")));//宣传品费用amount
                if (!"".equals(Util.null2String(rs.getString("xcpfyamount")))){
                    Double hjje = Double.parseDouble(Util.null2String(rs.getString("xcpfyamount")));
                    if (hjje>0){
                        dt9.put("hjje",hjje.toString());//合计金额
                        dt9List.add(dt9);
                    }
                }
                dt9.put("bgyp","0.0");//办公用品费用amount
                dt9.put("itbzyj","0.0");//IT标准硬件费用amount
                dt9.put("dzsb","0.0");//电子设备费用amount
                dt9.put("hc","0.0");//耗材费用amount
            }
            if (dzsbType.equals(type)){
                Map<String, String> dt9 = new LinkedHashMap<>();
                dt9.put("bm",Util.null2String(rs.getString("bm")));//华泰部门编码
                dt9.put("htbmbm",Util.null2String(rs.getString("htbmbm")));//华泰部门编码
                dt9.put("htbmmc",new ZgsDept(Util.null2String(rs.getString("bm"))).getDepName());//华泰部门名称
                dt9.put("dzsbmtrtypeid",Util.null2String(rs.getString("dzsbfymtrtypeid")));//电子设备费用mtrTypeId
                dt9.put("dzsb",Util.null2String(rs.getString("dzsbfyamount")));//电子设备费用amount
                dt9.put("itbzyjmtrtypeid",Util.null2String(rs.getString("itbzyjfymtrtypeid")));//IT标准硬件费用mtrTypeId
                dt9.put("itbzyj",Util.null2String(rs.getString("itbzyjfyamount")));//IT标准硬件费用amount
                Double hjje = 0.0;
                if (!"".equals(Util.null2String(rs.getString("dzsbfyamount")))){
                    Double dzsbfyamount = Double.parseDouble(Util.null2String(rs.getString("dzsbfyamount")));
                    if (dzsbfyamount>0){
                        hjje = hjje+dzsbfyamount;
                    }
                }
                if (!"".equals(Util.null2String(rs.getString("itbzyjfyamount")))){
                    Double itbzyjfyamount = Double.parseDouble(Util.null2String(rs.getString("itbzyjfyamount")));
                    if (itbzyjfyamount>0){
                        hjje = hjje+itbzyjfyamount;
                    }
                }
                if (hjje>0){
                    dt9.put("hjje",hjje.toString());//合计金额
                    dt9List.add(dt9);
                }
                dt9.put("bgyp","0.0");//办公用品费用amount
                dt9.put("hc","0.0");//耗材费用amount
                dt9.put("xcp","0.0");//宣传品费用amount
            }
        }
        return dt9List;
    }

    private List<Map<String, String>> getDt10(String id, String oldTbaleName,String type ) {
        RecordSet rs = new RecordSet();
        List<Map<String, String>> dt10List = new ArrayList<>();
        //获取费用确认明细表4的数据
        String olddt4SelectSQL = "select * from "+oldTbaleName+"_dt4 where mainid = '"+id+"' and mtrtypecode in ("+type+")";
        rs.execute(olddt4SelectSQL);
        while (rs.next()){
            Map<String, String> dt10 = new LinkedHashMap<>();
            dt10.put("sqdbh",Util.null2String(rs.getString("billNo")));//申请单编号 sqdbh
            dt10.put("spflid",Util.null2String(rs.getString("mtrTypeCode")));//商品分类ID spflid
            dt10.put("spflmc",Util.null2String(rs.getString("mtrTypeName")));//商品分类名称 spflmc
            dt10.put("spwlid",Util.null2String(rs.getString("mtrValueCode")));//商品物料ID   spwlid
            dt10.put("spwlmc",Util.null2String(rs.getString("mtrValue")));//商品物料名称   spwlmc
            dt10.put("spbm",Util.null2String(rs.getString("chanGoodsId")));//商品编码   spbm
            dt10.put("spmc",Util.null2String(rs.getString("cmmdtyName")));//商品名称  spmc
            dt10.put("pp",Util.null2String(rs.getString("brandName")));//品牌 pp
            dt10.put("xh",Util.null2String(rs.getString("model")));//型号 xh
            dt10.put("spdw",Util.null2String(rs.getString("spdw")));//商品单位 spdw
            dt10.put("bhsdj",Util.null2String(rs.getString("bhsdj")));//不含税单价 bhsdj
            dt10.put("sl",Util.null2String(rs.getString("shuil")));//税率   sl
            dt10.put("hsdj",Util.null2String(rs.getString("hsdj")));//含税单价   hsdj
            dt10.put("count",Util.null2String(rs.getString("sl")));//数量    count
            dt10.put("bhszj",Util.null2String(rs.getString("bhszj")));//不含税总价 bhszj
            dt10.put("hszj",Util.null2String(rs.getString("hszj")));//含税总价   hszj
            dt10.put("gysbh",Util.null2String(rs.getString("channelCode")));//供应商编号 gysbh
            dt10.put("gysmc",Util.null2String(rs.getString("channelName")));//供应商名称 gysmc
            dt10.put("xdsj",Util.null2String(rs.getString("effectiveOrderTime")));//下单时间   xdsj
            dt10.put("dwbh",Util.null2String(rs.getString("dwbh")));//单位编号 dwbh
            dt10.put("dwmc",Util.null2String(rs.getString("dwmc")));//单位名称   dwmc
            dt10.put("xdrgh",Util.null2String(rs.getString("empNo")));//下单人工号 xdrgh
            dt10.put("xdrxm",Util.null2String(rs.getString("xdrxm")));//下单人姓名 xdrxm
            dt10.put("grcgxqh",Util.null2String(rs.getString("grcgxqh")));//个人采购需求号 grcgxqh
            dt10.put("grcgxqyggh",Util.null2String(rs.getString("grcgxqyggh")));//个人采购需求员工工号   grcgxqyggh
            dt10.put("grcgxqygxm",Util.null2String(rs.getString("grcgxqygxm")));//个人采购需求员工姓名   grcgxqygxm
            dt10List.add(dt10);
        }
        return dt10List;
    }

    private List<Map<String, String>> getDt8(String id, String oldTbaleName,String type) {
        RecordSet rs = new RecordSet();
        List<Map<String, String>> dt8List = new ArrayList<>();
        //获取费用确认明细表4的数据
        String olddt4SelectSQL = "select sum(hszj) as hszj, sum(bhszj) as bhszj, BUDGETITEMCODE, bmcode from "+oldTbaleName+"_dt4 where mainid = '"+id+"' and MTRTYPECODE in ("+type+") group by BUDGETITEMCODE, bmcode";
        rs.execute(olddt4SelectSQL);
        while (rs.next()){
            Map<String, String> dt8 = new LinkedHashMap<>();
            ZgsDept dept = new ZgsDept(Util.null2String(rs.getString("bmcode")),"depCode");
            dt8.put("fysjcdbm",dept.getDepId());//费用承担部门 fysjcdbm
            PropBean propBean = new PropBean();
            String kmbmCode = propBean.getPropName("kmbmCode");//46021
            dt8.put("yskm",Util.null2String(rs.getString("BUDGETITEMCODE")));//预算科目 yskmid
            dt8.put("yskmid",kmbmCode+Util.null2String(rs.getString("BUDGETITEMCODE")));//预算科目 yskm 加前缀
            String hszjValue = Util.null2String(rs.getString("hszj"));//含税总价
            String bhsjeValue = Util.null2String(rs.getString("bhszj"));//不含税总价
            Double hszj = 0.0;
            if (!"".equals(hszjValue)){
                hszj = Double.parseDouble(hszjValue);
            }
            Double bhsje = hszj;
            if (!"".equals(bhsjeValue)){
                bhsje = Double.parseDouble(bhsjeValue);
            }
            Map<String, Object> getCysParams = new HashMap<>();
            getCysParams.put("deptNum", dept.getDepCode());
            getCysParams.put("deptType", dept.getDepTypeCode());
            getCysParams.put("Bgitem", Util.null2String(rs.getString("mtrTypeCode")));
            BigDecimal cysje = getBigDecimalCys(getCysParams);
            //超预算标识 0 未超预算 1 超预算 2未处理数据
            BigDecimal bhsjeBig = new BigDecimal(bhsje);
            int cys = getCys(bhsjeBig, cysje);
            Double sj = 0.0;
            if (hszj>0&&bhsje>0){
                sj = hszj-bhsje;
            }
            String sl = "0.00";
            if (sj>0&&hszj>0){
                DecimalFormat df=new DecimalFormat("0.00");
                sl = df.format(sj/hszj);
            }
            dt8.put("bhsje",bhsje.toString());//不含税金额 bhsje
            dt8.put("sj",sj.toString());//税金   sj
            dt8.put("jshjje",hszj.toString());//价税合计金额   jshjje

            dt8.put("sl",getSl(sl));//税率   sl
            dt8.put("cys", String.valueOf(cys));//超预算  cys
//            dt8.put("sy",Util.null2String(rs.getString("sy")));//事由 sy
            dt8.put("slz",sl);//税率值 slz
            dt8.put("fycdbmfzr",dept.getDirectorId());//部门负责人 fycdbmfzr
            dt8List.add(dt8);
        }
        return dt8List;
    }

    private String getSl(String slz) {
        String sl = "10";
        if("0.06".equals(slz)){
            sl = "0";
        }else if ("0.09".equals(slz)){
            sl = "1";
        }else if ("0.17".equals(slz)){
            sl = "2";
        }else if ("0.16".equals(slz)){
            sl = "3";
        }else if ("0.13".equals(slz)){
            sl = "4";
        }else if ("0.11".equals(slz)){
            sl = "5";
        }else if ("0.10".equals(slz)){
            sl = "6";
        }else if ("0.05".equals(slz)){
            sl = "7";
        }else if ("0.03".equals(slz)){
            sl = "8";
        }else if ("0.01".equals(slz)){
            sl = "9";
        }else if ("0.00".equals(slz)){
            sl = "10";
        }
        return sl;
    }

    //获取合同信息
    private Map<String,List<Map<String, String>>> getDt4AndDt11(String id, String oldTbaleName,String type) throws Exception {
        RecordSet rs = new RecordSet();
        List<Map<String, String>> dt4List = new ArrayList<>();
        List<Map<String, String>> dt11List = new ArrayList<>();
        //获取费用确认明细表4的数据
        String olddt5SelectSQL = "select sum(hszj) as hszj, contractCode from "+oldTbaleName+"_dt4 where mainid = "+id+" and  mtrtypecode in ( "+type+" ) group by contractCode";
        rs.execute(olddt5SelectSQL);
        while (rs.next()){
            String contractCode = Util.null2String(rs.getString("contractCode"));//合同编号 htbh
            String hszjStr = Util.null2String(rs.getString("hszj"));//含税合计以合同统计，本次申请金额;
            Map<String, String> dt4 = new LinkedHashMap<>();
            Map<String, String> htxxMap = ufCgsplDao.getHtxx(contractCode);
            ContractRequestParam param = new ContractRequestParam();
            param.setCode(contractCode);
            param.setUserCode(htxxMap.get("jbr"));//暂定
            if (!"".equals(contractCode)){
                PaymentServiceImpl paymentServiceImpl = new PaymentServiceImpl();
                ContractInfoVo contractInfoVo = paymentServiceImpl.queryContractPagination(param);
                List<ContractVo> data = contractInfoVo.getData();
                dt4.put("htbh",contractCode);//合同编号 htbh
                dt4.put("bqzfje",hszjStr);//本次申请金额   bqzfje
                if (data.size()>0){
                    ContractVo contractVo = data.get(0);
                    Double je = 0.0;
                    if (!StringUtils.isEmpty(contractVo.getTtl()) && !"0".equals(contractVo.getTtl())){
                        je = Double.parseDouble(contractVo.getTtl());
                    }
                    dt4.put("htmc",contractVo.getName());//合同名称 htmc
                    dt4.put("htze",je.toString());//合同总额 htze
                    String yfjeRes = paymentServiceImpl.queryContractPaidMoney(contractCode,data.get(0).getName());//调用接口获取已付金额
                    Double yfje = 0.0;
                    if(StringUtils.isNotBlank(yfjeRes)){
                        JSONObject yfObject = JSONObject.parseObject(yfjeRes);
                        String isSuccess = yfObject.getString("isSuccess");
                        //已付接口请求失败
                        if(isSuccess.equalsIgnoreCase("true")){
                            if (!"".equals(yfObject.getString("data"))){
                                yfje = Double.parseDouble(yfObject.getString("data"));
                            }
                        }
                    }
                    dt4.put("yfjebhbq",yfje.toString());//已付金额（不含本期）   yfjebhbq
                    Double wfje = je - yfje;
                    dt4.put("wfjebhbq",wfje.toString());//未付金额（不含本期）   wfjebhbq
                    dt4.put("bz",getBz(contractVo.getCurrency()));//币种  bz
                    dt4.put("ckhtxx",contractVo.getProcessCode());//操作，接口获取的流程编号
                    //一个合同对应一个收款单位
                    if (data.size()>0){
//                        List<BankFormation> bankFormationList = contractVo.getData();
//                        if(null!=bankFormationList&&bankFormationList.size()>0){
//                            BankFormation bankFormation = bankFormationList.get(0);
                        HashMap<String,String> dt11 = new HashMap<>();
//                            dt11.put("khxmc",Util.null2String(bankFormation.getBankName()));//开户行名称
//                                dt11.put("ss",bankFormation.getOaPayUrl()); //省市数据暂无
                        dt11.put("yxzfje",hszjStr);//银行支付为本次申请金额
                        dt11.put("xjzfje","0");//现金支付
                        dt11.put("dfkje",hszjStr);//合计金额已付金额
                        dt11.put("skdw", Util.null2String(htxxMap.get("skdw")));//收款单位
                        //暂定：
                        dt11.put("yxzh",Util.null2String(htxxMap.get("yxzh")));//银行账户
                        dt11.put("khx",Util.null2String(htxxMap.get("khx")));//开户行
                        dt11.put("khxmc",Util.null2String(htxxMap.get("khx")));//开户行名称
//                            if("".equals(bankFormation.getBankAccount())){
//                                dt11.put("yxzh","3705 0161 5552 0000 0726");//银行账户
//                            }
//                            if("".equals(bankFormation.getBankName())){
//                                dt11.put("khx","开户行");//银行账户
//                                dt11.put("khxmc","开户行名称");//银行账户
//                            }
//                            String ss = ufCgsplDao.getSs(dt11.get("yxzh"));
//                            if (!"".equals(Util.null2String(ss))){
//                                ss = "32,3202";
//                            }
                        dt11.put("ss",htxxMap.get("ss"));//省市
                        dt11List.add(dt11);
                        dt4.put("skdw",Util.null2String(htxxMap.get("skdw")));
                        dt4.put("yxzh",dt11.get("yxzh"));
                        dt4.put("khx",dt11.get("khx"));
                        dt4.put("ss",dt11.get("ss"));
//                        }
                    }
                }
                dt4List.add(dt4);
            }
        }
        Map<String,List<Map<String, String>>> map = new HashMap<>();
        map.put("dt4",dt4List);
        map.put("dt11",dt11List);
        return map;
    }

    private String getBz(String bzString) {
        String bz = null;
        if (bzString.contains("港币")){
            bz = "1";
        }else if (bzString.contains("美元")) {
            bz = "2";
        }else if (bzString.contains("欧元")) {
            bz = "3";
        }else if (bzString.contains("英镑")) {
            bz = "4";
        }else if (bzString.contains("日元")) {
            bz = "5";
        }else if (bzString.contains("人民币")) {
            bz = "0";
        }else if (bzString.contains("新加坡币")) {
            bz = "6";
        }
        return bz;
    }

    public DetailTable addDtRow(List<Map<String, String>> dt) {
        DetailTable dtRows = new DetailTable();
        if (CollectionUtils.isNotEmpty(dt)) {
            for (Map<String, String> map : dt) {
                Row row = new Row();
                for (String key : map.keySet()) {
                    Cell cell = new Cell();
                    cell.setName(key);
                    cell.setValue(map.get(key));
                    row.addCell(cell);
                }
                dtRows.addRow(row);
            }
        }
        return dtRows;
    }

    public static boolean getDoubleIsNull(double i){
        boolean flag=true;
        if(i<0){
            flag=false;
        }
        return flag;
    }

    //批量插入表单，切换数据源
    public boolean insertList(String sqlTableS,String sqlTableE,List<List> insertList,String tablename){
        boolean flag = true;
        try {
            RecordSet rs = new RecordSet();
            JAVATools.SetCmdwritelog("新表插入:", "表名" + tablename );
            JAVATools.SetCmdwritelog("sql:" + String.format("insert into %s (" + sqlTableS + ") values(" + sqlTableE + ") ", tablename));
            JAVATools.SetCmdwritelog("数据:" + insertList);
            //批量插入并切换数据源
            flag = rs.executeBatchSql(String.format("insert into %s (" + sqlTableS + ") values(" + sqlTableE + ") ", tablename), insertList);
        }catch (Exception exo){
            exo.printStackTrace();
            new BaseBean().writeLog("插入明细表失败:"+exo.getMessage());
        }
        return flag;
    }


    @Override
    public HashMap<String, String> getSplParam(String requestid) {
        HashMap<String, String> reqMap = new HashMap<>();
        List<ZgsDept> newDepartList = new ArrayList<>();
        RecordSet rs = new RecordSet();
        String mainTableName = JAVATools.getMaintable(requestid);
        String unumbercode = JAVATools.getmainunnumber(requestid);
        String fyly = "";
        Double hj = 0.0;
        Double hjxxjeitxmf = 0.0;
        String mainid = "";
        String ngr = "";
        String mainSelectSQL = "select * from "+mainTableName+" where requestid = '"+requestid+"'";
        rs.execute(mainSelectSQL);
        if (rs.next()){
            fyly = Util.null2String(rs.getString("fyly"));//区分总部还是分支
            if (!"".equals(Util.null2String(rs.getString("hj")))) {
                hj = Double.parseDouble(Util.null2String(rs.getString("hj")));
            }
            if (!"".equals(Util.null2String(rs.getString("hjxxjeitxmf")))) {
                hjxxjeitxmf = Double.parseDouble(Util.null2String(rs.getString("hjxxjeitxmf")));
            }
            mainid = Util.null2String(rs.getString("id"));//主表id
            ngr = Util.null2String(rs.getString("ngr"));//主表id
        }
        if ("".equals(fyly)){
            NewUser user = new NewUser(ngr);
            boolean isSub="010803".equals(user.getWorkCode())&&"ZZ001".equals(user.getDepCode());
            if (isSub){
                fyly = "zb";
            }else {
                fyly = "fzjg";
            }
        }
        reqMap.put("sslc",unumbercode);     //所属流程
        reqMap.put("fqbmlx",fyly);     //发起部门流程,区分总部还是分支
        //查询初步符合条件的审批链
        List<UfCgspl> settlePaymentSplList = ufCgsplDao.getUfCgspl(reqMap);
        if ("cgscfyqr".equals(unumbercode)){
            //采购商城费用确认
            String sqlDetail = "select * from "+mainTableName+"_dt3 where mainid = '"+mainid+"'";
            rs.execute(sqlDetail);
            reqMap.put("zfmxhj",hj.toString());     //支付明细合计
            String cgbm = "";//单项超过10万的部门
            while (rs.next()){
                String bm = Util.null2String(rs.getString("bm"));//部门
                newDepartList.add(new ZgsDept(bm));
                if(!"".equals(Util.null2String(rs.getString("dzje")))) {
                    Double hjje = Util.getDoubleValue(Util.null2String(rs.getString("dzje")));
                    if(hjje>=100000){
                        cgbm+=cgbm==""?bm:","+bm;
                    }
                }
            }
            reqMap.put("cgbm",cgbm);
            //获取物资类型
            String typeSql = "select sum(a.bgypfyamount) as bgypfyamount,sum(a.hcfyamount)as hcfyamount ,sum(a.xcpfyamount) as xcpfyamount ,sum(a.dzsbfyamount) as dzsbfyamount,sum(a.itbzyjfyamount) as itbzyjfyamount from  "+mainTableName+"_dt3 a where mainid = "+mainid ;
            rs.execute(typeSql);
            if (rs.next()){
                String bgypValue = Util.null2String(rs.getString("bgypfyamount"));
                String hcValue = Util.null2String(rs.getString("hcfyamount"));
                String xcpValue = Util.null2String(rs.getString("xcpfyamount"));
                String dzsbValue = Util.null2String(rs.getString("dzsbfyamount"));
                String itbzyjValue = Util.null2String(rs.getString("itbzyjfyamount"));
                if (!"".equals(bgypValue)&&Double.parseDouble(bgypValue)>0){
                    reqMap.put("mtrTypeId","1");     //办公品
                    reqMap.put("C1018681","C1018681");
                }
                if (!"".equals(hcValue)&&Double.parseDouble(hcValue)>0){
                    reqMap.put("mtrTypeId","1");     //耗材
                    reqMap.put("C1018682","C1018682");
                }
                if (!"".equals(itbzyjValue)&&Double.parseDouble(itbzyjValue)>0){
                    reqMap.put("mtrTypeId","3");     //IT标准硬件
                    reqMap.put("ITBZYJ","ITBZYJ");
                }
                if (!"".equals(xcpValue)&&Double.parseDouble(xcpValue)>0){
                    reqMap.put("mtrTypeId","2");     //宣传品
                    reqMap.put("C1018684","C1018684");
                }
                if (!"".equals(dzsbValue)&&Double.parseDouble(dzsbValue)>0){
                    reqMap.put("mtrTypeId","3");     //电子设备
                    reqMap.put("C1018683","C1018683");
                }
            }
        }else if ("cgscjsfk".equals(unumbercode)){
            //采购商城结算付款
            String sqlDetail = "select sum(a.bgyp) as bgypsum,sum(a.hc)as hcsum ,sum(a.xcp) as xcpsum ,sum(a.dzsb) as dzsbsum,sum(a.itbzyj) as itbzyjsum from "+mainTableName+"_dt9 a where a.mainid = '"+mainid+"'";
            rs.execute(sqlDetail);
            reqMap.put("zfmxhj",hjxxjeitxmf.toString());     //支付明细合计
            if (rs.next()){
                //采购商城结算付款
                String sqltype = "select sum(bgyp) as bgyp,sum(hc) as hc,sum(xcp) as xcp,sum(dzsb) as dzsb,sum(itbzyj) as itbzyj from "+mainTableName+"_dt9 a where mainid = "+mainid;
                rs.execute(sqltype);
                while (rs.next()){
                    String bgypValue = Util.null2String(rs.getString("bgyp"));
                    String hcValue = Util.null2String(rs.getString("hc"));
                    String xcpValue = Util.null2String(rs.getString("xcp"));
                    String dzsbValue = Util.null2String(rs.getString("dzsb"));
                    String itbzyjValue = Util.null2String(rs.getString("itbzyj"));
                    if (!"".equals(bgypValue)&&Double.parseDouble(bgypValue)>0){
                        reqMap.put("mtrTypeId","1");     //办公品
                        reqMap.put("C1018681","C1018681");
                    }
                    if (!"".equals(hcValue)&&Double.parseDouble(hcValue)>0){
                        reqMap.put("mtrTypeId","1");     //耗材
                        reqMap.put("C1018682","C1018682");
                    }
                    if (!"".equals(itbzyjValue)&&Double.parseDouble(itbzyjValue)>0){
                        reqMap.put("mtrTypeId","3");     //IT标准硬件
                        reqMap.put("ITBZYJ","ITBZYJ");
                    }
                    if (!"".equals(xcpValue)&&Double.parseDouble(xcpValue)>0){
                        reqMap.put("mtrTypeId","2");     //宣传品
                        reqMap.put("C1018684","C1018684");
                    }
                    if (!"".equals(dzsbValue)&&Double.parseDouble(dzsbValue)>0){
                        reqMap.put("mtrTypeId","3");     //电子设备
                        reqMap.put("C1018683","C1018683");
                    }
                }
                //获取部门
                String bmSql = " select bm,count(1) from  "+mainTableName+"_dt9 where mainid = "+mainid+"  group by bm";
                rs.execute(bmSql);
                while (rs.next()){
                    String bm = Util.null2String(rs.getString("bm"));//部门
                    newDepartList.add(new ZgsDept(bm));
                }
            }
        }
        //条件过滤并赋值
        List<SettlePaymentSplVO> settlePaymentSplVOList = convertModelToVO(settlePaymentSplList,reqMap,newDepartList);
        //将settlePaymentSplVOList去重相加转换为map
        HashMap<String,String> mapRes = removeDuplicateCommon(settlePaymentSplVOList);
        JAVATools.writelog("审批链Id:"+ mapRes.get("id"));
        JAVATools.writelog("预算管理员审核:"+ mapRes.get("bmysglysh"));
        JAVATools.writelog("营业部负责人审核:"+ mapRes.get("yybfzrsh"));
        JAVATools.writelog("部门负责人审核:"+ mapRes.get("wzcggkbmfzr"));
        JAVATools.writelog("物资采购对接人员审核:"+ mapRes.get("wzcgdjrysh"));
        JAVATools.writelog("财务中心会计审核:"+ mapRes.get("cwzxjl"));
        JAVATools.writelog("分公司财务经理审核:"+ mapRes.get("fgscwjlsh"));
        JAVATools.writelog("分公司负责人审批:"+ mapRes.get("fgsfzrsh"));
        JAVATools.writelog("分管领导审核:"+ mapRes.get("fgldsh"));
        JAVATools.writelog("分公司财务经理办结:"+ mapRes.get("fgscwjlbj"));
        JAVATools.writelog("总裁审批:"+ mapRes.get("zc"));
        JAVATools.writelog("预算管理员终审:"+ mapRes.get("ysglyzs"));
        JAVATools.writelog("费用会计审核:"+ mapRes.get("fyhj"));
        JAVATools.writelog("财务负责人审核:"+ mapRes.get("cwfzrsp"));
        JAVATools.writelog("财务总监审核:"+ mapRes.get("cwzj"));
        JAVATools.writelog("出纳:"+ mapRes.get("cn"));
        JAVATools.writelog("商城管理员审核:"+ mapRes.get("ysglycs"));
        return mapRes;
    }

    protected List<SettlePaymentSplVO> convertModelToVO(List<UfCgspl> settlePaymentSplList, HashMap<String, String> reqMap,List<ZgsDept> newDepartList) {
        List<SettlePaymentSplVO> resultList = new ArrayList<>();
        List<UfCgspl> respUfCgsplList = new ArrayList<>();
        for (UfCgspl ufCgspl:settlePaymentSplList){
            //判断条件
            if(null!=ufCgspl.getTj()&&!"".equals(ufCgspl.getTj())){
                if(!serviceTools.getConitionParams(ufCgspl.getTj(),reqMap)){
                    continue;
                }
            }
            respUfCgsplList.add(ufCgspl);
        }
        for (UfCgspl ufCgspl:respUfCgsplList){
            SettlePaymentSplVO settlePaymentSplVO = getVo(ufCgspl,reqMap,newDepartList);
            resultList.add(settlePaymentSplVO);
        }
        return resultList;
    }

    protected HashMap<String, String> removeDuplicateCommon(List<SettlePaymentSplVO> settlePaymentSplVOList) {
        HashMap<String, String> mapRes = new HashMap<>();
        String id = ""; //id
        String ysglycs = "";     //商城管理员审核
        String fgscwjlsh = "";   //分公司财务经理审核
        String wzcgdjrysh = "";  //物资采购对接人员审核
        String bmysglysh  = "";   //预算管理员审核
        String yybfzrsh = "";    //营业部负责人审核
        String bmfzrsh = "";     //部门负责人审核
        String wzcggkbmfzr = ""; //物资采购归口部门负责人
        String cwzxhj = "";      //财务中心会计审核
        String fyhj = "";        //费用会计审核
        String cwzxjl = "";      //财务中心经理审核
        String cwfzrsp = "";     //财务负责人审核
        String cwzj = "";        //财务总监审核
        String fgsfzrsh = "";    //分公司负责人审批
        String fgldsh = "";      //分管领导审核
        String zc = "";          //总裁审批
        String cn = "";          //出纳
        String ysglyzs = "";     //预算管理员终审,商城管理员办结
        String fgscwjlbj = "";   //分公司财务经理办结
        for (SettlePaymentSplVO vo:settlePaymentSplVOList){
            id = addIds(id, Util.null2String(vo.getId()));
            fgscwjlsh = addIds(fgscwjlsh,Util.null2String(vo.getFgscwjlsh()));
            wzcgdjrysh = addIds(wzcgdjrysh,Util.null2String(vo.getWzcgdjrysh()));
            bmysglysh = addIds(bmysglysh, Util.null2String(vo.getBmysglysh()));
            yybfzrsh = addIds(yybfzrsh, Util.null2String(vo.getYybfzrsh()));
            bmfzrsh = addIds(bmfzrsh, Util.null2String(vo.getBmfzrsh()));
            fgsfzrsh = addIds(fgsfzrsh, Util.null2String(vo.getFgsfzrsh()));
            fgldsh = addIds(fgldsh, Util.null2String(vo.getFgldsh()));
            ysglyzs = addIds(ysglyzs, Util.null2String(vo.getYsglyzs()));
            fyhj = addIds(fyhj, Util.null2String(vo.getFyhj()));
            cwfzrsp = addIds(cwfzrsp, Util.null2String(vo.getCwfzrsp()));
            cn = addIds(cn, Util.null2String(vo.getCn()));
            ysglycs = addIds(ysglycs, Util.null2String(vo.getYsglycs()));
            wzcggkbmfzr = addIds(wzcggkbmfzr, Util.null2String(vo.getWzcggkbmfzr()));
            wzcgdjrysh =  addIds(wzcgdjrysh, Util.null2String(vo.getWzcgdjrysh()));
            cwzxhj =  addIds(cwzxhj, Util.null2String(vo.getCwzxhj()));
            cwzxjl = addIds(cwzxjl, Util.null2String(vo.getCwzxjl()));
            cwzj = addIds(cwzj, Util.null2String(vo.getCwzj()));
            zc = addIds(zc, Util.null2String(vo.getZc()));
            fgscwjlbj = addIds(fgscwjlbj, Util.null2String(vo.getFgscwjlbj()));
        }
        //分管领导和总裁去重
        fgldsh = distinctById(fgldsh,zc);
        String cnrygh = JAVATools.gethrmidtoworkcode(cn);
        mapRes.put("id",id);
        mapRes.put("bmysglysh",bmysglysh);
        mapRes.put("yybfzrsh",yybfzrsh);
        mapRes.put("bmfzrsh",bmfzrsh);
        mapRes.put("fgsfzrsh",fgsfzrsh);
        mapRes.put("fgldsh",fgldsh);
        mapRes.put("ysglyzs",ysglyzs);
        mapRes.put("fyhj",fyhj);
        mapRes.put("cwfzrsp",cwfzrsp);
        mapRes.put("cn",cn);
        mapRes.put("ysglycs",ysglycs);
        mapRes.put("cnrygh",cnrygh);
        mapRes.put("fgscwjlsh",fgscwjlsh);
        mapRes.put("wzcgdjrysh",wzcgdjrysh);
        mapRes.put("wzcggkbmfzr",wzcggkbmfzr);
        mapRes.put("cwzxhj",cwzxhj);
        mapRes.put("cwzxjl",cwzxjl);
        mapRes.put("cwzj",cwzj);
        mapRes.put("zc",zc);
        mapRes.put("fgscwjlbj",fgscwjlbj);

        return mapRes;
    }

    private String distinctById(String param, String base) {
        String result = "";
        if (null!=base&&!"".equals(base)){
            List<String> baseArray = Arrays.asList(base.split(","));
            if (null!=param&&!"".equals(param)){
                List<String> paramArray = Arrays.asList(param.split(","));
                for (String str:paramArray){
                    if (!baseArray.contains(str)){
                        result+=result==""?str:","+str;
                    }
                }
            }
        }else {
            result = param;
        }
        return result;
    }

    @Override
    public String saveSubCompanySpl(HashMap<String, String> reqMap) {
        try {
            String tableName = JAVATools.getMaintable(reqMap.get("requestid"));//主表名
            String unumbercode = JAVATools.getmainunnumber(reqMap.get("requestid"));
            if ("cgscfyqr".equals(unumbercode)){
                //采购商城费用确认
                ufCgsplDao.updateMainFyqr(reqMap,tableName);
            }else if ("cgscjsfk".equals(unumbercode)){
                //采购商城结算付款
                ufCgsplDao.updateMainJsfk(reqMap,tableName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "FAIL";
        }
        return "SUCCESS";
    }

    @Override
    public String getSplNgr(String flowType,String orgCode) {
        String ngr = "";
        if ("zb".equals(flowType)){
            //总部 为郭逸凡
            String zbkjjl = new PropBean().getPropName("ZBKJJL");
            ngr = JAVATools.gethrmworkcodetoid(zbkjjl);
        }else if("fzjg".equals(flowType)){
            RecordSet rs = new RecordSet();
            ZgsDept fzjgDept = new ZgsDept(orgCode,"");
            String sql = "select kjjl from uf_fzjgfkgwpp where bm = "+ fzjgDept.getDepId();
            rs.execute(sql);
            if (rs.next()){
                ngr = Util.null2String(rs.getString("kjjl"));
            }
        }
        return ngr;
    }



    private SettlePaymentSplVO getVo(UfCgspl ufCgspl, HashMap<String, String> reqMap,List<ZgsDept> newDepartList) {
        SettlePaymentSplVO settlePaymentSplVO = new SettlePaymentSplVO();
        settlePaymentSplVO.setId(ufCgspl.getId());
        settlePaymentSplVO.setSslc(ufCgspl.getSslc());
        settlePaymentSplVO.setFqbmlx(ufCgspl.getFqbmlx());
        settlePaymentSplVO.setTj(ufCgspl.getTj());

        List<String> DepartList = getDepartList(newDepartList);    //获取JGLX04，JGLX02营业部其上级部门和非营业部bmid
        //获取财务信息
        List<ZgsDept> fgsDepartList = getfgsDepartList(DepartList);
        Map cwMap = ufCgsplDao.getCwMap(DepartList,reqMap.get("fqbmlx"));
        settlePaymentSplVO.setBmysglysh(getBmysglysh(Util.null2String(ufCgspl.getBmysglysh()),newDepartList));//部门预算管理员审核
        settlePaymentSplVO.setYybfzrsh(getYybfzrsh(Util.null2String(ufCgspl.getYybfzrsh()),newDepartList));//营业部负责人审核
        settlePaymentSplVO.setBmfzrsh(getBmfzrsh(Util.null2String(ufCgspl.getBmfzrsh()),newDepartList));//部门负责人审核
        settlePaymentSplVO.setFgsfzrsh(getFgsfzrsh(Util.null2String(ufCgspl.getFgsfzrsh()),fgsDepartList));//分公司负责人审核
        settlePaymentSplVO.setFgldsh(getFgldsh(Util.null2String(ufCgspl.getFgldsh()),newDepartList,reqMap.get("cgbm")));//分管领导审核
        settlePaymentSplVO.setYsglyzs(getYsglyzs(Util.null2String(ufCgspl.getYsglyzs()),newDepartList));//预算管理员终审
        settlePaymentSplVO.setFyhj(getNormal(Util.null2String(ufCgspl.getFyhj()),newDepartList));//费用会计
        settlePaymentSplVO.setCwfzrsp(getNormal(Util.null2String(ufCgspl.getCwfzrsp()),newDepartList));//财务负责人审批
        settlePaymentSplVO.setCn(getNormal(Util.null2String(ufCgspl.getCn()),newDepartList));//出纳
        settlePaymentSplVO.setYsglycs(getNormal(Util.null2String(ufCgspl.getYsglycs()),newDepartList));//预算管理员初审
        settlePaymentSplVO.setFgscwjlsh(getfgscwjlsh(Util.null2String(ufCgspl.getFgscwjlsh()),cwMap));//分公司财务经理审核
        settlePaymentSplVO.setWzcgdjrysh(getWzcgdjrysh(Util.null2String(ufCgspl.getWzcgdjrysh()),reqMap));//物资采购对接人员审核
        settlePaymentSplVO.setWzcggkbmfzr(getNormal(Util.null2String(ufCgspl.getWzcggkbmfzr()),newDepartList));//物资采购归口部门负责人
        settlePaymentSplVO.setCwzxhj(getCwzxhj(Util.null2String(ufCgspl.getCwzxhj()),cwMap));
        settlePaymentSplVO.setCwzxjl(getCwzxjl(Util.null2String(ufCgspl.getCwzxjl()),cwMap));
        settlePaymentSplVO.setCwzj(getNormal(Util.null2String(ufCgspl.getCwzj()),newDepartList));//财务总监审核
        settlePaymentSplVO.setZc(getNormal(Util.null2String(ufCgspl.getZc()),newDepartList));//财务总监审核
        settlePaymentSplVO.setCn(getCn(Util.null2String(ufCgspl.getCn()),cwMap));//出纳
        settlePaymentSplVO.setFgscwjlbj(getFgscwjlbj(Util.null2String(ufCgspl.getFgscwjlbj()),cwMap));//分公司财务经理办结
        return settlePaymentSplVO;
    }

    private String getFgscwjlbj(String value, Map cwMap) {
        String hrmids="";
        if("".equals(value)){
            return hrmids;
        }
        for (String hrmst:value.split(",") ) {
            String hrmid=getHrmType(hrmst);
            //不是指定WK_则判断是否为1
            if("".equals(hrmid)){
                if ("1".equals(hrmst)){
                    hrmids+=hrmids==""?Util.null2String(cwMap.get("kjjl")):","+Util.null2String(cwMap.get("kjjl"));
                }
            }else{
                hrmids+=hrmids==""?hrmid:","+hrmid;
            }
        }
        return hrmids ;
    }

    private String getCn(String value, Map cwMap) {
        String hrmids="";
        if("".equals(value)){
            return hrmids;
        }
        for (String hrmst:value.split(",") ) {
            String hrmid=getHrmType(hrmst);
            //不是指定WK_则判断是否为1
            if("".equals(hrmid)){
                if ("1".equals(hrmst)){
                    hrmids+=hrmids==""?Util.null2String(cwMap.get("cn")):","+Util.null2String(cwMap.get("cn"));
                }
            }else{
                hrmids+=hrmids==""?hrmid:","+hrmid;
            }
        }
        return hrmids ;
    }


    private List<ZgsDept> getfgsDepartList(List<String> departList) {
        List<ZgsDept> list = new ArrayList<>();
        HashSet<String> set = new HashSet<>(departList);
        for (String bm : set){
            ZgsDept depart = new ZgsDept(bm);
            list.add(depart);
        }
        return list;
    }

    private String getCwzxjl(String value, Map cwMap) {
        String hrmids="";
        if("".equals(value)){
            return hrmids;
        }
        for (String hrmst:value.split(",") ) {
            String hrmid=getHrmType(hrmst);
            //不是指定WK_则判断是否为1
            if("".equals(hrmid)){
                if ("1".equals(hrmst)){
                    hrmids+=hrmids==""?Util.null2String(cwMap.get("kjjl")):","+Util.null2String(cwMap.get("kjjl"));
                }
            }else{
                hrmids+=hrmids==""?hrmid:","+hrmid;
            }
        }
        return hrmids ;
    }

    private String getCwzxhj(String value, Map cwMap) {
        String hrmids="";
        if("".equals(value)){
            return hrmids;
        }
        for (String hrmst:value.split(",") ) {
            String hrmid=getHrmType(hrmst);
            //不是指定WK_则判断是否为1
            if("".equals(hrmid)){
                if ("1".equals(hrmst)){
                    hrmids+=hrmids==""?Util.null2String(cwMap.get("kj")):","+Util.null2String(cwMap.get("kj"));
                }
            }else{
                hrmids+=hrmids==""?hrmid:","+hrmid;
            }
        }
        return hrmids ;
    }

    //获取JGLX04，JGLX02营业部其上级部门和非营业部bmid
    private List<String> getDepartList(List<ZgsDept> newDepartList) {
        List<String> deppartList = new ArrayList<>();
        for (ZgsDept Depart:newDepartList){
            if ("JGLX02".equals(Depart.getDepTypeCode())||"JGLX04".equals(Depart.getDepTypeCode())){
                deppartList.add(Depart.getParentDepId());
            }else {
                deppartList.add(Depart.getDepId());
            }
        }
        return deppartList;
    }

    private String getWzcgdjrysh(String value, HashMap<String, String> reqMap) {
        String hrmids="";
        if("".equals(value)){
            return hrmids;
        }
        List<String> hrmidList = new ArrayList<>();
        for (String hrmst:value.split(",") ) {
            String hrmid=getHrmType(hrmst);
            hrmidList.add(hrmid);
        }
        if (hrmidList.size()>=3){
            //                    办公品   C1018681
            //                    耗材   C1018682
            if ("C1018681".equals(Util.null2String(reqMap.get("C1018681")))||"C1018682".equals(Util.null2String(reqMap.get("C1018682")))){
                //陈刚
                hrmids+=hrmids==""?hrmidList.get(0):","+hrmidList.get(0);
            }
            //                    宣传品     C1018684
            if ("C1018684".equals(Util.null2String(reqMap.get("C1018684")))){
                //潘王志
                hrmids+=hrmids==""?hrmidList.get(1):","+hrmidList.get(1);
            }
            //                    IT标准硬件    ITBZYJ
            //                    电子设备    C1018683
            if ("ITBZYJ".equals(Util.null2String(reqMap.get("ITBZYJ")))||"C1018683".equals(Util.null2String(reqMap.get("C1018683")))){
                //肖化铸
                hrmids+=hrmids==""?hrmidList.get(2):","+hrmidList.get(2);
            }
        }else {
            for (String hrmst:value.split(",") ) {
                String hrmid=getHrmType(hrmst);
                //不是指定WK_则判断是否为1
                if("".equals(hrmid)){
                    if ("1".equals(hrmst)){
//                    办公品   C1018681
//                    耗材   C1018682
                        if ("C1018681".equals(Util.null2String(reqMap.get("C1018681")))||"C1018682".equals(Util.null2String(reqMap.get("C1018682")))){
                            //陈刚
                            hrmids+=hrmids==""?JAVATools.gethrmworkcodetoid("001317"):","+JAVATools.gethrmworkcodetoid("001317");
                        }
//                    宣传品     C1018684
                        if ("C1018684".equals(Util.null2String(reqMap.get("C1018684")))){
                            //潘王志
                            hrmids+=hrmids==""?JAVATools.gethrmworkcodetoid("016298"):","+JAVATools.gethrmworkcodetoid("016298");
                        }
//                    IT标准硬件    ITBZYJ
//                    电子设备    C1018683
                        if ("ITBZYJ".equals(Util.null2String(reqMap.get("ITBZYJ")))||"C1018683".equals(Util.null2String(reqMap.get("C1018683")))){
                            //肖化铸
                            hrmids+=hrmids==""?JAVATools.gethrmworkcodetoid("012827"):","+JAVATools.gethrmworkcodetoid("012827");
                        }
                    }
                }else{
                    hrmids+=hrmids==""?hrmid:","+hrmid;
                }
            }
        }
        return hrmids ;
    }


    private String getfgscwjlsh(String value, Map cwMap) {
        String hrmids="";
        if("".equals(value)){
            return hrmids;
        }
        for (String hrmst:value.split(",") ) {
            String hrmid=getHrmType(hrmst);
            //不是指定WK_则判断是否为1
            if("".equals(hrmid)){
                if ("1".equals(hrmst)){
                    hrmids+=hrmids==""?Util.null2String(cwMap.get("kjjl")):","+Util.null2String(cwMap.get("kjjl"));
                }
            }else{
                hrmids+=hrmids==""?hrmid:","+hrmid;
            }
        }
        return hrmids ;
    }


    //根据type来获取人员
    public String getHrmType(String value){
        if("".equals(value)){
            return "";
        }
        if(value.indexOf("WK_")>=0){
            String workcodeS=value.split("WK_")[1];
            String[] codeArray = workcodeS.split("_");
            String workcode = codeArray[0];
            if(codeArray.length>1){
                String deptcode = codeArray[1];
                return ufCgsplDao.getUserIdByCode(workcode,deptcode);
            }else{
                return JAVATools.GetWorkcodetoid(workcode);
            }
        }
        return "";
    }

    private String getYsglyzs(String value, List<ZgsDept> newDepartList) {
        if("".equals(value)){
            return "";
        }
        if(value.indexOf("WK_")>=0){
            String workcode=value.split("WK_")[1];
            return JAVATools.GetWorkcodetoid(workcode);
        }
        return "";
    }

    private String getBmysglysh(String value, List<ZgsDept> newDepartList) {
        String hrmids="";
        if("".equals(value)){
            return hrmids;
        }
        for (String hrmst:value.split(",") ) {
            String hrmid=getHrmType(hrmst);
            //不是指定WK_则判断是否为1
            if("".equals(hrmid)){
                if ("1".equals(hrmst)){
                    String bms = "";
                    for (ZgsDept newDepart:newDepartList){
                        bms+=bms==""?newDepart.getDepId():","+newDepart.getDepId();
                    }
                    hrmid = ufCgsplDao.getBmysglysh(bms);
                    hrmids+=hrmids==""?hrmid:","+hrmid;
                }
            }else{
                hrmids+=hrmids==""?hrmid:","+hrmid;
            }
        }
        return hrmids ;
    }

    private String getYybfzrsh(String value, List<ZgsDept> newDepartList) {
        String hrmids="";
        if("".equals(value)){
            return hrmids;
        }
        for (String hrmst:value.split(",") ) {
            String hrmid=getHrmType(hrmst);
            //不是指定WK_则判断是否为1
            if("".equals(hrmid)){
                //如果是1的情况下，DEPTDIRECTORS
                if ("1".equals(hrmst)){
                    for (ZgsDept newDepart:newDepartList){
                        if ("JGLX02".equals(newDepart.getDepTypeCode())||"JGLX04".equals(newDepart.getDepTypeCode())){
                            hrmids+=hrmids==""?newDepart.getDirectorId():","+newDepart.getDirectorId();
                        }
                    }
                }
            }else{
                hrmids+=hrmids==""?hrmid:","+hrmid;
            }
        }
        return hrmids ;
    }

    private String getBmfzrsh(String value, List<ZgsDept> newDepartList) {
        String hrmids="";
        if("".equals(value)){
            return hrmids;
        }
        for (String hrmst:value.split(",") ) {
            String hrmid=getHrmType(hrmst);
            //不是指定WK_则判断是否为1
            if("".equals(hrmid)){
                //如果是1的情况下，DEPTDIRECTORS
                if ("1".equals(hrmst)){
                    for (ZgsDept newDepart:newDepartList){
                        hrmids+=hrmids==""?newDepart.getDirectorId():","+newDepart.getDirectorId();
                    }
                }
            }else{
                hrmids+=hrmids==""?hrmid:","+hrmid;
            }
        }
        return hrmids ;
    }

    private String getFgsfzrsh(String value, List<ZgsDept> newDepartList) {
        String hrmids="";
        if("".equals(value)){
            return hrmids;
        }
        for (String hrmst:value.split(",") ) {
            String hrmid=getHrmType(hrmst);
            //不是指定WK_则判断是否为1
            if("".equals(hrmid)){
                //如果是1的情况下，DEPTDIRECTORS
                if ("1".equals(hrmst)){
                    for (ZgsDept ZgsDept:newDepartList){
                        hrmids+=hrmids==""?ZgsDept.getDirectorId():","+ZgsDept.getDirectorId();
                    }
                }
            }else{
                hrmids+=hrmids==""?hrmid:","+hrmid;
            }
        }
        return hrmids ;
    }

    private String getFgldsh(String value, List<ZgsDept> newDepartList, String cgbm) {

        List<ZgsDept> newDepartCgbmList = new ArrayList<>();
        if(!StringUtils.isEmpty(cgbm)){
            List<String> cgbmList = Arrays.asList(cgbm.split(","));
            for(String bm:cgbmList){
                newDepartCgbmList.add(new ZgsDept(bm));
            }
        }
        String hrmids="";
        if("".equals(value)){
            return hrmids;
        }
        for (String hrmst:value.split(",") ) {
            String hrmid=getHrmType(hrmst);
            //不是指定WK_则判断是否为1
            if("".equals(hrmid)){
                //如果是1的情况下，DEPTDIRECTORS
                if ("1".equals(hrmst)){
                    for (ZgsDept newDepart:newDepartCgbmList){
                        if(!"".equals(newDepart.getLeaderId())){
                            hrmids+=hrmids==""?newDepart.getLeaderId():","+newDepart.getLeaderId();
                        }
                    }
                }
            }else{
                hrmids+=hrmids==""?hrmid:","+hrmid;
            }
        }
        return hrmids ;
    }

    //数据库直接配置人员类型
    private String getNormal(String value, List<ZgsDept> newDepartList) {
        String hrmids="";
        if("".equals(value)){
            return hrmids;
        }
        for (String hrmst:value.split(",") ) {
            String hrmid=getHrmType(hrmst);
            hrmids+=hrmids==""?hrmid:","+hrmid;
        }
        return hrmids;
    }
    public String addIds(String ids,String value){
        if(value==null||"".equals(value)){
            List idArray = new ArrayList(Arrays.asList(ids.split(",")));
            HashSet idSet = new HashSet(idArray);
            ids = String.join(",", idSet);
            return ids;
        }
        if(ids==null||"".equals(ids)){
            List valueArray = new ArrayList(Arrays.asList(value.split(",")));
            HashSet valueSet = new HashSet(valueArray);
            value = String.join(",", valueSet);
            return value;
        }
        List idArray = new ArrayList(Arrays.asList(ids.split(",")));
        List valueArray = new ArrayList(Arrays.asList(value.split(",")));
        idArray.addAll(valueArray);
        HashSet idSet = new HashSet(idArray);
        String str = String.join(",", idSet);
        return str;
    }

    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) {
                    JAVATools.writelog("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;
    }

    @Override
    public boolean doBudgetMiddleTable(String requestNo, String billStatus) {
        JAVATools.writelog("采购商城付款流程,预算中间表更新\n  @requestNo=" + requestNo + ",billStatus=" + billStatus );
        RecordSet rs = new RecordSet();
        try {
            String tableName = JAVATools.getMaintable(requestNo);
            String sql = "select LCBH,FKLX from " + tableName + " where REQUESTID=" + requestNo;
            rs.executeQuery(sql);
            String bz = "0";
            String lx = "";
            String title = "";
            if (rs.next()) {
                lx = rs.getString("FKLX");
                title = rs.getString("LCBH");
            }
            String yskmTable = tableName + "_DT8";
//            return bds.doBudgetMiddleTable(title, billStatus,null, yskmTable, tableName, isItFlag);
            //预算中间表外部数据源
            String budgetTableName = pp.getPropName("BudgetTableName");
            String nameIsExist = budgetDao.fNameIsExist(budgetTableName, title);
            JAVATools.writelog("预算数据是否存在sql @" + nameIsExist + "@");
            RecordSetDataSource rsd = new RecordSetDataSource("BudgetRecords");
            rsd.execute(nameIsExist);
            if (rsd.next() && org.apache.commons.lang3.StringUtils.isNotBlank(title)) {
                String deleteAll = String.format("delete from %s where FNAME='%s'",
                        budgetTableName, title);
                rsd.executeUpdateWithDatasource(deleteAll, "BudgetRecords");
                insertBudgetMiddleTable(title, billStatus, yskmTable, tableName);
            } else {
                insertBudgetMiddleTable(title, billStatus, yskmTable, tableName);
            }
            return true;
        } catch (Exception e) {
            JAVATools.writelog("\n 更新预算中间表出现异常 \n");
            JAVATools.writelog("catch: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean insertBudgetMiddleTable(String requestMark, String billStatus,String yskmTable,String mainTable) throws Exception {
        Map<String, Object> budgetBody = getBudgetBody(requestMark, mainTable, yskmTable);
        List<Object> mainInfo = (List<Object>) budgetBody.get("main"); //主表数据
        List<List<Object>> dtInfo = (List<List<Object>>) budgetBody.get("dt"); //预算数据
        if (dtInfo.size() == 0) {
            JAVATools.writelog("插入预算表中止,因为科目信息为空");
            return false;
        }
        DateTimeFormatter dfOnlyYear = DateTimeFormatter.ofPattern("yyyy"); //年
        DateTimeFormatter dfDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); //当前操作时间
        try {
            String budgetTableName = new PropBean().getPropName("BudgetTableName");
            for (List<Object> singleValue : dtInfo) {
                List<Object> insertValues = new ArrayList<>();
                insertValues.add(billStatus);//FBILLSTATUS
                insertValues.addAll(mainInfo);//FNAME,FBILLTITLE,FPESONNAME
                insertValues.add(dfOnlyYear.format(LocalDateTime.now()));//YSND
                insertValues.add(dfDateTime.format(LocalDateTime.now()));//FBIZDATE
                insertValues.addAll(singleValue);
                String insert = budgetDao.insertMiddleTable(budgetTableName);
                RecordSet recordSet = new RecordSet();
                recordSet.executeUpdateWithDatasource(insert, "BudgetRecords", insertValues);
            }
            return true;
        } catch (Exception e) {
            JAVATools.writelog("insertBudgetMiddleTable异常, [" + e + "]");
            return false;
        }
    }

    /**
     * 获取插入表中的数据
     *
     * @param requestMark 流程编号
     * @return map
     */
    private Map<String, Object> getBudgetBody(String requestMark, String main, String budgetKmTable) throws Exception {
        Map<String, Object> res = new HashMap<>();
        JAVATools.writelog("差旅报销流程表名: @" + main + "@");
        JAVATools.writelog("差旅报销预算表名: @" + budgetKmTable + "@");
        RecordSet rs = new RecordSet();
        String mainInfo = budgetDao.mainInfo(main, requestMark);
        rs.executeQuery(mainInfo);
        List<Object> mainValues = new ArrayList<>();
        String mainId = ""; //主副表关联id
        if (rs.next()) {
            mainValues.add(requestMark);//FNAME 流程编码
            mainValues.add(Util.null2String(rs.getString("REQUESTNAME"))); //流程名 FBILLTITLE
            mainValues.add(Util.null2String(rs.getString("LASTNAME"))); //拟稿人名称 FPESONNAME
            mainId = Util.null2String(rs.getString("ID"));
        }
        JAVATools.writelog("主表数据: @" + mainValues + "@");
        res.put("main", mainValues);
        String budgetKmTableInfo = "select fysjcdbm,yskmid,bhsje,sj,jshjje,sl,cys,slz,fycdbmfzr,yskm from "+budgetKmTable+" where mainid = "+mainId;
        DepartmentComInfo dc = new DepartmentComInfo();
        rs.execute(budgetKmTableInfo);
        List<List<Object>> allDtValues = new ArrayList<>(); //所有明细科目数据 add dtValues 单行明细科目数据
        while (rs.next()) {
            String yskm = Util.null2String(rs.getString("YSKM")); //科目
            String fycdbmfzr = Util.null2String(rs.getString("fycdbmfzr")); //费用承担部门负责人
            String fysjcdbm = Util.null2String(rs.getString("fysjcdbm")); //费用承担部门
            String JSHJJE = Util.null2String(rs.getString("jshjje"));//价税合计金额
            String BHSJE = Util.null2String(rs.getString("bhsje"));//不含税金额
            String SJ = Util.null2String(rs.getString("sj"));//税金
            String CYS = Util.null2String(rs.getString("CYS"));//超预算
            String sl = Util.null2String(rs.getString("sl"));//税率
            List<Object> dtValues = new ArrayList<>(); //单行明细科目数据
            dtValues.add(yskm);//FITEMDETAILNUM
            dtValues.add(PayUtil.superBudgetSubject(yskm)); //一级预算科目 FCOSTITEMNUM
            if ("".equals(JSHJJE)) {
                dtValues.add(0.00); // 价税合计金额 FSJAMOUNT
            } else {
                dtValues.add(Double.parseDouble(JSHJJE)); // 价税合计金额 FSJAMOUNT
            }
            if ("".equals(BHSJE)) {
                dtValues.add(0.00); // 未税金额 FNOTAXAMOUNT
            } else {
                dtValues.add(Double.parseDouble(BHSJE)); // 未税金额 FNOTAXAMOUNT
            }
            if ("".equals(SJ)) {
                dtValues.add(0.00); //FTAXAMOUNT
            } else {
                dtValues.add(Double.parseDouble(SJ)); //税金 FTAXAMOUNT
            }
            dtValues.add(0.00); // 实际报销金额 FACTUALAMOUNT
            dtValues.add(0.00); // 差旅标准金额 FSTANDARDAMOUNT
            dtValues.add(PayUtil.overWeight(CYS)); // 是否超标  FOVERWEIGHT
            dtValues.add("否");//ISITITEM
            dtValues.add(""); // it项目编码 ITITEMCODE
            dtValues.add(""); // it项目名称 ITITEMNAME
            dtValues.add(dc.getDepartmentCode(fysjcdbm));//FDEPTNUMBER 取明细实际费用承担部门
            allDtValues.add(dtValues);
        }
        JAVATools.writelog("预算表数据" + budgetKmTable + "  @" + allDtValues + "@");
        res.put("dt", allDtValues);
        return res;
    }

    @Override
    public JSONObject getSettlePaymentSplWeb(HashMap<String, String> reqMap) {
        String unnumbercode = reqMap.get("unnumbercode").toString();//cgscfyqr，采购商城费用确认，cgscjsfk 采购商城结算付款
        String fyly = Util.null2String(reqMap.get("fyly"));
//        String zfmxhj = Util.null2String(reqMap.get("zfmxhj"));
        String bmValue = Util.null2String(reqMap.get("bm"));
        String splb = Util.null2String(reqMap.get("splb"));
        List<String> bmIdList = Arrays.asList(bmValue.split(","));
        List<ZgsDept> newDepartList = new ArrayList<>();
        if(null!=bmIdList&&bmIdList.size()>0){
            for(String id:bmIdList){
                newDepartList.add(new ZgsDept(id));
            }
        }
        HashMap<String, String> mapDao = new HashMap<>();
        mapDao.put("sslc",unnumbercode);     //类型
        mapDao.put("fqbmlx",fyly);     //发起部门流程,区分总部还是分支
        List<UfCgspl> settlePaymentSplList = ufCgsplDao.getUfCgspl(mapDao);
        reqMap.put("fqbmlx",fyly);
        reqMap.put("sslc",unnumbercode);     //类型
        if ("1".equals(splb)){
            reqMap.put("mtrTypeId","1");     //办公品
            reqMap.put("C1018681","C1018681");
            reqMap.put("C1018682","C1018682");//耗材
        }
        if ("3".equals(splb)){
            reqMap.put("mtrTypeId","3");     //IT标准硬件
            reqMap.put("ITBZYJ","ITBZYJ");
            reqMap.put("C1018683","C1018683");//电子设备
        }
        if ("2".equals(splb)){
            reqMap.put("mtrTypeId","2");     //宣传品
            reqMap.put("C1018684","C1018684");
        }
        //条件过滤并赋值
        List<SettlePaymentSplVO> settlePaymentSplVOList = convertModelToVO(settlePaymentSplList,reqMap,newDepartList);
        //将settlePaymentSplVOList去重相加转换为map
        HashMap<String,String> mapRes = removeDuplicateCommon(settlePaymentSplVOList);
        JAVATools.writelog("审批链Id:"+ mapRes.get("id"));
        JAVATools.writelog("预算管理员审核:"+ mapRes.get("bmysglysh"));
        JAVATools.writelog("营业部负责人审核:"+ mapRes.get("yybfzrsh"));
        JAVATools.writelog("部门负责人审核:"+ mapRes.get("wzcggkbmfzr"));
        JAVATools.writelog("物资采购对接人员审核:"+ mapRes.get("wzcgdjrysh"));
        JAVATools.writelog("财务中心会计审核:"+ mapRes.get("cwzxjl"));
        JAVATools.writelog("分公司财务经理审核:"+ mapRes.get("fgscwjlsh"));
        JAVATools.writelog("分公司负责人审批:"+ mapRes.get("fgsfzrsh"));
        JAVATools.writelog("分管领导审核:"+ mapRes.get("fgldsh"));
        JAVATools.writelog("分公司财务经理办结:"+ mapRes.get("fgscwjlbj"));
        JAVATools.writelog("总裁审批:"+ mapRes.get("zc"));
        JAVATools.writelog("预算管理员终审:"+ mapRes.get("ysglyzs"));
        JAVATools.writelog("费用会计审核:"+ mapRes.get("fyhj"));
        JAVATools.writelog("财务负责人审核:"+ mapRes.get("cwfzrsp"));
        JAVATools.writelog("财务总监审核:"+ mapRes.get("cwzj"));
        JAVATools.writelog("出纳:"+ mapRes.get("cn"));
        JAVATools.writelog("商城管理员审核:"+ mapRes.get("ysglycs"));
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(mapRes);
        return jsonObject;
    }


    @Override
    public Map<String, String> doBudgetByBatchIdZb(String ids, String isDiscard) throws Exception {
        Assert.notBlank(ids, "同步预算数据id为空");
        Assert.notBlank(isDiscard, "同步预算状态为空");

        RecordSet rs = new RecordSet();
        rs.writeLog(String.format("同步预算数据，ids: %s; discard:%s, (-1为废弃)", ids, isDiscard));

        BranchBizUtil biz = new BranchBizUtil();
        List<UfCash> ufCashList = getUfCashList(ids, "UF_ZBFK");

        Map<String, String> resp = new HashMap<>();
        for (UfCash uf : ufCashList) {
            SettlePaymentCommand command = new SettlePaymentCommand();
            try {
                String finish = "";
                if ("1".equals(isDiscard)) {
                    finish = Objects.requireNonNull(command).finish(uf.getRid());
                    resp.put(uf.getrMark(), OperateMsg.BUDGET_SUCCESS.getMsg("返回值：" + finish));
                } else if ("-1".equals(isDiscard)) {
                    finish = Objects.requireNonNull(command).reject(uf.getRid());
                    resp.put(uf.getrMark(), OperateMsg.BUDGET_CANCEL_SUCCESS.getMsg("返回值：" + finish));
                    //废弃后更新发票关联关系: uf_pjxxgl 浪潮
                    BizUtils bizUtils = new BizUtils();
                    bizUtils.cancelInvLink(uf.getRid());
                }
                //更新预算状态
                if ("F1001".equalsIgnoreCase(finish)) {
                    biz.updateBudgetStatus(uf.getId(), isDiscard, "UF_ZBFK");
                }
            } catch (Exception e) {
                rs.writeLog(e);
                resp.put(uf.getrMark(), OperateMsg.BUDGET_FAIL.getMsg("异常消息：" + e.getMessage()));
            }

        }
        return resp;
    }



    @Override
    public Map<String, String> doAccountByBatchIdZb(String ids) throws Exception {
        Assert.notBlank(ids, "同步核算id为空");

        RecordSet rs = new RecordSet();
        HTUtil ht = new HTUtil();
        rs.writeLog(String.format("同步核算数据ids：%s", ids));

        BranchBizUtil biz = new BranchBizUtil();
        List<UfCash> ufCashList = biz.getUfCashList(ids, "UF_ZBFK");

        Map<String, String> resp = new HashMap<>();
        for (UfCash uf : ufCashList) {
            try {
                CostAccountDto costAccountDto = BranchCostDTOFactory.getSettlePaymentCostDTO(uf.getRid(), uf.getType());
                String costAccountDtoJsonStr = JSON.toJSONString(costAccountDto);
                @SuppressWarnings("unchecked")
                Map<String, Object> costDtoMap = JSONObject.parseObject(costAccountDtoJsonStr);
                rs.writeLog(String.format("核算入参，%s", costDtoMap));
                String response = ht.saveFydj(costDtoMap);
                if ("success".equalsIgnoreCase(response)) {
                    resp.put(uf.getrMark(), OperateMsg.ACCOUNTING_SUCCESS.getMsg());
                    //更新核算状态
                    biz.updateCostStatus(uf.getId(), uf.getRid(), "UF_ZBFK");
                } else {
                    resp.put(uf.getrMark(), OperateMsg.ACCOUNTING_FAIL.getMsg("返回值：" + response));
                }
            } catch (Exception e) {
                rs.writeLog(e);
                resp.put(uf.getrMark(), OperateMsg.ACCOUNTING_FAIL.getMsg("异常消息：" + e.getMessage()));
            }
        }
        return resp;
    }


    @Override
    public Map<String, String> doBudgetByBatchIdFzjg(String ids, String isDiscard) throws Exception {
        Assert.notBlank(ids, "同步预算数据id为空");
        Assert.notBlank(isDiscard, "同步预算状态为空");

        RecordSet rs = new RecordSet();
        rs.writeLog(String.format("同步预算数据，ids: %s; discard:%s, (-1为废弃)", ids, isDiscard));

        BranchBizUtil biz = new BranchBizUtil();
        List<UfCash> ufCashList = getUfCashList(ids, "UF_FZJGFK");

        Map<String, String> resp = new HashMap<>();
        for (UfCash uf : ufCashList) {
            SettlePaymentCommand command = new SettlePaymentCommand();
            try {
                String finish = "";
                if ("1".equals(isDiscard)) {
                    finish = Objects.requireNonNull(command).finish(uf.getRid());
                    resp.put(uf.getrMark(), OperateMsg.BUDGET_SUCCESS.getMsg("返回值：" + finish));
                } else if ("-1".equals(isDiscard)) {
                    finish = Objects.requireNonNull(command).reject(uf.getRid());
                    resp.put(uf.getrMark(), OperateMsg.BUDGET_CANCEL_SUCCESS.getMsg("返回值：" + finish));
                    //废弃后更新发票关联关系: uf_pjxxgl 浪潮
                    command.cancelInvLink(uf.getRid());
                }
                //更新预算状态
                if ("F1001".equalsIgnoreCase(finish)) {
                    biz.updateBudgetStatus(uf.getId(), isDiscard, "UF_FZJGFK");
                }
            } catch (Exception e) {
                rs.writeLog(e);
                resp.put(uf.getrMark(), OperateMsg.BUDGET_FAIL.getMsg("异常消息：" + e.getMessage()));
            }

        }
        return resp;
    }

    @Override
    public Map<String, String> doPaymentByBatchIdZb(String ids) throws Exception {
        Assert.notBlank(ids, "同步预算数据id为空");

        RecordSet rs = new RecordSet();
        rs.writeLog(String.format("同步付款数据， ids: %s", ids));

        BranchBizUtil biz = new BranchBizUtil();
        HTUtil ht = new HTUtil();
        List<UfCash> ufCashList = biz.getUfCashList(ids, "UF_ZBFK");

        Map<String, String> resp = new HashMap<>();
        for (UfCash cash : ufCashList) {
            //预算
            SettlePaymentCommand command = new SettlePaymentCommand();
            try {
                String finish = Objects.requireNonNull(command).finish(cash.getRid());

                resp.put(cash.getrMark(), OperateMsg.BUDGET_SUCCESS.getMsg("返回值：" + finish));
                //更新预算状态
                if ("F1001".equalsIgnoreCase(finish)) {
                    biz.updateBudgetStatus(cash.getId(), "1", "UF_ZBFK");
                }
            } catch (Exception e) {
                rs.writeLog(e);
                resp.put(cash.getrMark(), String.join(",",
                        OperateMsg.BUDGET_FAIL.getMsg("异常消息：" + e.getMessage()),
                        OperateMsg.PAY_FAIL.getMsg()));
                throw new Exception("预算执行失败，抛出异常：" + e.getMessage());
            }

            //核算
            try {
                CostAccountDto costAccountDto = BranchCostDTOFactory.getCostDTOByType(cash.getRid(), cash.getType());
                String costAccountDtoJsonStr = JSON.toJSONString(costAccountDto);
                @SuppressWarnings("unchecked")
                Map<String, Object> costDtoMap = JSONObject.parseObject(costAccountDtoJsonStr);
                rs.writeLog(String.format("核算入参，%s", costDtoMap));
                String response = ht.saveFydj(costDtoMap);
                if ("success".equalsIgnoreCase(response)) {
                    resp.put(cash.getrMark(), OperateMsg.PAY_SUCCESS.getMsg());
                    //更新核算状态
                    biz.updateCostStatus(cash.getId(), cash.getRid(), "UF_ZBFK");
                    //更新uf_ShoppingMalPool
                    String gllc = ufCgsplDao.getfkqr(cash.getRid());
                    Boolean flag = getUpdatePoolFlag(gllc,cash.getRid());
                    if(flag){
                        ufCgsplDao.updateShoppingMalPoolEnd(gllc);
                    }
                } else {
                    resp.put(cash.getrMark(), String.join(",", OperateMsg.BUDGET_SUCCESS.getMsg(),
                            OperateMsg.ACCOUNTING_FAIL.getMsg("返回值：" + response),
                            OperateMsg.PAY_FAIL.getMsg()));
                }
            } catch (Exception e) {
                rs.writeLog(e);
                resp.put(cash.getrMark(), String.join(",", OperateMsg.BUDGET_SUCCESS.getMsg(),
                        OperateMsg.ACCOUNTING_FAIL.getMsg("异常消息：" + e.getMessage()),
                        OperateMsg.PAY_FAIL.getMsg()));
            }

        }

        return resp;
    }

    public Boolean getUpdatePoolFlag(String gllc, String requestid) {
        Boolean flag = true;
        String mainTable = JAVATools.getMaintable(requestid);
        RecordSet rs = new RecordSet();
        List<String> ids = new ArrayList();
        String sql = "select requestid from " + mainTable + " where glfyqrlc = '"+gllc+"'";
        rs.execute(sql);
        while (rs.next()) {
            ids.add(Util.null2String(rs.getString("requestid")));
        }
        String idJoin = String.join("','", ids);
        String sqlFk = "select tbdlcyszt,tbdlczt,fkzt from UF_ZBFK where REQUTID in ('"+idJoin+"')";
        rs.execute(sqlFk);
        while (rs.next()) {
            if("1".equals(rs.getString("fkzt"))){
                flag = false;
            }
        }
        return flag;
    }

    @Override
    public Map<String, String> doPaymentByBatchIdFzjg(String ids) throws Exception {
        Assert.notBlank(ids, "同步预算数据id为空");

        RecordSet rs = new RecordSet();
        rs.writeLog(String.format("同步付款数据， ids: %s", ids));

        BranchBizUtil biz = new BranchBizUtil();
        HTUtil ht = new HTUtil();
        List<UfCash> ufCashList = biz.getUfCashList(ids, "UF_FZJGFK");

        Map<String, String> resp = new HashMap<>();
        for (UfCash cash : ufCashList) {
            //预算
            SettlePaymentCommand command = new SettlePaymentCommand();
            try {
                String finish = Objects.requireNonNull(command).finish(cash.getRid());

                resp.put(cash.getrMark(), OperateMsg.BUDGET_SUCCESS.getMsg("返回值：" + finish));
                //更新预算状态
                if ("F1001".equalsIgnoreCase(finish)) {
                    biz.updateBudgetStatus(cash.getId(), "1", "UF_ZBFK");
                }
            } catch (Exception e) {
                rs.writeLog(e);
                resp.put(cash.getrMark(), String.join(",",
                        OperateMsg.BUDGET_FAIL.getMsg("异常消息：" + e.getMessage()),
                        OperateMsg.PAY_FAIL.getMsg()));
                throw new Exception("预算执行失败，抛出异常：" + e.getMessage());
            }

            //核算
            try {
                CostAccountDto costAccountDto = BranchCostDTOFactory.getCostDTOByType(cash.getRid(), cash.getType());
                String costAccountDtoJsonStr = JSON.toJSONString(costAccountDto);
                @SuppressWarnings("unchecked")
                Map<String, Object> costDtoMap = JSONObject.parseObject(costAccountDtoJsonStr);
                rs.writeLog(String.format("核算入参，%s", costDtoMap));
                String response = ht.saveFydj(costDtoMap);
                if ("success".equalsIgnoreCase(response)) {
                    resp.put(cash.getrMark(), OperateMsg.PAY_SUCCESS.getMsg());
                    //更新核算状态
                    biz.updateCostStatus(cash.getId(), cash.getRid(), "UF_ZBFK");
                    //更新uf_ShoppingMalPool
                    String gllc = ufCgsplDao.getfkqr(cash.getRid());
                    ufCgsplDao.updateShoppingMalPoolEnd(gllc);
                } else {
                    resp.put(cash.getrMark(), String.join(",", OperateMsg.BUDGET_SUCCESS.getMsg(),
                            OperateMsg.ACCOUNTING_FAIL.getMsg("返回值：" + response),
                            OperateMsg.PAY_FAIL.getMsg()));
                }
            } catch (Exception e) {
                rs.writeLog(e);
                resp.put(cash.getrMark(), String.join(",", OperateMsg.BUDGET_SUCCESS.getMsg(),
                        OperateMsg.ACCOUNTING_FAIL.getMsg("异常消息：" + e.getMessage()),
                        OperateMsg.PAY_FAIL.getMsg()));
            }

        }

        return resp;
    }

    @Override
    public String updateManualPaymentStatusZb(String rids) {
        BranchBizUtil bizUtil = new BranchBizUtil();
        return bizUtil.updateManualPaymentStatus(rids, "UF_ZBFK");
    }

    @Override
    public String updateManualPaymentStatusFzjg(String rids) {
        BranchBizUtil bizUtil = new BranchBizUtil();
        return bizUtil.updateManualPaymentStatus(rids, "UF_FZJGFK");
    }


    @Override
    public Map<String, String> doAccountByBatchIdFzjg(String ids) throws Exception {
        Assert.notBlank(ids, "同步核算id为空");

        RecordSet rs = new RecordSet();
        HTUtil ht = new HTUtil();
        rs.writeLog(String.format("同步核算数据ids：%s", ids));

        BranchBizUtil biz = new BranchBizUtil();
        List<UfCash> ufCashList = biz.getUfCashList(ids, "UF_FZJGFK");

        Map<String, String> resp = new HashMap<>();
        for (UfCash uf : ufCashList) {
            try {
                CostAccountDto costAccountDto = BranchCostDTOFactory.getSettlePaymentCostDTO(uf.getRid(), uf.getType());
                String costAccountDtoJsonStr = JSON.toJSONString(costAccountDto);
                @SuppressWarnings("unchecked")
                Map<String, Object> costDtoMap = JSONObject.parseObject(costAccountDtoJsonStr);
                rs.writeLog(String.format("核算入参，%s", costDtoMap));
                String response = ht.saveFydj(costDtoMap);
                if ("success".equalsIgnoreCase(response)) {
                    resp.put(uf.getrMark(), OperateMsg.ACCOUNTING_SUCCESS.getMsg());
                    //更新核算状态
                    biz.updateCostStatus(uf.getId(), uf.getRid(), "UF_FZJGFK");
                } else {
                    resp.put(uf.getrMark(), OperateMsg.ACCOUNTING_FAIL.getMsg("返回值：" + response));
                }
            } catch (Exception e) {
                rs.writeLog(e);
                resp.put(uf.getrMark(), OperateMsg.ACCOUNTING_FAIL.getMsg("异常消息：" + e.getMessage()));
            }
        }
        return resp;
    }

    /**
     * 获取建模表里的数据
     */
    public List<UfCash> getUfCashList(String ids, String uf) {
        RecordSet rs = new RecordSet();
        String idJoin = String.join("','", Arrays.asList(ids.split(",")));
        rs.executeQuery("select ID,FKLX,REQUTID,LCBH from " + uf + " where REQUTID in ('" + idJoin + "')");
        List<UfCash> lists = new ArrayList<>();
        while (rs.next()) {
            UfCash ufCash = new UfCash();
            ufCash.setId(Util.null2String(rs.getString("ID")));
            ufCash.setType(Util.null2String(rs.getString("FKLX")));
            ufCash.setRid(Util.null2String(rs.getString("REQUTID")));
            ufCash.setrMark(Util.null2String(rs.getString("LCBH")));
            lists.add(ufCash);
        }
        return lists;
    }


    //对接xp系统，调用updatepayStatus接口
    public String updatepayStatus(String fyqr, String jsfk ,String htPayStatus){
        String result = "";
        try {
            PropBean pp = new PropBean();
            if ("".equals(fyqr)){
                fyqr = ufCgsplDao.getfkqr(jsfk);
            }
            List<MallPayBizModel> mallPayBizNo = ufCgsplDao.getJsfk(fyqr,jsfk);
            String requestUrl = pp.getPropName("updatepayStatusUrl");
            MallUpdatePayStatusRequest mallUpdatePayStatusRequest = new MallUpdatePayStatusRequest();
            mallUpdatePayStatusRequest.setMallConfirmBizNo(ufCgsplDao.getLcbh(fyqr));
            mallUpdatePayStatusRequest.setMallPayBizModelList(mallPayBizNo);
            mallUpdatePayStatusRequest.setHtPayStatus(htPayStatus);
            HTUtil htUtil = new HTUtil();
            Map<String, String> appHeader = htUtil.getUserHeader(pp.getPropName("ZBKJJL"));
            JAVATools.writelog("getAppHeader@" + appHeader + "@");
            JAVATools.writelog("mallUpdatePayStatusRequest@" + JSON.toJSONString(mallUpdatePayStatusRequest) + "@");
            //新增token校验
            String resp = HttpUtil.postApplicationJson(requestUrl, JSON.toJSONString(mallUpdatePayStatusRequest), appHeader);
            Map<String,String> resultMap = JSON.parseObject(resp, HashMap.class);
            result = Util.null2String(resultMap.get("data"));
            JAVATools.writelog("updatepayStatus>>接口调用返回 resp : @" + resp + "@");
        } catch (Exception e) {
            JAVATools.writelog("updatepayStatus接口返回异常：" + e);
            e.printStackTrace();
        }
        return result;
    }

}
