package com.sifang.modules.customer.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.alioss.AliyunOSSClientUtil;
import com.sifang.modules.changes.dao.*;
import com.sifang.modules.changes.entity.*;
import com.sifang.modules.changes.service.CustomerEntryChangeDesignService;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.constant.GFFirstStateKM;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.*;
import com.sifang.modules.esign.constants.ESignConstants;
import com.sifang.modules.partner.service.GuangfaOperatingService;
import com.sifang.modules.partner.utils.StatusFormVo;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.GuardUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @title: GuangFaManagemnetService
 * @Author Tan
 * @Date: 2024/7/19 14:36
 * @Version 1.0
 */
@Service
public class GuangFaManagemnetService extends BaseService {

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

    @Autowired
    private CrmYxIncomingLogDao yxIncomingLogDao;

    @Autowired
    private CrmCustomerIncomingApplicationDao applicationDao;

    @Autowired
    private ContractManagementDao contractManagementDao;

    @Autowired
    private CustomerEntryTenantDao tenantDao;

    @Autowired
    CustomerEntryMsgService msgService;

    @Autowired
    @Lazy
    private CustomerEntryService customerEntryService;
    @Autowired
    private CrmCustomerIncomingApplicationInsuranceDao insuranceDao;
    @Autowired
    CustomerEntryExtraService extraService;
    @Autowired
    private CustomerEntryComponentDao customerEntryComponentDao;

    @Autowired
    private CustomerEntrySurveyRecordDao surveyRecordDao;
    @Autowired
    private GuangfaOperatingService guangfaOperatingService;

    @Autowired
    private CustomerEntryExtraService customerEntryExtraService;

    @Autowired
    private CrmCustomerIncomingApplicationDao incomingApplicationDao;
    @Autowired
    private CustomerEntryChangeRecordDao customerEntryChangeRecordDao;
    @Autowired
    CustomerEntryMsgService entryMsgService;
    @Autowired
    private CustomerEntrySurveyChangeRecordDao surveyChangeRecordDao;
    @Autowired
    @Lazy
    private CustomerEntryChangeDesignService designService;
    @Autowired
    @Lazy
    private CrmCompletionInfoChangeDao completionInfoChangeDao;
    @Autowired
    private CrmCustomerEntryTenantChangeRecordDetailDao tenantChangeRecordDetailDao;
    @Autowired
    private CrmCustomerEntryTenantChangeRecordDao tenantChangeRecordDao;
    @Autowired
    private CrmMaterialInformationChangeApplyDetailDao detailDao;
    @Autowired
    private CrmMaterialInformationChangeApplyDao materialInformationChangeApplyDao;



    public void changePreStatus(StatusFormVo statusFormVo, CrmCustomerIncomingApplication incomingApplication, CustomerEntry entry){
        Gson gson=new Gson();
        logger.info("changePreStatus   statusFormVo:{}",gson.toJson(statusFormVo));
        Operator operator = Operator.of("1", "资方-广发", "资方");
        if (statusFormVo.getTerminateInputPieceState() == null ){
            statusFormVo.setTerminateInputPieceState(0);
        }
        if (statusFormVo.getTerminateInputPieceState() != 0 && ( !"40".equals(incomingApplication.getTerminateInputPieceState()) || statusFormVo.getTerminateInputPieceState() != 40)) {
            logger.info("....广发终止进件状态 ：{},{}", statusFormVo.getTerminateInputPieceMsg(), statusFormVo.getTerminateInputPieceState());
            if (!String.valueOf(statusFormVo.getTerminateInputPieceState()).equals(incomingApplication.getTerminateInputPieceState())) {
                incomingApplication.setTerminateInputPieceState(String.valueOf(statusFormVo.getTerminateInputPieceState()));
                String entryApplyStatus = getEntryCancelInputStatus(statusFormVo.getTerminateInputPieceState());
                entry.setApplyStatus(entryApplyStatus);
                incomingApplication.setStatus(entryApplyStatus);
                if (statusFormVo.getTerminateInputPieceState() == 40) {
                    incomingApplication.setStatus("a");
                    incomingApplication.setTenantStatus(null);
                    incomingApplication.setProjectStatus(null);
                    incomingApplication.setFarmerSignStatus(null);
                    entry.setCredit("1");
                    entry.setFirstApplyStatus("10");
                    entry.setNextApplyStatus("10");
                    entry.setSignStatus(CustomerEntryConstants.SIGN_STATUS_UNSTART);
                    //作废对应进件的合同
                    CrmCustomerContractManagement management = contractManagementDao.getContractByEntryId(entry.getId());
                    if (management != null){
                        if (ESignConstants.GF_CONTRACT_STATUS_WAIT.equals(management.getStatus()) || ESignConstants.GF_CONTRACT_STATUS_QSZ.equals(management.getStatus())
                                || ESignConstants.GF_CONTRACT_STATUS_DGZ.equals(management.getStatus()) || ESignConstants.GF_CONTRACT_STATUS_GZZ.equals(management.getStatus())
                                || ESignConstants.GF_CONTRACT_STATUS_YWC.equals(management.getStatus())
                        ){
                            management.setStatus(ESignConstants.GF_CONTRACT_STATUS_ZF);
                            contractManagementDao.save(management);
                            guangfaOperatingService.guangFaTerminateContract(PartnerConstants.PARTNER_ID_GF, incomingApplication.getInputPieceId(), "终止进件作废合同");
                            entry.setSignStatus(ESignConstants.GF_CONTRACT_STATUS_WAITADD);
                        }
                    }
                    msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.INCOMING_CANCEL_PASS, statusFormVo.getTerminateInputPieceMsg(), "");
                }
                // 审核状态 0.待审核 1.审核中 2.审核通过 3.审核不通过
                String auditStatus = "2";
                Integer terStatus = statusFormVo.getTerminateInputPieceState();
                if (-10 == terStatus || 50 == terStatus) {
                    auditStatus = "3";
                    msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.INCOMING_CANCEL_REFUSE, statusFormVo.getTerminateInputPieceMsg(), "");
                } else if (20 == terStatus) {
                    auditStatus = "0";
                } else if (30 == terStatus) {
                    auditStatus = "1";
                }

                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(), "1", "CLOSED", "0", auditStatus, statusFormVo.getTerminateInputPieceMsg());
                yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(), incomingApplication.getPartnersContractNumber(), "0", "终止进件状态查询：" + getDhCancelContent(statusFormVo), null);
            }
        } else if( statusFormVo.getBusinesssSate()!=null && (!CustomerEntryConstants.CREDIT_APPROVED.equals(entry.getCredit()) || statusFormVo.getBusinesssSate()!=30)){
            //预审状态
            String credit=getCreditStatus(statusFormVo.getBusinesssSate());
            if(!credit.equals(entry.getCredit())){
                entry.setCredit(credit);
                Integer businessSate= statusFormVo.getBusinesssSate();
                String auditStatus="";
                incomingApplication.setTenantStatus(String.valueOf(statusFormVo.getBusinesssSate()));
                if(30==businessSate){
                    incomingApplication.setStatus(CustomerEntryConstants.APPLY_STATUS_YSCG);
                    auditStatus="2"; //预审通过
                    // 更改客户信息预审状态 为预审通过
                    tenantDao.updateYxFlag(entry.getTenantId(), "1");
                    entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSCG);
                    entry.setCreditDsc(null);
                    entry.setPreAuditTime(new Date());
                    entry.setAddressFlag("1");
                    if (!CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK.equals(entry.getDesignAuditFlag())) {
                        entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
                    }
                    msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ENTRY_ZF_YSTG, "预审通过", "");
                }else if(40==businessSate || 50==businessSate){
                    incomingApplication.setStatus(CustomerEntryConstants.APPLY_STATUS_YSBH);
                    auditStatus="3";  //预审不通过
                    entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSBH);
                    entry.setCreditDsc(statusFormVo.getBusinesssMsg());
                    // 更改客户信息预审状态 为预审不通过
                    tenantDao.updateYxFlag(entry.getTenantId(), "2");
                    msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ENTRY_ZF_YSBTG,
                            "预审不通过，" + statusFormVo.getBusinesssMsg(), "");
                }else if(60==businessSate || 25 == businessSate ){
                    incomingApplication.setStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                    auditStatus="1";   //预审中
                }
                else {
                    auditStatus="4";   //待提交
                }
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"1",String.valueOf(statusFormVo.getBusinesssSate()),"0",auditStatus,statusFormVo.getBusinesssMsg());
                yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(),incomingApplication.getPartnersContractNumber(),"0","预审状态查询："+getDhYxContent(statusFormVo,"1"),null);
            }
        }else if(statusFormVo.getFirstSate()!=null && (!"30".equals(entry.getFirstApplyStatus()) || statusFormVo.getFirstSate()!=30)){
            logger.info("广发更新第一次进件状态，statusFormVo:{} , inputPieceId:{}",gson.toJson(statusFormVo),incomingApplication.getInputPieceId());
            customerEntryService.updateFirstState(entry.getId(), incomingApplication.getInputPieceId(), statusFormVo.getFirstSate().toString(), statusFormVo.getFirstMsg());
        } else if(statusFormVo.getCompleteSate() != null && (!"30".equals(entry.getNextApplyStatus()) || statusFormVo.getCompleteSate()!=30) && statusFormVo.getCompleteSate()!=10){
            //第二次进件
            GFFirstStateKM innerState = GFFirstStateKM.externalOf(statusFormVo.getCompleteSate());

            boolean changeFlag = (!innerState.getCode().equals(entry.getNextApplyStatus()));

            entry.setNextApplyStatus(innerState.getCode());
            String type="4";
            entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_WGSH);
            entry.setApplyBackReason("");
            if(StringUtil.isNotBlank(entry.getApplyStatus()) && Integer.valueOf(entry.getApplyStatus())>17){
                type="5";
            }

            String auditStatus = "0";
            if (StringUtil.equalsAny(innerState.getCode(),"25","60")) {
                auditStatus = "1";
            } else if ("30".equals(innerState.getCode())) {
                entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_WGSHTG);
                auditStatus = "2";
                if (changeFlag) {
                    msgService.saveEntryMsg(operator, entry.getId(),
                            CustomerEntryConstants.INCOMING_WGJJ_TG,"完工进件成功");
                }
            }else if (StringUtil.equalsAny(innerState.getCode(),"40","50")) {
                entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_WGSHBH);
                auditStatus = "3";
                msgService.saveEntryMsg(operator, entry.getId(),
                        CustomerEntryConstants.INCOMING_WGJJ_BTG,"完工进件失败，失败原因："+statusFormVo.getCompleteMsg());
                entry.setApplyBackReason(statusFormVo.getCompleteMsg());
            }

            CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),type,innerState.getCode(),"0",auditStatus,statusFormVo.getCompleteMsg());


            incomingApplication.setStatus(innerState.getInternalCode().toString());
            incomingApplication.setProjectStatus(innerState.getCode());
            incomingApplicationDao.save(incomingApplication);

//            if("30".equals(innerState.getCode()) && !CustomerEntryConstants.ENTRY_STATUS_DBW.equals(entry.getStatus())){
//                logger.info("updateIncomingApplicationStatus  entryStatus:{},entryId:{}",entry.getStatus(),entry.getId());
//                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DBW);
//                entry.setMergeFlag(CustomerEntryConstants.MERGE_FLAG_ZFSHTG);
//                entry.setPaymentStatus(CustomerEntryConstants.PAYMENT_STATUS_WAIT);// 等待放款：投放审核成功，付款申请审核通过之前的状态
//                //生成结算记录
//                customerEntryExtraService.bwSettle(entry);
//            }
            customerEntryService.saveByUpdate(entry);
        }else if (statusFormVo.getMergeSate() != null && (!"30".equals(entry.getThreeApplyStatus()) || statusFormVo.getMergeSate() != 30) && statusFormVo.getMergeSate()!=10) {
            String zfMergeState = String.valueOf(statusFormVo.getMergeSate());
            boolean changeFlag=false;
            if (!zfMergeState.equals(incomingApplication.getMergeSate())) {
                yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(), incomingApplication.getPartnersContractNumber(), "0", "第三次进件状态查询：" + getDhYxContent(statusFormVo, "5"), null);
                changeFlag=true;
            }
            //进件状态
            String applyStatus = entry.getApplyStatus();
            String auditStatus = "1";
            String errMsg = "";
            /**
             * 10-待进件   待进件：并网进件未开始；
             * 20-待审核   待审核：进件审核未完成；
             * 25-审核中
             4.30-成功    成功：已进件并审核通过；
             4.40-失败    失败：进件前置校验不通过，进件单没到资产系统；
             4.50-审核不通过 审核不通过：前置校验通过，进件单人工审核不通过/附件下载失败，系统自动不通过；
             4.60-进行中   进行中：进件的附件下载中；
             */
            Integer mergeSate = statusFormVo.getMergeSate();
            if (mergeSate == 10) {
                applyStatus = CustomerEntryConstants.APPLY_STATUS_DBWTJ;
            } else if (mergeSate == 20 || mergeSate == 25 || mergeSate == 60) {
                applyStatus = CustomerEntryConstants.APPLY_STATUS_BWYTJ;
            } else if (mergeSate == 30) {
                auditStatus = "2";
                applyStatus = CustomerEntryConstants.APPLY_STATUS_BWSHTG;
                if(changeFlag){
                    msgService.saveEntryMsg(operator, entry.getId(),
                            CustomerEntryConstants.INCOMING_THREE,"并网进件成功");
                }
            } else if (mergeSate == 40 || mergeSate == 50) {
                applyStatus = CustomerEntryConstants.APPLY_STATUS_BWSHBH;
                errMsg = statusFormVo.getMergeMsg();
                auditStatus = "3";
                if(changeFlag){
                    msgService.saveEntryMsg(operator, entry.getId(),
                            CustomerEntryConstants.INCOMING_THREE,"并网进件失败，失败原因："+errMsg);
                }
            }
            entry.setApplyStatus(applyStatus);
            entry.setThreeApplyStatus(zfMergeState);
            entry.setApplyBackReason(errMsg);
            incomingApplication.setMergeSate(zfMergeState);
            if (30 == statusFormVo.getMergeSate()) {
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_YWC);
                entry.setMergeFlag(CustomerEntryConstants.MERGE_FLAG_ZFSHTG);
                if (entry.getPaymentTime() == null) {
                    entry.setPaymentTime(new Date());//广发的回款时间 存并网进件通过时间
                }
            }
            CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(), "5", String.valueOf(statusFormVo.getMergeSate()), "0", auditStatus, errMsg);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void gridIncomingApplication(CustomerEntry entry, CrmCustomerIncomingApplication  incomingApplication, CrmAcceptingReport report , Operator operator){
        logger.info("....gridIncomingApplication  第三次进件 进件序号:{}",incomingApplication.getInputPieceId());

        List<CrmCustomerIncomingApplicationInsurance> insurancesList = insuranceDao.getByEntryIds(entry.getId());
        if (insurancesList ==null || insurancesList.isEmpty()) {
            throw new IllegalArgumentException("该项目无保险信息!");
        }
        String entryId = entry.getId();

//        GuardUtils.notNull(entry.getFirstGenerationTime(),"尚未获取到首日发电日期，不允许并网信息推送！");

        // insurance.setEntryId(entryId);
        BigDecimal totalInsuranceAmount=BigDecimal.ZERO;
        boolean flag = true;
        for(CrmCustomerIncomingApplicationInsurance insurance:insurancesList){
            if("工程安装一切险".equals(insurance.getInsuranceName())){
                flag=false;
            }
            if (insurance.getInsuranceAmount() != null) {
                totalInsuranceAmount=totalInsuranceAmount.add(insurance.getInsuranceAmount());
            }
        }

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

        //if(SourceConstants.STATUS_ONE.equals(addIncomingApplication.getResultType())){   //提交
        if ("1".equals(entry.getTenantType()) && !StringUtil.equalsAny(entry.getSignStatus(),"2","3","5","g","e")) {
            throw new BusinessException("当前电站未签约《农户合同》，请在签约后再操作并网");
        }
        if (StringUtil.isNotBlank(entry.getThreeApplyStatus())&&!StringUtil.equalsAny(entry.getThreeApplyStatus(),"10","20","40","50")) {
            throw new IllegalArgumentException("资方完工资料还未审核通过 ，无法并网验收通过进行并网信息推送");
        }

            boolean isType1Valid = true;
            boolean isType5Valid = true;
            for (CrmCustomerIncomingApplicationInsurance insurance : insurancesList) {
                GuardUtils.notBlank(insurance.getInsuranceNumber(), "保险单号不能为空！");
                GuardUtils.notBlank(insurance.getInsuranceType(), "险种类型不能为空！");
                GuardUtils.notBlank(insurance.getInsurancePolicy(), "保险单不能为空！");
                if ("1".equals(insurance.getInsuranceType())) {
                    isType1Valid = false;
                }
                if ("5".equals(insurance.getInsuranceType())) {
                    isType5Valid = false;
                }
                if("工程安装一切险".equals(insurance.getInsuranceName())){
                    isType1Valid = false;
                    isType5Valid = false;
                }
                if (!StringUtil.equalsAny(insurance.getInsuranceType(), "1", "5")) {
                    throw new IllegalArgumentException("当前保险类型不支持！");
                }
            }

            if(isType1Valid)
                throw new IllegalArgumentException("当前保险缺少财产险信息！");
            if(isType5Valid)
              throw new IllegalArgumentException("当前保险缺少工程险信息！");
            //提交进件申请
            CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entry.getId());
            List<Record> components =  customerEntryComponentDao.findByEntryId4(entry.getId());
            try {
                guangfaOperatingService.gridIncomingApplication(entry,surveyRecord,incomingApplication,report,components,insurancesList);
                entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_BWYTJ);
                entry.setThreeApplyStatus("20");
                incomingApplication.setApplyTime(new Date());
                incomingApplication.setMergeSate("20");
                incomingApplication.setStatus(entry.getApplyStatus());
                yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(),incomingApplication.getPartnersContractNumber(),"5","推送进件信息 ",operator);
            }catch (Exception e){
                e.printStackTrace();
                logger.error("gridIncomingApplication  e:{}",e);
                throw new IllegalArgumentException("并网进件失败，"+e.getMessage());
            }
            applicationDao.save(incomingApplication);
        }
    //电站信息变更
    @Transactional(rollbackFor = Exception.class)
    public void stationInfoUpdate(CustomerEntry entry,CrmCustomerEntryTenantChangeRecord record,String inputPieceId ){
        List<Record> details = tenantChangeRecordDetailDao.getDetails(record.getId());
        String address = details.stream().filter(r -> "address".equals(r.getStr("item_code"))).map(r -> r.getStr("after_change")).findFirst().orElse("");
        String changeNumber =  guangfaOperatingService.stationInfoUpdate(entry,record.getChangeReason(),address,inputPieceId);
        logger.info("stationInfoUpdate changeNumber:{}",changeNumber);
        CrmCustomerEntryChangeRecord changeRecord = new CrmCustomerEntryChangeRecord();
        changeRecord.setChangeId(record.getId());
        changeRecord.setChangeStatus("20");
        changeRecord.setChangeType("7");
        changeRecord.setChangeNumber(changeNumber);
        changeRecord.setCreateTime(new Date());
        customerEntryChangeRecordDao.save(changeRecord);
        getChangeStatus(changeNumber);
    }
    // 业主信息变更
    @Transactional(rollbackFor = Exception.class)
    public void customerInfoUpdate(CustomerEntry entry, CrmCustomerEntryTenantChangeRecord record,String inputPieceId) {
        String changeNumber = guangfaOperatingService.customerInfoUpdate(entry, record, inputPieceId);
        logger.info("customerInfoUpdate changeNumber:{}",changeNumber);
        CrmCustomerEntryChangeRecord changeRecord = new CrmCustomerEntryChangeRecord();
        changeRecord.setChangeId(record.getId());
        changeRecord.setChangeStatus("20");
        changeRecord.setChangeType("1");
        changeRecord.setChangeNumber(changeNumber);
        changeRecord.setCreateTime(new Date());
        customerEntryChangeRecordDao.save(changeRecord);
        getChangeStatus(changeNumber);
    }
    // 勘测变更
    @Transactional(rollbackFor = Exception.class)
    public void prospectInfoUpdate(CustomerEntry entry, CustomerEntrySurveyChangeRecord surveyChangeRecord,String inputPieceId) {
        String changeNumber = guangfaOperatingService.prospectInfoUpdate(entry, surveyChangeRecord, inputPieceId);
        CrmCustomerEntryChangeRecord changeRecord = new CrmCustomerEntryChangeRecord();
        changeRecord.setChangeId(surveyChangeRecord.getId());
        changeRecord.setChangeStatus("20");
        changeRecord.setChangeType("2");
        changeRecord.setChangeNumber(changeNumber);
        changeRecord.setCreateTime(new Date());
        customerEntryChangeRecordDao.save(changeRecord);
        getChangeStatus(changeNumber);
    }
    // 设计变更
    @Transactional(rollbackFor = Exception.class)
    public void designInfoUpdate(CustomerEntry entry, CrmCustomerEntryChangeDesign design, String inputPieceId) {
        String changeNumber = guangfaOperatingService.designInfoUpdate(entry, design, inputPieceId);
        CrmCustomerEntryChangeRecord changeRecord = new CrmCustomerEntryChangeRecord();
        changeRecord.setChangeId(design.getId());
        changeRecord.setChangeStatus("20");
        changeRecord.setChangeType("3");
        changeRecord.setChangeNumber(changeNumber);
        changeRecord.setCreateTime(new Date());
        customerEntryChangeRecordDao.save(changeRecord);
        getChangeStatus(changeNumber);
    }
    @Transactional(rollbackFor = Exception.class)
    public void completionInfoUpdate(CustomerEntry entry, CustomerEntryCompletionChangeRecord reportChange, String inputPieceId) {
        String changeNumber = guangfaOperatingService.completionInfoUpdate(entry, reportChange, inputPieceId);
        CrmCustomerEntryChangeRecord changeRecord = new CrmCustomerEntryChangeRecord();
        changeRecord.setChangeId(reportChange.getId());
        changeRecord.setChangeStatus("20");
        changeRecord.setChangeType("4");
        changeRecord.setChangeNumber(changeNumber);
        changeRecord.setCreateTime(new Date());
        customerEntryChangeRecordDao.save(changeRecord);
        getChangeStatus(changeNumber);
    }
    //物料信息变更
    @Transactional(rollbackFor = Exception.class)
    public void materialInfoUpdate(CustomerEntry entry, CrmMaterialInformationChangeApply apply, String inputPieceId) {
        //获取物料详情
        List<Record> records = detailDao.findMaterialDetailsByApplyId(apply.getId());
        String changeNumber = guangfaOperatingService.materialInfoUpdate(entry, records, inputPieceId,apply.getChangeReason());
        CrmCustomerEntryChangeRecord changeRecord = new CrmCustomerEntryChangeRecord();
        changeRecord.setChangeId(apply.getId());
        changeRecord.setChangeStatus("20");
        changeRecord.setChangeType("5");
        changeRecord.setChangeNumber(changeNumber);
        changeRecord.setCreateTime(new Date());
        customerEntryChangeRecordDao.save(changeRecord);
        getChangeStatus(changeNumber);
    }
    @Transactional(rollbackFor = Exception.class)
    public void getChangeStatus(String changeNumbers){
        try {
            JSONArray jsonArray =guangfaOperatingService.getChangeStatus(changeNumbers);
            for(int i=0;i<jsonArray.size();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String changeNo = jsonObject.getString("changeNo");
                String state = jsonObject.getString("state");
                String errorMsg =jsonObject.getString("errMsg") ;
                Db.update("UPDATE `crm_customer_entry_change_record` SET change_status=?,change_reason = ?,update_time = now() WHERE change_number=?"
                        ,state, errorMsg,changeNo);
                if(!"20".equals(state)){
                    CrmCustomerEntryChangeRecord changeRecord = customerEntryChangeRecordDao.findByChangeNo(changeNo);
                    switch (changeRecord.getChangeType()){
                        case "1": // 客户信息
                        case "7": //电站信息（地址）
                            CrmCustomerEntryTenantChangeRecord tenantChangeRecord=tenantChangeRecordDao.get(changeRecord.getChangeId());
                            entryMsgService.saveCustomerEntryMsg(Operator.of("1","资方-广发","资方"), tenantChangeRecord.getEntryId()
                                    , CustomerEntryConstants.ENTRY_CHANGE_FIND, String.format("第%d次客户信息变更结果查询：",tenantChangeRecord.getChangeCount())+errorMsg,null);
                            break;
                        case "2": // 勘测结果查询
                            CustomerEntrySurveyChangeRecord customerEntrySurveyChangeRecord = surveyChangeRecordDao.get(changeRecord.getChangeId());
                            entryMsgService.saveCustomerEntryMsg(Operator.of("1","资方-广发","资方"), customerEntrySurveyChangeRecord.getEntryId()
                                    , CustomerEntryConstants.ENTRY_CHANGE_FIND, String.format("第%d次勘测信息变更结果查询："+errorMsg, customerEntrySurveyChangeRecord.getNum()), null);
                            break;
                        case "3":
                            CrmCustomerEntryChangeDesign crmCustomerEntryChangeDesign = designService.get(changeRecord.getChangeId());
                            entryMsgService.saveCustomerEntryMsg(Operator.of("1","资方-广发","资方"), crmCustomerEntryChangeDesign.getEntryId()
                                    , CustomerEntryConstants.ENTRY_CHANGE_FIND, String.format("第%d次设计信息变更结果查询："+errorMsg, crmCustomerEntryChangeDesign.getNum()), null);
                            break;
                        case "4":
                            CustomerEntryCompletionChangeRecord customerEntryCompletionChangeRecord = completionInfoChangeDao.get(changeRecord.getChangeId());
                            entryMsgService.saveCustomerEntryMsg(Operator.of("1","资方-广发","资方"), customerEntryCompletionChangeRecord.getEntryId()
                                    , CustomerEntryConstants.ENTRY_CHANGE_FIND, String.format("第%d次完工信息变更结果查询："+errorMsg, customerEntryCompletionChangeRecord.getNum()), null);
                            break;
                        case "5": //物料信息
                            CrmMaterialInformationChangeApply materialChangeApply = materialInformationChangeApplyDao.get(changeRecord.getChangeId());
                            entryMsgService.saveCustomerEntryMsg(Operator.of("1","资方-广发","资方"), materialChangeApply.getEntryId()
                                    , CustomerEntryConstants.ENTRY_CHANGE_FIND, String.format("第%d次物料信息变更结果查询："+errorMsg, materialChangeApply.getChangeTime()), null);
                            break;
                    }
                }

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public String getCreditStatus(Integer businessSate){
        /** 预审状态 0.暂存 1.待预审 2.预审待审批 3.预审审批中 4.预审通过 5.预审拒绝
         * 30-成功  40-失败   50-审核不通过  60-进行中
         * 商机进件当前仅支持系统自动审核
         * 成功：已进件并审核通过；
         * 失败：进件前置校验不通过，进件单没到资产系统；
         * 审核不通过：附件下载失败，系统自动不通过；
         * 进行中：进件的附件下载中；
         */
        switch (businessSate){
            case 10:
                return "1";
            case 20:
                return "2";
                case 30:
                return "4";
            case 40:
            case 50:
                return "5";
            case 60:
                return "3";
            default:
                return "";

        }
    }

    //获取预审的过程信息
    public String getDhYxContent(StatusFormVo formVo,String type){
        String content = "";
        if("1".equals(type)){
            //预审结果:* 30-成功  40-失败   50-审核不通过  60-进行中
            switch (formVo.getBusinesssSate()) {
                case 30:
                    content = "预审通过";
                    break;
                case 40:
                    content = "预审拒绝"+(StringUtil.isNotBlank(formVo.getBusinesssMsg())?",拒绝原因："+formVo.getBusinesssMsg():"");
                    break;
                case 50:
                    content = "预审拒绝"+(StringUtil.isNotBlank(formVo.getBusinesssMsg())?",拒绝原因："+formVo.getBusinesssMsg():"");
                    break;
                case 60:
                    content = "预审中";
                    break;
                default:
            }
        }else if("2".equals(type)){  //首次进件
                switch (formVo.getFirstSate()){
                    case 20:
                        content = "待审核";
                        break;
                    case 25:
                        content = "审核中";
                        break;
                    case 30:
                        content = "审核通过";
                        break;
                    case 40:
                        content = "失败"+(StringUtil.isNotBlank(formVo.getFirstMsg())?",原因："+formVo.getFirstMsg():"");
                        break;
                    case 50:
                        content = "审核不通过"+(StringUtil.isNotBlank(formVo.getFirstMsg())?",原因："+formVo.getFirstMsg():"");
                        break;
                    case 60:
                        content = "进行中";
                        break;
                }
            }else if("5".equals(type)){  //首次进件
            switch (formVo.getMergeSate()){
                case 20:
                    content = "待审核";
                    break;
                case 25:
                    content = "审核中";
                    break;
                case 30:
                    content = "审核通过";
                    break;
                case 40:
                    content = "失败"+(StringUtil.isNotBlank(formVo.getMergeMsg())?",原因："+formVo.getMergeMsg():"");
                    break;
                case 50:
                    content = "审核不通过"+(StringUtil.isNotBlank(formVo.getMergeMsg())?",原因："+formVo.getMergeMsg():"");
                    break;
                case 60:
                    content = "进行中";
                    break;
            }
        }
        return content;
    }

    //获取终止进件的过程信息 -10-终止申请失败（附件下载失败等原因）,0-未开始-未申请终止,20-待审核-终止申请待审核,30-处理中-下载附件,40-已完成终止,50-审核不通过,拒绝终止申请
    public String getDhCancelContent(StatusFormVo formVo){
        String content = "";
        //预审结果:* 30-成功  40-失败   50-审核不通过  60-进行中
        switch (formVo.getTerminateInputPieceState()) {
            case -10:
                content = "终止申请失败"+(StringUtil.isNotBlank(formVo.getTerminateInputPieceMsg())?",失败原因："+formVo.getTerminateInputPieceMsg():"");
                break;
            case 30:
                content = "终止申请处理中"+(StringUtil.isNotBlank(formVo.getTerminateInputPieceMsg())?","+formVo.getTerminateInputPieceMsg():"");
                break;
            case 50:
                content = "终止申请审核不通过,拒绝终止申请"+(StringUtil.isNotBlank(formVo.getTerminateInputPieceMsg())?",拒绝原因："+formVo.getTerminateInputPieceMsg():"");
                break;
            case 20:
                content = "终止申请待审核";
                break;
            case 40:
                content = "已完成终止";
                break;
            default:
        }
        return content;
    }

    /**
     * 进件状态 0.待预审 1.预审中 2.预审成功 3.预审驳回 4.待进件 5.进件审核中 6.进件审核成功 7.进件审核驳回 8.合同待签约 9.合同已签约
     * 10.合同审核中 11.合同签约驳回 12.合同已审核 13.待提交完工资料 14.完工资料审核中 15.完工资料审核通过 16.完工资料审核驳回 17.待提交并网资料
     * 18.并网资料已提交 19.并网资料审核中 20.并网资料审批通过 21.并网资料审批拒绝 13.5 完工资料待审核
     */
    public String getApplyStatus(String oldApplyStatus,StatusFormVo statusFormVo){
        if(statusFormVo.getBusinesssSate()!=null && statusFormVo.getBusinesssSate()!=30){
            switch (statusFormVo.getBusinesssSate()){
                case 40:
                    return "3";
                case 50:
                    return "3";
                case 60:
                    return "1";
            }
        }else if(statusFormVo.getFirstSate()!=null && statusFormVo.getFirstSate()!=30){
            switch (statusFormVo.getFirstSate()){
                case 10:
                    return "4";
                case 20:
                    return "5";
                case 40:
                    return "7";
                case 50:
                    return "7";
                case 60:
                    return "5";
            }
        }
        //todo 后面的状态未判断

        return "";

    }

    //获取终止进件的状态  -10-终止申请失败（附件下载失败等原因）,0-未开始-未申请终止,20-待审核-终止申请待审核,30-处理中-下载附件,40-已完成终止,50-审核不通过,拒绝终止申请
    // -10终止进件待审核 -11终止进件处理中 -12终止进件失败 a.取消进件
    public String getEntryCancelInputStatus(Integer terminateInputPieceState){
        switch (terminateInputPieceState){
            case 20:
                return "-10";
            case -10:
            case 50:
                return "-12";
            case 30:
                return "-11";
            case 40:
                return "0";
        }

        return "";
    }

    public String getQrCodeUrl(String entryId) throws IOException {
        CustomerEntry entry = customerEntryService.getById(entryId);
        CrmCustomerIncomingApplication application = incomingApplicationDao.getByEntryId(entryId);
        String inputPieceId = application.getInputPieceId();
        if(StringUtil.isBlank(entry.getQrCodeUrl())) {
            String partnerId = "03";//广发资方id
            JSONArray jsonArray = guangfaOperatingService.queryQrCodeUrl(partnerId, inputPieceId);
            String url = jsonArray.getJSONObject(0).getString("qrCodeUrl");
            // 转 存
            logger.info("广发二维码获取 getQrCodeUrl -------fileMessage:{} ", url);
            String path = AliyunOSSClientUtil.saveUrlWeb(url,"png");
            logger.info(">>>>>>>>>>>>>getQrCodeUrl  path:{}", path);
            entry.setQrCodeUrl(path);
            customerEntryService.save(entry);
            return path;
        }
        return entry.getQrCodeUrl();
    }

}
