package com.sifang.modules.flowable.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.account.dao.CrmTraderSupportSettleDetailsDao;
import com.sifang.modules.account.dao.TraderAccountDao;
import com.sifang.modules.account.entity.CrmTraderAccount;
import com.sifang.modules.account.entity.CrmTraderAccountSettleDetail;
import com.sifang.modules.account.entity.CrmTraderSupportSettleDetails;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.flowpath.constant.BondApplyConstant;
import com.sifang.modules.flowpath.dao.*;
import com.sifang.modules.flowpath.entity.*;
import com.sifang.modules.flowpath.service.SupplyWarehouseApplyService;
import com.sifang.modules.flowpath.vo.TaskVo;
import com.sifang.modules.kingdee.service.KingDeePayableService;
import com.sifang.modules.kingdee.service.PurchaseService;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.q7link.entity.WuziOrder;
import com.sifang.modules.q7link.utils.OpenapiTemplate;
import com.sifang.modules.sunshine.SystemSetting.dao.TraderDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmSubconractorSettlementSchemeApply;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.order.constant.DeliverOrderConstants;
import com.sifang.modules.supply.order.dao.SupplyOrderAuditDao;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.supply.order.service.CrmSupplyMaterialDeliverOrderService;
import com.sifang.modules.supply.order.vo.OrderTbQqVO;
import com.sifang.modules.supply.setting.service.CrmSupplySupplierService;
import com.sifang.modules.supply.setting.service.CrmSupplyWarehouseSettingService;
import com.sifang.modules.supply.warehouse.dao.CrmFittingStockUpApplyDao;
import com.sifang.modules.supply.warehouse.entity.CrmFittingStockUpApply;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyAllocationOrder;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyInventoryOrder;
import com.sifang.modules.supply.warehouse.service.CrmSupplyAllocationOrderService;
import com.sifang.modules.supply.warehouse.service.InventoryOrderService;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.util.CrmUtils;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class ApplicationDetailService extends BaseService {
    @Autowired
    public TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ExamineInfoDao examineInfoDao;

    @Autowired
    private DistributionGoodsApplyDao goodsApplyDao;

    @Autowired
    private WarrantyDepositAdjustmentApplyDao adjustmentApplyDao;

    @Autowired
    private TraderApplyDao traderApplyDao;
    @Autowired
    private TraderApplyAgentDao agentDao;

    @Autowired
    private SupplySupplierApplyDao supplierApplyDao;

    @Autowired
    private BondApplyDao bondApplyDao;

    @Autowired
    private SubpackageStandardPriceApplyDao standardPriceApplyDao;

    @Autowired
    private SettlementAmountAdjustmentApplyDao settlementAmountAdjustmentApplyDao;

    @Autowired
    private TraderAccountDao accountDao;

    @Autowired
    private TraderService traderService;

    @Autowired
    private CrmSupplySupplierService supplySupplierService;

    @Autowired
    private InventoryOrderService inventoryOrderService;

    @Autowired
    private SupplyOrderAuditDao supplyOrderDao;

    @Autowired
    CrmSupplyAllocationOrderService allocationOrderService;

    @Autowired
    SupplyWarehouseApplyService warehouseApplyService;

    @Autowired
    CrmSupplyWarehouseSettingService crmSupplyWarehouseSettingService;

    @Autowired
    private TraderDao traderDao;

    @Autowired
    private CashOutApplyDao cashOutApplyDao;

    @Autowired
    PurchaseService purchaseService;

    @Autowired
    KingDeePayableService payableService;

    @Autowired
    private PriceCoefficientApplyDao priceCoefficientApplyDao;

    @Autowired
    private CrmFittingStockUpApplyDao fittingStockUpApplyDao;

    @Autowired
    private BondLimitApplyDao bondLimitApplyDao;
    @Autowired
    private CrmTraderSupportSettleDetailsDao settledetailsDao;

    @Autowired
    private ProcessFlowableService flowableService;

    @Resource
    private CrmSupplyMaterialDeliverOrderService crmSupplyMaterialDeliverOrderService;

    public void createTaskChangeTaskName(String applicationId,String formId,String taskName,String userId,String processInstanceId){
        logger.info(">>>>>>>>>>>>>>>>>createTaskChangeTaskName>>>>formId:{},applicationId:{},taskName{}",formId,applicationId,taskName);
        try{
            logger.info(">>>>>>>>>>>>>>>>>createTaskChangeTaskName");
            if(FormUtils.DISTRIBUTION_ADJUSTMENT_APPLICATION.equals(formId)){    //授信额调整申请
                DistributionGoodsApply apply=goodsApplyDao.getByApplyId(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    goodsApplyDao.save(apply);
                }
            }else if(FormUtils.WITHDRAWAL_WARRANTY_APPLICATION.equals(formId)){    //质保金请款申请
                logger.info(">>>>>>>>>>>>>>>>>createTaskChangeTaskName>>>>05,{}",1);
                WarrantyDepositAdjustmentApply apply=adjustmentApplyDao.getByApplyId(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    adjustmentApplyDao.save(apply);
                }
            }else if(FormUtils.AGENT_ADMISSION_APPLICATION.equals(formId)){   //代理商准入申请
                TraderApply apply = traderApplyDao.get(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    traderApplyDao.save(apply);
                }
            }else if(FormUtils.SUPPLIER_ADMISSION_APPLICATION.equals(formId)){   //供应商准入申请
                SupplySupplierApply apply = supplierApplyDao.get(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    supplierApplyDao.save(apply);
                }
            }else if(FormUtils.MARGIN_ADJUSTMENT_APPLICATION.equals(formId)){  // 保证金调整申请
                BondApply apply=bondApplyDao.getByApplyId(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    bondApplyDao.save(apply);
                }
            }else if(FormUtils.SUBCONTRACTING_STANDARD_PRICE_APPLICATION.equals(formId)){  //分包保准价申请
                CrmSubconractorSettlementSchemeApply apply=standardPriceApplyDao.getByApplyId(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    standardPriceApplyDao.save(apply);
                }
            }else if(FormUtils.SETTLE_AMOUNT_ADJUST_APPLICATION.equals(formId)){   //结算额调整申请
                SettlementAmountAdjustmentApply apply=settlementAmountAdjustmentApplyDao.getByApplyId(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    settlementAmountAdjustmentApplyDao.save(apply);
                }
            }else if(FormUtils.SUPPLY_ORDER_APPLICATION.equals(formId)){  //订单审批
                CrmSupplyMaterialDeliverOrder apply=supplyOrderDao.get(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    supplyOrderDao.save(apply);
                }
            }else if(FormUtils.PURCHASE_ORDER_APPLICATION.equals(formId)){  //采购申请
                CrmSupplyMaterialDeliverOrder apply=supplyOrderDao.get(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    supplyOrderDao.save(apply);
                }
            }else if(FormUtils.INVEBNTORY_ORDER_APPLICATION.equals(formId)){   //盘点单申请
                CrmSupplyInventoryOrder apply= inventoryOrderService.getByid(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    inventoryOrderService.save(apply);
                }
            }else if(FormUtils.TRANSFER_ORDER_APPLICATION.equals(formId)){   //调拨申请
                CrmSupplyAllocationOrder apply=allocationOrderService.getById(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    allocationOrderService.saveOrder(apply);
                }
            }else if(FormUtils.CASH_OUT_APPLY.equals(formId)){  //请款申请
                CashOutApply apply=cashOutApplyDao.getByApplyId(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    cashOutApplyDao.save(apply);
                }
            }else if(FormUtils.WAREHOUSE_APPLY.equals(formId)){   //仓库申请
                SupplyWarehouseApply apply = warehouseApplyService.get(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    warehouseApplyService.save(apply);
                }
            } else if(FormUtils.PRICE_COEFFICIENT_APPLY.equals(formId)){    //零售价系数申请
                PriceCoefficientApply apply=priceCoefficientApplyDao.getByApplyId(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    priceCoefficientApplyDao.save(apply);
                }
            } else if(FormUtils.STOCK_UP_APPLY.equals(formId)){    //备货申请流程
                CrmFittingStockUpApply apply=fittingStockUpApplyDao.getByApplyId(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    fittingStockUpApplyDao.save(apply);
                }
            }else if(FormUtils.BOND_LIMIT_APPLY.equals(formId)){    //保证金额度
                BondLimitApply apply= bondLimitApplyDao.getByApplyId(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    bondLimitApplyDao.save(apply);
                }
            }else if(FormUtils.BRACKET_ORDER_APPLY.equals(formId)){  //支架订单审批
                CrmSupplyMaterialDeliverOrder apply=supplyOrderDao.get(applicationId);
                if(apply!=null){
                    apply.setTaskName(taskName);
                    apply.setOperateUserIds(apply.getOperateUserIds()+","+userId);
                    supplyOrderDao.save(apply);
                }
            }
        }catch (Exception e){
            logger.error(">>>>>>>>>>>驳回到提交节点 后执行错误 editApplyStatus  Exeception:{}",e);
            e.printStackTrace();
        }
        Db.update(" UPDATE `crm_item_manage` SET  current_task_name=? WHERE process_instance_id=? ",taskName,processInstanceId);
    }

    //驳回到提交节点
    @Transactional(rollbackFor = Exception.class)
    public void editApplyStatus(String processInstanceId){
        String applicationId = (String)runtimeService.getVariable(processInstanceId, "applicationId");
        Object formId = runtimeService.getVariable(processInstanceId, "formId");
        logger.info("editApplyStatus-----{applicationId}:----- "+applicationId+"---------{formId}-----------"+formId);
        try{
            if(FormUtils.DISTRIBUTION_ADJUSTMENT_APPLICATION.equals(formId)){    //授信额调整申请
                DistributionGoodsApply apply=goodsApplyDao.getByApplyId(applicationId);
                apply.setTaskName("审核不通过");
                apply.setStatus(BondApplyConstant.APPLYSTATUS_ZERO);
                goodsApplyDao.save(apply);
            }else if(FormUtils.WITHDRAWAL_WARRANTY_APPLICATION.equals(formId)){    //质保金请款申请
                WarrantyDepositAdjustmentApply apply=adjustmentApplyDao.getByApplyId(applicationId);
                apply.setTaskName("审核不通过");
                apply.setStatus(BondApplyConstant.APPLYSTATUS_ZERO);
                adjustmentApplyDao.save(apply);
            }else if(FormUtils.AGENT_ADMISSION_APPLICATION.equals(formId)){   //代理商准入申请
                TraderApply apply = traderApplyDao.get(applicationId);
                apply.setTaskName("审核不通过");
                apply.setStatus(BondApplyConstant.APPLYSTATUS_TWO);
                traderApplyDao.save(apply);
            }else if(FormUtils.SUPPLIER_ADMISSION_APPLICATION.equals(formId)){   //供应商准入申请
                SupplySupplierApply apply = supplierApplyDao.get(applicationId);
                apply.setTaskName("审核不通过");
                apply.setStatus(BondApplyConstant.APPLYSTATUS_ZERO);
                supplierApplyDao.save(apply);
            }else if(FormUtils.MARGIN_ADJUSTMENT_APPLICATION.equals(formId)){  // 保证金调整申请
                BondApply apply= bondApplyDao.getByApplyId(applicationId);
                apply.setTaskName("审核不通过");
                apply.setStatus(BondApplyConstant.APPLYSTATUS_ZERO);
                bondApplyDao.save(apply);
            }else if(FormUtils.SUBCONTRACTING_STANDARD_PRICE_APPLICATION.equals(formId)){  //分包保准价申请
                CrmSubconractorSettlementSchemeApply apply= standardPriceApplyDao.getByApplyId(applicationId);
                apply.setTaskName("审核不通过");
                apply.setStatus(BondApplyConstant.APPLYSTATUS_ZERO);
                standardPriceApplyDao.save(apply);
            }else if(FormUtils.SETTLE_AMOUNT_ADJUST_APPLICATION.equals(formId)){   //结算额调整申请
                SettlementAmountAdjustmentApply apply= settlementAmountAdjustmentApplyDao.getByApplyId(applicationId);
                apply.setTaskName("审核不通过");
                apply.setStatus(BondApplyConstant.APPLYSTATUS_ZERO);
                settlementAmountAdjustmentApplyDao.save(apply);
            }else if(FormUtils.SUPPLY_ORDER_APPLICATION.equals(formId)){  //赊销下单订单审批
                CrmSupplyMaterialDeliverOrder order=supplyOrderDao.get(applicationId);
               /* //根据任务名称获取是几级审批
                Integer sort=FormUtils.getProcessSort(order.getProcessDefId(),order.getTaskName());
                if(sort!=null && sort==1){
                    order.setStatus(DeliverOrderConstants.STATUS_DELETED);
                }*/
                order.setProcessInstanceId("");
                order.setOrderExamineStatus(BondApplyConstant.APPLYSTATUS_ZERO);
                order.setTaskName("审核不通过");
                supplyOrderDao.save(order);
                //删除流程
                flowableService.deleteApplication2(order.getId(),order.getProcessInstanceId(),"","2",FormUtils.SUPPLY_ORDER_APPLICATION,"驳回到可编辑状态");
               /* supplyOrderDao.changeDetailStatus(applicationId);*/
            }else if(FormUtils.PURCHASE_ORDER_APPLICATION.equals(formId)){
                CrmSupplyMaterialDeliverOrder order=supplyOrderDao.get(applicationId);
                logger.info(">>>>>>>>>>>>>>editApplyStatus  order:{}",order.getId());
                if(DeliverOrderConstants.PATTERN_SUPPLY.equals(order.getPattern())){
                    order.setStatus(DeliverOrderConstants.STATUS_PROCUREMENT_ALLOCATION);//采购分配
                }else if(DeliverOrderConstants.PATTERN_PLAT_PURCHASE.equals(order.getPattern())){
                    order.setPurchaseOrderExamineStatus(BondApplyConstant.APPLYSTATUS_ZERO); //编辑
                    order.setTaskName("审核不通过");
                    supplyOrderDao.save(order);
                }
                supplyOrderDao.save(order);
            }else if(FormUtils.INVEBNTORY_ORDER_APPLICATION.equals(formId)){   //盘点单申请
                CrmSupplyInventoryOrder order = inventoryOrderService.getByid(applicationId);
                order.setTaskName("审核不通过");
                order.setStatus(BondApplyConstant.APPLYSTATUS_ZERO);
                inventoryOrderService.save(order);
            }else if(FormUtils.TRANSFER_ORDER_APPLICATION.equals(formId)){   //调拨申请
                CrmSupplyAllocationOrder order = allocationOrderService.getById(applicationId);
                order.setTaskName("审核不通过");
                order.setOrderStatus(BondApplyConstant.APPLYSTATUS_FOUR);
                order.setStatus(BondApplyConstant.APPLYSTATUS_ZERO);
                allocationOrderService.saveOrder(order);
            }else if(FormUtils.CASH_OUT_APPLY.equals(formId)){  //请款申请
                logger.info(">>>>>>>>>>>editApplyStatus endProcess");
                CashOutApply cashOutApply=cashOutApplyDao.getByApplyId(applicationId);
                cashOutApply.setTaskName("审核不通过");
                cashOutApply.setStatus(BondApplyConstant.APPLYSTATUS_ZERO);

                //将结算明细里面状态改成未请款,将结算额调整 扣款的记录 改成未抵消
               /* cashOutApplyDao.updateSettleStatus(cashOutApply.getSettleIds(),"0");
                cashOutApplyDao.updateSettleApplyStatus(cashOutApply.getAdjustmentApplyIds(),"0");*/
                cashOutApplyDao.save(cashOutApply);
            }else if(FormUtils.WAREHOUSE_APPLY.equals(formId)){   //仓库申请
                SupplyWarehouseApply apply = warehouseApplyService.get(applicationId);

                apply.setTaskName("审核不通过");
                apply.setStatus(BondApplyConstant.APPLYSTATUS_ZERO);
                warehouseApplyService.save(apply);
            } else if(FormUtils.PRICE_COEFFICIENT_APPLY.equals(formId)){    //零售价系数申请
                PriceCoefficientApply apply=priceCoefficientApplyDao.getByApplyId(applicationId);
                apply.setTaskName("审核不通过");
                apply.setStatus(BondApplyConstant.APPLYSTATUS_ZERO);
                priceCoefficientApplyDao.save(apply);
            } else if(FormUtils.STOCK_UP_APPLY.equals(formId)){    //备货申请流程
                CrmFittingStockUpApply apply=fittingStockUpApplyDao.getByApplyId(applicationId);
                apply.setTaskName("审核不通过");
                apply.setStatus(BondApplyConstant.APPLYSTATUS_TWO);
                fittingStockUpApplyDao.save(apply);
            }else if(FormUtils.BOND_LIMIT_APPLY.equals(formId)){   //保证金额度
                BondLimitApply apply= bondLimitApplyDao.getByApplyId(applicationId);
                apply.setTaskName("审核不通过");
                apply.setStatus(BondApplyConstant.APPLYSTATUS_ZERO);
                bondLimitApplyDao.save(apply);
            }else if(FormUtils.BRACKET_ORDER_APPLY.equals(formId)){  //支架订单审批
                CrmSupplyMaterialDeliverOrder order=supplyOrderDao.get(applicationId);
                //根据任务名称获取是几级审批
//                Integer sort=FormUtils.getProcessSort(order.getProcessDefId(),order.getTaskName());
//                if(sort!=null && sort==1){
//                    order.setStatus(DeliverOrderConstants.STATUS_DELETED);
//                }
                order.setProcessInstanceId("");
                order.setOrderExamineStatus(BondApplyConstant.APPLYSTATUS_ZERO);
                order.setTaskName("审核不通过");
                supplyOrderDao.save(order);
                //删除流程
                flowableService.deleteApplication2(order.getId(),order.getProcessInstanceId(),"","2",FormUtils.BRACKET_ORDER_APPLY,"驳回到可编辑状态");
                /* supplyOrderDao.changeDetailStatus(applicationId);*/
            }
        }catch (Exception e){
            logger.error(">>>>>>>>>>>驳回到提交节点 后执行错误 editApplyStatus  Exeception:{}",e);
            e.printStackTrace();
        }
        Db.update(" UPDATE `crm_item_manage` SET  current_task_name=? WHERE process_instance_id=? ","驳回至提交节点",processInstanceId);
    }

    /**
     * 现有库存量     代理商的实时库存总额   A
     * 安装未验收    安装验收下对应电站的物料  B
     * 并网未验收    电站并网、上传合同、合同签署、并网验收下的物料  C
     * 未入库订单    平台端代理商订单下待审批、待匹配、待发货订单以及代理商端待收货订单的物料汇总  D
     * 退货未入库    发起电站的退货，尚未入库的物料汇总  E
     *
     *
     * 授信额增额    申请给代理商的授信额增额
     * 授信额减额    申请给代理商的授信额减额
     * 说明:
     * 1、标准授信额: 保证金 *系数+增+减额
     * 2、可授信额上限: 保证金*系数+增额+减额
     * 3、标准授信额余额=标准授信额-A-B-D-E
     * 4、可授信额上限余额=可授信额上限-A-B-C-D-E
     */
    @Transactional(rollbackFor = Exception.class)
    public void endProcess(String processInstanceId){
        String applicationId = (String)runtimeService.getVariable(processInstanceId, "applicationId");
        String formId = (String)runtimeService.getVariable(processInstanceId, "formId");
        logger.info("endProcess-----{applicationId}:----- "+applicationId+"---------{formId}-----------"+formId);
        User currentUser = UserUtils.getUser();
        String userName= CrmUtils.getUserXM(currentUser);
        String ccUserId="";
        Date date=new Date();
        try{
            if(FormUtils.DISTRIBUTION_ADJUSTMENT_APPLICATION.equals(formId)){    //授信额调整申请
                DistributionGoodsApply apply=goodsApplyDao.getByApplyId(applicationId);
                apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
                apply.setFinishTime(date);
                apply.setTaskName("已完成");
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(apply.getProcessDefId());
                apply.setOperateUserIds(apply.getOperateUserIds()+","+ccUserId);
                goodsApplyDao.save(apply);

                //修改账户金额
                CrmTraderAccount account= accountDao.getAccountByTraderId(apply.getTraderId());
                logger.info(">>>>>>>>>>>>>>>endProcess 04 account:{},{},{},{},{},{},{}:",account,account.getBasicQuotaAmount(),account.getBasicQuotaAmountBzj()
                        ,account.getBasicQuotaAmountBalance(),account.getMaxQuotaAmount(),account.getMaxQuotaAmountBzj(),account.getMaxQuotaAmountBalance());
                String adjustType=apply.getAdjustType(); // 调整类型 1.增额 2.减额  (增额（加法）、减额（减法))
                BigDecimal adjustAmount=apply.getAmount();  //调整的授信额
                if(StringUtil.equalsAny(adjustType,BondApplyConstant.KJ)){
                    adjustAmount=BigDecimal.ZERO.subtract(adjustAmount);
                }
                logger.info(">>>>>>>>>>>>>>>endProcess 04 adjustAmount:{}",adjustAmount);
                account.setBasicQuotaAmount(account.getBasicQuotaAmount().add(adjustAmount)); //标准授信额 -总额
                account.setBasicQuotaAmountBzj(account.getMaxQuotaAmountBzj().add(adjustAmount));   //标准授信额 -保证金计算的金额
                account.setBasicQuotaAmountBalance(account.getBasicQuotaAmountBalance().add(adjustAmount)); //标准授信额 -余额

                account.setMaxQuotaAmount(account.getMaxQuotaAmount().add(adjustAmount));   //可授信额上限
                account.setMaxQuotaAmountBzj(account.getMaxQuotaAmountBzj().add(adjustAmount));  // 可授信额上限 -保证金计算的金额
                account.setMaxQuotaAmountBalance(account.getMaxQuotaAmountBalance().add(adjustAmount));   //可授信额上限 -余额

                logger.info(">>>>>>>>>>>>>>>endProcess_end 04 account:{},{},{},{},{},{},{}:",account,account.getBasicQuotaAmount(),account.getBasicQuotaAmountBzj()
                        ,account.getBasicQuotaAmountBalance(),account.getMaxQuotaAmount(),account.getMaxQuotaAmountBzj(),account.getMaxQuotaAmountBalance());
                accountDao.save(account);

            }else if(FormUtils.WITHDRAWAL_WARRANTY_APPLICATION.equals(formId)){    //质保金调整申请
                WarrantyDepositAdjustmentApply apply=adjustmentApplyDao.getByApplyId(applicationId);
                apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
                apply.setFinishTime(date);
                apply.setTaskName("已完成");
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(apply.getProcessDefId());
                apply.setOperateUserIds(apply.getOperateUserIds()+","+ccUserId);
                adjustmentApplyDao.save(apply);
                //修改账户金额
                CrmTraderAccount account= accountDao.getAccountByTraderId(apply.getTraderId());
                logger.info(">>>>>>>>>>>>>>endProcess ---05   account:{},{},{},{}",account,account.getQaAmount(),account.getQaAmountUsable(),account.getQaAmountIncdec());
                String adjustType=apply.getAdjustType(); // 调整类型 1.请款 2.扣减  (请款（减法）、扣减（减法）)
                BigDecimal adjustAmount=apply.getAmount();  //调整的质保金金额
                if(StringUtil.equalsAny(adjustType,BondApplyConstant.KJ)){
                    adjustAmount=BigDecimal.ZERO.subtract(adjustAmount);
                }
                logger.info(">>>>>>>>>>>>>>>endProcess 05 adjustAmount:{}",adjustAmount);
                 account.setQaAmount(account.getQaAmount().add(adjustAmount));
                 account.setQaAmountUsable(account.getQaAmountUsable().add(adjustAmount));
                 account.setQaAmountIncdec(account.getQaAmountIncdec().add(adjustAmount));
                logger.info(">>>>>>>>>>>>>>endProcess_end ---05   account:{},{},{},{}",account,account.getQaAmount(),account.getQaAmountUsable(),account.getQaAmountIncdec());
                 accountDao.save(account);
            }else if(FormUtils.AGENT_ADMISSION_APPLICATION.equals(formId)){   //代理商准入申请
                TraderApply apply = traderApplyDao.get(applicationId);
                apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
                apply.setTaskName("已完成");
                String qqCompanyCode = null; // 为null 表示需要生成企企客户信息，为''表示不处理，为有效值表示需要同步企企修改客户名称
                CrmTrader oldData;
                String flag = "1"; // 用于标记 是否同步企企，1.同步 2.不同步
                // 新增代理商时，需要同步到企企 生成客户信息
                // 修改代理商信息 需要获取企企的客户编码 用户同步最新的代理商名称至企企
                if (StringUtil.isNotBlank(apply.getTraderId())) {
                    qqCompanyCode = "";
                    oldData = traderDao.get(apply.getTraderId());
                    if (oldData != null) {
                        if(!oldData.getName().equals(apply.getName())){
                            Db.update(" update crm_customer_entry set create_trader_name = ? where create_trader_id = ? ",apply.getName(),apply.getTraderId());
                            Db.update(" update crm_customer_entry set trader_name = ? where distributor_id = ? ",apply.getName(),apply.getTraderId());
                        }
                        if (oldData.getName().equals(apply.getName())) {
                            // 未修改代理商名称 则不需要同步企企系统
                            flag = "2";
                        }
                        if (StringUtil.isNotBlank(oldData.getQqCompanyCode())) {
                            qqCompanyCode = oldData.getQqCompanyCode();
                        }
                    }
                }
                //添加trader 和user 表数据
                String traderId = traderService.addTraderByApply(apply);
                apply.setTraderId(traderId);
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(apply.getProcessDefId());
                apply.setOperateUserIds(apply.getOperateUserIds()+","+ccUserId);
                traderApplyDao.save(apply);
                agentDao.updateTraderId(traderId,applicationId);

                if(!"2".equals(flag)){
                    if(qqCompanyCode == null){
                        qqCompanyCode = OpenapiTemplate.addTradeToQQ(apply.getName(), traderId);
                        CrmTrader trader = traderDao.get(traderId);
                        trader.setQqCompanyCode(qqCompanyCode);
                        traderDao.save(trader);
                    }else if (StringUtil.isNotBlank(qqCompanyCode)){
                        logger.info("开始修改供应商名称-------");
                        OpenapiTemplate.updateTradeToQQ(apply.getName(),qqCompanyCode);
                    }
                }

                //TODO 用于系统验收
              /*  CrmTrader trader = traderDao.get(apply.getTraderId());
                trader.setContractSigning("1");
                traderDao.save(trader);*/
              //  Db.update("UPDATE `sys_user` SET status='0' WHERE id=?",trader.getUserId());

            }else if(FormUtils.SUPPLIER_ADMISSION_APPLICATION.equals(formId)){   //供应商准入申请
                SupplySupplierApply apply = supplierApplyDao.get(applicationId);
                apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
                apply.setTaskName("已完成");
                String supplierId = supplySupplierService.addSupplierByApply(apply);
                apply.setSupplierId(supplierId);
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(apply.getProcessDefId());
                apply.setOperateUserIds(apply.getOperateUserIds()+","+ccUserId);
                supplierApplyDao.save(apply);
            }else if(FormUtils.MARGIN_ADJUSTMENT_APPLICATION.equals(formId)){   // 保证金调整申请
                BondApply apply= bondApplyDao.getByApplyId(applicationId);
                apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
                apply.setFinishTime(date);
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(apply.getProcessDefId());
                apply.setOperateUserIds(apply.getOperateUserIds()+","+ccUserId);
                apply.setTaskName("已完成");


                //修改账户金额
                CrmTraderAccount account= accountDao.getAccountByTraderId(apply.getTraderId());

                String adjustType=apply.getAdjustType(); // 调整类型 1.打款 2.扣除 3.退还  (打款（加法）、扣减（减法）、退还（加法）；)
                BigDecimal amount=apply.getAmount();  //调整的保证金
                if(StringUtil.equalsAny(adjustType,BondApplyConstant.KJ)){
                    amount=BigDecimal.ZERO.subtract(amount);
                }
               /* Record phe=accountDao.getXsByTraderVsAccount(apply.getTraderId(),"1"); //获取标准授信额的 系数
                if(phe==null){
                    throw new RuntimeException("请先设置标准授信额系数");
                }
                logger.info(">>>>>>>>>>>>>>>>>>endProcess  xs:{}",phe.toString());
                BigDecimal xs1=phe.getBigDecimal("amount");
                BigDecimal adjustAmount1=amount.multiply(xs1);   // 调整的 保证金*系数
                logger.info(">>>>>>>>>>>>>>endProcess1 ---03   account:{},{},{},{},{},{}",account,account.getBzjAmount(),account.getBasicQuotaAmount(),
                        account.getBasicQuotaAmountBalance(),account.getBasicQuotaAmountBzj(),adjustAmount1);*/
                account.setBzjAmount(account.getBzjAmount().add(amount));  //保证金金额
                /*account.setBasicQuotaAmount(account.getBasicQuotaAmount().add(adjustAmount1)); //标准授信额 -总额
                account.setBasicQuotaAmountBzj(account.getMaxQuotaAmountBzj().add(adjustAmount1));   //标准授信额 -保证金计算的金额
                account.setBasicQuotaAmountBalance(account.getBasicQuotaAmountBalance().add(adjustAmount1)); //标准授信额 -余额
                logger.info(">>>>>>>>>>>>>>endProcess_end1 ---03   account:{},{},{},{},{}",account,account.getBzjAmount(),account.getBasicQuotaAmount(),
                        account.getBasicQuotaAmountBalance(),account.getBasicQuotaAmountBzj());

                Record phe2=accountDao.getXsByTraderVsAccount(apply.getTraderId(),"2");  //可授信额上限 系数
                if(phe2==null){
                    throw new RuntimeException("请先设置可授信额上限系数");
                }
                logger.info(">>>>>>>>>>>>>>>>>>endProcess  xs2:{}",phe2.toString());
                BigDecimal xs2=phe2.getBigDecimal("amount");
                BigDecimal adjustAmount2=amount.multiply(xs2);   // 调整的 保证金*系数
                logger.info(">>>>>>>>>>>>>>endProcess2 ---03   account:{},{},{},{},{}",account,account.getMaxQuotaAmount(),account.getMaxQuotaAmountBzj(),account.getMaxQuotaAmountBalance(),adjustAmount2);

                account.setMaxQuotaAmount(account.getMaxQuotaAmount().add(adjustAmount2));   //可授信额上限
                account.setMaxQuotaAmountBzj(account.getMaxQuotaAmountBzj().add(adjustAmount2));  // 可授信额上限 -保证金计算的金额
                account.setMaxQuotaAmountBalance(account.getMaxQuotaAmountBalance().add(adjustAmount2));   //可授信额上限 -余额*/

                bondApplyDao.save(apply);
                logger.info(">>>>>>>>>>>>>>endProcess_end2 ---03   account:{},{},{},{}",account,account.getMaxQuotaAmount(),account.getMaxQuotaAmountBzj(),account.getMaxQuotaAmountBalance());
                accountDao.save(account);
                //修改代理商保证金金额
                CrmTrader trader = traderDao.get(apply.getTraderId());
                trader.setBond(account.getBzjAmount());
                traderDao.save(trader);

            }else if(FormUtils.SUBCONTRACTING_STANDARD_PRICE_APPLICATION.equals(formId)){  //分包保准价申请
                CrmSubconractorSettlementSchemeApply apply= standardPriceApplyDao.getByApplyId(applicationId);
                apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
                apply.setFinishTime(date);
                apply.setTaskName("已完成");
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(apply.getProcessDefId());
                apply.setOperateUserIds(apply.getOperateUserIds()+","+ccUserId);
                standardPriceApplyDao.save(apply);
                standardPriceApplyDao.updateSettlementScheme(apply.getId());
            }else if(FormUtils.SETTLE_AMOUNT_ADJUST_APPLICATION.equals(formId)){   //结算额调整申请
                SettlementAmountAdjustmentApply apply= settlementAmountAdjustmentApplyDao.getByApplyId(applicationId);
                apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
                apply.setFinishTime(date);
                apply.setTaskName("已完成");
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(apply.getProcessDefId());
                apply.setOperateUserIds(apply.getOperateUserIds()+","+ccUserId);
                settlementAmountAdjustmentApplyDao.save(apply);
                //修改账户金额
                CrmTraderAccount account= accountDao.getAccountByTraderId(apply.getTraderId());

                String adjustType=apply.getAdjustType(); // 调整类型 1、请款（减法）、2、扣减（减法）、3、返利（加法）；
                BigDecimal adjustAmount=apply.getAmount();  //调整的 结算额
                if(StringUtil.equalsAny(adjustType,BondApplyConstant.KJ)){
                    account.setSettleDeductionAmount(account.getSettleDeductionAmount().add(adjustAmount));
                    adjustAmount=BigDecimal.ZERO.subtract(adjustAmount);
                }
                logger.info(">>>>>>>>>>endProcess----07>>>>adjustAmount:{},account:{}",adjustAmount,account.getSettleAmount());
                account.setSettleAmount(account.getSettleAmount().add(adjustAmount));
                logger.info(">>>>>>>>>>endProcess----07>>>>account:{}",account.getSettleAmount());
                //推入金蝶系统
                CrmTraderAccountSettleDetail settleDetail=new CrmTraderAccountSettleDetail();
                settleDetail.setNumber(apply.getApplyNumber());
                settleDetail.setCreateTime(date);
                settleDetail.setAmount(adjustAmount);
            /*    CrmTrader trader = traderDao.get(apply.getTraderId());
                try {
                    String kingId= payableService.kingDeeSavePayable(settleDetail, trader);
                    apply.setKingDeeId(kingId);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("电站变更时，结算推入金蝶异常 : {}",e);
                    throw new BusinessException("电站变更时，结算推入金蝶异常！"+e.getMessage());
                }*/
                accountDao.save(account);


            }else if(FormUtils.SUPPLY_ORDER_APPLICATION.equals(formId)){  //赊销下单申请 审批
                CrmSupplyMaterialDeliverOrder order=supplyOrderDao.get(applicationId);
                order.setOrderExamineStatus(BondApplyConstant.APPLYSTATUS_THREE);
                logger.info(">>>>>>>>>>>>>订单审批 >editApplyStatus  order:{}",order.getId());
                order.setTaskName("已完成");
                order.setStatus(DeliverOrderConstants.STATUS_PROCUREMENT_ALLOCATION);
                order.setAuditTime(date);
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(order.getProcessDefId());
                order.setOperateUserIds(order.getOperateUserIds()+","+ccUserId);
                supplyOrderDao.save(order);

//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            Thread.sleep(5000);
//                            insertQQ(order.getId(),"01");
//                        } catch (Exception r) {
//                            r.printStackTrace();
//                        }
//
//                    }
//                }).start();

            }else if(FormUtils.PURCHASE_ORDER_APPLICATION.equals(formId)){   //采购审批
                CrmSupplyMaterialDeliverOrder order=supplyOrderDao.get(applicationId);
                logger.info(">>>>>>>>>>>>>>editApplyStatus2  order:{}",order.getId());
                order.setPurchaseOrderExamineStatus(BondApplyConstant.APPLYSTATUS_THREE);
                order.setTaskName("已完成");
                order.setStatus(DeliverOrderConstants.STATUS_WAIT_DELIVER);
                ccUserId=FormUtils.getLastAuditStep(order.getProcessDefId());
                order.setPurchaseOperateUserIds(order.getPurchaseOperateUserIds()+","+ccUserId);
                supplyOrderDao.save(order);
            }else if(FormUtils.INVEBNTORY_ORDER_APPLICATION.equals(formId)){   //盘点单申请
                CrmSupplyInventoryOrder apply = inventoryOrderService.getByid(applicationId);
                apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
                apply.setTaskName("已完成");
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(apply.getProcessDefId());
                apply.setOperateUserIds(apply.getOperateUserIds()+","+ccUserId);
                inventoryOrderService.inventoryLogic(apply);
                //
            } else if(FormUtils.TRANSFER_ORDER_APPLICATION.equals(formId)){   //掉拨单申请
                CrmSupplyAllocationOrder order=allocationOrderService.getById(applicationId);
                order.setOrderStatus(BondApplyConstant.APPLYSTATUS_ONE);
                order.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
                order.setTaskName("已完成");
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(order.getProcessDefId());
                order.setOperateUserIds(order.getOperateUserIds()+","+ccUserId);
                allocationOrderService.saveOrder(order);
            }else if(FormUtils.CASH_OUT_APPLY.equals(formId)){ //请款申请
                logger.info(">>>>>>>>>>>请款申请 endProcess");
                CashOutApply apply= cashOutApplyDao.getByApplyId(applicationId);
                apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
                apply.setFinishTime(date);
                apply.setTaskName("已完成");
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(apply.getProcessDefId());
                apply.setOperateUserIds(apply.getOperateUserIds()+","+ccUserId);
                CrmTrader trader = traderDao.get(apply.getTraderId());
                //推入金蝶系统
                // 1、获取请款关联的结算明细kingId  2、获取请款时抵消结算额调整里面的扣款明细 kingId
               // String needXiaTuiKingIds=cashOutApplyDao.getKingDeeId(apply.getSettleIds(), apply.getAdjustmentApplyIds());

                    //质保金等释放的时候才上推到金蝶说
                  //  String FID=payableService.pushDown(needXiaTuiKingIds);
                  //  apply.setPushId(FID);

                 //   String kingId= kingDeePayService.kingDeeSaveCashOut(apply,trader,FID);
                 //   apply.setKingDeeId(kingId);


                cashOutApplyDao.save(apply);
                BigDecimal deductAmount=BigDecimal.ZERO;
                if(StringUtil.isNotBlank(apply.getAdjustmentApplyIds())){
                    //获取该请款抵消的金额
                  deductAmount=cashOutApplyDao.getDeductAmount(apply.getAdjustmentApplyIds());
                }

                //修改账户金额
                BigDecimal outCash=apply.getOutCash();  //请款的金额(真正的实付金额)
                if(BondApplyConstant.JS_ACCOUNT.equals(apply.getObjType()) && apply.getPayAmount()!=null){ //待结算账户
                    outCash=apply.getPayAmount();
                }
                if(outCash.compareTo(BigDecimal.ZERO)>0){
                    CrmTraderAccount account= accountDao.getAccountByTraderId(apply.getTraderId());
                    logger.info(">>>>>>>>>>>>>>endProcess ---12   account:{},{},{},{}",account,account.getSettleAmount(),account.getQaAmountUsable(),account.getQaAmountIncdec());
                    String objType=apply.getObjType(); // 请款账户  :0.待结算账户 1.质保金账户

                    logger.info(">>>>>>>>>>>>>>>endProcessCASH_OUT_APPLY 12 outCash:{}",outCash);
                    if(BondApplyConstant.JS_ACCOUNT.equals(objType)){  //待结算账户
                        account.setSettleAmount(account.getSettleAmount().subtract(outCash));
                        if(apply.getOffsetBondAmount()!=null && apply.getOffsetBondAmount().compareTo(BigDecimal.ZERO)>0){
                            account.setBzjAmount(account.getBzjAmount().add(apply.getOffsetBondAmount()));  //请款扣除部分抵消的保证金 到保证金账户
                            //生成一条保证金的明细
                            BondApply bondApplyRecord=bondApplyDao.createBondRecord(apply.getTraderId(),apply.getOffsetBondAmount(),date);
                            bondApplyRecord.setRelateId(apply.getId());
                            bondApplyDao.save(bondApplyRecord);
                        }
                    }else{   //质保金账户
                        account.setQaAmountUsable(account.getQaAmountUsable().subtract(outCash));
                        account.setQaAmountIncdec(account.getQaAmountIncdec().subtract(outCash));
                    }
                    logger.info(">>>>>>>>>>>>>>>>>>>>deductAmount:{}",deductAmount);
                    account.setSettleDeductionAmount(account.getSettleDeductionAmount().subtract(deductAmount));
                    logger.info(">>>>>>>>>>>>>>endProcess_endCASH_OUT_APPLY ---12   account:{},{},{},{}",account,account.getSettleAmount(),account.getQaAmountUsable(),account.getQaAmountIncdec());
                    accountDao.save(account);
                }

            }else if(FormUtils.PRICE_COEFFICIENT_APPLY.equals(formId)){    //零售价系数申请
                PriceCoefficientApply apply=priceCoefficientApplyDao.getByApplyId(applicationId);
                apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
                apply.setFinishTime(date);
                apply.setTaskName("已完成");
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(apply.getProcessDefId());
                apply.setOperateUserIds(apply.getOperateUserIds()+","+ccUserId);
                priceCoefficientApplyDao.save(apply);
            }else if(FormUtils.WAREHOUSE_APPLY.equals(formId)){   //仓库申请
                SupplyWarehouseApply apply = warehouseApplyService.get(applicationId);
                apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
                apply.setTaskName("已完成");
                String warehouseld = crmSupplyWarehouseSettingService.addTraderWarehouse(apply);
                apply.setWarehouseId(warehouseld);
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(apply.getProcessDefId());
                apply.setOperateUserIds(apply.getOperateUserIds()+","+ccUserId);
                warehouseApplyService.save(apply);
            }else if(FormUtils.STOCK_UP_APPLY.equals(formId)){    //备货申请流程
                CrmFittingStockUpApply apply=fittingStockUpApplyDao.getByApplyId(applicationId);
                apply.setTaskName("已完成");
                apply.setFinishTime(date);
                apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(apply.getProcessDefId());
                apply.setOperateUserIds(apply.getOperateUserIds()+","+ccUserId);
                fittingStockUpApplyDao.save(apply);
            }else if(FormUtils.BOND_LIMIT_APPLY.equals(formId)){    //保证金额度申请
                BondLimitApply apply= bondLimitApplyDao.getByApplyId(applicationId);
                apply.setTaskName("已完成");
                apply.setFinishTime(date);
                apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(apply.getProcessDefId());
                apply.setOperateUserIds(apply.getOperateUserIds()+","+ccUserId);
                bondLimitApplyDao.save(apply);
                //修改账户的保证金额度
                CrmTraderAccount account= accountDao.getAccountByTraderId(apply.getTraderId());
                account.setBondAmountLimit(apply.getAmount());
                accountDao.save(account);
            }else if(FormUtils.BRACKET_ORDER_APPLY.equals(formId)){    //现金下单申请
                CrmSupplyMaterialDeliverOrder order=supplyOrderDao.get(applicationId);
                order.setOrderExamineStatus(BondApplyConstant.APPLYSTATUS_THREE);
                logger.info(">>>>>>>>>>>>>订单审批 >editApplyStatus  order:{}",order.getId());
                order.setTaskName("已完成");
                order.setStatus(DeliverOrderConstants.STATUS_PROCUREMENT_ALLOCATION);
                order.setAuditTime(date);
                //获取流程审批，最后一级的抄送人
                ccUserId=FormUtils.getLastAuditStep(order.getProcessDefId());
                order.setOperateUserIds(order.getOperateUserIds()+","+ccUserId);
                supplyOrderDao.save(order);
                //修改账户的保证金额度
                CrmTraderAccount account= accountDao.getAccountByTraderId(order.getTraderId());
                account.setArrearsAmount(account.getArrearsAmount().add(order.getPredictAmount()));
                accountDao.save(account);
                //新增明细
                CrmTraderSupportSettleDetails details = new CrmTraderSupportSettleDetails();
                details.setNumber(PlantformUtils.findOrderNumber("ZJLS"));
                details.setType("1");
                details.setAmount(order.getPredictAmount());
                details.setTakeAmountUnit("贵州能辉智慧能源科技有限公司");
                details.setTakeAmountAccount("121943001210616");
                details.setRate(new BigDecimal("13"));
                details.setCreateTime(new Date());
                details.setStatus("1");
                details.setTraderId(order.getTraderId());
                details.setRelateOrderNumber(order.getNumber());
                details.setRelateOrderId(order.getId());
                settledetailsDao.save(details);

//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            Thread.sleep(5000);
//                            insertQQ(order.getId(),"02");
//                        } catch (Exception r) {
//                            r.printStackTrace();
//                        }
//
//                    }
//                }).start();

            }

            if(com.sifang.modules.sys.common.utils.StringUtil.isNotBlank(ccUserId)){
                logger.info(">>>>>>>>>>>>>>>>OneTaskCompleteListener  ccUserId:{}",ccUserId);
                String[] userids = ccUserId.split(",");
                for(String id:userids){
                    logger.info("----oneTaskCompleteListener 抄送id:{}",id);
                    Task ta = taskService.newTask();
                    ta.setName("抄送");
                    ta.setCategory(TaskVo.TYPE_THREE);
                    ta.setAssignee(id);
                    ta.setFormKey(formId);
                    ta.setParentTaskId(processInstanceId);
                    ta.setTenantId(applicationId);
                    taskService.saveTask(ta);
                    Map<String,String> mapc=new HashMap<>();
                    mapc.put("applicationId",applicationId);
                    mapc.put("formId",formId);
                    mapc.put("processInstanceId",processInstanceId);
                    taskService.setVariables(ta.getId(),mapc);
                }
            }
            }catch (Exception e){
            logger.error(">>>>>>>>>>>>审核通过后执行错误 endProcess  Exeception:{}",e);
            logger.info(">>>>>审核通过后执行错误 endProcess  formId:{}  ; applicationId {}: ;",formId, applicationId);
            e.printStackTrace();
            throw new BusinessException("内部错误,请刷新稍后再试!");
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>>审批完成 formId:{}",formId);
        //保存流程的过程信息
        examineInfoDao.saveExamineInfo(applicationId,userName+"(审批完成)",new Date(),userName,formId);
        Db.update("UPDATE `crm_item_manage` SET end_time=?,status='2',current_task_name='已完成' WHERE process_instance_id=? AND STATUS='1' ",date,processInstanceId);
        logger.info(">>>>>>>>>>>>>>审批完成 ");
    }

    /**
     * 订单数据推送企企
     * @param orderId
     */
    public void insertQQ(String orderId,String way ){
        OrderTbQqVO orderTbQq = crmSupplyMaterialDeliverOrderService.tbDate(orderId);
        String msg;
        String  result;
        if ("03".equals(way)) {
            msg = "甲供材料领用单";
            result = OpenapiTemplate.addJGOrderToQQ(orderTbQq);
        } else {
            msg = "小E或代理商销售单";
            result = OpenapiTemplate.addXiaoEOrderToQQ(orderTbQq, way);
        }
        Map map=(Map) JSONObject.parseObject(result);
        if(map != null && map.get("code") != null && map.get("id") != null){
            String qqCode=String.valueOf(map.get("code"));
            String qqId=String.valueOf(map.get("id"));
            int insertResult=crmSupplyMaterialDeliverOrderService.saveEntity(orderId,qqCode,qqId);
            // 获取物资需求单的详情记录
            WuziOrder order = OpenapiTemplate.getWZXQDdetail(qqId, orderTbQq);
            crmSupplyMaterialDeliverOrderService.saveWuziInfo(order);
            logger.info("------->>>>>>推送" + msg + "返回的结果:{}",insertResult);
        }
    }



}
