package com.sifang.modules.changes.service;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.dao.CustomerEntrySupplementDao;
import com.sifang.modules.changes.dao.CustomerEntrySupplementDetailDao;
import com.sifang.modules.changes.entity.CustomerEntrySupplement;
import com.sifang.modules.changes.entity.CustomerEntrySupplementDetail;
import com.sifang.modules.customer.Service.*;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.constant.FileCodeConstants;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.*;
import com.sifang.modules.customer.form.FinanceProjectFile;
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.platform.utils.PlantformUtils;
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.GuardUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.taskdispatch.service.CrmPriorReviewSettingService;
import com.sifang.modules.utils.util.IsInteger;
import com.sifang.modules.taskdispatch.dao.CrmReviewDispatchDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CustomerEntrySupplementService extends BaseService {

    @Autowired
    private CustomerEntrySupplementDao customerEntrySupplementDao;


    @Autowired
    CustomerEntryService entryService;

    @Autowired
    private CrmCustomerIncomingApplicationDao applicationDao;

    @Autowired
    private CustomerEntrySupplementDetailDao supplementDetailDao;

    @Autowired
    CustomerEntryMsgService entryMsgService;

    @Autowired
    OperatingLeaseService operatingLeaseService;

    @Autowired
    private CrmCustomerIncomingApplicationInsuranceDao insuranceDao;

    @Autowired
    private CrmCustomerIncomingApplicationDao crmCustomerIncomingApplicationDao;


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

    @Value("${yx.setting}")
    private String YX;

    @Autowired
    CustomerEntryDao customerDao;

    @Autowired
    private CustomerEntryExtraService entryExtraService;

    @Autowired
    private CrmAcceptingReportDao reportDao;

    @Autowired
    private ItemManageDao itemManageDao;

    @Autowired
    private ItemTaskDetailDao itemTaskDetailDao;

    @Autowired
    private CustomerEntrySurveyRecordDao surveyRecordDao;

    @Autowired
    private CrmReviewDispatchDao reviewDispatchDao;

    @Autowired
    @Lazy
    GuangFaManagemnetService guangFaManagemnetService;

    @Autowired
    HuaRongManagementService huaRongManagementService;

    @Autowired
    private CrmPriorReviewSettingService crmPriorReviewSettingService;


    public void listData(LayuiPage<Record> page, Map<String, String> reqMap, User user) {
        page.setData(customerEntrySupplementDao.selectList(page, reqMap, user));
    }

    public Record getChangeRecord(String id){
        Record record=customerEntrySupplementDao.getChangeRecord(id);
        return record;
    }

    public CustomerEntrySupplementDetail getChangeRecordDetail(String mainId, String type){
        CustomerEntrySupplementDetail detail=supplementDetailDao.getChangeRecordDetail(mainId,type);
        return detail;
    }

    //保存变更记录
    @Transactional(rollbackFor = Exception.class)
    public void addChangeRecord(CustomerEntrySupplementDetail recordVo){
        User user= UserUtils.getUser();
        //平台这边申请的记录 直接保存，不需要审核，代理商申请的变更，需要审核
        CustomerEntry entry = entryService.getById(recordVo.getEntryId());

        //判断电站是否有变更中的数据
        Long ifHaveChangeRecord=customerEntrySupplementDao.getIfHaveChangeRecord(recordVo.getEntryId());
        if(ifHaveChangeRecord>0){
            throw new BusinessException(" 有审核中的变更申请，不能重复申请!");
        }
        //进件状态是 并网资料待审核  和 并网商务审批拒绝的时候 才可以提交并网信息变更
        logger.info(">>>>>addChangeRecord   applyStatus:{},nextApplyStatus:{}",entry.getApplyStatus(),entry.getNextApplyStatus());
        if(PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())){
            if(("21".equals(entry.getApplyStatus()) || "NEW".equals(entry.getNextApplyStatus()) || "WAITING".equals(entry.getNextApplyStatus())) && Double.valueOf(entry.getApplyStatus())>16){

            }else{
                throw new BusinessException("越秀进件状态不允许提交并网信息变更!");
            }
        }else if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId()) && !"DS".equals(entry.getNextApplyStatus())){  //华融
            throw new BusinessException("华融进件状态不允许提交并网信息变更!");
        }else if(PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){  //广发
             if(StringUtil.isNotBlank(entry.getThreeApplyStatus()) && !StringUtil.equalsAny(entry.getThreeApplyStatus(),"20","40","50","10")){
                 throw new BusinessException("广发进件状态不允许提交并网信息变更!");
             }
        }


        //并网提交后的电站，校验必填
       /* if(StringUtil.equalsAny(entry.getMergeFlag(),"1","3","4")){
            GuardUtils.notBlank(recordVo.getGeneratorNo(),"变更后的发电户号不能为空!");
            GuardUtils.notBlank(recordVo.getProvinceCode(),"变更后的电力公司不能为空!");
            GuardUtils.notBlank(recordVo.getAddressConsistent(),"变更后的购售电地址是否一致不能为空!");
            if("N".equals(recordVo.getAddressConsistent())){
                GuardUtils.notBlank(recordVo.getElectricProvince(),"购售电地址-省不能为空!");
                GuardUtils.notBlank(recordVo.getElectricCity(),"购售电地址-市不能为空!");
                GuardUtils.notBlank(recordVo.getElectricArea(),"购售电地址-区不能为空!");
                GuardUtils.notBlank(recordVo.getElectricAddress(),"购售电地址-详细地址不能为空!");
            }
            GuardUtils.notBlank(recordVo.getYxImg(),"变更后的近三天发电量照片不能为空!");
        }*/
        CustomerEntrySupplement record=new CustomerEntrySupplement();
        record.setId(IdGen.uuid());
        record.setNumber(PlantformUtils.getOrderNumber());
        record.setEntryId(recordVo.getEntryId());
        record.setPowerStationCode(entry.getPowerStationCode());
        if("Y".equals(recordVo.getAddressConsistent())){  //购售电地址一样
            recordVo.setElectricProvince(entry.getProvince());
            recordVo.setElectricCity(entry.getCity());
            recordVo.setElectricArea(entry.getArea());
            recordVo.setElectricAddress(entry.getAddress());
        }
        Integer maxNum = customerEntrySupplementDao.selectMaxNum(recordVo.getEntryId());
        if(maxNum==null){
            record.setChangeCount(1);
        }else {
            record.setChangeCount(maxNum+1);
        }

        //获取电站进件
        CrmCustomerIncomingApplication application=crmCustomerIncomingApplicationDao.getByEntryId(entry.getId());

        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entry.getId());
        Date date=new Date();
        record.setCreator(user.getUserName());
        record.setCreateBy(user.getId());
        record.setCreateTime(date);
        record.setChangeReason(recordVo.getReason());
        record.setStatus("2");
        record.setAuditRemarks("");

        recordVo.setMainId(record.getId());
        recordVo.setChangeType("1");
        recordVo.setPowerStationCode(entry.getPowerStationCode());
        CrmAcceptingReport report = entryService.getReportById(entry.getReceivingReportId());
        recordVo.setPartnersContractNumber(application.getPartnersContractNumber());
        CustomerEntrySupplementDetail oldRecordDetail=new CustomerEntrySupplementDetail();
        oldRecordDetail.setMainId(record.getId());
        oldRecordDetail.setChangeType("0");
        oldRecordDetail.setEntryId(record.getEntryId());
        oldRecordDetail.setPowerStationCode(record.getPowerStationCode());
        oldRecordDetail.setPartnersContractNumber(recordVo.getPartnersContractNumber());
        oldRecordDetail.setResidenceBooklet(entry.getResidenceBooklet());
        oldRecordDetail.setBankCard(entry.getBankCard());
        oldRecordDetail.setBpFile(entry.getBpFile());
        oldRecordDetail.setHouseOwnership(surveyRecord.getHouseOwnership());
        oldRecordDetail.setGeneratorNo(entry.getGeneratorNo());
        oldRecordDetail.setProvinceCode(entry.getProvinceCode());
        oldRecordDetail.setAddressConsistent(entry.getAddressConsistent());
        oldRecordDetail.setElectricProvince(entry.getElectricProvince());
        oldRecordDetail.setElectricCity(entry.getElectricCity());
        oldRecordDetail.setElectricArea(entry.getElectricArea());
        oldRecordDetail.setElectricAddress(entry.getElectricAddress());
        oldRecordDetail.setYxImg(report.getYxImg());
        oldRecordDetail.setGebImg(report.getGebImg());
        oldRecordDetail.setTssBankNum(entry.getTssBankNum());
        oldRecordDetail.setTssBankNumName(entry.getTssBankNumName());
        oldRecordDetail.setBankCode(entry.getBankCode());
        oldRecordDetail.setIdCardFront(entry.getIdCardFront());
        oldRecordDetail.setIdCardBack(entry.getIdCardBack());
        oldRecordDetail.setAddress(entry.getAddress());
        oldRecordDetail.setBpCardBack(entry.getBpCardBack());
        oldRecordDetail.setBpCardFront(entry.getBpCardFront());
        oldRecordDetail.setCreateTime(date);
        oldRecordDetail.setPartnersContractNumber(application.getPartnersContractNumber());

        oldRecordDetail.setDbImgs(report.getDbImgs());
        oldRecordDetail.setContract(entry.getContract());
        oldRecordDetail.setContractFilename(entry.getContractFilename());

        oldRecordDetail.setGebImg2(report.getGebImg2());
        oldRecordDetail.setArchivesImg(report.getArchivesImg());
        oldRecordDetail.setContractVideoUrl(entry.getContractVideoUrl());
        oldRecordDetail.setDbxImgs(report.getDbxImgs());
        oldRecordDetail.setTlzhjkImgs(report.getTlzhjkImgs());
        oldRecordDetail.setPowerPlantCode(entry.getPowerPlantCode());
        oldRecordDetail.setProvinceCodeHand(entry.getProvinceCodeHand());
        oldRecordDetail.setPowerCapacityUrl(report.getPowerCapacityUrl());
        List<CrmCustomerIncomingApplicationInsurance> insurances=insuranceDao.getByEntryIds(entry.getId());
        insurances.forEach(insurance -> {
            oldRecordDetail.setBwtsFile(insurance.getBwtsFile());
            oldRecordDetail.setBwtsFilename(insurance.getBwtsFilename());
        });
        supplementDetailDao.save(oldRecordDetail);
        supplementDetailDao.save(recordVo);
        customerEntrySupplementDao.save(record);

        entryMsgService.saveCustomerEntryMsg(Operator.of(user), entry.getId(), CustomerEntryConstants.ENTRY_ADD_CHANGE
                , String.format("第%d次提交电站并网信息变更申请", record.getChangeCount()), null);
        String stationName = entry.getProvince()+entry.getArea()+entry.getTenantName();
        IsInteger str = new IsInteger();
        if(str.isInteger(entry.getStatus())&& StringUtil.equalsAny(entry.getStatus(),"0", "1", "2", "3","4") ){
            stationName = stationName +
                    (new BigDecimal(entry.getDesignCapacity()).divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString());
        }else{
            stationName= stationName +
                    (entry.getActualCapacity().divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString());
        }
        stationName = stationName + "KW光伏电站";
        ItemManage itemManage=itemManageDao.addItemChange(FormUtils.ENTRY_CHANGE_BWXXBG,entry.getId(),record.getId(),"并网信息变更("+stationName+"-"+entry.getPowerStationCode()+")-"+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss"),date,user.getUserName());
        //获取最近一次 并网验收/并网信息变更审核人
        String userId=itemManageDao.getLastAuditUserId("94,100",record.getEntryId());
        if(StringUtil.isNotBlank(userId)){
//			itemManage.setAssignAuditUserId(userId);
            itemManage.setPreferUserId(userId);
        }
        itemManageDao.save(itemManage);
        //大代理商优先审核
        String groupName = "并网审核";
        crmPriorReviewSettingService.traderPriorityReview(entry.getCreateTraderId(),itemManage.getId(),groupName);
    }

    //暂存
    @Transactional(rollbackFor = Exception.class)
    public void temp(String id,String auditRemarks) {
        CustomerEntrySupplement reportChange = customerEntrySupplementDao.get(id);
        if (!"2".equals(reportChange.getStatus())) {
            throw new BusinessException("状态已改变,刷新后重试");
        }
        reportChange.setAuditRemarks(auditRemarks);
        customerEntrySupplementDao.save(reportChange);
    }

    //审核通过
    @Transactional(rollbackFor = Exception.class)
    public void pass(String id,String auditRemarks){
        CustomerEntrySupplement reportChange = customerEntrySupplementDao.get(id);
        if (!"2".equals(reportChange.getStatus())) {
            throw new BusinessException("状态已改变,刷新后重试");
        }

        Date date=new Date();
        User user = UserUtils.getUser();
        reportChange.setStatus("3");
        reportChange.setAuditor(user.getUserName());
        reportChange.setAuditBy(user.getId());
        reportChange.setAuditTime(date);
        reportChange.setAuditRemarks(auditRemarks);
        customerEntrySupplementDao.save(reportChange);

        CustomerEntry entry = entryService.getById(reportChange.getEntryId());

        //变更后信息
        CustomerEntrySupplementDetail recordVo=supplementDetailDao.getChangeRecordDetail(reportChange.getId(),"1");
        //变更前信息
        CustomerEntrySupplementDetail oldRecord=supplementDetailDao.getChangeRecordDetail(reportChange.getId(),"0");
        //过程记录
        entryMsgService.saveCustomerEntryMsg(Operator.of(user), reportChange.getEntryId()
                , CustomerEntryConstants.ENTRY_CHANGE_PASS, "并网信息变更申请通过", null);

        CrmAcceptingReport report = entryService.getReportById(entry.getReceivingReportId());
        report.setYxImg(recordVo.getYxImg());
        report.setGebImg(recordVo.getGebImg());

        report.setGebImg2(recordVo.getGebImg2());
        report.setArchivesImg(recordVo.getArchivesImg());
        report.setDbxImgs(recordVo.getDbxImgs());
        report.setPowerCapacityUrl(recordVo.getPowerCapacityUrl());
        reportDao.save(report);

        if(StringUtil.isNotBlank(recordVo.getGeneratorNo())){
            entry.setGeneratorNo(recordVo.getGeneratorNo());
        }
        entry.setProvinceCode(recordVo.getProvinceCode());
        entry.setAddressConsistent(recordVo.getAddressConsistent());
        entry.setElectricProvince(recordVo.getElectricProvince());
        entry.setElectricCity(recordVo.getElectricCity());
        entry.setElectricArea(recordVo.getElectricArea());
        entry.setElectricAddress(recordVo.getElectricAddress());

        //客户信息
        if(StringUtil.isNotBlank(recordVo.getTssBankNum())){
             entry.setTssBankNum(recordVo.getTssBankNum());
             entry.setTssBankNumName(recordVo.getTssBankNumName());
        }
        if(StringUtil.isNotBlank(recordVo.getBankCode())){
            entry.setBankCode(recordVo.getBankCode());
        }
        if(StringUtil.isNotBlank(recordVo.getIdCardFront())){
            entry.setIdCardFront(recordVo.getIdCardFront());
        }
        if(StringUtil.isNotBlank(recordVo.getIdCardBack())){
            entry.setIdCardBack(recordVo.getIdCardBack());
        }
        if(StringUtil.isNotBlank(recordVo.getHouseOwnership())){
            CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entry.getId());
            surveyRecord.setHouseOwnership(recordVo.getHouseOwnership());
            surveyRecordDao.save(surveyRecord);
        }
        if(StringUtil.isNotBlank(recordVo.getBankCard())){
            entry.setBankCard(recordVo.getBankCard());
        }
        if(StringUtil.isNotBlank(recordVo.getAddress())){
            entry.setAddress(recordVo.getAddress());
        }
        if(StringUtil.isNotBlank(recordVo.getBpCardFront())){
            entry.setBpCardFront(recordVo.getBpCardFront());
        }
        if(StringUtil.isNotBlank(recordVo.getBpCardBack())){
            entry.setBpCardBack(recordVo.getBpCardBack());
        }
        if(StringUtil.isNotBlank(recordVo.getBpFile())){
            entry.setBpFile(recordVo.getBpFile());
        }
        if(StringUtil.isNotBlank(recordVo.getDbImgs())){
           report.setDbImgs(recordVo.getDbImgs());
        }
        if(StringUtil.isNotBlank(recordVo.getContract())){
            entry.setContract(recordVo.getContract());
        }
        if(StringUtil.isNotBlank(recordVo.getContractFilename())){
            entry.setContractFilename(recordVo.getContractFilename());
        }
        if(StringUtil.isNotBlank(recordVo.getBwtsFile())){
            List<CrmCustomerIncomingApplicationInsurance> insurances=insuranceDao.getByEntryIds(entry.getId());
            insurances.forEach(insurance->{
                insurance.setBwtsFile(recordVo.getBwtsFile());
                insurance.setBwtsFilename(recordVo.getBwtsFilename());
            });
            insuranceDao.save(insurances);
        }

        entry.setContractVideoUrl(recordVo.getContractVideoUrl());
        entry.setPowerPlantCode(recordVo.getPowerPlantCode());
        entry.setProvinceCodeHand(recordVo.getProvinceCodeHand());
        entry.setGridInstitution(recordVo.getGridInstitution());

        Operator operator=Operator.of(user);
        if(PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())){  //越秀
            //判断是否要重新推送并网信息 或者 只推送附件
            Boolean tsFg=false;
            Boolean fjFg=false;
            logger.info(">>>>>pass  并网信息变更通过   applyStatus:{}",entry.getApplyStatus());
            if("21".equals(entry.getApplyStatus())){  //这个是越秀并网资料审核驳回的
                //判断哪些是需要重新推送并网资料 哪些是直接推送附件就可以
                if(StringUtil.isNotBlank(recordVo.getTssBankNum()) || StringUtil.isNotBlank(recordVo.getBankCode()) || StringUtil.isNotBlank(recordVo.getAddress())){ //重新推送并网资料
                    tsFg=true;
                }else if(!entry.getGeneratorNo().equals(recordVo.getGeneratorNo())){  //发电户号
                    tsFg=true;
                }else if(!entry.getProjectCode().equals(recordVo.getProvinceCode())){ //电力公司
                    tsFg=true;
                }else if(!entry.getAddressConsistent().equals(recordVo.getAddressConsistent())){ // 购售电地址是否一致
                    tsFg=true;
                }else if(!entry.getElectricProvince().equals(recordVo.getElectricProvince())){   //购售电地址(省）
                    tsFg=true;
                }else if(!entry.getElectricCity().equals(recordVo.getElectricCity())){   //购售电地址(市）
                    tsFg=true;
                }else if(!entry.getElectricArea().equals(recordVo.getElectricArea())){   //购售电地址(区）
                    tsFg=true;
                }else if(!entry.getElectricAddress().equals(recordVo.getElectricAddress())){   //购售电地址(详细地址）
                    tsFg=true;
                }
                fjFg=true;
            }
            logger.info(">>>>>pass  并网信息变更通过   tsFg:{},fjFj:{}",tsFg,fjFg);
            if(tsFg){ //重新推送并网资料(这里面附件资料一并推送了)
                entryExtraService.addIncomingApplicationSec(entry,operator,recordVo);
                entryMsgService.saveEntryMsg(operator, entry.getId(), CustomerEntryConstants.INCOMING_THREE,"并网信息变更审核通过后，推送并网资料！");
                logger.info(">>>>>pass   重新推送并网资料");
            }else if(fjFg){  //只推送附件
                pushYueXiu(entry,recordVo,oldRecord);
                logger.info(">>>>>pass   只推送附件");
                entryMsgService.saveEntryMsg(operator, entry.getId(), CustomerEntryConstants.INCOMING_THREE,"并网信息变更审核通过后，推送变更的附件资料！");
            }
        }else if(PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){   //广发
            CrmCustomerIncomingApplication application = applicationDao.getByEntryId(entry.getId());
            if(StringUtil.isNotBlank(entry.getThreeApplyStatus()) && StringUtil.equalsAny(application.getMergeSate(),"20","40","50")){  //审核驳回 、待审核
                guangFaManagemnetService.gridIncomingApplication(entry,application,report,operator);
            }
        }else if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){    //华融
//            CrmCustomerIncomingApplication application = applicationDao.getByEntryId(entry.getId());
//            if(StringUtil.isNotBlank(application.getFarmerSignStatus()) && StringUtil.equalsAny(application.getFarmerSignStatus(),"DS","RJ")){  //审核驳回 、待进件
//                huaRongManagementService.accessProjectApplyTwo(entry, application,operator);
//            }
        }


        entryService.saveByUpdate(entry);

        ItemManage itemManage= itemManageDao.getItemManagementByProcessInstanceId(reportChange.getId(),FormUtils.ENTRY_CHANGE_BWXXBG);
        if (itemManage != null) {
            itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_CHANGE_BWXXBG,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);
        }
    }

    /**
     * 越秀并网驳回之后，需要补充信息授权书 只适用于这个特殊情况
     * @param entry
     */
    public Result pushAuthorizationYueXiu(CustomerEntry entry) {
        try {
            CrmCustomerIncomingApplication application = applicationDao.getByEntryId(entry.getId()); //进件信息
            List<FinanceProjectFile> fileList = new ArrayList<>();
            String contractPath = entryService.getContractPath(entry);
            FinanceProjectFile projectFileb = new FinanceProjectFile();
            int filenameLengb = contractPath.lastIndexOf(".");
            String extNameb = contractPath.substring(filenameLengb).toLowerCase();
            projectFileb.setFileName("信息授权使用书-补充" + extNameb);
            projectFileb.setFileCode(FileCodeConstants.GR_FILE_C_12);
            projectFileb.setFileAddress(commonStaticImgPath + contractPath);
            fileList.add(projectFileb);
            return operatingLeaseService.updateFile2(entry, fileList, "01", application.getPartnersContractNumber(), "4");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Result.fail(e.getMessage());
        }

    }

    public void pushYueXiu(CustomerEntry entry,CustomerEntrySupplementDetail recordVo,CustomerEntrySupplementDetail oldRecord){
        List<FinanceProjectFile> fileList = new ArrayList<>();
        String codeFile14 = ("1".equals(entry.getTenantType()) ? FileCodeConstants.GR_FILE_C_07 : FileCodeConstants.DW_FILE_C_01);
        if(!oldRecord.getYxImg().equals(recordVo.getYxImg())){
            FinanceProjectFile projectFile7 = new FinanceProjectFile();
            int filenameLeng7 = recordVo.getYxImg().lastIndexOf(".");
            String extName7 = recordVo.getYxImg().substring(filenameLeng7).toLowerCase();
            projectFile7.setFileName("并网资料-近3天发电量" + extName7);
            projectFile7.setFileCode(codeFile14);
            projectFile7.setFileAddress(commonStaticImgPath+recordVo.getYxImg());
            fileList.add(projectFile7);
        }

        if(!oldRecord.getDbImgs().equals(recordVo.getDbImgs())){
            FinanceProjectFile projectFile9 = new FinanceProjectFile();
            int filenameLeng9 = recordVo.getDbImgs().lastIndexOf(".");
            String extName9 = recordVo.getDbImgs().substring(filenameLeng9).toLowerCase();
            projectFile9.setFileName("并网资料-电表照片" + extName9);
            projectFile9.setFileCode(codeFile14);
            projectFile9.setFileAddress(commonStaticImgPath+recordVo.getDbImgs());
            fileList.add(projectFile9);
        }

        if(!oldRecord.getContract().equals(recordVo.getContract())){
            String[] arr=recordVo.getContract().split(",");
            int i=1;
            for(String fcz:arr){
                if(StringUtil.isBlank(fcz)){
                    continue;
                }
                FinanceProjectFile projectFileb = new FinanceProjectFile();
                int filenameLengb = fcz.lastIndexOf(".");
                String extNameb = fcz.substring(filenameLengb).toLowerCase();
                projectFileb.setFileName("购售电合同"+i + extNameb);
                projectFileb.setFileCode(codeFile14);
                projectFileb.setFileAddress(commonStaticImgPath+fcz);
                fileList.add(projectFileb);
                i++;
            }
        }

        if ("1".equals(entry.getTenantType())) {
           if(!oldRecord.getBwtsFile().equals(recordVo.getBwtsFile())){
               FinanceProjectFile projectFile13 = new FinanceProjectFile();
               int filenameLeng13 = recordVo.getBwtsFile().lastIndexOf(".");
               String extName13 = recordVo.getBwtsFile().substring(filenameLeng13).toLowerCase();
               projectFile13.setFileName("并网调试报告" + extName13);
               projectFile13.setFileCode(codeFile14);
               projectFile13.setFileAddress(commonStaticImgPath + recordVo.getBwtsFile());
               fileList.add(projectFile13);
           }
        }
        String codeFile12 = ("1".equals(entry.getTenantType()) ? FileCodeConstants.GR_FILE_C_12 : FileCodeConstants.DW_FILE_C_15);
        if(!oldRecord.getGebImg().equals(recordVo.getGebImg())){
            FinanceProjectFile projectFileb = new FinanceProjectFile();
            int filenameLengb = recordVo.getGebImg().lastIndexOf(".");
            String extNameb = recordVo.getGebImg().substring(filenameLengb).toLowerCase();
            projectFileb.setFileName("并网资料-补充" + extNameb);
            projectFileb.setFileCode(codeFile12);
            projectFileb.setFileAddress(commonStaticImgPath+recordVo.getGebImg());
            fileList.add(projectFileb);
        }
        if(StringUtil.isNotBlank(recordVo.getIdCardFront())){  //身份证正面
            FinanceProjectFile projectFileb = new FinanceProjectFile();
            int filenameLengb = recordVo.getIdCardFront().lastIndexOf(".");
            String extNameb = recordVo.getIdCardFront().substring(filenameLengb).toLowerCase();
            projectFileb.setFileName("身份证正面" + extNameb);
            projectFileb.setFileCode(codeFile12);
            projectFileb.setFileAddress(commonStaticImgPath+recordVo.getIdCardFront());
            fileList.add(projectFileb);
        }
        if(StringUtil.isNotBlank(recordVo.getIdCardBack())){  //身份证反面
            FinanceProjectFile projectFileb = new FinanceProjectFile();
            int filenameLengb = recordVo.getIdCardBack().lastIndexOf(".");
            String extNameb = recordVo.getIdCardBack().substring(filenameLengb).toLowerCase();
            projectFileb.setFileName("身份证反面" + extNameb);
            projectFileb.setFileCode(codeFile12);
            projectFileb.setFileAddress(commonStaticImgPath+recordVo.getIdCardBack());
            fileList.add(projectFileb);
        }
        if(StringUtil.isNotBlank(recordVo.getHouseOwnership())){  //房产证
            String[] arr=recordVo.getHouseOwnership().split(",");
            int i=1;
            for(String fcz:arr){
                if(StringUtil.isBlank(fcz)){
                    continue;
                }
                FinanceProjectFile projectFileb = new FinanceProjectFile();
                int filenameLengb = fcz.lastIndexOf(".");
                String extNameb = fcz.substring(filenameLengb).toLowerCase();
                projectFileb.setFileName("房产证明文件"+i + extNameb);
                projectFileb.setFileCode(codeFile12);
                projectFileb.setFileAddress(commonStaticImgPath+fcz);
                fileList.add(projectFileb);
                i++;
            }

        }
        if(StringUtil.isNotBlank(recordVo.getBpCardFront())){  //共签人身份证正面
            FinanceProjectFile projectFileb = new FinanceProjectFile();
            int filenameLengb = recordVo.getBpCardFront().lastIndexOf(".");
            String extNameb = recordVo.getBpCardFront().substring(filenameLengb).toLowerCase();
            projectFileb.setFileName("共签人身份证正面" + extNameb);
            projectFileb.setFileCode(codeFile12);
            projectFileb.setFileAddress(commonStaticImgPath+recordVo.getBpCardFront());
            fileList.add(projectFileb);
        }
        if(StringUtil.isNotBlank(recordVo.getBpCardBack())){  //共签人身份证反面
            FinanceProjectFile projectFileb = new FinanceProjectFile();
            int filenameLengb = recordVo.getBpCardBack().lastIndexOf(".");
            String extNameb = recordVo.getBpCardBack().substring(filenameLengb).toLowerCase();
            projectFileb.setFileName("共签人身份证反面" + extNameb);
            projectFileb.setFileCode(codeFile12);
            projectFileb.setFileAddress(commonStaticImgPath+recordVo.getBpCardBack());
            fileList.add(projectFileb);
        }
        if(StringUtil.isNotBlank(recordVo.getBpFile())){  //共签人子女证明材料
            FinanceProjectFile projectFileb = new FinanceProjectFile();
            int filenameLengb = recordVo.getBpFile().lastIndexOf(".");
            String extNameb = recordVo.getBpFile().substring(filenameLengb).toLowerCase();
            projectFileb.setFileName("共签人子女证明材料" + extNameb);
            projectFileb.setFileCode(codeFile12);
            projectFileb.setFileAddress(commonStaticImgPath+recordVo.getBpFile());
            fileList.add(projectFileb);
        }
        if(StringUtil.isNotBlank(recordVo.getBankCard())){  //
            FinanceProjectFile projectFileb = new FinanceProjectFile();
            int filenameLengb = recordVo.getBankCard().lastIndexOf(".");
            String extNameb = recordVo.getBankCard().substring(filenameLengb).toLowerCase();
            projectFileb.setFileName("银行卡照片" + extNameb);
            projectFileb.setFileCode(codeFile12);
            projectFileb.setFileAddress(commonStaticImgPath+recordVo.getBankCard());
            fileList.add(projectFileb);
        }

        if(StringUtil.isNotBlank(recordVo.getOtherAttachment())){
            String[] arr=recordVo.getOtherAttachment().split(",");
            int i=1;
            for(String qtfj:arr){
                if(StringUtil.isBlank(qtfj)){
                    continue;
                }
                FinanceProjectFile projectFileb = new FinanceProjectFile();
                int filenameLengb = qtfj.lastIndexOf(".");
                String extNameb = qtfj.substring(filenameLengb).toLowerCase();
                projectFileb.setFileName("其他附件信息"+i + extNameb);
                projectFileb.setFileCode(codeFile12);
                projectFileb.setFileAddress(commonStaticImgPath+qtfj);
                fileList.add(projectFileb);
                i++;
            }
        }
        if(fileList.size()>0){
            //上传附件
            operatingLeaseService.updateFile2(entry,fileList,"01",recordVo.getPartnersContractNumber(),"4");
        }

    }

    //审核驳回
    @Transactional(rollbackFor = Exception.class)
    public void refuse(String id,String auditRemarks){
        CustomerEntrySupplement surveyChangeRecord = customerEntrySupplementDao.get(id);
        if (!"2".equals(surveyChangeRecord.getStatus())) {
            throw new BusinessException("状态已改变,刷新后重试");
        }

        User user = UserUtils.getUser();
        Date date=new Date();
        surveyChangeRecord.setStatus("4");
        surveyChangeRecord.setAuditor(CrmUtils.getUserXM(user));
        surveyChangeRecord.setAuditBy(user.getId());
        surveyChangeRecord.setAuditTime(date);
        surveyChangeRecord.setAuditRemarks(auditRemarks);
        customerEntrySupplementDao.save(surveyChangeRecord);
        String msg=StringUtil.isBlank(auditRemarks)?"":",驳回原因:"+auditRemarks;
        entryMsgService.saveCustomerEntryMsg(Operator.of(user), surveyChangeRecord.getEntryId()
                , CustomerEntryConstants.ENTRY_CHANGE_REFUSE, "并网信息变更申请驳回"+msg, null);

        ItemManage itemManage= itemManageDao.getItemManagementByProcessInstanceId(surveyChangeRecord.getId(),FormUtils.ENTRY_CHANGE_BWXXBG);
        if (itemManage != null) {
            Operator operator=Operator.of(user);
            itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_CHANGE_BWXXBG,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 back(String id) {
        CustomerEntrySupplement changeRecord = customerEntrySupplementDao.get(id);
        if (!StringUtil.equalsAny(changeRecord.getStatus(),"1","2")) {
            throw new BusinessException("状态已改变,刷新后重试");
        }
        User user = UserUtils.getUser();
        changeRecord.setStatus("0");
        changeRecord.setAuditor(CrmUtils.getUserXM(user));
        changeRecord.setAuditBy(user.getId());
        customerEntrySupplementDao.save(changeRecord);

        entryMsgService.saveCustomerEntryMsg(Operator.of(user), changeRecord.getEntryId()
                , CustomerEntryConstants.ENTRY_CHANGE_CANCEL, "并网信息变更申请撤回", null);

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

    }

}
