package com.sifang.modules.changes.service;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.dao.CrmCustomerEntryTenantChangeRecordDao;
import com.sifang.modules.changes.dao.CrmCustomerEntryTenantChangeRecordDetailDao;
import com.sifang.modules.changes.dao.CustomerEntryChangeRecordDao;
import com.sifang.modules.changes.entity.CrmCustomerEntryTenantChangeRecord;
import com.sifang.modules.changes.entity.CrmCustomerEntryTenantChangeRecordDetail;
import com.sifang.modules.changes.vo.CustomerInformationChangeVo;
import com.sifang.modules.customer.Service.*;
import com.sifang.modules.customer.constant.*;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.*;
import com.sifang.modules.customer.form.FinanceProjectFile;
import com.sifang.modules.customer.utils.EmployeRoleUtils;
import com.sifang.modules.esign.constants.ESignConstants;
import com.sifang.modules.flowable.constants.ItemConstants;
import com.sifang.modules.flowable.dao.ItemManageDao;
import com.sifang.modules.flowable.dao.ItemTaskDetailDao;
import com.sifang.modules.flowable.entity.ItemManage;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.partner.service.GuangfaOperatingService;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.setting.constant.ProcessSetConstants;
import com.sifang.modules.sunshine.SystemSetting.service.FormSetService;
import com.sifang.modules.sunshine.SystemSetting.service.ProjectInfoSettingService;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
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.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.FormSetUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.taskdispatch.dao.CrmReviewDispatchDao;
import com.sifang.modules.taskdispatch.service.CrmPriorReviewSettingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CustomerInformationChangeService extends BaseService {

    Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private CrmCustomerEntryTenantChangeRecordDao tenantChangeRecordDao;

    @Autowired
    private CrmCustomerEntryTenantChangeRecordDetailDao tenantChangeRecordDetailDao;

    @Autowired
    private CustomerEntryService entryService;

    @Autowired
    private CrmCustomerIncomingApplicationDao customerIncomingApplicationDao;

    @Autowired
    private TenantYxBankCardDao tenantYxBankCardDao;

    @Autowired
    private CustomerEntryMsgService msgService;

    @Autowired
    private OperatingLeaseService operatingLeaseService;

    @Autowired
    private CrmYxIncomingProcessDao processDao;

    @Autowired
    CustomerEntrySurveyRecordDao customerEntrySurveyRecordDao;

    @Autowired
    ProjectInfoSettingService projectService;

    @Autowired
    private ItemTaskDetailDao itemTaskDetailDao;

    @Autowired
    private ItemManageDao itemManageDao;
    @Autowired
    private CrmReviewDispatchDao reviewDispatchDao;

    @Autowired
    private YueXiuProjectOperatingService yueXiuProjectOperatingService;

    @Autowired
    private CrmYxIncomingLogDao yxIncomingLogDao;

    @Autowired
    private FormSetService formSetService;

    @Autowired
    private CustomerEntryOrgFilesDao orgFilesDao;
    @Autowired
    private GuangFaManagemnetService guangFaManagemnetService;

    @Autowired
    private GuangfaOperatingService guangfaOperatingService;

    @Autowired
    private ContractManagementDao contractManagementDao;

    @Autowired
    private HuaRongContractService huaRongContractService;

    @Autowired
    private CustomerEntryChangeRecordDao customerEntryChangeRecordDao;

    @Value("${img.domain}")
    private String commonStaticImgPath;

    @Autowired
    private CrmPriorReviewSettingService crmPriorReviewSettingService;

    public void getListData(LayuiPage<Record> page, Map<String,String> map, Operator operator){
        tenantChangeRecordDao.getListData(page,map,operator);
    }

    public Record getByChangeId(String id){
        return tenantChangeRecordDao.getByChangeId(id);
    }

    public List<Record> getDetails(String mainId){
        return tenantChangeRecordDetailDao.getDetails(mainId);
    }

    //开发说明：
    //1、预审通过后、安装验收前，可以提交客户信息变更，影响合同的字段在变更审核通过后要提交重新进件。
    public Map<String,Object> getCanChangeEntry(String powerStationCode){
        Map<String, String> paramMap = Maps.newHashMap();
        User user=UserUtils.getUser();
       /* if(StringUtil.equalsAny(user.getUserType(),UserConstants.TYPE_TRADER,User.USER_TYPE_ADVISOR)){
            Record record=CrmUtils.getUserTrader(user.getUserType(),user.getId());
            String traderId=record.getStr("id");
            paramMap.put("traderId",traderId);
        }*/
        CustomerEntry customerEntry = tenantChangeRecordDao.getCanChangeEntry(powerStationCode,paramMap);
        if (customerEntry == null) {
           throw  new BusinessException("未找到电站信息");
        }
        if(!"4".equals(customerEntry.getCredit())){
            throw  new BusinessException("预审未通过，不可进行客户信息变更");
        }
        //安装验收状态：0.未开始 1.待自审 2.自审通过 3.验收驳回 4.验收通过
//        if("4".equals(customerEntry.getCheckAcceptFlag())){
//            throw  new BusinessException("安装验收通过后，不可进行客户信息变更");
//        }
//        if("APPROVING".equals(customerEntry.getNextApplyStatus())){//审批中的不能变更客户信息
//            throw new BusinessException("进件审批中，不可变更客户信息。");
//        }
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("customerEntry",customerEntry);
        CustomerEntrySurveyRecord surveyRecord = customerEntrySurveyRecordDao.findOneByEntryId(customerEntry.getId());
        resultMap.put("surveyRecord", surveyRecord);
        resultMap.put("project", projectService.getById(customerEntry.getProjectId()));
        resultMap.put("info6",formSetService.getListByCondition("06", customerEntry.getPartnerId()) );
        resultMap.put("orgFiles", orgFilesDao.findOneByEntryId(customerEntry.getId()));
        resultMap.put("whetherItAffectsTheContractChange", FormSetUtils.processSetEnable(customerEntry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZFSH));
        return resultMap;
    }
    //保存变更记录
    @Transactional(rollbackFor = Exception.class)
    public String savaEntryChange(CustomerInformationChangeVo changeVo){
        logger.info("savaEntryChange changeVo:{}",new Gson().toJson(changeVo));
        User user= UserUtils.getUser();
        //判断电站是否有变更中的数据
        Long ifHaveChangeRecord=tenantChangeRecordDao.getIfHaveChangeRecord(changeVo.getEntryId());
        if(ifHaveChangeRecord>0){
            throw new BusinessException(" 有审核中的变更申请，不能重复申请!");
        }
        //判断电站是否有资方审核中的数据
        Long count = customerEntryChangeRecordDao.getIfHaveTenantChange(changeVo.getEntryId());
        if(count>0){
            throw new BusinessException("该电站有待资方审核的变更记录，请审核后再提交");
        }
        CustomerEntry customerEntry = entryService.getById(changeVo.getEntryId());
//        if (StringUtil.equalsAny(customerEntry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_DBW, CustomerEntryConstants.ENTRY_STATUS_DYS
//                , CustomerEntryConstants.ENTRY_STATUS_YSBH, CustomerEntryConstants.ENTRY_STATUS_YWC)) {
//            throw new BusinessException("操作失败，只有安装验收前的电站才可提交变更申请");
//        }
        if (StringUtil.equalsAny(customerEntry.getApplyStatus(),"5","14","19")){
            throw new BusinessException("操作失败，进件审核中的电站不可提交变更申请");
        }
        if (StringUtil.equalsAny(customerEntry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_YWC)){
            throw new BusinessException("操作失败，已完成的电站不可提交变更申请");
        }
        if("APPROVING".equals(customerEntry.getFirstApplyStatus())){
            throw new BusinessException("进件审批中，不可变更客户信息。");
        }
        //判断有没有变更中的审批
        String checkApplyResult = CrmUtils.checkExistApply(customerEntry.getStatus(), customerEntry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            throw new BusinessException(checkApplyResult);
        }
        Date date=new Date();
        CrmCustomerEntryTenantChangeRecord changeRecord;
        if(StringUtil.isBlank(changeVo.getId())){  //新增变更记录
            changeRecord=new CrmCustomerEntryTenantChangeRecord();
            changeRecord.setId(IdGen.uuid());
            changeRecord.setNumber(PlantformUtils.getOrderNumber());
            changeRecord.setEntryId(changeVo.getEntryId());
            changeRecord.setPowerStationCode(changeVo.getPowerStationCode());
            changeRecord.setChangeReason(changeVo.getReason());
            changeRecord.setEntryStatus(changeVo.getEntryStatus());
            //获取变更次数
            Long num=tenantChangeRecordDao.getNumber(changeVo.getEntryId());
            if(num==null){
                changeRecord.setChangeCount(1);
            }else{
                changeRecord.setChangeCount(Integer.valueOf(String.valueOf(num))+1);
            }
        }else{
            changeRecord=tenantChangeRecordDao.get(changeVo.getId());
        }
        changeRecord.setStatus(changeVo.getSaveType());
        changeRecord.setCreateBy(user.getId());
        changeRecord.setCreateName(user.getUserName());
        changeRecord.setCreateTime(date);
        List<CrmCustomerEntryTenantChangeRecordDetail> list=changeVo.getDetails();
        boolean fg=false;
        boolean changeFg=false;
        boolean changeFgHR=false;
        for(CrmCustomerEntryTenantChangeRecordDetail detail:list){
            detail.setMainId(changeRecord.getId());
            if("1".equals(detail.getIfChange())){
                  fg=true;

                  String itemCode=detail.getItemCode();
                  if("mobile".equals(itemCode)){  //手机号
                      changeFg=true;
                      changeFgHR=true;
                  }else if("idCardFront".equals(itemCode)){  //身份证正面
                      changeFg=true;
                  }else if("idCardBack".equals(itemCode)){  //身份证反面
                      changeFg=true;
                  }else if("bankCard".equals(itemCode)){ //银行卡
                      changeFg=true;
                  }else if("tssBankNumName".equals(itemCode)){
                      changeFgHR=true;
                  }else if("address".equals(itemCode)){
                      changeFgHR=true;
                  }else if("bankCode".equals(itemCode)){
                      changeFgHR=true;
                  }
            }
        }
        logger.info("savaEntryChange   firstApplyStatus:{},changeFg",customerEntry.getFirstApplyStatus(),changeFg);
        if (FormSetUtils.processSetEnable(customerEntry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZFSH)){
            switch (customerEntry.getPartnerId()){
                case PartnerConstants.PARTNER_ID_YX:
                    if("APPROVED".equals(customerEntry.getFirstApplyStatus()) && changeFg){
                        if(!"true".equals(changeVo.getConfirmTrue())){
                            return "208";    //页面确定 是否坚持 执行 取消进件后再次进件
                        }
                    }
                    break;
                case PartnerConstants.PARTNER_ID_GF:
                    if ("4".equals(customerEntry.getCredit())){
                        if(!"true".equals(changeVo.getConfirmTrue())){
                            return "208";    //页面确定 是否坚持 执行 取消进件后再次进件
                        }
                    }
                    break;
                case PartnerConstants.PARTNER_ID_HR:
                    if("FT".equals(customerEntry.getFirstApplyStatus()) && changeFgHR){
                        if(!"true".equals(changeVo.getConfirmTrue())){
                            return "209";    //页面确定 是否坚持 执行 合同重签
                        }
                    }
                    break;
            }
        }


        if("2".equals(changeVo.getSaveType()) && !fg){
            throw new BusinessException("没有变更的数据，不可提交变更");
        }
        //删除历史保存的明细数据
        tenantChangeRecordDetailDao.deleteDetails(changeRecord.getId());
        tenantChangeRecordDao.save(changeRecord);
        tenantChangeRecordDetailDao.save(list);
        String content = String.format("第%d次提交客户信息变更申请", changeRecord.getChangeCount());
        msgService.saveCustomerEntryMsg(user,customerEntry.getId(), CustomerEntryConstants.ENTRY_ADD_CHANGE,content);

        //所有的变更审核 要走待办事项审批流程，默认审批人为原审核人员  客户信息变更审核 查询的是档案审核/客户信息变更审核人；
        if("2".equals(changeVo.getSaveType())){  //提交，生成待办任务
            ItemManage itemManage=itemManageDao.addItemChange(FormUtils.ENTRY_CHANGE_KHXXBG,customerEntry.getId(),changeRecord.getId(),"客户信息变更("+customerEntry.getTenantName()+"-"+customerEntry.getPowerStationCode()+")-"+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss"),date,user.getUserName());
            //获取最近一次 档案审核/客户信息变更审核人
            String userId=itemManageDao.getLastAuditUserId("92,98",changeRecord.getEntryId());
            if(StringUtil.isNotBlank(userId)){
//                itemManage.setAssignAuditUserId(userId);
                itemManage.setPreferUserId(userId);
            }
            itemManageDao.save(itemManage);
            //大代理商优先审核
            String groupName = "档案审核";
            crmPriorReviewSettingService.traderPriorityReview(customerEntry.getCreateTraderId(),itemManage.getId(),groupName);
        }


        return "200";
    }

    //审核驳回
    @Transactional(rollbackFor = Exception.class)
    public void changeRecordBack(String id,String auditRemarks){
        logger.info("changeRecordBack  id:{},auditRemarks:{}",id,auditRemarks);
        User user=UserUtils.getUser();
        Date date=new Date();
        CrmCustomerEntryTenantChangeRecord changeRecord=tenantChangeRecordDao.get(id);
        changeRecord.setAuditName(user.getUserName());
        changeRecord.setAuditBy(user.getId());
        changeRecord.setAuditRemarks(auditRemarks);
        changeRecord.setAuditTime(date);
        changeRecord.setStatus("4");
        tenantChangeRecordDao.save(changeRecord);
        String msg = (StringUtil.isNotBlank(auditRemarks) ? ","+ auditRemarks : "");
        String content = String.format("第%d次客户信息变更申请，审核驳回" + msg, changeRecord.getChangeCount());
        msgService.saveCustomerEntryMsg(user,changeRecord.getEntryId(), CustomerEntryConstants.ENTRY_CHANGE_REFUSE, content);
        ItemManage itemManage= itemManageDao.getItemManagementByProcessInstanceId(changeRecord.getId(),FormUtils.ENTRY_CHANGE_KHXXBG);
        if (itemManage != null) {
            Operator operator=Operator.of(user);
            itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_CHANGE_KHXXBG,itemManage.getApplicationId(), itemManage.getProcessInstanceId(), itemManage.getProcessInstanceId(), ItemConstants.RESULT_BACK, date, operator, "客户信息变更");
            itemManage.setStatus(ItemConstants.ITEM_STATUS_FINISH);
            itemManage.setEndTime(date);
            itemManageDao.save(itemManage);
            reviewDispatchDao.markDispatchFinish(itemManage);
        }
    }

    //申请撤回
    @Transactional(rollbackFor = Exception.class)
    public void revokeChangeRecord(String id){
        CrmCustomerEntryTenantChangeRecord changeRecord=tenantChangeRecordDao.get(id);
        if(!"2".equals(changeRecord.getStatus())){
             throw new BusinessException("申请状态 不支持撤回操作!");
        }
        User user=UserUtils.getUser();
        Date date=new Date();
        changeRecord.setStatus("0");
        changeRecord.setAuditName(user.getUserName());
        changeRecord.setAuditBy(user.getId());
        changeRecord.setAuditRemarks("用户撤回申请");
        changeRecord.setAuditTime(date);
        tenantChangeRecordDao.save(changeRecord);
        String content = String.format("第%d次客户信息变更申请，撤回", changeRecord.getChangeCount());
        msgService.saveCustomerEntryMsg(user,changeRecord.getEntryId(), CustomerEntryConstants.ENTRY_CHANGE_CANCEL,content);

        ItemManage itemManage= itemManageDao.getItemManagementByProcessInstanceId(changeRecord.getId(),FormUtils.ENTRY_CHANGE_KHXXBG);
        if(itemManage !=null){
            itemManage.setStatus(ItemConstants.ITEM_STATUS_CANCEL);
            itemManage.setEndTime(new Date());
            itemManageDao.save(itemManage);
        }
    }

    //审核通过
    @Transactional(rollbackFor = Exception.class)
    public void changeRecordApprove(String id, String auditRemarks, String confirmTrue){
        logger.info("changeRecordApprove  id:{},auditRemarks:{}",id,auditRemarks);
        User user=UserUtils.getUser();
        Date date=new Date();
        CrmCustomerEntryTenantChangeRecord changeRecord=tenantChangeRecordDao.get(id);
        changeRecord.setAuditName(user.getUserName());
        changeRecord.setAuditBy(user.getId());
        changeRecord.setAuditRemarks(auditRemarks);
        changeRecord.setAuditTime(date);
        changeRecord.setStatus("3");
        tenantChangeRecordDao.save(changeRecord);
        CustomerEntry customerEntry = entryService.getById(changeRecord.getEntryId());
        if (PartnerConstants.PARTNER_ID_GF.equals(customerEntry.getPartnerId())) {
            customerEntry.setAddressFlag("1");
        }
        CustomerEntryOrgFiles orgFiles = orgFilesDao.findOneByEntryId(customerEntry.getId());
        List<Record> details=getDetails(id);
        boolean changeFg=false;
        boolean addressFlag = false;//是否改变地址信息
        boolean HrFg=false;  //是否引起合同重签
        List<FinanceProjectFile> fileList = new ArrayList<>();
        for(Record r:details){
            String item=r.getStr("item_code");
            String ifChange=r.getStr("if_change");
            String afterChange=r.getStr("after_change");
            if("1".equals(ifChange)){
                if("mobile".equals(item)){
                    customerEntry.setMobile(afterChange);
                    changeFg=true;

                    HrFg=true;
                 }else if("tssBankNumName".equals(item)){  //开户行    二次进件的时候会再次传该信息
                     customerEntry.setTssBankNumName(afterChange);
                     if(CustomerEntryConstants.FILING_TYPE_COMPANY.equals(customerEntry.getFilingType())){  //项目公司备案的合同里面涉及了开户行信息
                         HrFg=true;
                     }
                 }else if("tssBankNum".equals(item)){    //TSS联行号    二次进件的时候会再次传该信息
                    customerEntry.setTssBankNum(afterChange);

                 }else if("bankCode".equals(item)){ //银行账号      二次进件的时候会再次传该信息
                     customerEntry.setBankCode(afterChange);
                    if(CustomerEntryConstants.FILING_TYPE_COMPANY.equals(customerEntry.getFilingType())){  //项目公司备案的合同里面涉及了开户行信息
                        HrFg=true;
                    }
                 }else if("idCardFront".equals(item)){  //身份证正面
                     customerEntry.setIdCardFront(afterChange);

                     FinanceProjectFile projectFile1 = new FinanceProjectFile();
                     projectFile1.setFileName("身份证正面.jpg");
                     projectFile1.setFileCode(FileCodeConstants.GR_FILE_B_01);
                     projectFile1.setFileAddress(commonStaticImgPath + customerEntry.getIdCardFront());
                     fileList.add(projectFile1);
                 }else if("idCardBack".equals(item)){ //身份证反面
                     customerEntry.setIdCardBack(afterChange);

                     FinanceProjectFile projectFile2 = new FinanceProjectFile();
                     projectFile2.setFileName("身份证反面.jpg");
                     projectFile2.setFileCode(FileCodeConstants.GR_FILE_B_02);
                     projectFile2.setFileAddress(commonStaticImgPath + customerEntry.getIdCardBack());
                     fileList.add(projectFile2);
                 }else if("HouseOwnership".equals(item)){ //房产证   二次进件的时候才会传
                    CustomerEntrySurveyRecord surveyRecord = customerEntrySurveyRecordDao.findOneByEntryId(customerEntry.getId());
                    surveyRecord.setHouseOwnership(afterChange);
                    customerEntrySurveyRecordDao.save(surveyRecord);
                }else if("bankCard".equals(item)){    //银行卡
                     customerEntry.setBankCard(afterChange);

                     FinanceProjectFile projectFile5 = new FinanceProjectFile();
                     int filenameLeng5 = customerEntry.getBankCard().lastIndexOf(".");
                     String extName5 = customerEntry.getBankCard().substring(filenameLeng5).toLowerCase();
                     projectFile5.setFileName("银行卡" + extName5);
                     projectFile5.setFileCode(FileCodeConstants.GR_FILE_B_05);
                     projectFile5.setFileAddress(commonStaticImgPath + customerEntry.getBankCard());
                     fileList.add(projectFile5);
                 } else if("address".equals(item)) { // 地址
                    customerEntry.setAddress(afterChange);
                    addressFlag = true;

                    HrFg=true;
                } else if ("bpCardFront".equals(item)) {//共签人身份证正面
                    customerEntry.setBpCardFront(afterChange);
                } else if ("bpCardBack".equals(item)) {//共签人身份证反面
                    customerEntry.setBpCardBack(afterChange);
                } else if ("bpFile".equals(item)) {//子女证明材料
                    customerEntry.setBpFile(afterChange);
                } else if ("resolutionPaperUrl".equals(item)) {//村民代表大会决议书
                    orgFiles.setResolutionPaperUrl(afterChange);
                } else if ("yszcUrl".equals(item)) {//村委议事章程
                    orgFiles.setYszcUrl(afterChange);
                } else if ("accountInfoUrl".equals(item)) {//对公账户信息
                    orgFiles.setAccountInfoUrl(afterChange);
                } else if ("ownershipCertificateUrl".equals(item)) {//产权证明-集体土地使用证
                    orgFiles.setOwnershipCertificateUrl(afterChange);
                } else if ("otherOwnershipCertificateUrl".equals(item)) {//产权证明-不动产证书/查册证明/相关确权文件
                    orgFiles.setOtherOwnershipCertificateUrl(afterChange);
                } else if ("regnoUrl".equals(item)) {//营业执照
                    orgFiles.setRegnoUrl(afterChange);
                }
            }
        }
        orgFilesDao.save(orgFiles);
        String msg = (StringUtil.isNotBlank(auditRemarks) ? ","+ auditRemarks : "");
        String content = String.format("第%d次客户信息变更申请，审核通过" + msg, changeRecord.getChangeCount());
        msgService.saveCustomerEntryMsg(user,changeRecord.getEntryId(), CustomerEntryConstants.ENTRY_CHANGE_PASS,content);
        //变更了客户信息，如果已经进件，那么就要取消之前的进件，然后重新进件
        //以下状态可更新进件信息:NEW-待审批,REJECTED - 审批拒绝,APPROVED_RETURN - 退回,CANCEL - 撤回.可更新单据状态下，信息更新成功后，单据状态更新为待审批
        if(FormSetUtils.processSetEnable(customerEntry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZFSH)) {
            CrmCustomerIncomingApplication application = customerIncomingApplicationDao.getByEntryId(customerEntry.getId());
            switch (customerEntry.getPartnerId()){
                case PartnerConstants.PARTNER_ID_YX:
                    logger.info("changeRecordApprove firstApplyStatus:{},changeFg:{},fileList.size:{}", application, changeFg, fileList);
                    if (application != null && application.getProjectStatus() != null) {
                        logger.info(">>>>>>>changeRecordApprove  ProjectStatus:{}", application.getProjectStatus());
                        Operator operator = Operator.of(user);
                        if (StringUtil.equalsAny(application.getProjectStatus(), "NEW", "REJECTED", "APPROVED_RETURN", "CANCEL")) {
                            if (changeFg) {
                                //重新推送第一次
                                CrmTenantYxBankCard card = tenantYxBankCardDao.getByIdCard(customerEntry.getIdCode(), customerEntry.getManagementType(),customerEntry.getPartnerId());
                                Result result = entryService.accessProjectApply(customerEntry, card, operator,null);
                                logger.info(">>>>>>>>>>changeRecordApprove  result:{}", new Gson().toJson(result));
                                if (!"200".equals(result.getCode())) {
                                    throw new BusinessException("推送进件请求失败；" + result.getErrMsg());
                                }
                                msgService.saveCustomerEntryMsg(user, customerEntry.getId(), CustomerEntryConstants.INCOMING_ONE, "客户信息变更申请通过，重新推送进件信息");
                            }
                            if (fileList.size() > 0 && !changeFg) { //附件上传 如果 changeFg=true 那么 就会在此推送附件
                                Result result = operatingLeaseService.updateFile2(customerEntry, fileList, "01", application.getPartnersContractNumber(), "2");
                                if (!result.isOk()) {
                                    throw new BusinessException("推送进件资料失败：" + result.getErrMsg());
                                }
                            }
                        } else if ("APPROVING".equals(application.getProjectStatus())) {//审批中的不能变更客户信息
                            throw new BusinessException("进件审批中，不可变更客户信息。");
                        } else if ("APPROVED".equals(application.getProjectStatus()) && (changeFg || fileList.size() > 0)) {  //进件审批通过，那么需要取消进件，重新进件
                            if (!"true".equals(confirmTrue)) {
                                throw new BusinessException("208", "修改的内容涉及退回进件，是否确认通过变更");    //页面确定 是否坚持 执行 取消进件后再次进件
                            }
                  /*  //推越秀取消进件
                    operatingLeaseService.cancelProjectApply(application.getPartnersContractNumber(), "客户信息变更","");
                    application.setStatus("a");
                    application.setProjectStatus("CLOSED");
                    application.setCancelReason("客户信息变更");
                    application.setUpdateTime(new Date());
                    application.setUpdateBy(user.getId());
                    application.setIfDelete("1");
                    customerIncomingApplicationDao.save(application);
                    customerEntry.setApplyStatus("4");
                    customerEntry.setFirstApplyStatus(null);
                    customerEntry.setNextApplyStatus(null);
                    //重新进件
                    CrmTenantYxBankCard card = tenantYxBankCardDao.getByIdCard(customerEntry.getIdCode(), customerEntry.getManagementType());
                    Result result = entryService.accessProjectApply(customerEntry, card, operator);
                    logger.info(">>>>>>>>>>changeRecordApprove  result:{}", new Gson().toJson(result));
                    if (!"200".equals(result.getCode())) {
                        throw new BusinessException("重新进件请求失败；" + result.getErrMsg());
                    }
                    //删除原来的进件进程记录
                    processDao.deleteLog(customerEntry.getId());
                    msgService.saveCustomerEntryMsg(user, customerEntry.getId(), CustomerEntryConstants.INCOMING_ONE, "客户信息变更申请通过，取消进件后，重新进件");*/
                            //退回进件
                            operatingLeaseService.cancelProjectApply(application.getPartnersContractNumber(),"客户信息变更", SourceConstants.RETURN_TYPE_RETURN);
                            String str= yxIncomingLogDao.getIncomingStatusStr(application.getProjectStatus(),application.getFarmerSignStatus());
                            yxIncomingLogDao.addCrmYxIncomingLog(customerEntry.getId(),application.getPartnersContractNumber(),"2","退回进件,退回前状态："+str,operator);
                            logger.info("changeRecordApprove str:{}",str);
                            application.setProjectStatus("APPROVED_RETURN");
                            application.setFarmerSignStatus(null);
                            application.setStatus("4");
                            customerIncomingApplicationDao.save(application);
                            customerEntry.setFirstApplyStatus("APPROVED_RETURN");
                            customerEntry.setApplyStatus("4");
                            //删除原来的进件进程记录
                            processDao.deleteLog(customerEntry.getId());
                            //重新推送进件信息
                            yueXiuProjectOperatingService.againPushIncoming(customerEntry,"oneIncoming");
                            logger.info("changeRecordApprove entryStatus:{},firstApplyStatus:{}",customerEntry.getApplyStatus(),customerEntry.getFirstApplyStatus());
                            customerEntry.setFirstApplyStatus("NEW");
                            customerEntry.setApplyStatus("5");
                            msgService.saveCustomerEntryMsg(user,customerEntry.getId(), CustomerEntryConstants.INCOMING_ONE,"客户信息变更申请通过，退回进件后，重新推送进件信息");
                        }
                    }
                    break;
                case PartnerConstants.PARTNER_ID_GF:
                    try {
                        if (application != null){
                            if (StringUtil.equalsAny(customerEntry.getApplyStatus(),CustomerEntryConstants.APPLY_STATUS_JJSH,CustomerEntryConstants.APPLY_STATUS_WGSH,CustomerEntryConstants.APPLY_STATUS_BWSHZ)){
                                throw new IllegalArgumentException("进件审批中，不可变更客户信息。");
                            }else {
                                if(addressFlag){
                                    //电站信息变更
                                    guangFaManagemnetService.stationInfoUpdate(customerEntry,changeRecord,application.getInputPieceId());
                                }
                                //业主信息变更
                                guangFaManagemnetService.customerInfoUpdate(customerEntry,changeRecord,application.getInputPieceId());
                                //合同作废
                                CrmCustomerContractManagement management = contractManagementDao.getContractByEntryId(customerEntry.getId());
                                if (management != null){
                                    if (ESignConstants.GF_CONTRACT_STATUS_WAIT.equals(management.getStatus()) || ESignConstants.GF_CONTRACT_STATUS_QSZ.equals(management.getStatus())
                                     || ESignConstants.GF_CONTRACT_STATUS_DGZ.equals(management.getStatus()) || ESignConstants.GF_CONTRACT_STATUS_GZZ.equals(management.getStatus())
                                     || ESignConstants.GF_CONTRACT_STATUS_YWC.equals(management.getStatus())
                                    ){
                                        management.setStatus(ESignConstants.GF_CONTRACT_STATUS_ZF);
                                        contractManagementDao.save(management);
                                        guangfaOperatingService.guangFaTerminateContract(PartnerConstants.PARTNER_ID_GF, application.getInputPieceId(), "客户信息变更作废合同");
                                        customerEntry.setSignStatus(ESignConstants.GF_CONTRACT_STATUS_WAITADD);
                                        //生成新合同
                                        Db.update(" insert into crm_customer_contract_management (id,status,entry_id,power_station_code,trader_id) values (?,?,?,?,?) ",IdGen.uuid(), ESignConstants.GF_CONTRACT_STATUS_WAITADD,customerEntry.getId(),customerEntry.getPowerStationCode(),customerEntry.getDistributorId());
                                    }
                                }

                            }
                        }
                    }catch (Exception e) {
                        throw new IllegalArgumentException("提交客户信息变更失败," + e.getMessage());
                    }
                    break;
                case PartnerConstants.PARTNER_ID_HR:
                    if (application!= null) {
                        if ("FR".equals(application.getProjectStatus()) || "MR".equals(application.getFarmerSignStatus())){
                            throw new IllegalArgumentException("进件审批中，不可变更客户信息。");
                        }
                        if( "FT".equals(application.getProjectStatus()) && HrFg){
                            if (!"true".equals(confirmTrue)) {
                                throw new BusinessException("208", "修改的内容涉及合同重签，是否确认通过变更");    //页面确定 是否坚持 执行 取消进件后再次进件
                            }
                            Operator operator = Operator.of(user);
                            huaRongContractService.changeCauseContractSignAgain(customerEntry.getId(),application.getPartnersContractNumber(),operator,"客户信息变更，引起合同重签",null);
                           /* contractManagementDao.changeHistoryContractStatus(application.getPartnersContractNumber());
                            CrmCustomerContractManagement contractManagement = new CrmCustomerContractManagement();
                            contractManagement.setStatus(ESignConstants.GF_CONTRACT_STATUS_DSC);
                            contractManagement.setEntryId(customerEntry.getId());
                            contractManagement.setPowerStationCode(customerEntry.getPowerStationCode());
                            contractManagement.setTraderId(customerEntry.getDistributorId());
                            contractManagement.setPartnersContractNumber(application.getPartnersContractNumber());
                            contractManagement.setProjectCompanyId(customerEntry.getProjectCompanyId());
                            contractManagement.setProjectCompanyName(customerEntry.getProjectCompanyName());
                            contractManagement.setTenantMobile(customerEntry.getMobile());
                            contractManagement.setInvitationId(operator.getUserId());
                            contractManagement.setInvitationName(operator.getUserName());
                            contractManagement.setInvitationTime(new Date());
                            contractManagementDao.save(contractManagement);
                            customerEntry.setSignStatus(ESignConstants.GF_CONTRACT_STATUS_DSC);*/
                        }
                    }
                    break;
            }
        }
        entryService.saveByUpdate(customerEntry);

        ItemManage itemManage= itemManageDao.getItemManagementByProcessInstanceId(changeRecord.getId(),FormUtils.ENTRY_CHANGE_KHXXBG);
        if (itemManage != null) {
            Operator operator=Operator.of(user);
            itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_CHANGE_KHXXBG,itemManage.getApplicationId(), itemManage.getProcessInstanceId(), itemManage.getProcessInstanceId(), ItemConstants.RESULT_OK, date, operator, "客户信息变更");
            itemManage.setStatus(ItemConstants.ITEM_STATUS_FINISH);
            itemManage.setEndTime(date);
            itemManageDao.save(itemManage);
            reviewDispatchDao.markDispatchFinish(itemManage);
        }
    }

    //暂存
    @Transactional(rollbackFor = Exception.class)
    public void changeRecordTemp(String id, String auditRemarks) {
        logger.info("changeRecordApprove  id:{},auditRemarks:{}", id, auditRemarks);
        CrmCustomerEntryTenantChangeRecord changeRecord = tenantChangeRecordDao.get(id);
        changeRecord.setAuditRemarks(auditRemarks);
        tenantChangeRecordDao.save(changeRecord);
    }

}
