package com.sifang.modules.customer.Service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.account.constant.TraderAccountSettleDetailConstants;
import com.sifang.modules.account.dao.TraderAccountDao;
import com.sifang.modules.account.dao.TraderAccountSettleDetailDao;
import com.sifang.modules.account.entity.CrmTraderAccount;
import com.sifang.modules.account.entity.CrmTraderAccountSettleDetail;
import com.sifang.modules.changes.entity.CustomerEntrySupplementDetail;
import com.sifang.modules.customer.constant.*;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.*;
import com.sifang.modules.customer.form.AddIncomingApplication;
import com.sifang.modules.customer.form.FinanceProjectFile;
import com.sifang.modules.customer.form.QueryDocumentRes;
import com.sifang.modules.flowable.dao.ItemManageDao;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.setting.constant.ProcessSetConstants;
import com.sifang.modules.sunshine.SystemSetting.service.SubconractorSettlementSchemeService;
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.sunshine.settleSet.dao.RewardsPunishWayDao;
import com.sifang.modules.sunshine.settleSet.entity.CrmRewardsPunishWay;
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.GuardUtils;
import com.sifang.modules.sys.util.SqlBuilder;
import com.sifang.modules.youkua.service.NhPowerStationService;
import org.apache.commons.lang3.StringUtils;
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.math.BigDecimal;
import java.util.*;


@Service
public class CustomerEntryExtraService extends BaseService {

    @Autowired
    private CustomerEntryService customerEntryService;
    @Autowired
    OperatingLeaseService operatingLeaseService;

    @Autowired
    private CrmCustomerIncomingApplicationBasicDao basicDao;

    @Autowired
    private CrmCustomerIncomingApplicationPerInfoDao perInfoDao;

    @Autowired
    private CrmCustomerIncomingApplicationRetailPayInfoDao retailPayInfoDao;

    @Autowired
    private CrmCustomerIncomingApplicationDao applicationDao;

    @Autowired
    private CrmCustomerIncomingApplicationLeaseItemDao itemDao;

    @Autowired
    private CrmCustomerIncomingApplicationInsuranceDao insuranceDao;

    @Autowired
    CustomerEntryMsgService msgService;

    @Autowired
    private TraderAccountSettleDetailDao accountSettleDetailDao;

    @Autowired
    private TraderAccountDao accountDao;

    @Autowired
    private CustomerEntryTenantDao tenantDao;

    @Autowired
    private CrmCustomerIncomingApplicationDao crmCustomerIncomingApplicationDao;

    @Autowired
    private CrmYxIncomingLogDao yxIncomingLogDao;

    @Autowired
    private ItemManageDao itemManageDao;

    @Autowired
    private RewardsPunishWayDao rewardsPunishWayDao;

    @Autowired
    private SubconractorSettlementSchemeService settlementSchemeService;

    @Autowired
    private AccountSetService accountSetService;

    @Autowired
    private CustomerEntrySurveyRecordDao surveyRecordDao;

    @Autowired
    private CrmEntryCombinerBoxGroupService boxGroupService;

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

    @Autowired
    private NhPowerStationService nhPowerStationService;


    @Transactional(rollbackFor = Exception.class)
    public void addIncomingApplication(AddIncomingApplication addIncomingApplication, Operator operator){

        String entryId=addIncomingApplication.getEntryId();

        CustomerEntry entry = customerEntryService.getById(entryId);



//        if(StringUtil.isBlank(entry.getManagementType())){
//            throw new IllegalArgumentException("该项目没有资方，不需要进件申请!");
//        }
        Date date= new Date();

        //基本信息
        CrmCustomerIncomingApplicationBasic applicationBasic=addIncomingApplication.getApplicationBasic();

        //客户信息
        CrmCustomerIncomingApplicationPerInfo perInfo=addIncomingApplication.getPerInfo();

        //设备清单
        CrmCustomerIncomingApplicationLeaseItem leaseItem=addIncomingApplication.getLeaseItem();

        CrmCustomerIncomingApplication application=applicationDao.getByEntryId(entryId); //之前申请过

        if(application==null){
            application=new CrmCustomerIncomingApplication();
            application.setEntryId(entryId);
        }
        application.setImgUpload(CustomerEntryConstants.IMG_UPLOAD_NO);
        application.setUpdateTime(date);

        applicationBasic.setEntryId(entryId);
        applicationBasic.setDistributor(entry.getTraderName());
        applicationBasic.setLeaseChannel("40");
        applicationBasic.setStatus(SourceConstants.STATUS_ZERO);


        perInfo.setEntryId(entryId);
        perInfo.setName(entry.getTenantName());
        perInfo.setIdCardNo(entry.getIdCode());
        perInfo.setTelephoneNum(entry.getMobile());
        perInfo.setFamilyAddr(getAddr(entry.getProvince(),entry.getCity(),entry.getArea()));
        perInfo.setFamilyAddrDetails(entry.getAddress());
        if(StringUtil.isNotBlank(perInfo.getProvince()) && StringUtil.isNotBlank(perInfo.getCity()) && StringUtil.isNotBlank(perInfo.getArea())){
            perInfo.setMailingAddr(perInfo.getProvince()+","+perInfo.getCity()+","+perInfo.getArea());
        }


        perInfo.setStatus(SourceConstants.STATUS_ZERO);

        leaseItem.setId(IdGen.uuid());
        leaseItem.setEntryId(entryId);

        if(SourceConstants.STATUS_ZERO.equals(addIncomingApplication.getResultType())){   //// 0 暂存  1 提交
        }else{
//            checkField(addIncomingApplication,"1");

            application.setApplyBy(operator.getUserId());
            application.setApplyTime(date);

            //提交进件申请
//            Result result = operatingLeaseService.accessProjectApply(entry,application,perInfo,leaseItem,applicationBasic);
//            if (!"200".equals(result.getCode())) {
//                throw new IllegalArgumentException(result.getErrMsg());
//            }
            msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.ADVANCE_TYPE_INCOMING_TYPE_SUBMIT);

            //上传资料
//            updateIncomingApplicationFile(entry);
        }
        customerEntryService.saveByUpdate(entry);

        applicationDao.save(application);

        //删除之前保存的申请信息
        basicDao.deleteRecord(application.getId());
        perInfoDao.deleteRecord(application.getId());

        itemDao.deleteRecord(entryId);

        itemDao.save(leaseItem);

        applicationBasic.setApplicationId(application.getId());
        basicDao.save(applicationBasic);

        perInfo.setApplicationId(application.getId());
        perInfoDao.save(perInfo);
    }

    @Transactional(rollbackFor = Exception.class)
    public void addIncomingApplicationSec(CustomerEntry entry, Operator operator, CustomerEntrySupplementDetail changeRecordVo){
   /*     logger.info(">>>>>>>>>>>推送并网信息 entryId:{}",addIncomingApplication.getEntryId());
        String entryId=addIncomingApplication.getEntryId();
        CustomerEntry entry = customerEntryService.getById(entryId);
*/
//        if (CustomerEntryConstants.APPLY_STATUS_BWYTJ.equals(entry.getApplyStatus())) {
//            throw new IllegalArgumentException("该项目进件状态已更新，请刷新!");
//        }

        CrmCustomerIncomingApplicationInsurance insurance = insuranceDao.getByEntryId(entry.getId());
        if (insurance ==null) {
            throw new IllegalArgumentException("该项目无保险信息!");
        }
        String entryId = entry.getId();

        // insurance.setEntryId(entryId);

        if (insurance.getInsuranceAmount() != null) {
            BigDecimal totalAmount = getTotalAmount(entryId);
            if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) {
                if (totalAmount.compareTo(insurance.getInsuranceAmount()) > 0) {
                    throw new IllegalArgumentException("保险金额要大于租赁物总额!");
                }
            }
        }

        //if(SourceConstants.STATUS_ONE.equals(addIncomingApplication.getResultType())){   //提交

        if ("1".equals(entry.getTenantType()) && !StringUtil.equalsAny(entry.getSignStatus(),"2","3","5","g","e")
        &&FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZFSH)) {
            throw new BusinessException("当前电站未签约《农户合同》，请在签约后再提交并网申请!");
        }
        if(FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_TFZLTS)){
            if (!"WAITING".equals(entry.getNextApplyStatus())) {
                throw new IllegalArgumentException("资方完工资料还未审核通过 ，无法并网验收通过进行并网信息推送");
            } else {
                checkField(insurance);
                  /*  //判断备案证 ，项目公司备案的时候是必传，农户备案的时候是非必填
                    if("2".equals(entry.getFilingType())){
                        GuardUtils.notBlank(insurance.getFilingCardFile(),"备案证不能为空！");
                    }*/
                GuardUtils.notBlank(insurance.getBwtsFile(),"并网调试报告不能为空！");
                CrmCustomerIncomingApplication incomingApplication=applicationDao.getByEntryId(entry.getId()); //进件信息
                //提交进件申请
                Result result = operatingLeaseService.accessProjectApplyThree(entry,insurance,incomingApplication);
                if (!"200".equals(result.getCode())) {
                    throw new IllegalArgumentException(result.getErrMsg());
                }
                //判断汇流组的发电户号
                boxGroupService.saveSameBoxGroupGeneratorNo(entryId,entry.getGeneratorNo());

                msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.ADVANCE_TYPE_INCOMING_TYPE_SUBMIT);
                    //上传资料
                    updateThirdFile(entry, insurance, incomingApplication.getPartnersContractNumber(),changeRecordVo);

                    entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_BWYTJ);
                    entry.setNextApplyStatus("NEW");
                    incomingApplication.setStatus(entry.getApplyStatus());
                    incomingApplication.setFarmerSignStatus("NEW");
                    applicationDao.save(incomingApplication);
                    yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(), incomingApplication.getPartnersContractNumber(), "5", "推送并网资料信息", operator);
                    //  customerEntryService.saveByUpdate(entry);
                }
             }
        insuranceDao.save(insurance);
    }


    @Transactional(rollbackFor = Exception.class)
    public void addIncomingApplicationSec(AddIncomingApplication application, Operator operator, boolean temp){
        String entryId=application.getEntryId();
        CustomerEntry entry = customerEntryService.getById(entryId);
//        if (CustomerEntryConstants.APPLY_STATUS_BWYTJ.equals(entry.getApplyStatus())) {
//            throw new IllegalArgumentException("该项目进件状态已更新，请刷新!");
//        }
        CrmCustomerIncomingApplicationInsurance insurancereq = application.getInsurance();

        List<CrmCustomerIncomingApplicationInsurance> insurances = insuranceDao.getByEntryIds(entry.getId());
        CrmCustomerIncomingApplicationInsurance insurance = null;
        if (insurances.isEmpty()) {
            insurances = new ArrayList<>();
            insurance = new CrmCustomerIncomingApplicationInsurance();
            insurance.setBwtsFile(insurancereq.getBwtsFile());
            insurance.setBwtsFilename(insurancereq.getBwtsFilename());
            insurance.setEntryId(entryId);
            insurances.add(insurance);
        }else{
            insurances.forEach(criteria -> {
                criteria.setBwtsFile(insurancereq.getBwtsFile());
                criteria.setBwtsFilename(insurancereq.getBwtsFilename());
                criteria.setEntryId(entryId);
            });
        }
        if(!temp){
    /*        if (insurance.getInsuranceAmount() != null) {
                BigDecimal totalAmount = getTotalAmount(entryId);
                if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) {
                    if (totalAmount.compareTo(insurance.getInsuranceAmount()) > 0) {
                        throw new IllegalArgumentException("保险金额要大于租赁物总额!");
                    }
                }
            }*/
        /*    if ("1".equals(entry.getTenantType()) &&!StringUtil.equalsAny(entry.getSignStatus(),"2","3","5")
            &&FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZFSH)) {
                throw new BusinessException("当前电站未签约《农户合同》，请在签约后再提交并网申请!");
            }*/

           // checkField(insurance);
        }

        insuranceDao.save(insurances);
    }

    //第三次进件资料上传-农户投放审查
    public Result updateThirdFile(CustomerEntry entry, CrmCustomerIncomingApplicationInsurance insurance,String partnersContractNumber, CustomerEntrySupplementDetail changeRecordVo) {
        List<FinanceProjectFile> fileList = new ArrayList<>();
        // 查询勘测记录
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entry.getId());
        String codeFile08 = ("1".equals(entry.getTenantType()) ? FileCodeConstants.GR_FILE_C_08 : FileCodeConstants.DW_FILE_C_02);
        FinanceProjectFile projectFile8 = new FinanceProjectFile();
        int filenameLeng8 = insurance.getInsurancePolicy().lastIndexOf(".");
        String extName8 = insurance.getInsurancePolicy().substring(filenameLeng8).toLowerCase();
        projectFile8.setFileName("保险单" + extName8);
        projectFile8.setFileCode(codeFile08);
        projectFile8.setFileAddress(commonStaticImgPath+insurance.getInsurancePolicy());
        fileList.add(projectFile8);

        String codeFile14 = ("1".equals(entry.getTenantType()) ? FileCodeConstants.GR_FILE_C_07 : FileCodeConstants.DW_FILE_C_01);
        if ("1".equals(entry.getTenantType())) {
            FinanceProjectFile projectFile13 = new FinanceProjectFile();
            int filenameLeng13 = insurance.getBwtsFile().lastIndexOf(".");
            String extName13 = insurance.getBwtsFile().substring(filenameLeng13).toLowerCase();
            projectFile13.setFileName("并网调试报告" + extName13);
            projectFile13.setFileCode(codeFile14);
            projectFile13.setFileAddress(commonStaticImgPath + insurance.getBwtsFile());
            fileList.add(projectFile13);
        }

        int j=1;
        String[] arrImg = entry.getContract().split(",");
        String names = "购售电合同";
        for(String img:arrImg){
            if(StringUtil.isBlank(img)) continue;
            FinanceProjectFile file = customerEntryService.createFinanceProjectFile(j, img, names, codeFile14);
            fileList.add(file);
            j++;
        }
        if (StringUtil.isNotBlank(entry.getContractVideoUrl())) {
            String[] arrVideoImg = entry.getContractVideoUrl().split(",");
            String nameVideos = "购售电合同视频";
            j=1;
            for(String img:arrVideoImg){
                if(StringUtil.isBlank(img)) continue;
                FinanceProjectFile file = customerEntryService.createFinanceProjectFile(j, img, nameVideos, codeFile14);
                fileList.add(file);
                j++;
            }
        }


        // 发电并网照片 - 近3天发电量
        CrmAcceptingReport report = customerEntryService.getReportById(entry.getReceivingReportId());
        FinanceProjectFile projectFile7 = new FinanceProjectFile();
        int filenameLeng7 = report.getYxImg().lastIndexOf(".");
        String extName7 = report.getYxImg().substring(filenameLeng7).toLowerCase();
        projectFile7.setFileName("并网资料-近3天发电量" + extName7);
        projectFile7.setFileCode(codeFile14);
        projectFile7.setFileAddress(commonStaticImgPath+report.getYxImg());
        fileList.add(projectFile7);

        // 并网资料 -三户档案截图
        if (StringUtil.isNotBlank(report.getArchivesImg())) {
            FinanceProjectFile projectFile9 = new FinanceProjectFile();
            int filenameLeng9 = report.getArchivesImg().lastIndexOf(".");
            String extName9 = report.getArchivesImg().substring(filenameLeng9).toLowerCase();
            projectFile9.setFileName("并网资料 -三户档案截图" + extName9);
            projectFile9.setFileCode(codeFile14);
            projectFile9.setFileAddress(commonStaticImgPath+report.getArchivesImg());
            fileList.add(projectFile9);
        }

        // 发电并网照片 - 补充
        if (StringUtil.isNotBlank(report.getGebImg())) {
            FinanceProjectFile projectFile9 = new FinanceProjectFile();
            int filenameLeng9 = report.getGebImg().lastIndexOf(".");
            String extName9 = report.getGebImg().substring(filenameLeng9).toLowerCase();
            projectFile9.setFileName("并网资料-补充" + extName9);
            projectFile9.setFileCode(codeFile14);
            projectFile9.setFileAddress(commonStaticImgPath+report.getGebImg());
            fileList.add(projectFile9);
        }

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

        //备案证
        if ("2".equals(entry.getFilingType())) {
            String codeFile15 = ("1".equals(entry.getTenantType()) ? FileCodeConstants.GR_FILE_C_14 : FileCodeConstants.DW_FILE_C_03);
            int i=1;
            String[] arr= surveyRecord.getFilingDocumentPhoto().split(",");
            String name = ("1".equals(entry.getTenantType()) ? "备案证" : "备案文件");
            for(String img:arr){
                if(StringUtil.isBlank(img)) continue;
                FinanceProjectFile file = customerEntryService.createFinanceProjectFile(i, img, name, codeFile15);
                fileList.add(file);
                i++;
            }
        }
        String codeFile12 = ("1".equals(entry.getTenantType()) ? FileCodeConstants.GR_FILE_C_12 : FileCodeConstants.DW_FILE_C_15);
        //资方审查补充资料
        if(StringUtil.isNotBlank(entry.getOtherAttachment())){
            String[] arr=entry.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(changeRecordVo!=null){
            if("1".equals(entry.getTenantType())){
                if(StringUtil.isNotBlank(changeRecordVo.getIdCardFront())){  //身份证正面
                    FinanceProjectFile projectFileb = new FinanceProjectFile();
                    int filenameLengb = changeRecordVo.getIdCardFront().lastIndexOf(".");
                    String extNameb = changeRecordVo.getIdCardFront().substring(filenameLengb).toLowerCase();
                    projectFileb.setFileName("身份证正面" + extNameb);
                    projectFileb.setFileCode(codeFile12);
                    projectFileb.setFileAddress(commonStaticImgPath+changeRecordVo.getIdCardFront());
                    fileList.add(projectFileb);
                }
                if(StringUtil.isNotBlank(changeRecordVo.getIdCardBack())){  //身份证反面
                    FinanceProjectFile projectFileb = new FinanceProjectFile();
                    int filenameLengb = changeRecordVo.getIdCardBack().lastIndexOf(".");
                    String extNameb = changeRecordVo.getIdCardBack().substring(filenameLengb).toLowerCase();
                    projectFileb.setFileName("身份证反面" + extNameb);
                    projectFileb.setFileCode(codeFile12);
                    projectFileb.setFileAddress(commonStaticImgPath+changeRecordVo.getIdCardBack());
                    fileList.add(projectFileb);
                }

                if(StringUtil.isNotBlank(changeRecordVo.getHouseOwnership())){  //房产证
                    String[] arr=changeRecordVo.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(changeRecordVo.getBpCardFront())){  //共签人身份证正面
                    FinanceProjectFile projectFileb = new FinanceProjectFile();
                    int filenameLengb = changeRecordVo.getBpCardFront().lastIndexOf(".");
                    String extNameb = changeRecordVo.getBpCardFront().substring(filenameLengb).toLowerCase();
                    projectFileb.setFileName("共签人身份证正面" + extNameb);
                    projectFileb.setFileCode(codeFile12);
                    projectFileb.setFileAddress(commonStaticImgPath+changeRecordVo.getBpCardFront());
                    fileList.add(projectFileb);
                }
                if(StringUtil.isNotBlank(changeRecordVo.getBpCardBack())){  //共签人身份证反面
                    FinanceProjectFile projectFileb = new FinanceProjectFile();
                    int filenameLengb = changeRecordVo.getBpCardBack().lastIndexOf(".");
                    String extNameb = changeRecordVo.getBpCardBack().substring(filenameLengb).toLowerCase();
                    projectFileb.setFileName("共签人身份证反面" + extNameb);
                    projectFileb.setFileCode(codeFile12);
                    projectFileb.setFileAddress(commonStaticImgPath+changeRecordVo.getBpCardBack());
                    fileList.add(projectFileb);
                }

                if(StringUtil.isNotBlank(changeRecordVo.getBpFile())){  //共签人子女证明材料
                    FinanceProjectFile projectFileb = new FinanceProjectFile();
                    int filenameLengb = changeRecordVo.getBpFile().lastIndexOf(".");
                    String extNameb = changeRecordVo.getBpFile().substring(filenameLengb).toLowerCase();
                    projectFileb.setFileName("共签人子女证明材料" + extNameb);
                    projectFileb.setFileCode(codeFile12);
                    projectFileb.setFileAddress(commonStaticImgPath+changeRecordVo.getBpFile());
                    fileList.add(projectFileb);
                }

                if(StringUtil.isNotBlank(changeRecordVo.getBankCard())){  //
                    FinanceProjectFile projectFileb = new FinanceProjectFile();
                    int filenameLengb = changeRecordVo.getBankCard().lastIndexOf(".");
                    String extNameb = changeRecordVo.getBankCard().substring(filenameLengb).toLowerCase();
                    projectFileb.setFileName("银行卡照片" + extNameb);
                    projectFileb.setFileCode(codeFile12);
                    projectFileb.setFileAddress(commonStaticImgPath+changeRecordVo.getBankCard());
                    fileList.add(projectFileb);
                }
            }

            if(StringUtil.isNotBlank(changeRecordVo.getOtherAttachment())){
                String[] arr=changeRecordVo.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++;
                }
            }
        }

        return operatingLeaseService.updateFile2(entry,fileList,"01",partnersContractNumber,"4");

    }

    //进件审核通过
    @Transactional(rollbackFor = Exception.class)
    public void examineIncomingApplication(String entryId, Operator operator,String result,String failReason,String originalAssetValue,String equipValue,String financingAmount,String reservedFieldFive,String netOriginalAssetValue){
        logger.info(">>>>>>>>>>>>>>>>>>>examineIncomingApplication  entryId:{} ",entryId);
        CustomerEntry entry = customerEntryService.getById(entryId);

        CrmCustomerIncomingApplication application=applicationDao.getByEntryId(entryId);
        if("1".equals(result)){//审核通过
            GuardUtils.notBlank(originalAssetValue,"租赁物原值不能为空");
            GuardUtils.notBlank(equipValue,"租赁物单价不能为空");
            GuardUtils.notBlank(financingAmount,"融资额不能为空");
            GuardUtils.notBlank(reservedFieldFive,"每W定价不能为空");

            //基本信息
            CrmCustomerIncomingApplicationBasic applicationBasic=basicDao.getByApplicationId(application.getId());
            if(Objects.deepEquals("2",applicationBasic.getLeaseType())){
                GuardUtils.notBlank(netOriginalAssetValue,"不含税原值不能为空");
            }
            basicDao.save(applicationBasic);

            //客户信息
            CrmCustomerIncomingApplicationPerInfo perInfo=perInfoDao.getByApplicationId(application.getId());

            //租赁方案信息
            CrmCustomerIncomingApplicationRetailPayInfo retailPayInfo= retailPayInfoDao.getByApplicationId(application.getId());
            retailPayInfo.setFinancingAmount(new BigDecimal(financingAmount));
            retailPayInfoDao.save(retailPayInfo);
            //设备清单
            CrmCustomerIncomingApplicationLeaseItem equipInfoNormal=itemDao.getByEntryId(entryId);

            itemDao.save(equipInfoNormal);

            //提交进件申请
//            operatingLeaseService.accessProjectApply(entry,application,retailPayInfo,applicationBasic,perInfo,equipInfoNormal,"1");
            entry.setInComingTime(new Date());//进件时间：第一次进件审核通过时间
            msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.ADVANCE_TYPE_INCOMING_TYPE_APPROVE);

        }else if("2".equals(result)){
            msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.ADVANCE_TYPE_INCOMING_TYPE_FAIL);
        }
        applicationDao.save(application);
        customerEntryService.saveByUpdate(entry);
    }


    public void SProjectApply(String code ,String type){


        logger.info("SProjectApply -- t推送进件信息 entryId :{}",code);
        if(StringUtil.isNotBlank(code)) {

            CustomerEntry entry = customerEntryService.findCustomerEntryById(code);

            CrmCustomerIncomingApplication application = applicationDao.getByEntryId(entry.getId());


            //基本信息
            CrmCustomerIncomingApplicationBasic applicationBasic = basicDao.getByApplicationId(application.getId());

            //客户信息
            CrmCustomerIncomingApplicationPerInfo perInfo = perInfoDao.getByApplicationId(application.getId());

            //租赁方案信息
            CrmCustomerIncomingApplicationRetailPayInfo retailPayInfo = retailPayInfoDao.getByApplicationId(application.getId());

            //设备清单
            CrmCustomerIncomingApplicationLeaseItem equipInfoNormal = itemDao.getByEntryId(entry.getId());


            //提交进件申请
//            operatingLeaseService.accessProjectApply(entry, application, retailPayInfo, applicationBasic, perInfo, equipInfoNormal, type);
        }
    }



    @Transactional(rollbackFor = Exception.class)
    public void supplyIncomingApplication(AddIncomingApplication addIncomingApplication, Operator operator){

        String entryId=addIncomingApplication.getEntryId();

        CustomerEntry entry = customerEntryService.getById(entryId);

//        if(StringUtil.isBlank(entry.getManagementType())){
//            throw new IllegalArgumentException("该项目没有资方，不需要进件申请!");
//        }
        if(CustomerEntryConstants.NEXT_STATUS_TJ.equals(entry.getNextApplyStatus())){
            throw new IllegalArgumentException("当前数据已经提交了第二次进件申请，不可重复提交!");
        }

        //设备清单
        CrmCustomerIncomingApplicationLeaseItem equipInfoNormal=addIncomingApplication.getLeaseItem();

        CrmCustomerIncomingApplication application=applicationDao.getByEntryId(entryId);
        CrmCustomerIncomingApplicationLeaseItem oldEquip=itemDao.getByEntryId(entryId);

        //基本信息
        CrmCustomerIncomingApplicationBasic applicationBasic=basicDao.getByApplicationId(application.getId());

  /*      //客户信息
        CrmCustomerIncomingApplicationPerInfo perInfo=perInfoDao.getByApplicationId(application.getId());

        //租赁方案信息
        CrmCustomerIncomingApplicationRetailPayInfo retailPayInfo= retailPayInfoDao.getByApplicationId(application.getId());

*/
        equipInfoNormal.setEntryId(entryId);

        if("0".equals(addIncomingApplication.getResultType())){   //// 0 暂存  1 提交审核
            entry.setNextApplyStatus(CustomerEntryConstants.NEXT_STATUS_ZC);
        }else{
            if(!SourceConstants.STATUS_QY.equals(entry.getApplyStatus())){
                throw new IllegalArgumentException("进件申请不在签约状态，不可以继续提交！");
            }
//            checkField(addIncomingApplication,"2");
            entry.setNextApplyStatus(SourceConstants.APPLY_STATUS_ONE);
            msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.ADVANCE_TYPE_INCOMING_TYPE_SUBMIT);
        }
        customerEntryService.saveByUpdate(entry);
        //删除之前保存的申请信息
        itemDao.deleteRecord(entryId);

        itemDao.save(equipInfoNormal);

    }
    /**
     * 审核通过
    */
    @Transactional(rollbackFor = Exception.class)
    public void approved(String entryId, Operator operator,String originalAssetValue,String netAssetValue,String netOriginalAssetValue){
        CustomerEntry entry = customerEntryService.getById(entryId);
        if(StringUtil.isBlank(entry.getManagementType())){
            throw new IllegalArgumentException("该项目没有资方，不需要进件申请!");
        }
        if(SourceConstants.APPLY_STATUS_TWO.equals(entry.getNextApplyStatus())){
            throw new IllegalArgumentException("当前数据已审核通过，不可重复提交!");
        }
        entry.setNextApplyStatus(SourceConstants.APPLY_STATUS_TWO);//审核通过

        CrmCustomerIncomingApplication application=applicationDao.getByEntryId(entryId);

        //基本信息
        CrmCustomerIncomingApplicationBasic applicationBasic=basicDao.getByApplicationId(application.getId());
        if(Objects.deepEquals("2",applicationBasic.getLeaseType())) {
            GuardUtils.notNull(originalAssetValue, "不含税原值不能为空！");
            GuardUtils.notNull(netAssetValue, "初始确认物净值不能为空！");
            GuardUtils.notNull(netOriginalAssetValue, "租赁物原值不能为空！");
        }


        //客户信息
        CrmCustomerIncomingApplicationPerInfo perInfo=perInfoDao.getByApplicationId(application.getId());

        //租赁方案信息
        CrmCustomerIncomingApplicationRetailPayInfo retailPayInfo= retailPayInfoDao.getByApplicationId(application.getId());

        //设备清单
        CrmCustomerIncomingApplicationLeaseItem equipInfoNormal=itemDao.getByEntryId(entryId);
        if(Objects.deepEquals("2",applicationBasic.getLeaseType())) {
            itemDao.save(equipInfoNormal);
        }
        //提交进件申请
//        operatingLeaseService.accessProjectApply(entry,application,retailPayInfo,applicationBasic,perInfo,equipInfoNormal,"2");
        customerEntryService.saveByUpdate(entry);
        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.ADVANCE_TYPE_INCOMING_TYPE_APPROVE);
    }

    /**
     * 审核不通过
     */
    @Transactional(rollbackFor = Exception.class)
    public void approvedNot(String entryId, Operator operator,String failReason){
        CustomerEntry entry = customerEntryService.getById(entryId);
        if(StringUtil.isBlank(entry.getManagementType())){
            throw new IllegalArgumentException("该项目没有资方，不需要进件申请!");
        }
        if(!SourceConstants.APPLY_STATUS_ONE.equals(entry.getNextApplyStatus())){
            throw new IllegalArgumentException("当前数据状态发生改变，不可重复提交!");
        }
        entry.setNextApplyStatus(SourceConstants.APPLY_STATUS_THEREE);//审核通过
        customerEntryService.saveByUpdate(entry);
        msgService.saveCustomerEntryMsg(operator, entryId, CustomerEntryConstants.ADVANCE_TYPE_INCOMING_TYPE_FAIL, "备注：" + failReason, "");
    }


    public String getAddr(String province,String city,String area){
       String address= Db.queryStr("SELECT CONCAT_WS(',',p.regionalism_code,s.regionalism_code,d.`regionalism_code`)AS addres " +
                "FROM `s_province` p " +
                "LEFT JOIN `s_city` s ON s.ProvinceId=p.`ProvinceID` " +
                "LEFT JOIN `s_district` d ON d.`CityId`=s.`CityID` " +
                "WHERE p.ProvinceName=? AND s.`CityName`=? AND d.`DistrictName`=? ",province,city,area);
        return address;
    }

    public void checkField(CrmCustomerIncomingApplicationInsurance insurance){
       // CrmCustomerIncomingApplicationInsurance insurance=addIncomingApplication.getInsurance();
        GuardUtils.notBlank(insurance.getInsuranceDateFrom(),"保险开始日期不能为空！");
        GuardUtils.notBlank(insurance.getInsuranceDateTo(),"保险结束日期不能为空！");
        GuardUtils.notBlank(insurance.getInsuranceCompany(),"保险公司不能为空！");
        GuardUtils.notBlank(insurance.getInsuranceNumber(),"保险编号不能为空！");
        if (insurance.getInsuranceAmount() == null) {
            throw new IllegalArgumentException("投保金额不能为空");
        }
        GuardUtils.notBlank(insurance.getInsurancePolicy(),"保险单不能为空！");

    }

    //获取使用的物料总额
    public BigDecimal getTotalAmount(String id) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT SUM(bd_sale_price*amount)")
                .line("FROM crm_supply_material_keep k")
                .line("LEFT JOIN crm_supply_material m ON m.id = k.material_id")
                .line("WHERE k.source_id =? AND k.type = '2' AND m.material_attribute = '0'",id);
        BigDecimal total = Db.queryBigDecimal(builder.build(),builder.params());
        return total;
    }

    /**
     * 更新进件状态
     * 当前只能用于越秀资方使用
     * @param res 越秀状态
     * @param partnersContractNumber 进件序号 /身份证号码
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateIncomingApplicationStatus(QueryDocumentRes res, String partnersContractNumber,CustomerEntry entry,CrmCustomerIncomingApplication incomingApplication){
        //todo 还有一处 未处理
        logger.info("越秀状态值回调 getTenantStatus ： {} getCredit :{}",res.getTenantStatus(),partnersContractNumber);
        if(entry==null && StringUtil.isNotBlank(res.getTenantStatus())){
            logger.info("预审结果 返回信息： idCard {}",partnersContractNumber);
            List<CustomerEntry> entries= customerEntryService.getCustomerEntryByIdCode(partnersContractNumber,
                    PartnerConstants.PARTNER_ID_YX);//预审的时候，没有进件，返回的idCardNo 是身份证号
            //更新电站预审状态
            String remarks = "";
            String auditStatus = "1";
            String credit=(customerEntryService.getMsgByType(res.getTenantStatus()));
            if (StringUtil.isNotBlank(res.getReason())) {
                remarks = res.getReason();
            }
            for(CustomerEntry entry1:entries){
                if(credit.equals(entry1.getCredit())){
                    continue;
                }
                entry1.setCredit(credit);
                entry1.setCreditDsc(res.getReason());
                if (StringUtil.equalsAny(entry1.getCredit(),"2","3")) {
                    entry1.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                } else if ("1".equals(entry1.getCredit())) {
                    entry1.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_DYS);
                } else if ("4".equals(entry1.getCredit())) {
                    entry1.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSCG);
                    entry1.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
                    if(entry1.getPreAuditTime()==null){
                        entry1.setPreAuditTime(new Date());
                    }
                    auditStatus = "2";
                    // 更改客户信息预审状态 为预审通过
                    tenantDao.updateYxFlag(entry1.getTenantId(), "1");
                    Operator operator = Operator.of("1","资方-越秀","资方");
                    msgService.saveCustomerEntryMsg(operator, entry1.getId(), CustomerEntryConstants.ENTRY_ZF_YSTG, "预审通过", "");
                    applicationDao.saveIncomingApplication(entry1);
                } else if ("5".equals(entry1.getCredit())) {
                    entry1.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSBH);
                    auditStatus = "3";
                    // 更改客户信息预审状态 为预审不通过
                    tenantDao.updateYxFlag(entry1.getTenantId(), "2");
                    Operator operator = Operator.of("1","资方-越秀","资方");
                    msgService.saveCustomerEntryMsg(operator, entry1.getId(), CustomerEntryConstants.ENTRY_ZF_YSBTG, "预审不通过，"+res.getReason(), "");
                }
                CrmYxIncomingProcessDao.addIncomingProcess(entry1.getId(),"1",res.getTenantStatus(),"0",auditStatus,remarks);
                customerEntryService.saveByUpdate(entry1);
                yxIncomingLogDao.addCrmYxIncomingLog(entry1.getId(),partnersContractNumber,"0","越秀推送预审状态"+yxIncomingLogDao.getYsContent(res.getTenantStatus(),remarks),null);
            }
            SqlBuilder builder = new SqlBuilder();
            builder.line("UPDATE crm_customer_yx_condition SET preaudit=?",credit);
            builder.line(",preaudit_reason=?",remarks);
            builder.line("WHERE id_code=?",partnersContractNumber);
            builder.line(" and partner_id=?", PartnerConstants.PARTNER_ID_YX);
            Db.update(builder.build(),builder.params());
        }
        if (entry == null) {
            return;
        }
        String content=yxIncomingLogDao.getDjContent(res.getProjectStatus(),res.getFarmerSignStatus(),res.getReason(),incomingApplication);
        yxIncomingLogDao.saveCrmYxIncomingLog(res,entry.getId(),partnersContractNumber,"0","越秀推送单据状态,"+content);

        Operator operator = Operator.of("1", "资方-越秀", "-1");
        if (!"APPROVED".equals(entry.getFirstApplyStatus())) {
            //风险审查状态
            if (StringUtil.isNotBlank(res.getProjectStatus())) {
                entry.setFirstApplyStatus(res.getProjectStatus());
                entry.setApplyStatus(getIncomingStatus(res.getProjectStatus()));
                entry.setApplyBackReason("");

                String auditStatus = "1";
                if ("6".equals(entry.getApplyStatus())) {
                    auditStatus = "2";
                } else if ("7".equals(entry.getApplyStatus())) {
                    auditStatus = "3";
                }

                String remarks = null;
                if (StringUtil.equalsAny(res.getProjectStatus(),"REJECTED","CLOSED","CANCEL")) {
                    //第一次进件审核不通过，电站状态改为设计自审

                    //判断是否需要设计自审
                    if (!FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_SJZS)) {
                        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DSH);
                        entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSTG);
                        Date date=new Date();
                        String stationName = CrmUtils.getStationName(entry);
                        String name = "设计审核("+stationName+"-"+entry.getPowerStationCode()+")-"+DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss");
                        itemManageDao.addItem("91",entry.getId(), PlantformUtils.getOrderNumber(),name,date,"进件退回");
                    } else {
                        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_KCZS);
                        entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHBH);
                    }
                    if (StringUtil.isNotBlank(res.getReason())) {
                        entry.setApplyBackReason(res.getReason());
                    }
                    remarks = res.getReason();
                    if(StringUtil.equalsAny(res.getProjectStatus(),"REJECTED")){
                        msgService.saveCustomerEntryMsg(operator, entry.getId(),
                                CustomerEntryConstants.ADVANCE_TYPE_INCOMING_TYPE_FAIL,remarks,"");
                    }

                }else if ("APPROVED".equals(entry.getFirstApplyStatus())) {
                    // 进件审核通过 进入待安装
                    if("0".equals(entry.getInstallFlag())){
                        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DAZ);
                        entry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_DPG);
                        entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHTG);
                    }
                    entry.setInComingTime(new Date());//进件时间：第一次进件审核通过时间
                    msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_INCOMING_TYPE_APPROVE);
                }

                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"2",res.getProjectStatus(),"0",auditStatus,remarks);
            }
        }
        if("REJECTED".equals(res.getFarmerSignStatus())){
            entry.setNextApplyStatus(res.getFarmerSignStatus());
        }
        if (StringUtil.isNotBlank(entry.getNextApplyStatus()) &&!"APPROVED".equals(entry.getNextApplyStatus())) {
            //农户投放状态
            if (StringUtil.isNotBlank(res.getFarmerSignStatus())) {
                boolean changeFlag = !res.getFarmerSignStatus().equals(entry.getNextApplyStatus());
                entry.setNextApplyStatus(res.getFarmerSignStatus());
                String type="4";
                String oldApplyStatus=entry.getApplyStatus();
                String applyStatus=getNewIncomingStatus(oldApplyStatus,res.getFarmerSignStatus(),res.getFarmerSignDetailsStatus());
                /*entry.setApplyStatus(getIncomingStatusSec(res.getFarmerSignStatus(),entry.getApplyStatus()));*/
                entry.setApplyStatus(applyStatus);
                entry.setApplyBackReason("");
                if(StringUtil.isNotBlank(entry.getApplyStatus()) && Integer.valueOf(entry.getApplyStatus())>17){
                    type="5";
                }

                String itemStatus = res.getFarmerSignStatus();
                String auditStatus = "0";
                logger.info(".....updateIncomingApplicationStatus  farmerSignStatus:{},changeFlag:{}",res.getFarmerSignStatus(),changeFlag);
                if ("APPROVING".equals(itemStatus)) {
                    auditStatus = "1";
                } else if ("APPROVED".equals(itemStatus)) {
                    auditStatus = "2";
                    if (changeFlag) {
                        msgService.saveCustomerEntryMsg(operator, entry.getId(),
                                CustomerEntryConstants.ADVANCE_TYPE_TWO_JJ_TYPE_APPROVE);
                    }
                }else if ("REJECTED".equals(itemStatus)) {
                    auditStatus = "3";
                    if (changeFlag) {
                        msgService.saveCustomerEntryMsg(operator, entry.getId(),
                                CustomerEntryConstants.ADVANCE_TYPE_TWO_JJ_TYPE_FAIL, res.getReason(), "");
                    }
                }else if("WAITING".equals(itemStatus) && Integer.valueOf(oldApplyStatus)>17){  //农户投放审查阶段拒绝/退回/撤单原因；当前新增农户投放审查流程中，状态为“WAITING”时，也会返回退回原因
                    //当前用户已经提交并网资料，只是被驳回了
                    auditStatus="3";
                    type="5";
                }else if("WAITING".equals(itemStatus)){
                    auditStatus = "2";
                }
                if("21".equals(applyStatus) && changeFlag){
                    msgService.saveCustomerEntryMsg(operator, entry.getId(),
                            CustomerEntryConstants.ADVANCE_TYPE_TWO_JJ_TYPE_FAIL,  res.getReason(), "");
                }
                String remarks = null;
                if (StringUtil.equalsAny(res.getFarmerSignStatus(),"REJECTED","CANCEL")) {
                    //第二次进件审核不通过，电站状态改为安装自审
//                    entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DAZ);
                    //2024-04-02  进件驳回 电站状态不做任何调整
                    if (StringUtil.isNotBlank(res.getReason())) {
                        entry.setApplyBackReason(res.getReason());
                    }
                    remarks = res.getReason();
//                    approvedEntry(entry);
                } else if ("WAITING".equals(res.getFarmerSignStatus())){
                    if (StringUtil.isNotBlank(res.getReason())) {
                        entry.setApplyBackReason(res.getReason());
                        remarks = res.getReason();
                    }
                }
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),type,itemStatus,"0",auditStatus,remarks);

                if("APPROVED".equals(res.getFarmerSignStatus()) && !CustomerEntryConstants.ENTRY_STATUS_YWC.equals(entry.getStatus())){
                    logger.info("updateIncomingApplicationStatus  entryStatus:{},entryId:{}",entry.getStatus(),entry.getId());
                    entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_YWC);
                    entry.setMergeFlag(CustomerEntryConstants.MERGE_FLAG_ZFSHTG);
                    entry.setPaymentStatus(CustomerEntryConstants.PAYMENT_STATUS_WAIT);// 等待放款：投放审核成功，付款申请审核通过之前的状态
                    //生成结算记录
                    bwSettle(entry);
                }
            }
        }

        //合同状态为起租（INCEPT）时，推送购售电合同
//        if (StringUtil.isNotBlank(res.getContractStatus()) && "INCEPT".equals(res.getContractStatus())) {
//            customerEntryService.powerSellFilePush(entry);
//        }
        incomingApplication.setTenantStatus(res.getTenantStatus());
        incomingApplication.setProjectStatus(res.getProjectStatus());
        incomingApplication.setFarmerSignStatus(res.getFarmerSignStatus());
        incomingApplication.setFarmerSignDetailsStatus(res.getFarmerSignDetailsStatus());
        incomingApplication.setContractTextStatus(res.getContractTextStatus());
        if("APPROVED".equals(res.getPaymentApplyStatus()) && !"APPROVED".equals(incomingApplication.getPaymentApplyStatus())){ //投放款付款状态审批通过
            incomingApplication.setPaymentFinishTime(new Date());
            //改变奖励政策的生效状态
            accountSettleDetailDao.changeRewardSettleStatus(entry.getId());
            entry.setPaymentStatus(CustomerEntryConstants.PAYMENT_STATUS_FINISH);//请款完成：付款申请审核通过，支付完成之前的状态
            if (entry.getWaitLoanTime() == null){
                entry.setWaitLoanTime(new Date());
            }
        }
        incomingApplication.setPaymentApplyStatus(res.getPaymentApplyStatus());

        if("PAID".equals(res.getPaymentStatus()) && !"PAID".equals(incomingApplication.getPaymentStatus())){
            entry.setPaymentStatus(CustomerEntryConstants.PAYMENT_STATUS_PAID);//已放款：支付已完成
            entry.setPaymentTime(new Date());

            //投放通过时间同步到监控系统
            nhPowerStationService.tbPaymentTime(entry.getId(),entry.getPaymentTime());
        }
        incomingApplication.setPaymentStatus(res.getPaymentStatus());
        incomingApplication.setStatus(entry.getApplyStatus());
        incomingApplication.setContractNumber(res.getContractNumber());
        crmCustomerIncomingApplicationDao.save(incomingApplication);
        // 当 第三次进件审核通过之后 只需要保存进件
        if (CustomerEntryConstants.ENTRY_STATUS_YWC.equals(entry.getStatus())) {
            return;
        }
        if("APPROVED".equals(res.getFarmerSignStatus())){
             entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_YWC);
             entry.setMergeFlag(CustomerEntryConstants.MERGE_FLAG_ZFSHTG);
        }
        customerEntryService.saveByUpdate(entry);
    }

    @Transactional(rollbackFor = Exception.class)
    public void bwSettle(CustomerEntry entry){
        //生成结算记录
        //并网验收生成代理商的分包并网结算金额，分包并网结算额=分包结算额*（1-预结算比例A）-质保金，质保金=组件单瓦数*数量*质保金结算单价
        CrmAcceptingReport report = customerEntryService.getReportById(entry.getReceivingReportId());
        Map<String, String> map = settlementSchemeService.calcPriceByProjectId(entry.getProjectId(), report.getComponentNum(), report.getCapacity(), entry.getDistributorId(), entry);
        String settleNumber = map.get("number");//结算方案编号
        BigDecimal fbAmount = new BigDecimal(map.get("fbAmount"));
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>mergeAcceptPass id :{},fbAmount:{}",entry.getId(),fbAmount);
        BigDecimal proportion = accountSetService.findYjsProportion(entry.getDistributorId());
        Record set=accountSetService.findZBJSinglePrice();//质保金设置规则
        String way = set.getStr("way");//结算方式1.按瓦数 2.按组件块数 3.按结算比例（质保金账户使用
        BigDecimal propor=set.getBigDecimal("proportion");
        logger.info("投放款审核通过生成结算明细 proportion:{},propor:{}",proportion,propor);
        BigDecimal zbjSinglePrice = null;
        if(AccountSetConstants.WAY_WS_ONE.equals(way)){
            zbjSinglePrice = report.getCapacity().multiply(propor);
        }else if(AccountSetConstants.WAY_ZJKS_TWO.equals(way)){
            zbjSinglePrice = new BigDecimal(report.getComponentNum()).multiply(propor);
        }else if(AccountSetConstants.WAY_JSBL_THREE.equals(way)){
            zbjSinglePrice=fbAmount.multiply(propor).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
        }

        logger.info(">>>>>>>>>>>>>>>>>>>>>>>mergeAcceptPass proportion :{},zbjSinglePrice:{}",proportion,zbjSinglePrice);
        BigDecimal fbbwAmount = fbAmount.multiply(new BigDecimal(1)
                .subtract(proportion.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP)))
                .subtract(zbjSinglePrice);
        //生成待结算账户分包并网结算记录
        Operator operator=Operator.of("1","","1");
        CrmTraderAccountSettleDetail settleDetail= customerEntryService.createSettleDetail(map,entry, fbbwAmount, operator, "1", "0",settleNumber);
        accountSettleDetailDao.save(settleDetail);
        //生成质保金账户结算记录
        CrmTraderAccountSettleDetail settleDetail2 =customerEntryService.createSettleDetail(map,entry, zbjSinglePrice, operator, "3", "1",settleNumber);
        accountSettleDetailDao.save(settleDetail2);
        //释放授信额上限余额、增加分包款余额、增加验收结算总额、增加质保金总额，增加冻结金额
        CrmTraderAccount account = accountDao.findByTraderId(entry.getDistributorId());
        BigDecimal totalAmount = customerEntryService.getTotalAmount(entry.getId(),"1");
        if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) {
            account.setMaxQuotaAmountBalance(account.getMaxQuotaAmountBalance().add(totalAmount));
        }
        BigDecimal cfAmount=BigDecimal.ZERO;
        //获取惩罚政策 并网天数超过90天（含90天）少于120天（含120天），处罚安装容量*0.05元/W；
        CrmRewardsPunishWay rewardsPunishWay=rewardsPunishWayDao.getRewardsPunishWay("2");
        if(rewardsPunishWay!=null){
            long lowDay=Long.valueOf(rewardsPunishWay.getLowData());
            //获取并网天数
            try{
                long betweenDay=DateUtils.daysBetween(DateUtils.formatDate(entry.getMaterialFixFinishTime(),"yyyy-MM-dd"),DateUtils.getDate());
                logger.info("...间隔时间 betweenDay：{}",betweenDay);
                if(betweenDay>=lowDay){
                    //超期则生成一条惩罚结算记录
                    cfAmount=report.getCapacity().multiply(new BigDecimal(rewardsPunishWay.getRatioData())).setScale(2,BigDecimal.ROUND_HALF_UP);
                    CrmTraderAccountSettleDetail cfSettleDetail =customerEntryService.createSettleCfDetail(map,entry, cfAmount.negate(), operator, "5", "0",rewardsPunishWay.getNumber(),rewardsPunishWay.getRatioData());
                    logger.info("..生成第一种惩罚记录金额 cfSettleDetail:{},entryId:{}",cfAmount,entry.getId());
                    accountSettleDetailDao.save(cfSettleDetail);
                }
            }catch (Exception e){
                logger.error("计算并网天数失败 e:",e);
                throw new BusinessException("计算并网天数失败！");
            }
        }
        BigDecimal cfAmount2=BigDecimal.ZERO;
        BigDecimal zbjCfAmount=BigDecimal.ZERO;
        //获取惩罚政策 单户装机容量≤10千瓦，基础结算价格每瓦减少0.15元  结算节点：安装验收、并网验收
        CrmRewardsPunishWay rewardsPunishWay3=rewardsPunishWayDao.getRewardsPunishWay("3");
        if(rewardsPunishWay3!=null){
            BigDecimal cap= new BigDecimal(String.valueOf(report.getCapacity())).divide(new BigDecimal("1000"),2, BigDecimal.ROUND_FLOOR); //运算后不要四舍五入
            logger.info("...单户装机容量 cap：{}",cap);
            if(cap.compareTo(new BigDecimal(rewardsPunishWay3.getHighData()))<=0){
                BigDecimal totalAmountCf=report.getCapacity().multiply(new BigDecimal(rewardsPunishWay3.getRatioData())); //总的惩罚金额
                //生成一条惩罚结算记录
                logger.info("投放款审核通过生成惩罚金额 proportion:{},propor:{}",proportion,propor);
                cfAmount2=totalAmountCf.multiply(new BigDecimal("100").subtract(proportion.add(propor))).divide(new BigDecimal("100"),2, BigDecimal.ROUND_HALF_UP);
                CrmTraderAccountSettleDetail cfSettleDetail2 =customerEntryService.createSettleCfDetail(map,entry, cfAmount2.negate(), operator, "5", "0",rewardsPunishWay3.getNumber(),rewardsPunishWay3.getRatioData());
                logger.info("..生成第二种惩罚记录结算账户金额 totalAmountCf:{} cfAmount2:{},entryId:{}",totalAmountCf,cfAmount2,entry.getId());
                accountSettleDetailDao.save(cfSettleDetail2);
                //生成质保金的惩罚金额  总的惩罚金额 -第一次 +第二次 惩罚的金额
                //获取第一次生成的惩罚金额
                BigDecimal oneCfAmount=report.getCapacity().multiply(new BigDecimal(rewardsPunishWay3.getRatioData())).multiply(proportion).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                zbjCfAmount=totalAmountCf.subtract(oneCfAmount).subtract(cfAmount2);
                logger.info("..生成质保金惩罚记录金额 zbjCfAmount:{},oneCfAmount:{}",zbjCfAmount,oneCfAmount);
                CrmTraderAccountSettleDetail cfSettleDetailZbj =customerEntryService.createSettleCfDetail(map,entry, zbjCfAmount.negate(), operator, "5", "1",rewardsPunishWay3.getNumber(),rewardsPunishWay3.getRatioData());
                accountSettleDetailDao.save(cfSettleDetailZbj);
            }
        }

        account.setSettleAmount(account.getSettleAmount().add(fbbwAmount).subtract(cfAmount).subtract(cfAmount2));
        account.setSettleRewardsPunishAmount(account.getSettleRewardsPunishAmount().subtract(cfAmount).subtract(cfAmount2));
        account.setSettleAmountYsjs(account.getSettleAmountYsjs().add(fbbwAmount));
        account.setQaAmount(account.getQaAmount().add(zbjSinglePrice).subtract(zbjCfAmount));
        account.setQaAmountFreeze(account.getQaAmountFreeze().add(zbjSinglePrice).subtract(zbjCfAmount));
        accountDao.save(account);
    }

    public String getIncomingStatus(String status){
        String content = "5";
        //风险审查结果:NEW-待审批; APPROVING - 审批中; APPROVED - 审批通过; REJECTED - 审批拒绝; CLOSED - 取消;
        // APPROVED_RETURN - 退回（农户投放审查退回到风险审查）; CANCEL - 撤回（越秀业务经理撤回流程）
        switch (status) {
            case "NEW":
                content = "5";
                break;
            case "APPROVING":
                content = "5";
                break;
            case "APPROVED":
                content = "6";
                break;
            case "REJECTED":
                content = "7";
                break;
            case "CLOSED":
                content = "4";
                break;
            /*case "APPROVED_RETURN":
                content = "5";
                break;
            case "CANCEL":
                content = "4";
                break;*/
            default:
        }
        return content;
    }

    //进件状态
    public String getIncomingStatusSec(String status,String applyStatus){
        String content = "13";
        //农户投放审查结果:NEW-待审批;APPROVING-审批中;APPROVED-审批通过;REJECTED-审批拒绝;CANCEL - 撤回（越秀业务经理撤回流程）
        //WAITING-等待推送/补充并网及投放信息
        //进件状态  0.待预审 1.预审中 2.预审成功 3.预审驳回 4.待进件 5.进件审核中 6.进件审核成功 7.进件审核驳回 8.合同待签约 9.合同已签约  10.合同审核中
        // 11.合同签约驳回 12.合同已审核 13.待提交完工资料 14.完工资料审核中 15.完工资料审核通过 16.完工资料审核驳回 17.待提交并网资料 18.并网资料已提交(待审核) 19.并网资料审核中  20.并网资料审批通过 21.并网资料审批拒绝'
        int applySta=Integer.valueOf(applyStatus);
        if(applySta>16){
            switch (status) {
                case "NEW":
                    content = "18";
                    break;
                case "APPROVING":
                    content = "19";
                    break;
                case "APPROVED":
                    content = "20";
                    break;
                case "REJECTED":
                    content = "21";
                    break;
                case "CANCEL":
                    content = "5";
                    break;
                case "WAITING":
                    content = "17";
                    break;
                default:
            }
        }
        if(applySta>=13 && applySta<17){
            switch (status) {
                case "NEW":
                    content = "14";
                    break;
                case "APPROVING":
                    content = "14";
                    break;
                case "APPROVED":
                    content = "15";
                    break;
                case "REJECTED":
                    content = "16";
                    break;
                case "WAITING":
                    content = "17";
                    break;
                default:
            }
        }
        return content;
    }

    public String getNewIncomingStatus(String oldApplyStatus,String status,String detailStatus){
        String content = "13";
        //农户投放审查结果:NEW-待审批;APPROVING-审批中;APPROVED-审批通过;REJECTED-审批拒绝;CANCEL - 撤回（越秀业务经理撤回流程）
        //WAITING-等待推送/补充并网及投放信息
        //进件状态  0.待预审 1.预审中 2.预审成功 3.预审驳回 4.待进件 5.进件审核中 6.进件审核成功 7.进件审核驳回 8.合同待签约 9.合同已签约  10.合同审核中
        // 11.合同签约驳回 12.合同已审核 13.待提交完工资料 14.完工资料审核中 15.完工资料审核通过 16.完工资料审核驳回 17.待提交并网资料 18.并网资料已提交(待审核) 19.并网资料审核中/并网商务审核
        // 20.并网资料审批通过 21.并网资料审批拒绝  22.完工资料撤回 23.发电审核'
       /* BUSAPPROVING-业务审核
        TECHAPPROVING-完工审核
        WAITING-等待推送并网及商务信息及附件
        GRIDRETURN-退回补充并网及商务信息及附件
        GRIDAPPROVING-并网商务审核
        GRIDPOWERAPPROVING-发电审核
        TECHREJECTED-完工审批拒绝
        GRIDREJECTED-并网商务审批拒绝*/
        Integer oldStatus=Integer.valueOf(oldApplyStatus);
        logger.info("getNewIncomingStatus  oldStatus:{}",oldStatus);
        switch (status) {
            case "NEW":
                content = "14";
                break;
            case "APPROVING":
                content = "14";
                if("GRIDAPPROVING".equals(detailStatus)){
                    content = "19";
                }else if("GRIDPOWERAPPROVING".equals(detailStatus)){
                    content = "23";
                }
                break;
            case "APPROVED":
                if(oldStatus>17){
                    content="20";
                }else {
                    content = "15";
                }
                break;
            case "REJECTED":
                if("TECHREJECTED".equals(detailStatus)){
                    content = "16";
                }else{
                    content = "21";
                }
                break;
            case "CANCEL":
                content = "22";
                break;
            case "WAITING":
                content = "17";
                if("GRIDRETURN".equals(detailStatus) && oldStatus>17){
                    content = "21";
                }
                break;
            default:
        }

/*        if(applySta>=13 && applySta<17){
            switch (status) {
                case "NEW":
                    content = "14";
                    break;
                case "APPROVING":
                    content = "14";
                    break;
                case "APPROVED":
                    content = "15";
                    break;
                case "REJECTED":
                    content = "16";
                    break;
                case "WAITING":
                    content = "17";
                    break;
                default:
            }
        }*/
        return content;
    }

    //整改结算记录
    @Transactional(rollbackFor = Exception.class)
    public void approvedEntry(CustomerEntry entry){
        // 查询 预结算记录
        CrmTraderAccountSettleDetail settleDetail = accountSettleDetailDao.findOneByCondition(entry.getDistributorId(),
                TraderAccountSettleDetailConstants.OBJ_TYPE_DJS, TraderAccountSettleDetailConstants.TYPE_YJS,entry.getId());
        // 查询账户信息
        CrmTraderAccount traderAccount = accountDao.findByTraderId(entry.getDistributorId());

        if (settleDetail != null) {
            Date now = new Date();
            User user = UserUtils.getUser();
            CrmTraderAccountSettleDetail settleDetailYJS = accountSettleDetailDao.createOne(settleDetail.getEntryId(), settleDetail.getPowerStationCode(),
                    settleDetail.getTraderId(), settleDetail.getTraderName(), settleDetail.getFlag(), settleDetail.getObjType(),
                    TraderAccountSettleDetailConstants.TYPE_DZZG, settleDetail.getAmount().negate(), settleDetail.getRoofType(), settleDetail.getSchemeType(),
                    settleDetail.getSchemeTypeId(), settleDetail.getSchemeTypeName(), settleDetail.getTenantName(), settleDetail.getMobile(),
                    settleDetail.getProjectCode(), settleDetail.getProjectName(),settleDetail.getUnitPrice(),settleDetail.getCapacity(), user.getId(), now);


            // 改变账户 预结算金额
            traderAccount.setSettleAmount(traderAccount.getSettleAmount().subtract(settleDetail.getAmount()));
            traderAccount.setSettleAmountYsjs(traderAccount.getSettleAmountYsjs().subtract(settleDetail.getAmount()));

            accountDao.save(traderAccount);

            if(settleDetailYJS!=null){
                //保存预结算明细
                accountSettleDetailDao.save(settleDetailYJS);
            }
        }
    }

    public CrmCustomerIncomingApplicationInsurance findByentryId(String entryId){
        CrmCustomerIncomingApplicationInsurance insurance = insuranceDao.getByEntryId(entryId);
        return insurance;
    }

    @Transactional(rollbackFor = Exception.class)
    public void updatePaymentStatus(QueryDocumentRes res,CustomerEntry entry,CrmCustomerIncomingApplication incomingApplication){
        if ("APPROVED".equals(res.getFarmerSignStatus()) && !"APPROVED".equals(incomingApplication.getFarmerSignStatus())) {
            entry.setPaymentStatus(CustomerEntryConstants.PAYMENT_STATUS_WAIT);//等待放款：投放审核成功，付款申请审核通过之前的状态

        }
        incomingApplication.setFarmerSignStatus(res.getFarmerSignStatus());
        if("APPROVED".equals(res.getPaymentApplyStatus()) && !"APPROVED".equals(incomingApplication.getPaymentApplyStatus())){
            entry.setPaymentStatus(CustomerEntryConstants.PAYMENT_STATUS_FINISH);//请款完成：付款申请审核通过，支付完成之前的状态
            if (entry.getWaitLoanTime() == null){
                entry.setWaitLoanTime(new Date());
            }
        }
        incomingApplication.setPaymentApplyStatus(res.getPaymentApplyStatus());
        if("PAID".equals(res.getPaymentStatus()) && !"PAID".equals(incomingApplication.getPaymentStatus())){
            entry.setPaymentStatus(CustomerEntryConstants.PAYMENT_STATUS_PAID);//已放款：支付已完成
            entry.setPaymentTime(new Date());
            //投放通过时间同步到监控系统
            nhPowerStationService.tbPaymentTime(entry.getId(),entry.getPaymentTime());
        }
        incomingApplication.setPaymentStatus(res.getPaymentStatus());
        customerEntryService.saveByUpdate(entry);
        applicationDao.save(incomingApplication);
    }
}
