package com.sifang.modules.customer.Service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.jfinal.kit.StrKit;
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.alioss.AliyunOSSClientUtil;
import com.sifang.modules.changes.dao.*;
import com.sifang.modules.changes.entity.CrmCustomerEntryChangeDesign;
import com.sifang.modules.changes.entity.CustomerEntrySupplementDetail;
import com.sifang.modules.config.SfCacheService;
import com.sifang.modules.customer.constant.*;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.*;
import com.sifang.modules.customer.form.*;
import com.sifang.modules.customer.pdf.PdfReport;
import com.sifang.modules.customer.utils.CheckMustFillUtil;
import com.sifang.modules.customer.utils.CustomerEntryUtil;
import com.sifang.modules.customer.utils.GaodeUtil;
import com.sifang.modules.esign.constants.ESignConstants;
import com.sifang.modules.esign.service.PartnerContractESignSignService;
import com.sifang.modules.esign.service.RedSunAskAuthContractService;
import com.sifang.modules.factory.BrandFactInfo;
import com.sifang.modules.factory.aiswei.AisweiApi;
import com.sifang.modules.factory.aiswei.AisweiRet;
import com.sifang.modules.factory.aiswei.dto.createStation.CreateStationProR;
import com.sifang.modules.factory.aiswei.dto.createStation.CreateStationProReq;
import com.sifang.modules.flowable.constants.ItemConstants;
import com.sifang.modules.flowable.dao.ItemManageDao;
import com.sifang.modules.flowable.dao.ItemTaskDetailDao;
import com.sifang.modules.flowable.entity.ItemManage;
import com.sifang.modules.flowable.service.ProcessFlowableService;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.flowpath.constant.BondApplyConstant;
import com.sifang.modules.ginlang.constant.GinLangConstan;
import com.sifang.modules.ginlang.utils.GinLangUtils;
import com.sifang.modules.gudewei.constant.GuDeConstan;
import com.sifang.modules.gudewei.utils.GuDeUtils;
import com.sifang.modules.insurance.constants.InsuranceConstants;
import com.sifang.modules.insurance.constants.InsuranceOrderConstants;
import com.sifang.modules.insurance.dao.CustomerEntryInsuranceDao;
import com.sifang.modules.insurance.entity.CrmCustomerEntryInsurance;
import com.sifang.modules.insurance.entity.CrmInsuranceList;
import com.sifang.modules.order.utils.excelExt.ExcelReader;
import com.sifang.modules.partner.service.GuangfaOperatingService;
import com.sifang.modules.partner.service.HuaRongApiService;
import com.sifang.modules.partner.utils.HuaRongCustomer;
import com.sifang.modules.partner.utils.HuaRongStatusFormVo;
import com.sifang.modules.partner.utils.StatusFormVo;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.platform.utils.ReduceSize;
import com.sifang.modules.quality.dao.CrmEntryQualitySeekEntryDao;
import com.sifang.modules.quality.entity.CrmEntryQualitySeekEntry;
import com.sifang.modules.setting.constant.ProcessSetConstants;
import com.sifang.modules.smallprogram.AddMaterialSnReq;
import com.sifang.modules.smallprogram.UsedMaterialDetailReq;
import com.sifang.modules.smallprogram.UsedMaterialReq;
import com.sifang.modules.smallprogram.stategrid.service.StateGridService;
import com.sifang.modules.sunshine.SystemSetting.dao.*;
import com.sifang.modules.sunshine.SystemSetting.entity.*;
import com.sifang.modules.sunshine.SystemSetting.service.*;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.RandomUtil;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.handler.CustomerEntryCodeImportHandler;
import com.sifang.modules.sunshine.partnerManagement.dao.PartnerBrandUtils;
import com.sifang.modules.sunshine.partnerManagement.dao.PartnerDao;
import com.sifang.modules.sunshine.partnerManagement.entity.CrmPartner;
import com.sifang.modules.sunshine.partnerManagement.service.PartnerService;
import com.sifang.modules.sunshine.settleSet.dao.RewardsPunishWayDao;
import com.sifang.modules.sunshine.settleSet.entity.CrmRewardsPunishWay;
import com.sifang.modules.supply.order.constant.DeliverOrderConstants;
import com.sifang.modules.supply.order.dao.*;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.supply.setting.dao.CrmSupplyMaterialTypeDao;
import com.sifang.modules.supply.setting.entity.CrmSupplyMaterialType;
import com.sifang.modules.supply.stock.FIFOStockImpl;
import com.sifang.modules.supply.stock.KeepUnit;
import com.sifang.modules.supply.stock.StockUnit;
import com.sifang.modules.supply.stock.dao.MaterialStockDao;
import com.sifang.modules.supply.stock.dao.SupplyMaterialDao;
import com.sifang.modules.supply.stock.entity.MaterialWarehouseStocks;
import com.sifang.modules.supply.stock.entity.SupplyMaterial;
import com.sifang.modules.supply.warehouse.dao.CrmSupplyBarcodeDao;
import com.sifang.modules.supply.warehouse.dao.CrmSupplyMaterialKeepDao;
import com.sifang.modules.supply.warehouse.dao.CrmSupplyPurchaseOrderDao;
import com.sifang.modules.supply.warehouse.dao.SupplyMaterialBatchDao;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyBarcode;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyMaterialKeep;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.persistence.Parameter;
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.dao.FormSetDao;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.entity.Ascription;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.*;
import com.sifang.modules.sys.util.http.GwEzTemplate;
import com.sifang.modules.sys.util.insurance.InsuranceBizService;
import com.sifang.modules.taskdispatch.dao.CrmReviewDispatchDao;
import com.sifang.modules.taskdispatch.service.CrmPriorReviewSettingService;
import com.sifang.modules.utils.img.DownImg;
import com.sifang.modules.youkua.service.NhPowerStationService;
import javafx.beans.binding.MapExpression;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.TaskService;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class CustomerEntryService extends BaseService {
    @Autowired
    CustomerEntryDao customerDao;

    @Autowired
    CrmCustomerIncomingApplicationDao incomingApplicationDao;

    @Autowired
    CustomerEntryMsgService msgService;

    @Autowired
    PlanMaterialEntryDao entryDao;

    @Autowired
    PlanMaterialDao materialDao;

    @Autowired
    PlanDao planDao;

    @Autowired
    UserDao userDao;

    @Autowired
    CrmAcceptingReportDao reportDao;

    @Autowired
    CrmAcceptingReportDetailDao reportDetailDao;

    @Autowired
    TenantYxBankCardCopyDao cardCopyDao;

    @Autowired
    ProjectSettingDao projectDao;

    @Autowired
    TraderPartnerDao traderPartnerDao;

    @Autowired
    ProjectCompanyDao companyDao;

    @Autowired
    ProjectCompanyDao projectCompanyDao;
    @Autowired
    ProjectInstallDao installDao;

    @Autowired
    HuaRongApiService huaRongApiService;

    @Autowired
    private CrmYxIncomingProcessDao crmYxIncomingProcessDao;

    @Autowired
    ProjectInfoSettingService projectInfoSettingService;

    @Autowired
    TraderDao traderDao;

    @Autowired
    ProjectContractService contractService;

    @Autowired
    ComposePlanService composePlanService;

    @Autowired
    private CrmSupplyPurchaseOrderDao purchaseOrderDao;

    @Autowired
    private MaterialDeliverDao deliverDao;

    @Autowired
    private MaterialDeliverDetailDao deliverDetailDao;

    @Autowired
    private MaterialDeliverOrderMsgDao deliverOrderMsgDao;

    @Autowired
    private MaterialApplyDao materialApplyDao;

    @Autowired
    private CheckPendingOrderDao checkPendingOrderDao;

    @Autowired
    GwEzTemplate gwEzTemplate;

    @Autowired
    private PartnerDao partnerDao;

    @Autowired
    SfCacheService cacheService;

    @Autowired
    @Lazy
    CustomerEntryExtraService customerEntryExtraService;

    @Autowired
    private CrmCustomerIncomingApplicationDao applicationDao;

    @Autowired
    @Lazy
    private CustomerEntryExtraService extraService;

    @Autowired
    private CrmCustomerIncomingApplicationLeaseItemDao equipInfoNormalDao;

    @Autowired
    private CustomerEntryComponentService customerEntryComponentService;

    @Autowired
    private RectificationSettingService rectificationSettingService;

    @Autowired
    CrmCustomerOrderDao customerOrderDao;

    @Autowired
    CrmCustomerOrderRelDao customerOrderRelDao;

    @Autowired
    ElectricSetDao electricSetDao;

    @Autowired
    private AccountSetService accountSetService;

    @Autowired
    private SubconractorSettlementSchemeService settlementSchemeService;

    @Autowired
    OperatingLeaseService operatingLeaseService;

    @Autowired
    private TraderAccountSettleDetailDao accountSettleDetailDao;

    @Autowired
    private TraderAccountDao accountDao;

    @Autowired
    TraderEmployeService traderEmployeService;

    @Autowired
    private ProcessFlowableService flowableService;

    @Autowired
    TaskService taskService;

    @Autowired
    private CrmSupplyBarcodeDao barcodeDao;

    @Autowired
    private SupplyMaterialDao supplyMaterialDao;

    @Autowired
    private CrmSupplyMaterialTypeDao materialTypeDao;

    @Autowired
    private CustomerEntryToExamineService examineService;

    @Autowired
    private MaterialStockDao materialStockDao;

    @Autowired
    private SupplyMaterialBatchDao batchDao;

    @Autowired
    private FIFOStockImpl fifoStock;

    @Autowired
    private CustomerRentVariableService customerRentVariableService;

    @Autowired
    private CustomerEntryCheckService customerEntryCheckService;

    @Autowired
    private CustomerEntryRentService customerEntryRentService;

    @Autowired
    private CustomerEntryComponentDao entryComponentDao;
    @Autowired
    TraderPcdDao traderPcdDao;

    @Autowired
    private RedSunAskAuthContractService askAuthContractService;

    @Autowired
    private CrmSupplyMaterialKeepDao materialKeepDao;

    @Autowired
    private TraderWarehouseRelDao traderWarehouseRelDao;

    @Autowired
    private TenantYxBankCardDao tenantYxBankCardDao;

    @Autowired
    private CustomerEntrySurveyRecordDao surveyRecordDao;

    @Autowired
    private CustomerEntryOrgFilesDao orgFilesDao;

    @Autowired
    private FormSetDao formSetDao;

    @Autowired
    private CrmCustomerYxConditionDao conditionDao;

    @Autowired
    private CrmReviewDispatchDao reviewDispatchDao;

    @Autowired
    private PartnerService partnerService;

    @Autowired
    private CrmYxIncomingLogDao yxIncomingLogDao;

    @Value("${server.hjzy.user.name}")
    private String USERNAME;

    @Value("${server.hjzy.user.password}")
    private String PASSWORD;

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

    @Autowired
    InsuranceBizService insuranceBizService;

    @Autowired
    CustomerEntryInsuranceDao entryInsuranceDao;

    @Autowired
    private CustomerEntryTenantDao tenantDao;

    @Autowired
    private TraderPcdService traderPcdService;

    @Autowired
    private ItemManageDao itemManageDao;

    @Autowired
    private ItemTaskDetailDao itemTaskDetailDao;

    @Autowired
    private CrmMaterialInformationChangeApplyDao materialInformationChangeApplyDao;

    @Autowired
    CrmCompletionInfoChangeDao completionInfoChangeDao;

    @Autowired
    TraderService traderService;

    @Autowired
    ProjectPcdDao projectPcdDao;

    @Autowired
    private RewardsPunishWayDao rewardsPunishWayDao;

    @Autowired
    private CustomerEntrySupplementDetailDao supplementDetailDao;

    @Autowired
    GuangfaOperatingService guangfaOperatingService;

    @Autowired
    @Lazy
    GuangFaManagemnetService guangFaManagemnetService;
    @Autowired
    @Lazy
    HuaRongManagementService huaRongManagementService;

    @Autowired
    private ContractManagementDao contractManagementDao;

    @Autowired
    private StateGridService stateGridService;

    @Autowired
    private NhPowerStationService nhPowerStationService;

    @Autowired
    private PartnerContractESignSignService contractESignSignService;

    @Autowired
    private CrmCustomerYxAuthorizationDao customerYxAuthorizationDao;

    @Autowired
    private AisweiApi aisweiApi;

    @Autowired
    private CustomerEntryChangeDesignComponentDao customerEntryChangeDesignComponentDao;

    @Autowired
    private CrmEntryCombinerBoxGroupService combinerBoxGroupService;

    @Autowired
    private CrmEntryQualitySeekEntryDao qualitySeekEntryDao;

    @Autowired
    private CrmCustomerEntryProjectDao crmCustomerEntryProjectDao;

    @Autowired
    private CrmCustomerEntrySurveyRecordDetailDao recordDetailDao;
    @Autowired
    private CrmCustomerEntrySurveyRecordDetailService recordDetailService;
    @Autowired
    private CrmCustomerEntryDesignService entryDesignService;
    @Autowired
    private CrmCustomerEntryDesignDao crmCustomerEntryDesignDao;

    @Autowired
    private CrmCustomerEntrySurveyRecordDetailDao crmCustomerEntrySurveyRecordDetailDao;

    @Autowired
    private CrmPriorReviewSettingService crmPriorReviewSettingService;

    private static final String FILE_PATH_TEMPLATE = System.getProperty("java.io.tmpdir") + "/tempdf/%s";

    public List<Record> getInputPieceInProgress(String partnerId) {
        return customerDao.getInputPieceInProgress(partnerId);
    }

    public CustomerEntry findCustomerEntryById(String powerStationCode) {
        return customerDao.findCustomerEntryById(powerStationCode);
    }

    public List<CustomerEntry> getCustomerEntryByIdCode(String idCode, String partnerId){
        return customerDao.getCustomerEntryByIdCode(idCode, partnerId);
    }

    /**
     * 查询该身份证是否存在 预审通过的信息
     * @param tenantType
     * @return
     */
    public List<Record> getCustomerEntryInfoByIdCode(String keywords,String tenantType){
        return customerDao.getCustomerEntryInfoByIdCode(keywords,tenantType);
    }


    // private static final String projectCode = "G2-21093,G2-21095,G2-21094,G2-21091,G2-21092,G2-21084,G2-21086,G2-21085,G2-21083,G2-21088,G2-21087,G2-21078,G2-21079,G2-21077,G2-21081,G2-21082,G2-21080,G2-21089,G2-21090";

    public CrmAcceptingReport getReportById(String reportId) {
        return reportDao.get(reportId);
    }

    public CustomerEntry getById(String id) {
        return customerDao.get(id);
    }
    public void save(CustomerEntry customerEntry) {
        customerDao.save(customerEntry);
    }

    public Record getRecordById(String id) {
        SqlBuilder sq = new SqlBuilder();
        sq.line("select e.*, DATE_FORMAT(e.lease_date,'%Y-%m-%d') AS leaseDate,")
                .line("DATE_FORMAT(e.create_time,'%Y-%m-%d %H:%i:%s') AS createTime,")
                .line("sr.*,f.regno_url AS regnoUrl,f.resolution_paper_url AS resolutionPaperUrl,")
                .line("f.yszc_url AS yszcUrl,f.account_info_url AS accountInfoUrl,")
                .line("f.ownership_certificate_url AS ownershipCertificateUrl,f.credit_certificate , ")
                .line("f.other_ownership_certificate_url AS otherOwnershipCertificateUrl ,d.yz_code")
                .line("from crm_customer_entry e")
                .line("LEFT JOIN crm_customer_entry_survey_record sr ON sr.entry_id = e.id")
                .line("LEFT JOIN crm_customer_entry_org_files f ON f.entry_id = e.id")
                .line(" left join crm_plan_material_entry as d on e.nbq_sn=d.nbq_sn ")
                .line(" where e.id=?",id);
        return Db.findFirst(sq.build(), sq.params());
    }




    public void saveByUpdate(CustomerEntry entry) {
        customerDao.save(entry);
    }


    public void getCustomerList(String port, LayuiPage<Record> page, Map<String, String> map, User user) {
        List<Record> list = customerDao.getCustomerList(port, page, map, user);
        InformationEncryption(list,user.getUserType());
        page.setData(list);
    }

    public void getGdtCustomerList(LayuiPage<Record> page, Map<String, String> map, User user) {
        List<Record> list = customerDao.getGdtCustomerList(page, map, user);
        InformationEncryption(list,user.getUserType());
        page.setData(list);

    }

    public void getJjshCustomerList(LayuiPage<Record> page, Map<String, String> map, User user) {
        List<Record> list = customerDao.getJjShCustomerList(page, map, user);
        InformationEncryption(list,user.getUserType());

        page.setData(list);
    }


    /**
     * 信息登记时 修改电站逻辑
     */
    @Transactional(rollbackFor = Exception.class)
    public String editEntryForIXDJ(AddEntryReq req, Operator operator) {
        logger.info("editEntryForIXDJ entry={}",new Gson().toJson(req));
        // 获取资方信息
        CrmPartner partner = partnerService.getById(req.getZfId());
        // 当前要求 信息登记时
        CustomerEntry entry = customerDao.get(req.getId());
        if (!CustomerEntryConstants.ENTRY_STATUS_ZC.equals(entry.getStatus())) {
            return "当前状态不满足操作要求，暂存状态下才可进行修改";
        }
        Date now = DateUtils.getNowDate();
        Record pro = null;
        if (StringUtil.isNotBlank(req.getProjectId())) {
            pro = projectDao.getProject(req.getProjectId());
        }
        StringBuilder sf = new StringBuilder();
        if (StringUtil.isBlank(entry.getProjectId()) && StringUtil.isBlank(req.getProjectId())) {

        }
        else if (StringUtil.isBlank(entry.getProjectId()) || StringUtil.isBlank(req.getProjectId())
                || !req.getProjectId().equals(entry.getProjectId())) {
            // 修改后 产品被清空
            if (pro == null) {
                sf.append("修改项目信息,取消选择：").append(entry.getProjectName()).append(";");
            }
            else {
                // 修改前 产品未设置
                if (StringUtil.isBlank(entry.getProjectId())) {
                    sf.append("修改项目信息,修改为：").append(pro.getStr("name")).append(";");
                }
                // 修改前与修改后 产品不一样
                else {
                    sf.append("修改项目信息,修改前：").append(entry.getProjectName()).
                            append(" ,修改后 ：").append(pro.getStr("name")).append(";");
                }
                if (!entry.getPartnerId().equals(pro.getStr("management"))) {
                    return "选择的产品不属于" + entry.getPartnerName() + ",请重新选择产品";
                }
            }
            entry.setProjectId(pro == null ? null : req.getProjectId());
            entry.setProjectName(pro == null ? null : pro.getStr("name"));
            entry.setProjectCode(pro == null ? null : pro.getStr("code"));

            //EPC单价/ 每W定价
            entry.setEpcPrice(pro == null ? BigDecimal.ZERO : pro.getBigDecimal("epc_price"));
            //产品线
            entry.setProductLineId(pro == null ? null : pro.getStr("product_line_id"));
            entry.setProductLineName(pro == null ? null : pro.getStr("lineName"));
            //业务属性 1.纯租25年业务、2.经营性租赁、3.融资租赁、4.光伏贷、5.全款、6.其他
            entry.setProductLine(pro == null ? null : pro.getStr("attribute"));
            //租金支付周期 1按月支付 2按季支付 3按年支付
            entry.setPayCycle(pro == null ? null : pro.getStr("pay_cycle"));
            entry.setFilingType(pro == null ? null : pro.getStr("filing_type"));
            //删除旧租金信息
            customerRentVariableService.deleteRentVariable(req.getId());
            //更新租金信息
            if (pro != null) {
                customerRentVariableService.saveEntryComponent(req.getId(), req.getProjectId());
            }
        }
        if (!Objects.equals(req.getTenantName(),entry.getTenantName())) {
            sf.append("修改业主姓名：修改前：").append(entry.getTenantName()).append(" ,修改后 ：").append(req.getTenantName()).append(";");
            entry.setTenantName(req.getTenantName());
        }
        if (!Objects.equals(req.getIdCode(),entry.getIdCode())) {
            sf.append("修改身份证号：修改前：").append(entry.getIdCode()).append(" ,修改后 ：").append(req.getIdCode()).append(";");
            entry.setIdCode(req.getIdCode().toUpperCase());
            entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_WAIT);
        }
        if (!(req.getProvince() + req.getCity() + req.getArea()).equals(entry.getProvince() + entry.getCity() + entry.getArea())) {
            sf.append("修改地址：修改前：").append(entry.getProvince()).append(entry.getCity()).append(entry.getArea()).append(" ,修改后 ：").
                    append(req.getProvince()).append(req.getCity()).append(req.getArea()).append(";");
            entry.setProvince(StringUtil.isBlank(req.getProvince()) ? "" : req.getProvince());
            entry.setCity(StringUtil.isBlank(req.getCity()) ? "" : req.getCity());
            entry.setArea(StringUtil.isBlank(req.getArea()) ? "" : req.getArea());
            entry.setStreet(StringUtil.isBlank(req.getStreet()) ? "" : req.getStreet());
            entry.setLongitude(req.getLongitude());
            entry.setLatitude(req.getLatitude());
        }

        if (!Objects.equals(req.getAddress(),entry.getAddress())) {
            sf.append("修改详细地址：修改前：").append(entry.getAddress()).append(" ,修改后 ：").
                    append(req.getAddress()).append(";");
            entry.setAddress(StringUtil.isBlank(req.getAddress()) ? "" : req.getAddress().trim());
        }
        if (!Objects.equals(req.getMobile(),entry.getMobile())) {
            sf.append("修改联系方式：修改前：").append(entry.getMobile()).append(" ,修改后 ：").append(req.getMobile()).append(";");
            entry.setMobile(req.getMobile().trim());
        }
        entry.setWindPressure(req.getWindPressure());
        entry.setSnowPressure(req.getSnowPressure());
        entry.setPressureLevel(req.getPressureLevel());
        entry.setExigenceName(req.getExigenceName());
        entry.setExigencePhone(req.getExigencePhone());
        entry.setResidenceBooklet(req.getResidenceBooklet());
        entry.setGender(req.getGender());
        entry.setAge(req.getAge());
        entry.setIdCardFront(req.getIdCardFront());
        entry.setIdCardBack(req.getIdCardBack());
        entry.setCorp(req.getCorp());
        entry.setRegno(req.getRegno());
        entry.setBankName(req.getBankName());
        entry.setBankCode(req.getBankCode().trim());
        entry.setBankCard(req.getBankCard());
        entry.setTssBankNum(req.getTssBankNum());
        entry.setTssBankNumName(req.getTssBankNumName());
        entry.setBpName(req.getBpName());
        entry.setBpRelation(req.getBpRelation());
        entry.setBpMobile(req.getBpMobile());
        entry.setBpCardFront(req.getBpCardFront());
        entry.setBpCardBack(req.getBpCardBack());
        entry.setBpFile(req.getBpFile());
        entry.setExamineRemarks(null);
        entry.setIcValidityEnd(req.getIcValidityEnd());
        entry.setIcValidityBegin(req.getIcValidityBegin());
        entry.setBirthdayDate(req.getBirthdayDate());
        //修改产品信息
        if (StringUtil.isNotBlank(req.getProjectId())){
            entry.setProjectId(pro.getStr("id"));
            entry.setProjectName(pro.getStr("name"));
            entry.setProjectCode(pro.getStr("code"));
            //产品数量
            entry.setProjectNum(1);
        }
        //修改项目公司信息
        if (StringUtil.isNotBlank(req.getCompany())){
            ProjectCompanySettings projectCompanySettings = companyDao.get(req.getCompany());
            entry.setProjectCompanyId(projectCompanySettings.getId());
            entry.setProjectCompanyName(projectCompanySettings.getName());
            entry.setManagementType(projectCompanySettings.getCompanyCode());
            if (pro != null) {
                String filingType = pro.getStr("filing_type");
                if (!filingType.equals(projectCompanySettings.getFilingType())) {
                    throw new IllegalArgumentException("选择的产品、项目公司所属备案类型不一致");
                }
            }
        } else {
            entry.setProjectCompanyId(null);
            entry.setProjectCompanyName(null);
            entry.setManagementType(null);
        }
        if (StringUtil.isNotBlank(req.getBpIdCard()) && req.getBpIdCard().equals(entry.getIdCode())) {
            throw new IllegalArgumentException("共签人证件号码不能与业主身份证号相同!");
        }
        entry.setBpIdCard(req.getBpIdCard());

        // 提交时，校验区域 代理商是否授权
        if (CustomerEntryConstants.TYPE_TJ.equals(req.getType())) {
            boolean checkAuth = traderPcdService.checkAuth(entry.getCreateTraderId(), req.getProvince(), req.getCity(), req.getArea());
            if (!checkAuth) {
                throw new IllegalArgumentException("代理商区域暂未授权");
            }
            //编辑接口
            //TODO 校验产品区域权限  产品是否授权
            if (pro != null) {
                boolean b = projectDao.checkAuth(req.getProjectId(), req.getProvince(), req.getCity(), req.getArea());
                if (!b) {
                    throw new IllegalArgumentException("产品区域暂未授权");
                }
            }
            //TODO 校验项目公司区域  产品是否授权
            boolean b1 = companyDao.checkAuth2(req.getCompany(), req.getProvince(), req.getCity(), req.getArea());
            if (!b1) {
                throw new IllegalArgumentException("项目公司区域暂未授权");
            }
            // 越秀要求提交信息时 必须保持身份证/法人登记注册号码
            if ("01".equals(entry.getPartnerId())) {
                if ("1".equals(entry.getTenantType()) && StringUtil.isBlank(entry.getIdCode())) {
                    throw new IllegalArgumentException("请填写身份证号");
                }
                else if ("2".equals(entry.getTenantType()) && StringUtil.isBlank(entry.getRegno())) {
                    throw new IllegalArgumentException("请填写信用代码");
                }
            }
        }
        if (StringUtil.isNotBlank(req.getTenantId())) {
            entry.setTenantId(req.getTenantId());
        }
        String signFlowId = "";
        //获取电站业主授权信息
        boolean pushSmsFlag = false; // 用于判断是否需要发送授权使用短信
        CrmCustomerYxCondition condition = null;
        CrmCustomerYxAuthorization customerYxAuthorization = null;
        String keyInfo = null;
        if ("1".equals(entry.getTenantType()) && StringUtil.isNotBlank(entry.getIdCode())) {
            keyInfo = entry.getIdCode();
        }
        else if ("2".equals(entry.getTenantType()) && StringUtil.isNotBlank(entry.getRegno())) {
            keyInfo = entry.getRegno();
        }
        String modPreaudit = "1"; // 修改预审标记：1.待预审 2.预审通过 3.需要发起预审
        String authorization = "1"; // 信息使用授权状态：1.未授权 2.已发起 3.已授权
        String otherMsg = "";
        // 修改时提交
        if (CustomerEntryConstants.TYPE_TJ.equals(req.getType())) { //提交
                List<Record> list = formSetDao.findListByCondition("01", entry.getPartnerId());
                Result result = requiredCheckForRegisterInfo(entry, req.getRegnoUrl(), list, "1",req.getCreditCertificate(),req.getHouseOwnership());
                if (!"200".equals(result.getCode())) {
                    throw new IllegalArgumentException(result.getErrMsg());
                }
            if (FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZGYS)) {
                //partner.getTenantFlag 客户预审方式：0.同一客户只需要一次预审即可 1.一个电站需要一次预审
                if (PartnerConstants.PARTNER_ID_HR.equals(partner.getId())){//华融区分备案类型
                    condition = conditionDao.findCustomerYxCondition(keyInfo,partner.getId(),entry.getFilingType());
                    customerYxAuthorization = customerYxAuthorizationDao.findCustomerYxAuthorization(keyInfo,partner.getId(),entry.getFilingType());
                }else {
                    condition = conditionDao.findCustomerYxCondition(keyInfo,partner.getId());
                    customerYxAuthorization = customerYxAuthorizationDao.findCustomerYxAuthorization(keyInfo,partner.getId());
                }
                otherMsg = "提交审核 ";
                entry.setCredit(CustomerEntryConstants.CREDIT_WAIT);
                boolean needCondition = true;
                boolean needAuthorization = true;
                //个人时需要判断 信息授权是否完成，完成则调用预审接口，未完成则先走信息授权流程
                if (condition == null || ("1".equals(req.getTenantType()) && "1".equals(condition.getAuthorization()))) {
                    //推送授权使用的签约短信签约短信
                    // 改变预审状态，授权信息状态，进件状态
                    if ("1".equals(req.getTenantType())) {
                        //华融区分备案类型
                        if (PartnerConstants.PARTNER_ID_HR.equals(partner.getId())){
                            if (CustomerEntryConstants.FILING_TYPE_FARMER.equals(entry.getFilingType())){
                                pushSmsFlag = true;
                                entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUBMITTED);
                            }else {
                                needAuthorization = false;
                                authorization="3";
                                entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                                entry.setCredit(CustomerEntryConstants.CREDIT_APPROVE);
                                entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                                modPreaudit = "3";
                            }
                        }else {
                            pushSmsFlag = true;
                            entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUBMITTED);
                        }
                    }else {
                        entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                        entry.setCredit(CustomerEntryConstants.CREDIT_APPROVE);
                        entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                        modPreaudit = "3";
                        if ("1".equals(partner.getTenantFlag())) {
                            needCondition = false;
                            //客户类型是单位、且一个电站需要一次预审时，则不需要生成授权预审记录
                        }
                    }
                } else {
                    if ("1".equals(partner.getTenantFlag())) {
                        if ("1".equals(entry.getTenantType()) && "2".equals(condition.getAuthorization())) {
                            //如果已完成授权 直接发起预审
                            // 信息使用授权状态：1.未授权 2.已发起 3.已授权
                            // 预审状态 1.待预审 2.预审中 3.预审不通过 4.预审通过
                            throw new IllegalArgumentException("信息授权中，请先签署完成生成的信息授权");
                        }
                        entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                        entry.setCredit(CustomerEntryConstants.CREDIT_APPROVE);
                        entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                        modPreaudit = "3";
                    }
                    else {
                        entry.setCredit(condition.getPreaudit());
                        entry.setAuthorization(condition.getAuthorization());
                        if (StringUtil.isBlank(req.getApplyStatus()) || Integer.parseInt(req.getApplyStatus()) < 4) {
                            entry.setApplyStatus(dealYxConditionPreauditToApplyStatus(condition.getPreaudit()));
                        }
                        // 校验是否存在已预审通过
                        if("4".equals(condition.getPreaudit())){
                            modPreaudit = "2";
                            entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
                            entry.setPreAuditTime(now);
                            if (PartnerConstants.PARTNER_ID_HR.equals(partner.getId())){
                                //预审通过自动发起合同
                                createHRContract(entry,operator);
                            }
                        }
                    }
                }
                // 客户类型为个人时需要开二类卡 需要查询该身份证是否已开过卡
                if (!"1".equals(partner.getTenantFlag()) && "1".equals(req.getTenantType())) {
                    Record bankCondition = customerDao.findYxBankCondition(entry.getIdCode(), entry.getMobile(),entry.getPartnerId());
                    if (bankCondition != null && "4".equals(bankCondition.getStr("status"))) {
                        entry.setSecCardStatus("1");
                    }
                }

                // 新建客户信息
                Result res = createTenant(entry, req.getRegnoUrl());
                if (res.isOk()) {
                    entry.setTenantId(res.getMsg());
                } else {
                    throw new IllegalArgumentException(res.getErrMsg());
                }
                if (condition == null && needCondition) {
                    String id = IdGen.uuid();
                    String preaudit = "1";
                    // 生成 已发起开卡申请 待预审的记录
                    logger.info("生成 crm_customer_yx_condition 记录,id:{},name:{},mobile:{},id_code:{},preaudit :{},authorization:{}",
                            id, entry.getTenantName(), entry.getMobile(), keyInfo, preaudit, authorization);
                    condition = conditionDao.addYxCondition(id, entry.getTenantName(), entry.getMobile(),
                            keyInfo, preaudit, authorization, null,entry.getPartnerId(),entry.getFilingType());
                    if (needAuthorization){
                        customerYxAuthorization = customerYxAuthorizationDao.addYxAuthorization(entry.getTenantName(), entry.getMobile(),
                                keyInfo,  authorization, null,entry.getPartnerId(),entry.getFilingType());
                    }
                }

            }else {
                entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                entry.setCredit(CustomerEntryConstants.CREDIT_APPROVED);
//                entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSCG);
                entry.setApplyStatus(null);
//                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DSH);
                entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
                // 新建客户信息
                Result res = createTenant(entry, req.getRegnoUrl());
                if (res.isOk()) {
                    entry.setTenantId(res.getMsg());
                } else {
                    throw new IllegalArgumentException(res.getErrMsg());
                }
            }
            customerDao.save(entry);
            //信息授权完成，直接发起预审
            if ("3".equals(modPreaudit)) {
                String houseOwnership = req.getHouseOwnership();
                String regnoUrl = req.getRegnoUrl();
                saveEntryToAdmittance(entry, condition, houseOwnership, regnoUrl);
            }
        }
        //保存房产证信息
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entry.getId());
        if (surveyRecord == null) {
            surveyRecord = new CustomerEntrySurveyRecord();
            surveyRecord.setEntryId(entry.getId());
            surveyRecord.setTraderId(entry.getDistributorId());
            surveyRecord.setCreateTime(new Date());
        }
        surveyRecord.setHouseOwnership(req.getHouseOwnership());
        surveyRecordDao.save(surveyRecord);
        // 电站的承租类型法人的文件上传记录表
        CustomerEntryOrgFiles orgFiles = orgFilesDao.findOneByEntryId(entry.getId());
        if (orgFiles == null) {
            if (Objects.equals("2", entry.getTenantType())) {
                orgFilesDao.createOne(entry.getId(), entry.getDistributorId(), req.getRegnoUrl(),null);
            } else {
                orgFilesDao.createOne(entry.getId(), entry.getDistributorId(), null,req.getCreditCertificate());
            }
        } else {
            if (StringUtils.isNotBlank(req.getRegnoUrl())){
                orgFiles.setRegnoUrl(req.getRegnoUrl());
            }
            if (StringUtils.isNotBlank(req.getCreditCertificate())){
                orgFiles.setCreditCertificate(req.getCreditCertificate());
            }
            orgFilesDao.save(orgFiles);
        }
        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_AUDIT
                , otherMsg + sf.toString(), null);
        if (!"1".equals(partner.getTenantFlag())) {
            applicationDao.saveIncomingApplication(entry);
        }

        if (pushSmsFlag) {
            String address=entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress();
            signFlowId = askAuthContractService.createAskAuthContract(req.getIdCode(), entry.getMobile(),address,entry.getPartnerId());
            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.AUTH_SIGN, "发起签约授权 ", "");
            condition.setAuthorization("2");
            condition.setSignFlowId(signFlowId);
            conditionDao.save(condition);
            customerYxAuthorization.setAuthorization("2");
            customerYxAuthorization.setSignFlowId(signFlowId);
            customerYxAuthorizationDao.save(customerYxAuthorization);
        }
        return "200";
    }

    /**
     * 信息登记时 修改电站逻辑
     */
    @Transactional(rollbackFor = Exception.class)
    public String editHREntryForIXDJ(AddEntryReq req, Operator operator) {
        logger.info("editEntryForIXDJ entry={}",new Gson().toJson(req));
        // 获取资方信息
        CrmPartner partner = partnerService.getById(req.getZfId());
        // 当前要求 信息登记时
        CustomerEntry entry = customerDao.get(req.getId());
        if (!CustomerEntryConstants.ENTRY_STATUS_ZC.equals(entry.getStatus())) {
            return "当前状态不满足操作要求，暂存状态下才可进行修改";
        }
        Date now = DateUtils.getNowDate();

        String projectCode = "";
        String projectName = "";
        String payCycle = "";
        BigDecimal epcPrice = new BigDecimal(0);
        String productLineId = "";
        String lineName = "";
        String attribute = "";
        String filingType = "";
        if(req.getProjectList() != null){
            if("04".equals(entry.getPartnerId())){
                List<ProjectInfoVo> projectList = req.getProjectList();
                if (projectList==null||projectList.isEmpty()) {
                    throw new IllegalArgumentException("请选择产品");
                }else {
                    Set<String> projectSet = new HashSet<>();
                    for (ProjectInfoVo projectInfoVo : projectList) {
                        if (StringUtil.isBlank(projectInfoVo.getProjectId())) {
                            throw new IllegalArgumentException("请选择产品");
                        }
                        if(StringUtil.isBlank(projectInfoVo.getRoofType())){
                            throw new IllegalArgumentException("请选择屋顶类型");
                        }
                        if(!projectSet.add(projectInfoVo.getProjectId())){
                            throw new IllegalArgumentException(projectInfoVo.getProjectName()+"重复");
                        }
                        if(!projectSet.add(projectInfoVo.getRoofType())){
                            throw new IllegalArgumentException(projectInfoVo.getRoofType()+"重复");
                        }
                    }
                }
            }
            for(ProjectInfoVo vo :req.getProjectList()){
                if (StringUtil.isNotBlank(req.getProjectId())) {
                    Record pro = null;
                    pro = projectDao.getProject(vo.getProjectId());
                    if (pro.getStr("code") != null) {
                        projectCode += pro.getStr("code")+",";
                    }
                    if (pro.getStr("name") != null) {
                        projectName += pro.getStr("name")+",";
                    }
                    if (pro.getStr("pay_cycle") != null) {
                        if("按月支付".equals(pro.getStr("pay_cycle"))){
                            payCycle = "1";
                        }else if("按季支付".equals(pro.getStr("pay_cycle"))){
                            payCycle = "2";
                        }else if("按年支付".equals(pro.getStr("pay_cycle"))){
                            payCycle = "3";
                        }
                    }
                    if (pro.get("epc_price") != null) {
                        //EPC单价/ 每W定价
                        epcPrice = epcPrice.add(pro.getBigDecimal("epc_price"));
                    }
                    //产品线
                    if (StringUtil.isNotBlank(pro.getStr("product_line_id"))) {
                        productLineId = pro.getStr("product_line_id");
                    }
                    if (StringUtil.isNotBlank(pro.getStr("lineName"))) {
                        lineName = pro.getStr("lineName");
                    }
                    //业务属性 1.纯租25年业务、2.经营性租赁、3.融资租赁、4.光伏贷、5.全款、6.其他
                    if (StringUtil.isNotBlank(pro.getStr("attribute"))) {
                        if("BT业务".equals(pro.getStr("attribute"))){
                            attribute = "1";
                        }else if("经营性租赁".equals(pro.getStr("attribute"))){
                            attribute = "2";
                        }else if("融资租赁".equals(pro.getStr("attribute"))){
                            attribute = "3";
                        }else if("光伏贷".equals(pro.getStr("attribute"))){
                            attribute = "4";
                        }else if("全款".equals(pro.getStr("attribute"))){
                            attribute = "5";
                        }else {
                            attribute = "6";
                        }
                    }
                    if (StringUtil.isNotBlank(pro.getStr("filing_type"))) {
                        filingType = pro.getStr("filing_type");
                    }
                }
            }
            projectCode = projectCode.substring(0,projectCode.length()-1);
            projectName = projectName.substring(0,projectName.length()-1);
            epcPrice = epcPrice.divide(new BigDecimal(req.getProjectList().size()), 2, RoundingMode.HALF_UP);
        }
        StringBuilder sf = new StringBuilder();
        if (StringUtil.isBlank(entry.getProjectId()) && StringUtil.isBlank(req.getProjectId())) {

        }
        else if (StringUtil.isBlank(entry.getProjectId()) || StringUtil.isBlank(req.getProjectId())
                || !req.getProjectId().equals(entry.getProjectId())) {
            if(req.getProjectList() != null) {
                for (ProjectInfoVo vo : req.getProjectList()) {
                    if (StringUtil.isNotBlank(req.getProjectId())) {
                        Record pro = null;
                        pro = projectDao.getProject(vo.getProjectId());
                        // 修改后 产品被清空
                        if (pro == null) {
                            sf.append("修改项目信息,取消选择：").append(entry.getProjectName()).append(";");
                        }
                        else {
                            // 修改前 产品未设置
                            if (StringUtil.isBlank(entry.getProjectId())) {
                                sf.append("修改项目信息,修改为：").append(pro.getStr("name")).append(";");
                            }
                            // 修改前与修改后 产品不一样
                            else {
                                sf.append("修改项目信息,修改前：").append(entry.getProjectName()).
                                        append(" ,修改后 ：").append(pro.getStr("name")).append(";");
                            }
                            if (!entry.getPartnerId().equals(pro.getStr("management"))) {
                                return "选择的产品不属于" + entry.getPartnerName() + ",请重新选择产品";
                            }
                        }
                    }
                }
            }
            entry.setProjectId(req.getProjectId() == null ? null : req.getProjectId());
            entry.setProjectName("".equals(projectName) ? null : projectName);
            entry.setProjectCode("".equals(projectCode) ? null : projectCode);

            //EPC单价/ 每W定价
            entry.setEpcPrice(epcPrice == null ? BigDecimal.ZERO : epcPrice);
            //产品线
            entry.setProductLineId("".equals(productLineId) ? null : productLineId);
            entry.setProductLineName("".equals(lineName) ? null : lineName);
            //业务属性 1.纯租25年业务、2.经营性租赁、3.融资租赁、4.光伏贷、5.全款、6.其他
            entry.setProductLine("".equals(attribute) ? null : attribute);
            //租金支付周期 1按月支付 2按季支付 3按年支付
            entry.setPayCycle(req.getPayCycle() == null ? null : req.getPayCycle());
            entry.setFilingType("".equals(filingType) ? null : filingType);
            //屋顶类型
            if(req.getProjectList().size()>0){
                String roofType = req.getProjectList().stream().map(ProjectInfoVo :: getRoofType).collect(Collectors.joining(","));
                entry.setRoofType(roofType);
            }
            //删除旧租金信息
            customerRentVariableService.deleteRentVariable(req.getId());
            //更新租金信息
            if(req.getProjectList() != null) {
                for (ProjectInfoVo vo : req.getProjectList()) {
                    if (StringUtil.isNotBlank(req.getProjectId())) {
                        Record pro = null;
                        pro = projectDao.getProject(vo.getProjectId());
                        if (pro != null) {
                            customerRentVariableService.saveEntryComponent(req.getId(), req.getProjectId());
                        }
                    }
                }
            }
        }
        if (!Objects.equals(req.getTenantName(),entry.getTenantName())) {
            sf.append("修改业主姓名：修改前：").append(entry.getTenantName()).append(" ,修改后 ：").append(req.getTenantName()).append(";");
            entry.setTenantName(req.getTenantName());
        }
        if (!Objects.equals(req.getIdCode(),entry.getIdCode())) {
            sf.append("修改身份证号：修改前：").append(entry.getIdCode()).append(" ,修改后 ：").append(req.getIdCode()).append(";");
            entry.setIdCode(req.getIdCode().toUpperCase());
            entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_WAIT);
        }
        if (!(req.getProvince() + req.getCity() + req.getArea()).equals(entry.getProvince() + entry.getCity() + entry.getArea())) {
            sf.append("修改地址：修改前：").append(entry.getProvince()).append(entry.getCity()).append(entry.getArea()).append(" ,修改后 ：").
                    append(req.getProvince()).append(req.getCity()).append(req.getArea()).append(";");
            entry.setProvince(StringUtil.isBlank(req.getProvince()) ? "" : req.getProvince());
            entry.setCity(StringUtil.isBlank(req.getCity()) ? "" : req.getCity());
            entry.setArea(StringUtil.isBlank(req.getArea()) ? "" : req.getArea());
            entry.setStreet(StringUtil.isBlank(req.getStreet()) ? "" : req.getStreet());
            entry.setLongitude(req.getLongitude());
            entry.setLatitude(req.getLatitude());
        }

        if (!Objects.equals(req.getAddress(),entry.getAddress())) {
            sf.append("修改详细地址：修改前：").append(entry.getAddress()).append(" ,修改后 ：").
                    append(req.getAddress()).append(";");
            entry.setAddress(StringUtil.isBlank(req.getAddress()) ? "" : req.getAddress().trim());
        }
        if (!Objects.equals(req.getMobile(),entry.getMobile())) {
            sf.append("修改联系方式：修改前：").append(entry.getMobile()).append(" ,修改后 ：").append(req.getMobile()).append(";");
            entry.setMobile(req.getMobile().trim());
        }
        entry.setWindPressure(req.getWindPressure());
        entry.setSnowPressure(req.getSnowPressure());
        entry.setPressureLevel(req.getPressureLevel());
        entry.setExigenceName(req.getExigenceName());
        entry.setExigencePhone(req.getExigencePhone());
        entry.setResidenceBooklet(req.getResidenceBooklet());
        entry.setGender(req.getGender());
        entry.setAge(req.getAge());
        entry.setIdCardFront(req.getIdCardFront());
        entry.setIdCardBack(req.getIdCardBack());
        entry.setCorp(req.getCorp());
        entry.setRegno(req.getRegno());
        entry.setBankName(req.getBankName());
        entry.setBankCode(req.getBankCode().trim());
        entry.setBankCard(req.getBankCard());
        entry.setTssBankNum(req.getTssBankNum());
        entry.setTssBankNumName(req.getTssBankNumName());
        entry.setBpName(req.getBpName());
        entry.setBpRelation(req.getBpRelation());
        entry.setBpMobile(req.getBpMobile());
        entry.setBpCardFront(req.getBpCardFront());
        entry.setBpCardBack(req.getBpCardBack());
        entry.setBpFile(req.getBpFile());
        entry.setExamineRemarks(null);
        entry.setIcValidityEnd(req.getIcValidityEnd());
        entry.setIcValidityBegin(req.getIcValidityBegin());
        entry.setBirthdayDate(req.getBirthdayDate());
        //修改产品信息
        if (StringUtil.isNotBlank(req.getProjectId())){
            entry.setProjectId(req.getProjectId());
            entry.setProjectName(projectName);
            entry.setProjectCode(projectCode);
            entry.setProjectNum(req.getProjectList().size());
        }
        //修改项目公司信息
        if (StringUtil.isNotBlank(req.getCompany())){
            ProjectCompanySettings projectCompanySettings = companyDao.get(req.getCompany());
            entry.setProjectCompanyId(projectCompanySettings.getId());
            entry.setProjectCompanyName(projectCompanySettings.getName());
            entry.setManagementType(projectCompanySettings.getCompanyCode());
            if(req.getProjectList() != null) {
                for (ProjectInfoVo vo : req.getProjectList()) {
                    if (StringUtil.isNotBlank(req.getProjectId())) {
                        Record pro = null;
                        pro = projectDao.getProject(vo.getProjectId());
                        if (pro != null) {
                            String filingTypeStr = pro.getStr("filing_type");
                            if (!filingTypeStr.equals(projectCompanySettings.getFilingType())) {
                                throw new IllegalArgumentException("选择的产品、项目公司所属备案类型不一致");
                            }
                        }
                    }
                }
            }
        } else {
            entry.setProjectCompanyId(null);
            entry.setProjectCompanyName(null);
            entry.setManagementType(null);
        }
        if (StringUtil.isNotBlank(req.getBpIdCard()) && req.getBpIdCard().equals(entry.getIdCode())) {
            throw new IllegalArgumentException("共签人证件号码不能与业主身份证号相同!");
        }
        entry.setBpIdCard(req.getBpIdCard());

        // 提交时，校验区域 代理商是否授权
        if (CustomerEntryConstants.TYPE_TJ.equals(req.getType())) {
            boolean checkAuth = traderPcdService.checkAuth(entry.getCreateTraderId(), req.getProvince(), req.getCity(), req.getArea());
            if (!checkAuth) {
                throw new IllegalArgumentException("代理商区域暂未授权");
            }
            //编辑接口
            //TODO 校验产品区域权限  产品是否授权
            if(req.getProjectList() != null) {
                for (ProjectInfoVo vo : req.getProjectList()) {
                    if (StringUtil.isNotBlank(req.getProjectId())) {
                        Record pro = null;
                        pro = projectDao.getProject(vo.getProjectId());
                        if (pro != null) {
                            boolean b = projectDao.checkAuth(vo.getProjectId(), req.getProvince(), req.getCity(), req.getArea());
                            if (!b) {
                                throw new IllegalArgumentException("产品区域暂未授权");
                            }
                        }
                    }
                }
            }
            //TODO 校验项目公司区域  产品是否授权
            boolean b1 = companyDao.checkAuth2(req.getCompany(), req.getProvince(), req.getCity(), req.getArea());
            if (!b1) {
                throw new IllegalArgumentException("项目公司区域暂未授权");
            }
            // 越秀要求提交信息时 必须保持身份证/法人登记注册号码
            if ("01".equals(entry.getPartnerId())) {
                if ("1".equals(entry.getTenantType()) && StringUtil.isBlank(entry.getIdCode())) {
                    throw new IllegalArgumentException("请填写身份证号");
                }
                else if ("2".equals(entry.getTenantType()) && StringUtil.isBlank(entry.getRegno())) {
                    throw new IllegalArgumentException("请填写信用代码");
                }
            }
        }
        if (StringUtil.isNotBlank(req.getTenantId())) {
            entry.setTenantId(req.getTenantId());
        }
        String signFlowId = "";
        //获取电站业主授权信息
        boolean pushSmsFlag = false; // 用于判断是否需要发送授权使用短信
        CrmCustomerYxCondition condition = null;
        CrmCustomerYxAuthorization customerYxAuthorization = null;
        String keyInfo = null;
        if ("1".equals(entry.getTenantType()) && StringUtil.isNotBlank(entry.getIdCode())) {
            keyInfo = entry.getIdCode();
        }
        else if ("2".equals(entry.getTenantType()) && StringUtil.isNotBlank(entry.getRegno())) {
            keyInfo = entry.getRegno();
        }
        String modPreaudit = "1"; // 修改预审标记：1.待预审 2.预审通过 3.需要发起预审
        String authorization = "1"; // 信息使用授权状态：1.未授权 2.已发起 3.已授权
        String otherMsg = "";
        // 修改时提交
        if (CustomerEntryConstants.TYPE_TJ.equals(req.getType())) { //提交
            List<Record> list = formSetDao.findListByCondition("01", entry.getPartnerId());
            Result result = requiredCheckForRegisterInfo(entry, req.getRegnoUrl(), list, "1",req.getCreditCertificate(),req.getHouseOwnership());
            if (!"200".equals(result.getCode())) {
                throw new IllegalArgumentException(result.getErrMsg());
            }
            if (FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZGYS)) {
                //partner.getTenantFlag 客户预审方式：0.同一客户只需要一次预审即可 1.一个电站需要一次预审
                if (PartnerConstants.PARTNER_ID_HR.equals(partner.getId())){//华融区分备案类型
                    condition = conditionDao.findCustomerYxCondition(keyInfo,partner.getId(),entry.getFilingType());
                    customerYxAuthorization = customerYxAuthorizationDao.findCustomerYxAuthorization(keyInfo,partner.getId(),entry.getFilingType());
                }else {
                    condition = conditionDao.findCustomerYxCondition(keyInfo,partner.getId());
                    customerYxAuthorization = customerYxAuthorizationDao.findCustomerYxAuthorization(keyInfo,partner.getId());
                }
                otherMsg = "提交审核 ";
                entry.setCredit(CustomerEntryConstants.CREDIT_WAIT);
                boolean needCondition = true;
                boolean needAuthorization = true;
                //个人时需要判断 信息授权是否完成，完成则调用预审接口，未完成则先走信息授权流程
                if (condition == null || ("1".equals(req.getTenantType()) && "1".equals(condition.getAuthorization()))) {
                    //推送授权使用的签约短信签约短信
                    // 改变预审状态，授权信息状态，进件状态
                    if ("1".equals(req.getTenantType())) {
                        //华融区分备案类型
                        if (PartnerConstants.PARTNER_ID_HR.equals(partner.getId())){
                            if (CustomerEntryConstants.FILING_TYPE_FARMER.equals(entry.getFilingType())){
                                pushSmsFlag = true;
                                entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUBMITTED);
                            }else {
                                needAuthorization = false;
                                authorization="3";
                                entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                                entry.setCredit(CustomerEntryConstants.CREDIT_APPROVE);
                                entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                                modPreaudit = "3";
                            }
                        }else {
                            pushSmsFlag = true;
                            entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUBMITTED);
                        }
                    }else {
                        entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                        entry.setCredit(CustomerEntryConstants.CREDIT_APPROVE);
                        entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                        modPreaudit = "3";
                        if ("1".equals(partner.getTenantFlag())) {
                            needCondition = false;
                            //客户类型是单位、且一个电站需要一次预审时，则不需要生成授权预审记录
                        }
                    }
                } else {
                    if ("1".equals(partner.getTenantFlag())) {
                        if ("1".equals(entry.getTenantType()) && "2".equals(condition.getAuthorization())) {
                            //如果已完成授权 直接发起预审
                            // 信息使用授权状态：1.未授权 2.已发起 3.已授权
                            // 预审状态 1.待预审 2.预审中 3.预审不通过 4.预审通过
                            throw new IllegalArgumentException("信息授权中，请先签署完成生成的信息授权");
                        }
                        entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                        entry.setCredit(CustomerEntryConstants.CREDIT_APPROVE);
                        entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                        modPreaudit = "3";
                    }
                    else {
                        entry.setCredit(condition.getPreaudit());
                        entry.setAuthorization(condition.getAuthorization());
                        if (StringUtil.isBlank(req.getApplyStatus()) || Integer.parseInt(req.getApplyStatus()) < 4) {
                            entry.setApplyStatus(dealYxConditionPreauditToApplyStatus(condition.getPreaudit()));
                        }
                        // 校验是否存在已预审通过
                        if("4".equals(condition.getPreaudit())){
                            String oldMobile = condition.getMobile();
                            String mobile = entry.getMobile();
                            if (oldMobile.equals(mobile)){//华融手机号相同预审通过无需预审
                                modPreaudit = "2";
                                entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
                                entry.setPreAuditTime(now);
                                if (PartnerConstants.PARTNER_ID_HR.equals(partner.getId())){
                                    //预审通过自动发起合同
                                    createHRContract(entry,operator);
                                }
                            }else {//华融手机号不同 预审通过 需要重新预审
                                condition.setMobile(mobile);
                                conditionDao.save(condition);
                                if (customerYxAuthorization != null){
                                    customerYxAuthorization.setMobile(mobile);
                                    customerYxAuthorizationDao.save(customerYxAuthorization);
                                }
                                modPreaudit = "3";
                                entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                                entry.setCredit(CustomerEntryConstants.CREDIT_APPROVE);
                                entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                            }
                        }
                    }
                }
                // 客户类型为个人时需要开二类卡 需要查询该身份证是否已开过卡
                if (!"1".equals(partner.getTenantFlag()) && "1".equals(req.getTenantType())) {
                    Record bankCondition = customerDao.findYxBankCondition(entry.getIdCode(), entry.getMobile(),entry.getPartnerId());
                    if (bankCondition != null && "4".equals(bankCondition.getStr("status"))) {
                        entry.setSecCardStatus("1");
                    }
                }

                // 新建客户信息
                Result res = createTenant(entry, req.getRegnoUrl());
                if (res.isOk()) {
                    entry.setTenantId(res.getMsg());
                } else {
                    throw new IllegalArgumentException(res.getErrMsg());
                }
                if (condition == null && needCondition) {
                    String id = IdGen.uuid();
                    String preaudit = "1";
                    // 生成 已发起开卡申请 待预审的记录
                    logger.info("生成 crm_customer_yx_condition 记录,id:{},name:{},mobile:{},id_code:{},preaudit :{},authorization:{}",
                            id, entry.getTenantName(), entry.getMobile(), keyInfo, preaudit, authorization);
                    condition = conditionDao.addYxCondition(id, entry.getTenantName(), entry.getMobile(),
                            keyInfo, preaudit, authorization, null,entry.getPartnerId(),entry.getFilingType());
                    if (needAuthorization){
                        customerYxAuthorization = customerYxAuthorizationDao.addYxAuthorization(entry.getTenantName(), entry.getMobile(),
                                keyInfo,  authorization, null,entry.getPartnerId(),entry.getFilingType());
                    }
                }

            }else {
                entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                entry.setCredit(CustomerEntryConstants.CREDIT_APPROVED);
//                entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSCG);
                entry.setApplyStatus(null);
//                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DSH);
                entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
                // 新建客户信息
                Result res = createTenant(entry, req.getRegnoUrl());
                if (res.isOk()) {
                    entry.setTenantId(res.getMsg());
                } else {
                    throw new IllegalArgumentException(res.getErrMsg());
                }
            }
            customerDao.save(entry);
            //信息授权完成，直接发起预审
            if ("3".equals(modPreaudit)) {
                String houseOwnership = req.getHouseOwnership();
                String regnoUrl = req.getRegnoUrl();
                saveEntryToAdmittance(entry, condition, houseOwnership, regnoUrl);
            }
        }
        //保存房产证信息
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entry.getId());
        if (surveyRecord == null) {
            surveyRecord = new CustomerEntrySurveyRecord();
            surveyRecord.setEntryId(entry.getId());
            surveyRecord.setTraderId(entry.getDistributorId());
            surveyRecord.setCreateTime(new Date());
        }
        surveyRecord.setHouseOwnership(req.getHouseOwnership());
        surveyRecordDao.save(surveyRecord);

        //电站关联产品表-针对一个电站多产品
        if(req.getProjectList() != null) {
            //删除关联信息
            crmCustomerEntryProjectDao.deleteEntryProjectById(entry.getId());
            for (ProjectInfoVo vo : req.getProjectList()) {
                CrmCustomerEntryProject entryProject = new CrmCustomerEntryProject();
                entryProject.setProjectId(vo.getProjectId());
                entryProject.setEntryId(entry.getId());
                entryProject.setRoofType(vo.getRoofType());
                crmCustomerEntryProjectDao.save(entryProject);

                //删除设计方案信息
                crmCustomerEntryDesignDao.deleteByEntryId(entry.getId());
                //电站的设计方案信息表
                CrmCustomerEntryDesign crmCustomerEntryDesign = new CrmCustomerEntryDesign();
                crmCustomerEntryDesign.setEntryId(entry.getId());
                crmCustomerEntryDesign.setProjectId(vo.getProjectId());
                crmCustomerEntryDesignDao.save(crmCustomerEntryDesign);

                //删除勘测信息
                crmCustomerEntrySurveyRecordDetailDao.deleteByEntryId(entry.getId());
                //电站的勘测信息-明细记录表
                CrmCustomerEntrySurveyRecordDetail crmCustomerEntrySurveyRecordDetail = new CrmCustomerEntrySurveyRecordDetail();
                crmCustomerEntrySurveyRecordDetail.setEntryId(entry.getId());
                crmCustomerEntrySurveyRecordDetail.setProjectId(vo.getProjectId());
                crmCustomerEntrySurveyRecordDetailDao.save(crmCustomerEntrySurveyRecordDetail);
            }
        }
        // 电站的承租类型法人的文件上传记录表
        CustomerEntryOrgFiles orgFiles = orgFilesDao.findOneByEntryId(entry.getId());
        if (orgFiles == null) {
            if (Objects.equals("2", entry.getTenantType())) {
                orgFilesDao.createOne(entry.getId(), entry.getDistributorId(), req.getRegnoUrl(),null);
            } else {
                orgFilesDao.createOne(entry.getId(), entry.getDistributorId(), null,req.getCreditCertificate());
            }
        } else {
            if (StringUtils.isNotBlank(req.getRegnoUrl())){
                orgFiles.setRegnoUrl(req.getRegnoUrl());
            }
            if (StringUtils.isNotBlank(req.getCreditCertificate())){
                orgFiles.setCreditCertificate(req.getCreditCertificate());
            }
            orgFilesDao.save(orgFiles);
        }
        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_AUDIT
                , otherMsg + sf.toString(), null);
        if (!"1".equals(partner.getTenantFlag())) {
            applicationDao.saveIncomingApplication(entry);
        }

        if (pushSmsFlag) {
            String address=entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress();
            signFlowId = askAuthContractService.createAskAuthContract(req.getIdCode(), entry.getMobile(),address,entry.getPartnerId());
            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.AUTH_SIGN, "发起签约授权 ", "");
            condition.setAuthorization("2");
            condition.setSignFlowId(signFlowId);
            conditionDao.save(condition);
            customerYxAuthorization.setAuthorization("2");
            customerYxAuthorization.setSignFlowId(signFlowId);
            customerYxAuthorizationDao.save(customerYxAuthorization);
        }
        return "200";
    }

    /**
     * 信息录入 创建电站逻辑
     */
    @Transactional(rollbackFor = Exception.class)
    public String createEntryForIXDJ(AddEntryReq req, Operator operator) {
        logger.info("createCustomerEntry entry={}",new Gson().toJson(req));
        // 当前要求 信息录入时 先设置资方-投资方， 产品字段不再必填项
        if (StringUtil.isBlank(req.getZfId())) {
            throw new IllegalArgumentException("请先选择投资方");
        }

        // 获取资方信息 pro.getStr("management")
        CrmPartner partner = partnerService.getById(req.getZfId());
        if(partner==null){
            throw new IllegalArgumentException("请先选择投资方");
        }
        Record pro = null;
        if (StringUtil.isNotBlank(req.getProjectId())) {
            pro = projectDao.getProject(req.getProjectId());
        }
        Date now = DateUtils.getNowDate();
        CustomerEntry cus = new CustomerEntry();
        cus.setCreateBy(operator.getUserId());
        cus.setCreator(operator.getUserName());
        cus.setCreateTime(now);
        String powerStationCode = PlantformUtils.getOrderNumber();
        cus.setPowerStationCode(powerStationCode);
        //获取项目公司信息
        if (req.getCompany() != null){
            ProjectCompanySettings projectCompanySettings = companyDao.get(req.getCompany());
            if (projectCompanySettings != null) {
                cus.setProjectCompanyId(projectCompanySettings.getId());
                cus.setProjectCompanyName(projectCompanySettings.getName());
                cus.setManagementType(projectCompanySettings.getCompanyCode());
                if (pro != null) {
                    String filingType = pro.getStr("filing_type");
                    if (!filingType.equals(projectCompanySettings.getFilingType())) {
                        throw new IllegalArgumentException("选择的产品、项目公司所属备案类型不一致");
                    }
                }
            }
        }
        cus = customerDao.createOne(req, cus);

        if (pro != null) {
            cus.setProjectId(pro.getStr("id"));
            cus.setProjectCode(pro.getStr("code"));
            cus.setProjectName(pro.getStr("name"));
            //EPC单价/ 每W定价
            if (pro.get("epc_price") != null) {
                cus.setEpcPrice(pro.getBigDecimal("epc_price"));
            }
            //产品线
            if (StringUtil.isNotBlank(pro.getStr("product_line_id"))) {
                cus.setProductLineId(pro.getStr("product_line_id"));
            }
            if (StringUtil.isNotBlank(pro.getStr("lineName"))) {
                cus.setProductLineName(pro.getStr("lineName"));
            }
            //业务属性 1.纯租25年业务、2.经营性租赁、3.融资租赁、4.光伏贷、5.全款、6.其他
            if (StringUtil.isNotBlank(pro.getStr("attribute"))) {
                cus.setProductLine(pro.getStr("attribute"));
            }
            //租金支付周期 1按月支付 2按季支付 3按年支付
            if (StringUtil.isNotBlank(pro.getStr("pay_cycle"))) {
                cus.setPayCycle(pro.getStr("pay_cycle"));
            }
            if (StringUtil.isNotBlank(pro.getStr("filing_type"))) {
                cus.setFilingType(pro.getStr("filing_type"));
            }
        }
        if (StringUtil.isNotBlank(req.getIdCode())) {
            cus.setIdCode(req.getIdCode().toUpperCase());
        }
        cus.setStatus(CustomerEntryConstants.ENTRY_STATUS_ZC);
        cus.setProvince(StringUtil.isBlank(req.getProvince()) ? "" : req.getProvince());
        cus.setCity(StringUtil.isBlank(req.getCity()) ? "" : req.getCity());
        cus.setArea(StringUtil.isBlank(req.getArea()) ? "" : req.getArea());
        cus.setStreet(StringUtil.isBlank(req.getStreet()) ? "" : req.getStreet());
        cus.setWindPressure(req.getWindPressure());
        cus.setSnowPressure(req.getSnowPressure());
        cus.setPressureLevel(req.getPressureLevel());
        cus.setAddress(StringUtil.isBlank(req.getAddress()) ? "" : req.getAddress().trim());
        cus.setMobile(StringUtil.isBlank(req.getMobile()) ? "" : req.getMobile().trim());
        cus.setRemarks(StringUtil.isBlank(req.getRemarks()) ? "" : req.getRemarks());
        cus.setComponentSpec("");
        cus.setDesignCapacity(0);
        cus.setToExamineStatus("1");
        cus.setDesignCapacity(0);
        cus.setInsuranceFlag("1");
        cus.setSignStatus(CustomerEntryConstants.SIGN_STATUS_UNSTART);
        cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_WAIT);
        cus.setCredit(CustomerEntryConstants.CREDIT_ZANCUN);
        cus.setFlag("0");
        cus.setExigenceName(StringUtil.isBlank(req.getExigenceName())? "" : req.getExigenceName());
        cus.setExigencePhone(StringUtil.isBlank(req.getExigencePhone())? "" : req.getExigencePhone());
        cus.setPartnerId(partner.getId());
        cus.setPartnerName(partner.getName());
        cus.setIcValidityEnd(req.getIcValidityEnd());
        cus.setBirthdayDate(req.getBirthdayDate());
        cus.setIcValidityBegin(req.getIcValidityBegin());
        //产品数量
        cus.setProjectNum(1);

        Record traderRecord=CrmUtils.getUserTrader(operator.getUserType(),operator.getUserId());
        cus.setCreateTraderId(traderRecord.getStr("id"));
        cus.setCreateTraderName(traderRecord.getStr("name"));
        //获取上级代理商
        String traderId="2".equals(traderRecord.getStr("type"))?traderRecord.getStr("parent_id"):traderRecord.getStr("id");
        CrmTrader trader = traderDao.get(traderId);
        if (trader == null) {
            throw new IllegalArgumentException("上级代理商不存在");
        }
        cus.setRegionId(trader.getId());
        cus.setDistributorId(trader.getId());
        cus.setTraderName(trader.getName());
        cus.setTraderTel(trader.getMobile());
        // 提交时，校验区域 代理商是否授权
        if (CustomerEntryConstants.TYPE_TJ.equals(req.getType())) {
            boolean checkAuth = traderPcdService.checkAuth(cus.getCreateTraderId(), cus.getProvince(), cus.getCity(), cus.getArea());
            if (!checkAuth) {
                throw new IllegalArgumentException("代理商区域暂未授权");
            }
            //TODO 校验产品区域权限  产品是否授权
            if (pro != null) {
                boolean b = projectDao.checkAuth(req.getProjectId(), req.getProvince(), req.getCity(), req.getArea());
                if (!b) {
                    throw new IllegalArgumentException("产品区域暂未授权");
                }
            }
            //TODO 校验项目公司区域  产品是否授权
            if (StringUtil.isBlank(req.getCompany())) {
                throw new IllegalArgumentException("请选择项目公司");
            }
            boolean b1 = companyDao.checkAuth2(req.getCompany(), req.getProvince(), req.getCity(), req.getArea());
            if (!b1) {
                throw new IllegalArgumentException("项目公司区域暂未授权");
            }
            // 资方要求提交信息时 必须保持身份证/法人登记注册号码
            if ("1".equals(cus.getTenantType()) && StringUtil.isBlank(cus.getIdCode())) {
                throw new IllegalArgumentException("请填写身份证号");
            }
            else if ("2".equals(cus.getTenantType()) && StringUtil.isBlank(cus.getRegno())) {
                throw new IllegalArgumentException("请填写信用代码");
            }
        }

        if (StringUtil.isNotBlank(req.getTenantId())) {
            cus.setTenantId(req.getTenantId());
        }
        customerDao.save(cus);
        //获取电站业主授权信息
        boolean pushSmsFlag = false; // 用于判断是否需要发送授权使用短信
        CrmCustomerYxCondition condition = null;
        CrmCustomerYxAuthorization customerYxAuthorization = null;
        String keyInfo = null;
        if ("1".equals(cus.getTenantType()) && StringUtil.isNotBlank(cus.getIdCode())) {
            keyInfo = cus.getIdCode();
        }
        else if ("2".equals(cus.getTenantType()) && StringUtil.isNotBlank(cus.getRegno())) {
            keyInfo = cus.getRegno();
        }
        String modPreaudit = "1"; // 修改预审标记：1.待预审 2.预审通过 3.需要发起预审
        String authorization = "1"; // 信息使用授权状态：1.未授权 2.已发起 3.已授权
        boolean needCondition = true;
        boolean needAuthorization = true;
        // 录单时直接提交
        if (CustomerEntryConstants.TYPE_TJ.equals(req.getType())) { //提交
            List<Record> list = formSetDao.findListByCondition("01", partner.getId());
            Result result = requiredCheckForRegisterInfo(cus, req.getRegnoUrl(), list, "1",req.getCreditCertificate(),req.getHouseOwnership());
            if (!"200".equals(result.getCode())) {
                throw new IllegalArgumentException(result.getErrMsg());
            }
            if (FormSetUtils.processSetEnable(cus.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZGYS)) {
                //partner.getTenantFlag 客户预审方式：0.同一客户只需要一次预审即可 1.一个电站需要一次预审
                if (PartnerConstants.PARTNER_ID_HR.equals(partner.getId())){//华融区分备案类型
                    condition = conditionDao.findCustomerYxCondition(keyInfo,partner.getId(),cus.getFilingType());
                    customerYxAuthorization = customerYxAuthorizationDao.findCustomerYxAuthorization(keyInfo,partner.getId(),cus.getFilingType());
                }else {
                    condition = conditionDao.findCustomerYxCondition(keyInfo,partner.getId());
                    customerYxAuthorization = customerYxAuthorizationDao.findCustomerYxAuthorization(keyInfo,partner.getId());
                }
                cus.setCredit(CustomerEntryConstants.CREDIT_WAIT);
                if (condition == null || ("1".equals(req.getTenantType()) && "1".equals(condition.getAuthorization()))) {
                    //推送授权使用的签约短信签约短信
                    // 改变预审状态，授权信息状态，进件状态
                    if ("1".equals(req.getTenantType())) {
                        //华融区分备案类型
                        if (PartnerConstants.PARTNER_ID_HR.equals(partner.getId())){
                            if (CustomerEntryConstants.FILING_TYPE_FARMER.equals(cus.getFilingType())){
                                pushSmsFlag = true;
                                cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUBMITTED);
                            }else {
                                needAuthorization = false;
                                authorization="3";
                                cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                                cus.setCredit(CustomerEntryConstants.CREDIT_APPROVE);
                                cus.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                                modPreaudit = "3";
                            }
                        }else {
                            pushSmsFlag = true;
                            cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUBMITTED);
                        }
                    }else {
                        cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                        cus.setCredit(CustomerEntryConstants.CREDIT_APPROVE);
                        cus.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                        modPreaudit = "3";
                        if ("1".equals(partner.getTenantFlag())) {
                            needCondition = false;
                            //客户类型是单位、且一个电站需要一次预审时，则不需要生成授权预审记录
                        }
                    }
                } else {
                    if ("1".equals(partner.getTenantFlag())) {
                        if ("1".equals(cus.getTenantType()) && "2".equals(condition.getAuthorization())) {
                            //如果已完成授权 直接发起预审
                            // 信息使用授权状态：1.未授权 2.已发起 3.已授权
                            // 预审状态 1.待预审 2.预审中 3.预审不通过 4.预审通过
                            throw new IllegalArgumentException("信息授权中，请先签署完成生成的信息授权");
                        }
                        cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                        cus.setCredit(CustomerEntryConstants.CREDIT_APPROVE);
                        cus.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                        modPreaudit = "3";
                    }
                    else {
                        cus.setCredit(condition.getPreaudit());
                        cus.setAuthorization(condition.getAuthorization());
                        if (StringUtil.isBlank(req.getApplyStatus()) || Integer.parseInt(req.getApplyStatus()) < 4) {
                            cus.setApplyStatus(dealYxConditionPreauditToApplyStatus(condition.getPreaudit()));
                        }
                        // 校验是否存在已预审通过
                        if("4".equals(condition.getPreaudit())){
                            modPreaudit = "2";
                            cus.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
                            cus.setPreAuditTime(now);
                            if (PartnerConstants.PARTNER_ID_HR.equals(partner.getId())){
                                //预审通过自动发起合同
                                createHRContract(cus,operator);
                            }
                        }
                    }
                }

                // 客户类型为个人时需要开二类卡 需要查询该身份证是否已开过卡
                if (!"1".equals(partner.getTenantFlag()) && "1".equals(req.getTenantType())) {
                    Record bankCondition = customerDao.findYxBankCondition(cus.getIdCode(), cus.getMobile(),cus.getPartnerId());
                    if (bankCondition != null && "4".equals(bankCondition.getStr("status"))) {
                        cus.setSecCardStatus("1");
                    }
                }
            }else {
                cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                cus.setCredit(CustomerEntryConstants.CREDIT_APPROVED);
                cus.setApplyStatus(null);
                cus.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
            }
        }

        customerDao.save(cus);//电站保存生成id
        CustomerEntrySurveyRecord surveyRecord = new CustomerEntrySurveyRecord();
        surveyRecord.setEntryId(cus.getId());
        surveyRecord.setTraderId(cus.getDistributorId());
        surveyRecord.setHouseOwnership(req.getHouseOwnership());
        surveyRecord.setCreateTime(new Date());
        surveyRecordDao.save(surveyRecord);
        String otherMsg = "";
        if (CustomerEntryConstants.TYPE_TJ.equals(req.getType())) { //提交
            otherMsg = "提交审核";
            // 新建客户信息
            Result res = createTenant(cus, req.getRegnoUrl());
            if (res.isOk()) {
                cus.setTenantId(res.getMsg());
                customerDao.save(cus);
            } else {
                throw new IllegalArgumentException(res.getErrMsg());
            }
            //保存租金信息
            if (StringUtil.isNotBlank(cus.getProjectId())) {
                customerRentVariableService.saveEntryComponent(cus.getId(), cus.getProjectId());
            }
            // 预审状态 1.待预审 2.预审待审批 3.预审审批中 4.预审通过 5.预审拒绝
            if (condition == null && FormSetUtils.processSetEnable(cus.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZGYS) && needCondition) {
                String id = IdGen.uuid();
                String preaudit = "1";
                // 生成 已发起开卡申请 待预审的记录
                logger.info("生成 crm_customer_yx_condition 记录,id:{},name:{},mobile:{},id_code:{},preaudit :{},authorization:{}",
                        id,cus.getTenantName(),cus.getMobile(),keyInfo,preaudit,authorization);
                condition = conditionDao.addYxCondition(id,cus.getTenantName(),cus.getMobile(),
                        keyInfo,preaudit,authorization,null,cus.getPartnerId(),cus.getFilingType());
                if (needAuthorization){
                    customerYxAuthorization = customerYxAuthorizationDao.addYxAuthorization(cus.getTenantName(), cus.getMobile(),
                            keyInfo,  authorization, null,cus.getPartnerId(),cus.getFilingType());
                }
                authorization = "2";
            }
            if ("3".equals(modPreaudit)) {
                String houseOwnership = req.getHouseOwnership();
                String regnoUrl = req.getRegnoUrl();
                saveEntryToAdmittance(cus, condition, houseOwnership, regnoUrl);
            }
        }
        // 电站的承租类型法人的文件上传记录表
        if (Objects.equals("2", cus.getTenantType())) {
            orgFilesDao.createOne(cus.getId(), cus.getDistributorId(), req.getRegnoUrl(),null);
        } else {
            orgFilesDao.createOne(cus.getId(), cus.getDistributorId(), null,req.getCreditCertificate());
        }
        msgService.saveCustomerEntryMsg(operator, cus.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_ADD, otherMsg,null);
        if (!"1".equals(partner.getTenantFlag())) {
            applicationDao.saveIncomingApplication(cus);
        }

        if (pushSmsFlag) {
            String address=cus.getProvince()+cus.getCity()+cus.getArea()+cus.getAddress();
            String signFlowId = askAuthContractService.createAskAuthContract(cus.getIdCode(), cus.getMobile(),address,cus.getPartnerId());
            msgService.saveCustomerEntryMsg(operator, cus.getId(), CustomerEntryConstants.AUTH_SIGN, "发起签约授权 ", "");
            condition.setAuthorization(authorization);
            condition.setSignFlowId(signFlowId);
            conditionDao.save(condition);
            customerYxAuthorization.setAuthorization("2");
            customerYxAuthorization.setSignFlowId(signFlowId);
            customerYxAuthorizationDao.save(customerYxAuthorization);
        }
        return "200";

    }

    @Transactional(rollbackFor = Exception.class)
    public String createHREntryForIXDJ(AddEntryReq req, Operator operator) {
        logger.info("createCustomerEntry entry={}",new Gson().toJson(req));
        // 当前要求 信息录入时 先设置资方-投资方， 产品字段不再必填项
        if (StringUtil.isBlank(req.getZfId())) {
            throw new IllegalArgumentException("请先选择投资方");
        }
        // 获取资方信息 pro.getStr("management")
        CrmPartner partner = partnerService.getById(req.getZfId());
        if(partner==null){
            throw new IllegalArgumentException("请先选择投资方");
        }
        String projectCode = "";
        String projectName = "";
        String payCycle = "";
        BigDecimal epcPrice = new BigDecimal(0);
        String productLineId = "";
        String lineName = "";
        String attribute = "";
        String filingType = "";
        if(req.getProjectList() != null){
            List<ProjectInfoVo> projectList = req.getProjectList();
            if (projectList==null||projectList.isEmpty()) {
                throw new IllegalArgumentException("请选择产品");
            }else {
                Set<String> projectSet = new HashSet<>();
                for (ProjectInfoVo projectInfoVo : projectList) {
                    if (StringUtil.isBlank(projectInfoVo.getProjectId())) {
                        throw new IllegalArgumentException("请选择产品");
                    }
                    if(StringUtil.isBlank(projectInfoVo.getRoofType())){
                        throw new IllegalArgumentException("请选择屋顶类型");
                    }
                    if(!projectSet.add(projectInfoVo.getProjectId())){
                        throw new IllegalArgumentException(projectInfoVo.getProjectName()+"重复");
                    }
                    if(!projectSet.add(projectInfoVo.getRoofType())){
                        throw new IllegalArgumentException(projectInfoVo.getRoofType()+"重复");
                    }
                }
            }
            for(ProjectInfoVo vo :req.getProjectList()){
                if (StringUtil.isNotBlank(req.getProjectId())) {
                    Record pro = null;
                    pro = projectDao.getProject(vo.getProjectId());
                    if (pro.getStr("code") != null) {
                        projectCode += pro.getStr("code")+",";
                    }
                    if (pro.getStr("name") != null) {
                        projectName += pro.getStr("name")+",";
                    }
                    if (pro.getStr("pay_cycle") != null) {
                        if("按月支付".equals(pro.getStr("pay_cycle"))){
                            payCycle = "1";
                        }else if("按季支付".equals(pro.getStr("pay_cycle"))){
                            payCycle = "2";
                        }else if("按年支付".equals(pro.getStr("pay_cycle"))){
                            payCycle = "3";
                        }
                    }
                    if (pro.get("epc_price") != null) {
                        //EPC单价/ 每W定价
                        epcPrice = epcPrice.add(pro.getBigDecimal("epc_price"));
                    }
                    //产品线
                    if (StringUtil.isNotBlank(pro.getStr("product_line_id"))) {
                        productLineId = pro.getStr("product_line_id");
                    }
                    if (StringUtil.isNotBlank(pro.getStr("lineName"))) {
                        lineName = pro.getStr("lineName");
                    }
                    //业务属性 1.纯租25年业务、2.经营性租赁、3.融资租赁、4.光伏贷、5.全款、6.其他
                    if (StringUtil.isNotBlank(pro.getStr("attribute"))) {
                        if("BT业务".equals(pro.getStr("attribute"))){
                            attribute = "1";
                        }else if("经营性租赁".equals(pro.getStr("attribute"))){
                            attribute = "2";
                        }else if("融资租赁".equals(pro.getStr("attribute"))){
                            attribute = "3";
                        }else if("光伏贷".equals(pro.getStr("attribute"))){
                            attribute = "4";
                        }else if("全款".equals(pro.getStr("attribute"))){
                            attribute = "5";
                        }else {
                            attribute = "6";
                        }
                    }
                    if (StringUtil.isNotBlank(pro.getStr("filing_type"))) {
                        filingType = pro.getStr("filing_type");
                    }

                }
            }
            projectCode = projectCode.substring(0,projectCode.length()-1);
            projectName = projectName.substring(0,projectName.length()-1);
            epcPrice = epcPrice.divide(new BigDecimal(req.getProjectList().size()), 2, RoundingMode.HALF_UP);
        }

        Date now = DateUtils.getNowDate();
        CustomerEntry cus = new CustomerEntry();
        cus.setCreateBy(operator.getUserId());
        cus.setCreator(operator.getUserName());
        cus.setCreateTime(now);
        String powerStationCode = PlantformUtils.getOrderNumber();
        cus.setPowerStationCode(powerStationCode);
        //获取项目公司信息
        if (req.getCompany() != null){
            ProjectCompanySettings projectCompanySettings = companyDao.get(req.getCompany());
            if (projectCompanySettings != null) {
                cus.setProjectCompanyId(projectCompanySettings.getId());
                cus.setProjectCompanyName(projectCompanySettings.getName());
                cus.setManagementType(projectCompanySettings.getCompanyCode());
                if(req.getProjectList() != null){
                    for(ProjectInfoVo vo :req.getProjectList()){
                        Record pro = null;
                        pro = projectDao.getProject(vo.getProjectId());
                        String filingTypePro = pro.getStr("filing_type");
                        if (!filingTypePro.equals(projectCompanySettings.getFilingType())) {
                            throw new IllegalArgumentException("选择的产品、项目公司所属备案类型不一致");
                        }
                    }
                }
            }
        }
        cus = customerDao.createOne(req, cus);

        if(req.getProjectList() != null){
            if (StringUtil.isNotBlank(req.getProjectId())) {
                cus.setProjectId(req.getProjectId());
            }
            if (StringUtil.isNotBlank(projectCode)) {
                cus.setProjectCode(projectCode);
            }
            if (StringUtil.isNotBlank(projectName)) {
                cus.setProjectName(projectName);
            }
            //EPC单价/ 每W定价
            cus.setEpcPrice(epcPrice);
            //产品线
            if (StringUtil.isNotBlank(productLineId)) {
                cus.setProductLineId(productLineId);
            }
            if (StringUtil.isNotBlank(lineName)) {
                cus.setProductLineName(lineName);
            }
            //业务属性 1.纯租25年业务、2.经营性租赁、3.融资租赁、4.光伏贷、5.全款、6.其他
            if (StringUtil.isNotBlank(attribute)) {
                cus.setProductLine(attribute);
            }
            //租金支付周期 1按月支付 2按季支付 3按年支付
            if (StringUtil.isNotBlank(payCycle)) {
                cus.setPayCycle(payCycle);
            }
            if (StringUtil.isNotBlank(filingType)) {
                cus.setFilingType(filingType);
            }
            cus.setProjectNum(req.getProjectList().size());
            String roofType = req.getProjectList().stream().map(ProjectInfoVo :: getRoofType).collect(Collectors.joining(","));
            cus.setRoofType(roofType);
        }
        if (StringUtil.isNotBlank(req.getIdCode())) {
            cus.setIdCode(req.getIdCode().toUpperCase());
        }
        cus.setStatus(CustomerEntryConstants.ENTRY_STATUS_ZC);
        cus.setProvince(StringUtil.isBlank(req.getProvince()) ? "" : req.getProvince());
        cus.setCity(StringUtil.isBlank(req.getCity()) ? "" : req.getCity());
        cus.setArea(StringUtil.isBlank(req.getArea()) ? "" : req.getArea());
        cus.setStreet(StringUtil.isBlank(req.getStreet()) ? "" : req.getStreet());
        cus.setAddress(StringUtil.isBlank(req.getAddress()) ? "" : req.getAddress().trim());
        cus.setWindPressure(req.getWindPressure());
        cus.setSnowPressure(req.getSnowPressure());
        cus.setPressureLevel(req.getPressureLevel());
        cus.setMobile(StringUtil.isBlank(req.getMobile()) ? "" : req.getMobile().trim());
        cus.setRemarks(StringUtil.isBlank(req.getRemarks()) ? "" : req.getRemarks());
        cus.setComponentSpec("");
        cus.setDesignCapacity(0);
        cus.setToExamineStatus("1");
        cus.setDesignCapacity(0);
        cus.setInsuranceFlag("1");
        cus.setSignStatus(CustomerEntryConstants.SIGN_STATUS_UNSTART);
        cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_WAIT);
        cus.setCredit(CustomerEntryConstants.CREDIT_ZANCUN);
        cus.setFlag("0");
        cus.setExigenceName(StringUtil.isBlank(req.getExigenceName())? "" : req.getExigenceName());
        cus.setExigencePhone(StringUtil.isBlank(req.getExigencePhone())? "" : req.getExigencePhone());
        cus.setPartnerId(partner.getId());
        cus.setPartnerName(partner.getName());
        cus.setIcValidityEnd(req.getIcValidityEnd());
        cus.setBirthdayDate(req.getBirthdayDate());
        cus.setIcValidityBegin(req.getIcValidityBegin());

        Record traderRecord=CrmUtils.getUserTrader(operator.getUserType(),operator.getUserId());
        cus.setCreateTraderId(traderRecord.getStr("id"));
        cus.setCreateTraderName(traderRecord.getStr("name"));
        //获取上级代理商
        String traderId="2".equals(traderRecord.getStr("type"))?traderRecord.getStr("parent_id"):traderRecord.getStr("id");
        CrmTrader trader = traderDao.get(traderId);
        if (trader == null) {
            throw new IllegalArgumentException("上级代理商不存在");
        }
        cus.setRegionId(trader.getId());
        cus.setDistributorId(trader.getId());
        cus.setTraderName(trader.getName());
        cus.setTraderTel(trader.getMobile());
        // 提交时，校验区域 代理商是否授权
        if (CustomerEntryConstants.TYPE_TJ.equals(req.getType())) {
            boolean checkAuth = traderPcdService.checkAuth(cus.getCreateTraderId(), cus.getProvince(), cus.getCity(), cus.getArea());
            if (!checkAuth) {
                throw new IllegalArgumentException("代理商区域暂未授权");
            }
            //TODO 校验产品区域权限  产品是否授权
            if(req.getProjectList() != null) {
                for (ProjectInfoVo vo : req.getProjectList()) {
                    Record pro = null;
                    pro = projectDao.getProject(vo.getProjectId());
                    if (pro != null) {
                        boolean b = projectDao.checkAuth(vo.getProjectId(), req.getProvince(), req.getCity(), req.getArea());
                        if (!b) {
                            throw new IllegalArgumentException("产品区域暂未授权");
                        }
                    }
                }
            }
            //TODO 校验项目公司区域  产品是否授权
            if (StringUtil.isBlank(req.getCompany())) {
                throw new IllegalArgumentException("请选择项目公司");
            }
            boolean b1 = companyDao.checkAuth2(req.getCompany(), req.getProvince(), req.getCity(), req.getArea());
            if (!b1) {
                throw new IllegalArgumentException("项目公司区域暂未授权");
            }
            // 资方要求提交信息时 必须保持身份证/法人登记注册号码
            if ("1".equals(cus.getTenantType()) && StringUtil.isBlank(cus.getIdCode())) {
                throw new IllegalArgumentException("请填写身份证号");
            }
            else if ("2".equals(cus.getTenantType()) && StringUtil.isBlank(cus.getRegno())) {
                throw new IllegalArgumentException("请填写信用代码");
            }
        }

        if (StringUtil.isNotBlank(req.getTenantId())) {
            cus.setTenantId(req.getTenantId());
        }
        customerDao.save(cus);
        //获取电站业主授权信息
        boolean pushSmsFlag = false; // 用于判断是否需要发送授权使用短信
        CrmCustomerYxCondition condition = null;
        CrmCustomerYxAuthorization customerYxAuthorization = null;
        String keyInfo = null;
        if ("1".equals(cus.getTenantType()) && StringUtil.isNotBlank(cus.getIdCode())) {
            keyInfo = cus.getIdCode();
        }
        else if ("2".equals(cus.getTenantType()) && StringUtil.isNotBlank(cus.getRegno())) {
            keyInfo = cus.getRegno();
        }
        String modPreaudit = "1"; // 修改预审标记：1.待预审 2.预审通过 3.需要发起预审
        String authorization = "1"; // 信息使用授权状态：1.未授权 2.已发起 3.已授权
        boolean needCondition = true;
        boolean needAuthorization = true;
        // 录单时直接提交
        if (CustomerEntryConstants.TYPE_TJ.equals(req.getType())) { //提交
            List<Record> list = formSetDao.findListByCondition("01", partner.getId());
            Result result = requiredCheckForRegisterInfo(cus, req.getRegnoUrl(), list, "1",req.getCreditCertificate(),req.getHouseOwnership());
            if (!"200".equals(result.getCode())) {
                throw new IllegalArgumentException(result.getErrMsg());
            }
            if (FormSetUtils.processSetEnable(cus.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZGYS)) {
                //partner.getTenantFlag 客户预审方式：0.同一客户只需要一次预审即可 1.一个电站需要一次预审
                if (PartnerConstants.PARTNER_ID_HR.equals(partner.getId())){//华融区分备案类型
                    condition = conditionDao.findCustomerYxCondition(keyInfo,partner.getId(),cus.getFilingType());
                    customerYxAuthorization = customerYxAuthorizationDao.findCustomerYxAuthorization(keyInfo,partner.getId(),cus.getFilingType());
                }else {
                    condition = conditionDao.findCustomerYxCondition(keyInfo,partner.getId());
                    customerYxAuthorization = customerYxAuthorizationDao.findCustomerYxAuthorization(keyInfo,partner.getId());
                }
                cus.setCredit(CustomerEntryConstants.CREDIT_WAIT);
                if (condition == null || ("1".equals(req.getTenantType()) && "1".equals(condition.getAuthorization()))) {
                    //推送授权使用的签约短信签约短信
                    // 改变预审状态，授权信息状态，进件状态
                    if ("1".equals(req.getTenantType())) {
                        //华融区分备案类型
                        if (PartnerConstants.PARTNER_ID_HR.equals(partner.getId())){
                            if (CustomerEntryConstants.FILING_TYPE_FARMER.equals(cus.getFilingType())){
                                pushSmsFlag = true;
                                cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUBMITTED);
                            }else {
                                needAuthorization = false;
                                authorization="3";
                                cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                                cus.setCredit(CustomerEntryConstants.CREDIT_APPROVE);
                                cus.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                                modPreaudit = "3";
                            }
                        }else {
                            pushSmsFlag = true;
                            cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUBMITTED);
                        }
                    }else {
                        cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                        cus.setCredit(CustomerEntryConstants.CREDIT_APPROVE);
                        cus.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                        modPreaudit = "3";
                        if ("1".equals(partner.getTenantFlag())) {
                            needCondition = false;
                            //客户类型是单位、且一个电站需要一次预审时，则不需要生成授权预审记录
                        }
                    }
                } else {
                    if ("1".equals(partner.getTenantFlag())) {
                        if ("1".equals(cus.getTenantType()) && "2".equals(condition.getAuthorization())) {
                            //如果已完成授权 直接发起预审
                            // 信息使用授权状态：1.未授权 2.已发起 3.已授权
                            // 预审状态 1.待预审 2.预审中 3.预审不通过 4.预审通过
                            throw new IllegalArgumentException("信息授权中，请先签署完成生成的信息授权");
                        }
                        cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                        cus.setCredit(CustomerEntryConstants.CREDIT_APPROVE);
                        cus.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                        modPreaudit = "3";
                    }
                    else {
                        cus.setCredit(condition.getPreaudit());
                        cus.setAuthorization(condition.getAuthorization());
                        if (StringUtil.isBlank(req.getApplyStatus()) || Integer.parseInt(req.getApplyStatus()) < 4) {
                            cus.setApplyStatus(dealYxConditionPreauditToApplyStatus(condition.getPreaudit()));
                        }
                        // 校验是否存在已预审通过
                        if("4".equals(condition.getPreaudit())){
                            String oldMobile = condition.getMobile();
                            String mobile = cus.getMobile();
                            if (oldMobile.equals(mobile)) {//华融手机号相同预审通过无需预审
                                modPreaudit = "2";
                                cus.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
                                cus.setPreAuditTime(now);
                                if (PartnerConstants.PARTNER_ID_HR.equals(partner.getId())){
                                    //预审通过自动发起合同
                                    createHRContract(cus,operator);
                                }
                            }else {//华融手机号不同 预审通过 需要重新预审
                                condition.setMobile(mobile);
                                conditionDao.save(condition);
                                if (customerYxAuthorization != null){
                                    customerYxAuthorization.setMobile(mobile);
                                    customerYxAuthorizationDao.save(customerYxAuthorization);
                                }
                                modPreaudit = "3";
                                cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                                cus.setCredit(CustomerEntryConstants.CREDIT_APPROVE);
                                cus.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                            }
                        }
                    }
                }

                // 客户类型为个人时需要开二类卡 需要查询该身份证是否已开过卡
                if (!"1".equals(partner.getTenantFlag()) && "1".equals(req.getTenantType())) {
                    Record bankCondition = customerDao.findYxBankCondition(cus.getIdCode(), cus.getMobile(),cus.getPartnerId());
                    if (bankCondition != null && "4".equals(bankCondition.getStr("status"))) {
                        cus.setSecCardStatus("1");
                    }
                }
            }else {
                cus.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
                cus.setCredit(CustomerEntryConstants.CREDIT_APPROVED);
                cus.setApplyStatus(null);
                cus.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
            }
        }

        customerDao.save(cus);//电站保存生成id
        CustomerEntrySurveyRecord surveyRecord = new CustomerEntrySurveyRecord();
        surveyRecord.setEntryId(cus.getId());
        surveyRecord.setTraderId(cus.getDistributorId());
        surveyRecord.setHouseOwnership(req.getHouseOwnership());
        surveyRecord.setCreateTime(new Date());
        surveyRecordDao.save(surveyRecord);
        //电站关联产品表-针对一个电站多产品
        if(req.getProjectList() != null) {
            for (ProjectInfoVo vo : req.getProjectList()) {
                CrmCustomerEntryProject entryProject = new CrmCustomerEntryProject();
                entryProject.setProjectId(vo.getProjectId());
                entryProject.setEntryId(cus.getId());
                entryProject.setRoofType(vo.getRoofType());
                crmCustomerEntryProjectDao.save(entryProject);

                //电站的设计方案信息表
                CrmCustomerEntryDesign crmCustomerEntryDesign = new CrmCustomerEntryDesign();
                crmCustomerEntryDesign.setEntryId(cus.getId());
                crmCustomerEntryDesign.setProjectId(vo.getProjectId());
                crmCustomerEntryDesignDao.save(crmCustomerEntryDesign);

                //电站的勘测信息-明细记录表
                CrmCustomerEntrySurveyRecordDetail crmCustomerEntrySurveyRecordDetail = new CrmCustomerEntrySurveyRecordDetail();
                crmCustomerEntrySurveyRecordDetail.setEntryId(cus.getId());
                crmCustomerEntrySurveyRecordDetail.setProjectId(vo.getProjectId());
                crmCustomerEntrySurveyRecordDetailDao.save(crmCustomerEntrySurveyRecordDetail);

            }
        }
        String otherMsg = "";
        if (CustomerEntryConstants.TYPE_TJ.equals(req.getType())) { //提交
            otherMsg = "提交审核";
            // 新建客户信息
            Result res = createTenant(cus, req.getRegnoUrl());
            if (res.isOk()) {
                cus.setTenantId(res.getMsg());
                customerDao.save(cus);
            } else {
                throw new IllegalArgumentException(res.getErrMsg());
            }
            //保存租金信息
            if (StringUtil.isNotBlank(cus.getProjectId())) {
                customerRentVariableService.saveEntryComponent(cus.getId(), cus.getProjectId());
            }
            // 预审状态 1.待预审 2.预审待审批 3.预审审批中 4.预审通过 5.预审拒绝
            if (condition == null && FormSetUtils.processSetEnable(cus.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZGYS) && needCondition) {
                String id = IdGen.uuid();
                String preaudit = "1";
                // 生成 已发起开卡申请 待预审的记录
                logger.info("生成 crm_customer_yx_condition 记录,id:{},name:{},mobile:{},id_code:{},preaudit :{},authorization:{}",
                        id,cus.getTenantName(),cus.getMobile(),keyInfo,preaudit,authorization);
                condition = conditionDao.addYxCondition(id,cus.getTenantName(),cus.getMobile(),
                        keyInfo,preaudit,authorization,null,cus.getPartnerId(),cus.getFilingType());
                if (needAuthorization){
                    customerYxAuthorization = customerYxAuthorizationDao.addYxAuthorization(cus.getTenantName(), cus.getMobile(),
                            keyInfo,  authorization, null,cus.getPartnerId(),cus.getFilingType());
                }
                authorization = "2";
            }
            if ("3".equals(modPreaudit)) {
                String houseOwnership = req.getHouseOwnership();
                String regnoUrl = req.getRegnoUrl();
                saveEntryToAdmittance(cus, condition, houseOwnership, regnoUrl);
            }
        }
        // 电站的承租类型法人的文件上传记录表
        if (Objects.equals("2", cus.getTenantType())) {
            orgFilesDao.createOne(cus.getId(), cus.getDistributorId(), req.getRegnoUrl(),null);
        } else {
            orgFilesDao.createOne(cus.getId(), cus.getDistributorId(), null,req.getCreditCertificate());
        }
        msgService.saveCustomerEntryMsg(operator, cus.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_ADD, otherMsg,null);
        if (!"1".equals(partner.getTenantFlag())) {
            applicationDao.saveIncomingApplication(cus);
        }

        if (pushSmsFlag) {
            String address=cus.getProvince()+cus.getCity()+cus.getArea()+cus.getAddress();
            String signFlowId = askAuthContractService.createAskAuthContract(cus.getIdCode(), cus.getMobile(),address,cus.getPartnerId());
            msgService.saveCustomerEntryMsg(operator, cus.getId(), CustomerEntryConstants.AUTH_SIGN, "发起签约授权 ", "");
            condition.setAuthorization(authorization);
            condition.setSignFlowId(signFlowId);
            conditionDao.save(condition);
            customerYxAuthorization.setAuthorization("2");
            customerYxAuthorization.setSignFlowId(signFlowId);
            customerYxAuthorizationDao.save(customerYxAuthorization);
        }
        return "200";

    }

    /**
     * 提交电站信息时 直接进行预审
     */
    public void saveEntryToAdmittance(CustomerEntry cus, CrmCustomerYxCondition condition,
                                      String houseOwnership,String regnoUrl) {
        JSONObject resultJson = null;
        if (PartnerConstants.PARTNER_ID_HR.equals(cus.getPartnerId())) {
            String contractPath = condition.getAuthorizationContractPath();
            resultJson = admittanceHuarongEntry(cus, contractPath);
        }
        else if (PartnerConstants.PARTNER_ID_GF.equals(cus.getPartnerId())) {
            CustomerEntryOrgFiles orgFiles = orgFilesDao.findOneByEntryId(cus.getId());
            CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(cus.getId());
            if(StringUtil.isBlank(regnoUrl) &&
                    orgFiles!=null && StringUtil.isNotBlank(orgFiles.getRegnoUrl())){
                regnoUrl = orgFiles.getRegnoUrl();
            }
            if(StringUtil.isBlank(houseOwnership) &&
                    surveyRecord!=null && StringUtil.isNotBlank(surveyRecord.getHouseOwnership())){
                houseOwnership = surveyRecord.getHouseOwnership();
            }
            resultJson = admittanceGuangFaEntry(cus,houseOwnership,regnoUrl);
        }
        else if (PartnerConstants.PARTNER_ID_YX.equals(cus.getPartnerId())) {
            resultJson = operatingLeaseService.admittanceEntry(cus);
        }
        if(StringUtil.equalsAny(cus.getPartnerId(), PartnerConstants.PARTNER_ID_HR, PartnerConstants.PARTNER_ID_YX,
                PartnerConstants.PARTNER_ID_GF)){
            if ("S".equals(resultJson.get("type"))) {
                if (condition != null) {
                    condition.setPreaudit("2");
                    condition.setTenantCode(resultJson.getString("businessKey"));
                    conditionDao.save(condition);
                }
                cus.setCredit(CustomerEntryConstants.CREDIT_SUBMITTED);
                cus.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
                customerDao.save(cus);//电站保存
                if (PartnerConstants.PARTNER_ID_YX.equals(cus.getPartnerId())) {
                    //上传信息使用授权书
                    updateAuditFile(cus);
                }
                dealHuaRongAdmittance(cus,resultJson);
            } else if ("E".equals(resultJson.get("type"))) {//失败
                throw new IllegalArgumentException("message");
            } else {
                throw new IllegalArgumentException("提交失败，预审申请失败");
            }
        }
    }

    // 新建客户信息
    private Result createTenant(CustomerEntry entry, String regnoUrl) {
        // 1.查询客户信息
        CustomerEntryTenant tenant = null;
        if (StringUtil.isNotBlank(entry.getTenantId())) {
            tenant = tenantDao.get(entry.getTenantId());
        }
        else {
            tenant = tenantDao.findOneByTypeAndCode(entry.getTenantType(), entry.getIdCode(), entry.getRegno());
        }
        if (tenant == null) {
            CrmPartner crmPartner = partnerService.getById(entry.getPartnerId());
            if("3".equals(crmPartner.getAuthType())){ //华能
                tenant = tenantDao.createTwo(entry, regnoUrl);
            }else {
                tenant = tenantDao.createOne(entry, regnoUrl);
            }
            String keyInfo = null;
            if ("1".equals(entry.getTenantType()) && StringUtil.isNotBlank(entry.getIdCode())) {
                keyInfo = entry.getIdCode();
            }
            else if ("2".equals(entry.getTenantType()) && StringUtil.isNotBlank(entry.getRegno())) {
                keyInfo = entry.getRegno();
            }
            CrmCustomerYxCondition condition = conditionDao.findCustomerYxCondition(keyInfo, crmPartner.getId());
            if(condition!=null){
                if ("3".equals(condition.getAuthorization())){
                    tenant.setYxFlag(TenantConstants.YX_FLAG_PASS);
                }
            }
        } else {
            boolean flag;
            if (Objects.equals("1", entry.getTenantType())) {
                flag = Objects.equals(entry.getIdCode(), tenant.getIdCode());
            } else {
                flag = Objects.equals(entry.getRegno(), tenant.getRegno());
            }
            if (!entry.getCreateTraderId().equals(tenant.getTraderId()) && Objects.equals("1", entry.getTenantType())) {
                return Result.fail("该客户已绑定其他代理商，您不能重复创建客户信息！");
            }
            // 判断是否预审通过
            if (!Objects.equals("1", tenant.getYxFlag())) {
                return Result.fail("信息预审中");
            } else {
                if (!flag || !Objects.equals(entry.getTenantName(), tenant.getTenantName())) {
                    return Result.fail("无需重复录入客户信息");
                }
                if (!Objects.equals(entry.getMobile(),tenant.getMobile())){
                    tenant.setMobile(entry.getMobile());
                    tenantDao.save(tenant);
                }
                if (Objects.equals("1", entry.getTenantType()) &&
                        !Objects.equals(entry.getGender(), tenant.getGender())) {
                    return Result.fail("无需重复录入客户信息");
                }
                if (!Objects.equals(entry.getGender(), tenant.getGender())) {
                    entry.setGender(tenant.getGender());
                }
            }
        }
        return Result.ok(tenant.getId());
    }

    /**
     * 根据代理商id获取可选择的资方列表
     */
    public List<Map> getCapital(String traderId){
        List<Record> records = traderPartnerDao.getListByTraderId(traderId);
        List<Map> list=new ArrayList<>();
        for(Record rd:records){
            Map map=new HashMap();
            map.put("id",rd.get("id"));
            map.put("name",rd.get("name"));
            list.add(map);
        }
        return list;
    }




    // 勘测暂存、 勘测提交自审
    @Transactional(rollbackFor = Exception.class)
    public String editCustomerEntry(AddEntryReq cus, Operator operator) {
        CustomerEntry entry = customerDao.get(cus.getId());
        Date now = DateUtils.getNowDate();
        CrmPartner crmPartner = partnerService.getById(entry.getPartnerId());
        // 生成勘测记录
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(cus.getId());
        if (surveyRecord == null) {
            surveyRecord = new CustomerEntrySurveyRecord();
        }
        Record pro = null;
        if (StringUtil.isNotBlank(cus.getProjectId())) {
            pro = projectDao.getProject(cus.getProjectId());
        }
        StringBuilder adSf = new StringBuilder();
        if (!(cus.getProvince() + cus.getCity() + cus.getArea()).equals(entry.getProvince() + entry.getCity() + entry.getArea())) {
            adSf.append("修改地址：修改前：").append(entry.getProvince()).append(entry.getCity()).append(entry.getArea()).append(" ,修改后 ：").
                    append(cus.getProvince()).append(cus.getCity()).append(cus.getArea()).append(";");
            entry.setProvince(StringUtil.isBlank(cus.getProvince()) ? "" : cus.getProvince());
            entry.setCity(StringUtil.isBlank(cus.getCity()) ? "" : cus.getCity());
            entry.setArea(StringUtil.isBlank(cus.getArea()) ? "" : cus.getArea());
            entry.setStreet(StringUtil.isBlank(cus.getStreet()) ? "" : cus.getStreet());
            entry.setLongitude(cus.getLongitude());
            entry.setLatitude(cus.getLatitude());
        }
        entry.setWindPressure(cus.getWindPressure());
        entry.setSnowPressure(cus.getSnowPressure());
        entry.setPressureLevel(cus.getPressureLevel());
        if (!Objects.equals(cus.getAddress(),entry.getAddress())) {
            if (StringUtil.isBlank(cus.getAddress())) {
                adSf.append("清除详细地址信息：修改前：").append(entry.getAddress()).append(";");
            }
            else if (StringUtil.isBlank(entry.getAddress())) {
                adSf.append("填写详细地址：").append(cus.getAddress()).append(";");
            }
            else {
                adSf.append("修改详细地址：修改前：").append(entry.getAddress()).append(" ,修改后 ：").
                        append(cus.getAddress()).append(";");
            }
            entry.setAddress(StringUtil.isBlank(cus.getAddress()) ? "" : cus.getAddress().trim());
        }
        //修改项目公司信息
        if (StringUtil.isNotBlank(cus.getCompany())){
            ProjectCompanySettings projectCompanySettings = companyDao.get(cus.getCompany());
            entry.setProjectCompanyId(projectCompanySettings.getId());
            entry.setProjectCompanyName(projectCompanySettings.getName());
            entry.setManagementType(projectCompanySettings.getCompanyCode());
            if (pro != null) {
                String filingType = pro.getStr("filing_type");
                if (!filingType.equals(projectCompanySettings.getFilingType())) {
                    throw new IllegalArgumentException("选择的产品、项目公司所属备案类型不一致");
                }
            }
        } else {
            entry.setProjectCompanyId(null);
            entry.setProjectCompanyName(null);
            entry.setManagementType(null);
        }

        //提交勘测和勘测暂存校验
        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            throw new IllegalArgumentException(checkApplyResult);
        }
        //产品必填项校验
        String roofType = cus.getRoofType();
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            List<ProjectInfoVo> projectList = cus.getProjectList();
            if (projectList==null||projectList.isEmpty()) {
                throw new IllegalArgumentException("请选择产品");
            }else {
                StringBuilder roofTypeSb = new StringBuilder();
                Set<String> projectSet = new HashSet<>();
                for (ProjectInfoVo projectInfoVo : projectList) {
                    if (StringUtil.isBlank(projectInfoVo.getProjectId())) {
                        throw new IllegalArgumentException("请选择产品");
                    }
                    if(StringUtil.isBlank(projectInfoVo.getRoofType())){
                        throw new IllegalArgumentException("请选择屋顶类型");
                    }
                    if(!projectSet.add(projectInfoVo.getProjectId())){
                        throw new IllegalArgumentException(projectInfoVo.getProjectName()+"重复");
                    }
                    if(!projectSet.add(projectInfoVo.getRoofType())){
                        throw new IllegalArgumentException(projectInfoVo.getRoofType()+"重复");
                    }
                    roofTypeSb.append(projectInfoVo.getRoofType()+",");
                }
                if(roofTypeSb.length()>0)
                    roofTypeSb.deleteCharAt(roofTypeSb.length()-1);
                roofType= roofTypeSb.toString();
            }
        }else {
            if (StringUtil.isBlank(cus.getProjectId())) {
                throw new IllegalArgumentException("请选择产品");
            }
        }

        //初勘提交时
        if (CustomerEntryConstants.TYPE_SH.equals(cus.getType())) {
            if (StringUtil.isAnyBlank(entry.getProjectCompanyId())) {
                throw new IllegalArgumentException("项目公司应为必填!");
            }
            if (StringUtil.isAnyBlank(cus.getProvince(),cus.getCity(),
                    cus.getArea(), cus.getAddress())) {
                throw new IllegalArgumentException("请填写安装地址");
            }
            // 提交时，校验区域 代理商是否授权
            boolean checkAuth = traderPcdService.checkAuth(entry.getCreateTraderId(),
                    cus.getProvince(), cus.getCity(), cus.getArea());
            if (!checkAuth) {
                throw new IllegalArgumentException("代理商区域暂未授权");
            }
            //TODO 校验产品区域权限  产品是否授权
            if (pro != null) {
                boolean b = projectDao.checkAuth(cus.getProjectId(), cus.getProvince(), cus.getCity(), cus.getArea());
                if (!b) {
                    throw new IllegalArgumentException("产品区域暂未授权");
                }
            }
            //TODO 校验项目公司区域  产品是否授权
            boolean b1 = companyDao.checkAuth2(entry.getProjectCompanyId(),
                    cus.getProvince(), cus.getCity(), cus.getArea());
            if (!b1) {
                throw new IllegalArgumentException("项目公司区域暂未授权");
            }
        }
        String code ="200";
        if (StringUtil.equalsAny(entry.getDesignAuditFlag(),CustomerEntryConstants.DESIGN_AUDIT_FLAG_DZS,
                CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSTG,CustomerEntryConstants.DESIGN_AUDIT_FLAG_SJSHTG,
                CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHZ,CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHTG,
                CustomerEntryConstants.DESIGN_AUDIT_FLAG_DSJ)) {
            throw new IllegalArgumentException("已提交，请先刷新页面");
        }
        entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_ZC);
        entry.setZsResult("0");
        StringBuilder sf = new StringBuilder();
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            StringBuilder projectCode = new StringBuilder();
            StringBuilder projectName = new StringBuilder();
            StringBuilder payCycle = new StringBuilder();
            String productLineId = "";
            String lineName = "";
            String attribute = "";
            BigDecimal epcPrice = new BigDecimal(0);
            StringBuilder sb = new StringBuilder();
            String projectId = "";
            for(ProjectInfoVo vo:cus.getProjectList()){
                if(StringUtil.isNotBlank(vo.getProjectId())){
                    if (StringUtil.isBlank(projectId)){
                        projectId=vo.getProjectId();
                    }else {
                        projectId=projectId+","+vo.getProjectId();
                    }
                    sb.append(vo.getProjectName()+",");
                    Record pro1 = projectDao.getProject(vo.getProjectId());

                    if (!entry.getPartnerId().equals(pro1.getStr("management"))) {
                        throw new IllegalArgumentException("选择的产品不属于" + entry.getPartnerName() + ",请重新选择产品");
                    }

                    projectCode.append(pro1.getStr("code")+",") ;
                    projectName.append( pro1.getStr("name")+",");
                    payCycle.append(pro1.getStr("pay_cycle")+",");
                    if (pro1.get("epc_price") != null) {
                        //EPC单价/ 每W定价
                        epcPrice = epcPrice.add(pro1.getBigDecimal("epc_price"));
                    }
                    //产品线 业务属性取一个
                    productLineId= pro1.getStr("product_line_id");
                    lineName = pro1.getStr("lineName");
                    attribute = pro1.getStr("attribute");
                }
                }
            if(projectName.length()>0)
                projectName.deleteCharAt(projectName.length()-1);
            entry.setProjectName(projectName.toString());
            if(projectCode.length()>0)
                projectCode.deleteCharAt(projectCode.length()-1);
            entry.setProjectCode(projectCode.toString());
            entry.setProjectId(projectId);
            //EPC单价/ 每W定价
            entry.setEpcPrice(epcPrice.divide(new BigDecimal(cus.getProjectList().size()), 2, BigDecimal.ROUND_HALF_UP));
            //产品线
            entry.setProductLineId(productLineId);
            entry.setProductLineName(lineName);
            //业务属性 1.纯租25年业务、2.经营性租赁、3.融资租赁、4.光伏贷、5.全款、6.其他
            entry.setProductLine(attribute);
            //租金支付周期 1按月支付 2按季支付 3按年支付
            if(payCycle.length()>0)
                payCycle.deleteCharAt(payCycle.length()-1);
            entry.setPayCycle(payCycle.toString());
            //备案类型
//            entry.setFilingType(cus.getFilingType());
            sb.deleteCharAt(sb.length()-1);
            if(!entry.getProjectName().contentEquals(projectName)){
                sf.append("修改产品：修改前：").append(entry.getProjectName());
                sf.append(" ,修改后 ：").append(projectName.toString()).append(";");
            }
        }else {
            if (StringUtil.isBlank(entry.getProjectId()) && StringUtil.isBlank(cus.getProjectId())) {
            } else if ((StringUtil.isBlank(entry.getProjectId()) || StringUtil.isBlank(cus.getProjectId())
                    || !cus.getProjectId().equals(entry.getProjectId())) && !PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())) {
                // 修改后 产品被清空
                if (pro == null) {
                    sf.append("修改项目信息,取消选择：").append(entry.getProjectName()).append(";");
                } else {
                    // 修改前 产品未设置
                    if (StringUtil.isBlank(entry.getProjectId())) {
                        sf.append("修改项目信息,修改为：").append(pro.getStr("name")).append(";");
                    }
                    // 修改前与修改后 产品不一样
                    else {
                        sf.append("修改项目信息,修改前：").append(entry.getProjectName()).
                                append(" ,修改后 ：").append(pro.getStr("name")).append(";");
                    }
                    if (!entry.getPartnerId().equals(pro.getStr("management"))) {
                        throw new IllegalArgumentException("选择的产品不属于" + entry.getPartnerName() + ",请重新选择产品");
                    }
                }
                entry.setProjectId(pro == null ? null : cus.getProjectId());
                entry.setProjectName(pro == null ? null : pro.getStr("name"));
                entry.setProjectCode(pro == null ? null : pro.getStr("code"));

                //EPC单价/ 每W定价
                entry.setEpcPrice(pro == null ? BigDecimal.ZERO : pro.getBigDecimal("epc_price"));
                //产品线
                entry.setProductLineId(pro == null ? null : pro.getStr("product_line_id"));
                entry.setProductLineName(pro == null ? null : pro.getStr("lineName"));
                //业务属性 1.纯租25年业务、2.经营性租赁、3.融资租赁、4.光伏贷、5.全款、6.其他
                entry.setProductLine(pro == null ? null : pro.getStr("attribute"));
                //租金支付周期 1按月支付 2按季支付 3按年支付
                entry.setPayCycle(pro == null ? null : pro.getStr("pay_cycle"));
                entry.setFilingType(pro == null ? null : pro.getStr("filing_type"));

                //删除旧租金信息
                customerRentVariableService.deleteRentVariable(cus.getId());
                //更新租金信息
                if (StringUtil.isNotBlank(cus.getProjectId())) {
                    customerRentVariableService.saveEntryComponent(cus.getId(), cus.getProjectId());
                }
            }
        }
        // 因为广发要求 在勘测时上传房产证明
        // 针对房产证明 做特殊处理，如果资方不是广发时，房产证明不修改
        if (!PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId()) &&
            StringUtil.isNotBlank(surveyRecord.getHouseOwnership())) {
            cus.setHouseOwnership(surveyRecord.getHouseOwnership());
        }

        sf.append(adSf);
        // 修改勘测记录
        cus.setDistributorId(entry.getDistributorId());
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            surveyRecord = recordDetailService.setBasicInfo(cus,surveyRecord, now);
            entry.setProjectNum(cus.getProjectList().size());
        }else {
            sf = surveyRecordDao.appendMsg(sf, surveyRecord, cus);
            surveyRecord = surveyRecordDao.setBasicInfo(cus, surveyRecord, now);
        }
        entry.setRoofType(roofType);
        surveyRecord.setEntryId(cus.getId());
        if (StringUtil.isBlank(surveyRecord.getRepaymentMethod())) {
            // 农户备案 对应 二类卡 ，项目公司备案 对应 其他
            String method = ("1".equals(entry.getFilingType()) ? "1" : "0");
            surveyRecord.setRepaymentMethod(method);
        }
        surveyRecordDao.save(surveyRecord);

        entry.setDesignDrawings(cus.getDesignDrawings());
//        entry.setDesignDrawingsName(cus.getDesignDrawingsName());
        entry.setInsuranceFlag(cus.getInsuranceFlag());
        entry.setLeaseDate(cus.getLeaseDate());
//        entry.setDzImgs(cus.getDzImgs());
        if (StringUtil.isNotBlank(cus.getBpIdCard()) && cus.getBpIdCard().equals(entry.getIdCode())) {
            throw new IllegalArgumentException("共签人证件号码不能与业主身份证号相同!");
        }
//        entry.setBpIdCard(cus.getBpIdCard());

        if (StringUtil.isNotBlank(cus.getSchemeId())) {
            CrmPlan plan = planDao.get(cus.getSchemeId());
            if (plan != null) {
                entry.setSchemeId(cus.getSchemeId());
                entry.setSchemeName(plan.getName());
            }
        }
        entry.setSchemeType(cus.getSchemeType());
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            if (!CustomerEntryConstants.SCHEME_TYPE_TWO.equals(cus.getSchemeType())) {
                entry.setSchemeRemarks(cus.getSchemeRemarks());
                entryDesignService.setEntryDesign(cus.getAddEntryReqDesignDetails(),cus.getItemList(), entry);
            }
        }else {
            if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(cus.getSchemeType())) {
                entry.setComponentSpec(cus.getComponentSpec());
                entry.setSchemeRemarks(cus.getSchemeRemarks());
                entry.setSchemeId("");
                entry.setSchemeName("");
            } else {
                //标准方案
                entry.setComponentSpec("");
                entry.setSchemeRemarks(cus.getSchemeRemarks());
                entry.setSchemeTypeId(cus.getSchemeTypeId());
                if (StringUtil.isNotBlank(cus.getSchemeTypeId())){
                    CrmProjectInstallWay way = installDao.get(cus.getSchemeTypeId());
                    if(way!= null){
                        entry.setSchemeTypeName(way.getName());
                    }
                }
                if (StringUtil.isNotBlank(cus.getSchemeId())) {
                    CrmPlan plan = planDao.get(cus.getSchemeId());
                    if (plan != null) {
                        entry.setSchemeName(plan.getName());
                    }
                }
            }
        }


        // 设计容量 组件类型是'组件'的 规格 × 数量
        int designCapacity = 0;
        if (cus.getItemList() != null) {
            for (CustomerEntryComponentVo v : cus.getItemList()) {
                if ("3".equals(v.getItemType())) {
                    if(StringUtil.isNotBlank(v.getItemId())){
                        CrmElectricSet crmElectricSet = electricSetDao.get(v.getItemId());
                        if (v.getNum() == null) {
                            continue;
                        }
                        designCapacity = designCapacity + (v.getNum() * Integer.parseInt(crmElectricSet.getModel()));
                    }
                }
            }
        }
        entry.setDesignCapacity(designCapacity);
        // 组件规格
        // 组件类型是'组件'的组件
        List<CustomerEntryComponentVo> zuJianList = new ArrayList<>();
        if (cus.getItemList() != null) {
            zuJianList = cus.getItemList().stream().filter(v -> "3".equals(v.getItemType())).collect(Collectors.toList());
        }
        if (!CollectionUtils.isEmpty(zuJianList)) {
            List<String> itemIds = zuJianList.stream().filter(e -> !e.getItemId().isEmpty()).map(CustomerEntryComponentVo::getItemId).collect(Collectors.toList());
            List<Record> records = electricSetDao.findByIds(itemIds);
            List<String> specList = records.stream().map(r -> r.getStr("model")).collect(Collectors.toList());
            entry.setComponentSpec(StringUtil.join(specList, ","));
        }

        short msgType=CustomerEntryConstants.ADVANCE_TYPE_OPT_AUDIT;
        String str="";
        //set新增字段
        entry.setLatitude(cus.getLatitude());
        entry.setLongitude(cus.getLongitude());
        entry.setZjpbImg(cus.getZjpbImg());
        entry.setZjzxImg(cus.getZjzxImg());
        entry.setZjcsImg(cus.getZjcsImg());
        entry.setZjhsImg(cus.getZjhsImg());

        if (CustomerEntryConstants.TYPE_SH.equals(cus.getType())) {//初勘提交
            if(!CustomerEntryConstants.AUTHORIZATION_SUCCESS.equals(entry.getAuthorization()) &&
                    !CustomerEntryConstants.TENANT_TYPE_COMPANY.equals(entry.getTenantType())){
                throw new IllegalArgumentException("请先完成信息授权!");
            }
            //初勘提交判断有没有开卡
            if ("1".equals(entry.getFilingType())&&"1".equals(crmPartner.getIsOpenBankCard())) {
                CrmTenantYxBankCard bankCard=tenantYxBankCardDao.getByIdCard(entry.getIdCode(),entry.getManagementType(),entry.getPartnerId());
                if (bankCard == null || StringUtil.isBlank(bankCard.getAccountCode())) {
                    throw new IllegalArgumentException("请先开通二类卡!");
                }
            }
            if(!StringUtil.equals(entry.getCredit(), CustomerEntryConstants.CREDIT_APPROVED)){
                throw new IllegalArgumentException("预审未通过，不可提交审核!");
            }

            // 查询项目信息
//            CrmProjectSetting projectSetting = projectDao.get(entry.getProjectId());

            List<Record> checkList = formSetDao.findListByCondition("02", entry.getPartnerId());
            // 校验必填项
            Result result = null;
            if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
                 result = requiredCheckForSurvey(entry, surveyRecord,cus.getAddEntryReqSurveyDetails(),cus.getProjectList(), checkList);
            }else {
                 result = requiredCheckForSurvey(entry, surveyRecord, checkList);
            }
            if (!"200".equals(result.getCode())) {
                throw new IllegalArgumentException(result.getErrMsg());
            }
            if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())) {
                result = requiredCheckForDesign(entry, cus.getItemList(),cus.getAddEntryReqDesignDetails(),cus.getProjectList(), checkList);
            }else {
                result = requiredCheckForDesign(entry, cus.getItemList(), checkList);
            }

            if (!"200".equals(result.getCode())) {
                throw new IllegalArgumentException(result.getErrMsg());
            }
            //判断设计自审是否需要
            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);
                itemManageDao.addItem(FormUtils.ENTRY_STATUS_SJSH,entry.getId(),PlantformUtils.getOrderNumber(),"设计审核("+stationName+"-"+entry.getPowerStationCode()+")-"+DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss"),date,operator.getUserName());
            } else {
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_KCZS);
                entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DZS);
            }
            if (CustomerEntryConstants.APPLY_STATUS_YSCG.equals(entry.getApplyStatus())) {
                entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_DJJ);
            }
            msgType=CustomerEntryConstants.ENTRY_CK;
            str="电站初勘提交";
        }

        //越秀汇流箱
        if(PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())){
            combinerBoxGroupService.addNewCombinerBoxGroup(entry,cus.getBoxTotalCount(),cus.getMergeType(),CustomerEntryConstants.TYPE_SH.equals(cus.getType()),operator,cus.getBoxGroupId());
        }

        customerDao.save(entry);
        applicationDao.saveIncomingApplication(entry);
        msgService.saveCustomerEntryMsg(operator, cus.getId(), msgType, sf.toString()+str,operator.getUserName());
        // 电站的承租类型法人的文件上传记录表
        CustomerEntryOrgFiles orgFiles = orgFilesDao.findOneByEntryId(cus.getId());
        if (orgFiles == null) {
            if (Objects.equals("2", entry.getTenantType())) {
                orgFilesDao.createOne(cus.getId(), cus.getDistributorId(), cus.getRegnoUrl(),null);
            } else {
                orgFilesDao.createOne(cus.getId(), cus.getDistributorId(), null,cus.getCreditCertificate());
            }
        } else if (StringUtils.isNotBlank(cus.getRegnoUrl())) {
            orgFiles.setRegnoUrl(cus.getRegnoUrl());
            orgFilesDao.save(orgFiles);
        }
        // 删除原先方案
        composePlanService.deleteComposePlanByEntryId(cus.getId());
        if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(cus.getSchemeType()) && !CollectionUtils.isEmpty(cus.getComposePlanLists())) {
            // 处理组合方案
            entry.setComposePlanLists(cus.getComposePlanLists());
            composePlanService.saveComposePlan(entry, entry.getId());
            // cus.setSchemeName(planName);

        } else {
            if (!PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())&&StringUtil.isNotBlank(cus.getSchemeId()) && CustomerEntryConstants.SCHEME_TYPE_ONE.equals(cus.getSchemeType())) {
                CrmPlan plan = planDao.get(cus.getSchemeId());
                if (plan != null) {
                    entry.setSchemeName(plan.getName());
                }
            }
        }
        // 删除原电器组件
        customerEntryComponentService.deleteEntryComponent(cus.getId());
        // 处理电器组件
        List<CustomerEntryComponentVo> itemList = cus.getItemList();
        if (itemList != null) {
            customerEntryComponentService.saveEntryComponent(itemList, cus.getId(), operator.getUserId());
        }
        //判断是否需要设计审核
        if (CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSTG.equals(entry.getDesignAuditFlag())
                && !FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_SJSH)) {
            toExamine(entry.getId(), entry.getExamineRemarks(), operator, UserUtils.getUser());
        }
        return code;
    }

    private Result requiredCheckForDesign(CustomerEntry entry, List<CustomerEntryComponentVo> itemList, List<AddEntryReqDesignDetail> addEntryReqDesignDetails, List<ProjectInfoVo> projectList, List<Record> list) {

        Result result = new Result();
        result.setCode("205");
        Map<String,String> projectMap = new HashMap<>();
        for(ProjectInfoVo projectInfoVo:projectList){
            projectMap.put(projectInfoVo.getProjectId(), projectInfoVo.getRoofType());
        }
        for(AddEntryReqDesignDetail addEntryReqDesignDetail:addEntryReqDesignDetails){
            if ("1".equals(entry.getSchemeType())) {
                //方案类型
                if (StringUtil.isBlank(addEntryReqDesignDetail.getSchemeTypeId())) {
                    result.setErrMsg(projectMap.get(addEntryReqDesignDetail.getProjectId())+"方案类型为空");
                    return result;
                }
                if (StringUtil.isBlank(addEntryReqDesignDetail.getSchemeId())) {
                    result.setErrMsg(projectMap.get(addEntryReqDesignDetail.getProjectId())+"方案名称为空");
                    return result;
                }
            }
            //设计图纸
            if (StringUtil.isBlank(addEntryReqDesignDetail.getDesignDrawings())
                    && CheckMustFillUtil.checkMustFill("design_drawings", list)) {
                result.setErrMsg(projectMap.get(addEntryReqDesignDetail.getProjectId())+"设计图纸为空");
                return result;
            } else if (addEntryReqDesignDetail.getDesignDrawings().split(",").length > 4
                    && CheckMustFillUtil.checkMustFill("design_drawings", list)) {
                result.setErrMsg(projectMap.get(addEntryReqDesignDetail.getProjectId())+"设计图纸最多四张");
                return result;
            }

            // 组件校验
            if (StringUtil.isBlank(addEntryReqDesignDetail.getComponentSpec())
                    && CheckMustFillUtil.checkMustFill("component3", list)) {
                result.setErrMsg(projectMap.get(addEntryReqDesignDetail.getProjectId())+"组件为空");
                return result;
            }
            //其他物料校验
            List<CustomerEntryComponentVo> collect = itemList.stream().filter(v -> addEntryReqDesignDetail.getProjectId().equals(v.getProjectId())).collect(Collectors.toList());
            String checkResult = checkSchMaterial(collect, list);
            if (StringUtil.isNotBlank(checkResult)) {
                result.setErrMsg(projectMap.get(addEntryReqDesignDetail.getProjectId())+checkResult);
                return result;
            }
        }

        return Result.ok();

    }

    private Result requiredCheckForSurvey(CustomerEntry entry,  CustomerEntrySurveyRecord surveyRecord,  List<AddEntryReqSurveyDetail> addEntryReqSurveyDetails,  List<ProjectInfoVo> projectList, List<Record> list) {
        Result result = new Result();
        result.setCode("205");
        if (StringUtil.isBlank(entry.getFilingType())
                && CheckMustFillUtil.checkMustFill("filing_type", list)) {
            result.setErrMsg("备案类型为空");
            return result;
        }
        if (StringUtil.isBlank(entry.getInsuranceFlag())
                && CheckMustFillUtil.checkMustFill("insurance_flag", list)) {
            result.setErrMsg("保险购买情况为空");
            return result;
        }
        if (entry.getLeaseDate() == null
                && CheckMustFillUtil.checkMustFill("lease_date", list)) {
            result.setErrMsg("预计投放日为空");
            return result;
        }


        //并网距离
        if (surveyRecord.getDistance() == null
                && CheckMustFillUtil.checkMustFill("distance", list)) {
            result.setErrMsg("并网距离为空");
            return result;
        }
        //方位角
        if (StringUtil.isBlank(surveyRecord.getAzimuth())
                && CheckMustFillUtil.checkMustFill("angle_azimuth", list)) {
            result.setErrMsg("方位角为空");
            return result;
        }
        //东西长
        if (surveyRecord.getEwLength() == null
                && CheckMustFillUtil.checkMustFill("ew_length", list)) {
            result.setErrMsg("东西长为空");
            return result;
        }
        //南北宽
        if (surveyRecord.getNsWide() == null
                && CheckMustFillUtil.checkMustFill("ns_wide", list)) {
            result.setErrMsg("南北宽为空");
            return result;
        }
        //屋顶面积
        if (surveyRecord.getRoofArea() == null
                && CheckMustFillUtil.checkMustFill("roof_area", list)) {
            result.setErrMsg("屋顶面积为空");
            return result;
        }
        //房产证明
        if (CheckMustFillUtil.checkMustFill("house_ownership", list)) {
            if(StringUtil.isBlank(surveyRecord.getHouseOwnership())){
                result.setErrMsg("房产证明图片为空");
                return result;
            } else if (surveyRecord.getHouseOwnership().split(",").length > 8) {
                result.setErrMsg("房产证明图片最多八张");
                return result;
            }
        }
        //经度
        if (entry.getLongitude() == null
                && CheckMustFillUtil.checkMustFill("longitude", list)) {
            result.setErrMsg("经度为空");
            return result;
        }
        //纬度
        if (entry.getLatitude() == null
                && CheckMustFillUtil.checkMustFill("latitude", list)) {
            result.setErrMsg("纬度为空");
            return result;
        }
        if (entry.getLatitude()!=null && entry.getLatitude().compareTo(new BigDecimal(90))>0
                && CheckMustFillUtil.checkMustFill("latitude", list)){
            result.setErrMsg("纬度数据不合法:"+entry.getLatitude()+"，请检查后重新提交");
            return result;
        }
        //建筑高度
        if (surveyRecord.getBuildingHeight() == null
                && CheckMustFillUtil.checkMustFill("building_height", list)) {
            result.setErrMsg("建筑高度为空");
            return result;
        }
        //还款方式
        if (StringUtil.isBlank(surveyRecord.getRepaymentMethod())
                && CheckMustFillUtil.checkMustFill("repayment_method", list) && "1".equals(entry.getTenantType())) {
            result.setErrMsg("划转方式为空");
            return result;
        }
        Map<String,String> projectMap = new HashMap<>();
        Set<String> projectSet =new HashSet<>();
        int i = 0;
        for(ProjectInfoVo projectInfoVo:projectList){
            i++;
            if(StringUtil.isBlank(projectInfoVo.getProjectId())){
                result.setErrMsg("产品信息第"+i+"行产品为空");
                return result;
            }
            if (StringUtil.isBlank(projectInfoVo.getRoofType())
                    && CheckMustFillUtil.checkMustFill("roof_type", list)) {
                result.setErrMsg("产品信息第"+i+"行房屋类型为空");
                return result;
            }
            if(!projectSet.add(projectInfoVo.getProjectId())){
                result.setErrMsg(projectInfoVo.getProjectName()+"重复");
                return result;
            }
            if(!projectSet.add(projectInfoVo.getRoofType())){
                result.setErrMsg(projectInfoVo.getRoofType()+"重复");
                return result;
            }
            projectMap.put(projectInfoVo.getProjectId(), projectInfoVo.getRoofType());
        }

        for(AddEntryReqSurveyDetail surveyDetail:addEntryReqSurveyDetails) {
//            if(StringUtils.isBlank(surveyDetail.getDipAngle().toString())){
//                result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"组件倾角为空");
//                return result;
//            }
            if (surveyDetail.getDipAngle() == null && CheckMustFillUtil.checkMustFill("dip_angle", list)) {
                result.setErrMsg("组件倾角为空");
                return result;
            }
            if (CheckMustFillUtil.checkMustFill("fly_imgs", list)) {
                if (StringUtil.isBlank(surveyDetail.getFlyImgs())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"无人机航拍图为空");
                    return result;
                } else if (surveyDetail.getFlyImgs().split(",").length < 3) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"无人机航拍图至少三张");
                    return result;
                }
            }
            if (CheckMustFillUtil.checkMustFill("fly_imgs_04", list)) {
                if (StringUtil.isBlank(surveyDetail.getFlyImgs())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"屋顶高空俯视照片为空");
                    return result;
                } else if (surveyDetail.getFlyImgs().split(",").length < 3) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"屋顶高空俯视照片至少三张");
                    return result;
                }
            }
            if (CheckMustFillUtil.checkMustFill("roof_photo_one", list)) {
                if (StringUtil.isBlank(surveyDetail.getRoofPhotoOne())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"安装区域整体照片为空");
                    return result;
                } else if (surveyDetail.getRoofPhotoOne().split(",").length < 2) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"安装区域整体照片至少两张");
                    return result;
                }
            }

            if (StringUtil.isBlank(surveyDetail.getRoofPhotoTwo())
                    && CheckMustFillUtil.checkMustFill("roof_photo_two", list)) {
                result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"安装区域东南角照片为空");
                return result;
            }
            if (CheckMustFillUtil.checkMustFill("roof_photo_two_04", list)) {
                if (StringUtil.isBlank(surveyDetail.getRoofPhotoTwo())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"屋顶东南照片为空");
                    return result;
                } else if (surveyDetail.getRoofPhotoTwo().split(",").length > 9) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"屋顶东南照片最多九张");
                    return result;
                }
            }

            if (StringUtil.isBlank(surveyDetail.getRoofPhotoThree())
                    && CheckMustFillUtil.checkMustFill("roof_photo_three", list)) {
                result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"安装区域西南角照片为空");
                return result;
            }
            if (StringUtil.isBlank(surveyDetail.getRoofPhotoThree())
                    && CheckMustFillUtil.checkMustFill("roof_photo_three_03", list)) {
                result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋屋顶西侧图片为空");
                return result;
            }
            if (StringUtil.isBlank(surveyDetail.getRoofPhotoThree())
                    && CheckMustFillUtil.checkMustFill("roof_photo_three_04", list)) {
                result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"屋顶西南照片为空");
                return result;
            }
            if (StringUtil.isBlank(surveyDetail.getRoofPhotoFour())
                    && CheckMustFillUtil.checkMustFill("roof_photo_four", list)) {
                result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"安装区域正南照片为空");
                return result;
            }
            if (StringUtil.isBlank(surveyDetail.getRoofPhotoFour())
                    && CheckMustFillUtil.checkMustFill("roof_photo_four_04", list)) {
                result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"屋顶正南照片为空");
                return result;
            }
            if (CheckMustFillUtil.checkMustFill("roof_photo_facade", list)) {
                if (StringUtil.isBlank(surveyDetail.getRoofPhotoFacade())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋内部结构照片为空");
                    return result;
                } else if (surveyDetail.getRoofPhotoFacade().split(",").length < 2) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋内部结构照片至少两张");
                    return result;
                }
            }
            if (CheckMustFillUtil.checkMustFill("roof_photo_interior", list)) {
                if (StringUtil.isBlank(surveyDetail.getRoofPhotoInterior())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋内部环境照片为空");
                    return result;
                } else if (surveyDetail.getRoofPhotoInterior().split(",").length < 2) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋内部环境照片至少两张");
                    return result;
                }
            }
            if (StringUtil.isBlank(surveyDetail.getRoofPhotoFive())
                    && CheckMustFillUtil.checkMustFill("roof_photo_five", list)) {
                result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"安装区域细节照片为空");
                return result;
            }
            if (StringUtil.isBlank(surveyDetail.getHouseSupplementOne())
                    && CheckMustFillUtil.checkMustFill("house_supplement_one", list)) {
                result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋其他障碍物照片为空");
                return result;
            }
            // detail_supplement_one
            if (StringUtil.isBlank(surveyDetail.getDetailSupplementOne())
                    && CheckMustFillUtil.checkMustFill("detail_supplement_one", list)) {
                result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"逆变器、配电箱预安装位置照片为空");
                return result;
            }
            // house_outline_photo
            if (StringUtil.isBlank(surveyDetail.getHouseOutlinePhoto())
                    && CheckMustFillUtil.checkMustFill("house_outline_photo", list)) {
                result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋轮廓照片为空");
                return result;
            }
            // 踏勘补充证明视频
            if (StringUtil.isBlank(surveyDetail.getSurveyVideo())
                    && CheckMustFillUtil.checkMustFill("survey_video", list)) {
                result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"踏勘补充证明视频为空");
                return result;
            }
            // 踏勘记录表文件
            if (CheckMustFillUtil.checkMustFill("survey_files", list)) {
                if (StringUtil.isBlank(surveyDetail.getSurveyFiles())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"踏勘记录表文件为空");
                    return result;
                } else if (surveyDetail.getSurveyFiles().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"踏勘记录表文件最少一张");
                    return result;
                } else if (surveyDetail.getSurveyFiles().split(",").length > 4) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"踏勘记录表文件最多四张");
                    return result;
                }
            }
            // 户用勘察记录表（1-9张）
            if (CheckMustFillUtil.checkMustFill("survey_files_03", list)) {
                if (StringUtil.isBlank(surveyDetail.getSurveyFiles())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"户用勘察记录表为空");
                    return result;
                } else if (surveyDetail.getSurveyFiles().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"户用勘察记录表最少一张");
                    return result;
                } else if (surveyDetail.getSurveyFiles().split(",").length > 9) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"户用勘察记录表最多九张");
                    return result;
                }
            }
            // 现场踏勘表
            if (CheckMustFillUtil.checkMustFill("survey_files_04", list)) {
                if (StringUtil.isBlank(surveyDetail.getSurveyFiles())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"现场踏勘表为空");
                    return result;
                } else if (surveyDetail.getSurveyFiles().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"现场踏勘表最少一张");
                    return result;
                } else if (surveyDetail.getSurveyFiles().split(",").length > 4) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"现场踏勘表最多四张");
                    return result;
                }
            }
            // 房屋整体图（VR全景）
            if (CheckMustFillUtil.checkMustFill("vr_roof_one", list)) {
                if (StringUtil.isBlank(surveyDetail.getVrRoofOne())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋整体图（VR全景）为空");
                    return result;
                } else if (surveyDetail.getVrRoofOne().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋整体图（VR全景）最少一张");
                    return result;
                } else if (surveyDetail.getVrRoofOne().split(",").length > 9) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋整体图（VR全景）最多九张");
                    return result;
                }
            }
            // 房屋整体俯视图（无人机）
            if (CheckMustFillUtil.checkMustFill("vr_roof_two", list)) {
                if (StringUtil.isBlank(surveyDetail.getVrRoofTwo())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋整体俯视图（无人机）为空");
                    return result;
                } else if (surveyDetail.getVrRoofTwo().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋整体俯视图（无人机）最少一张");
                    return result;
                } else if (surveyDetail.getVrRoofTwo().split(",").length > 9) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋整体俯视图（无人机）最多九张");
                    return result;
                }
            }
            // 房屋内部结构图（VR）
            if (CheckMustFillUtil.checkMustFill("vr_roof_three", list)) {
                if (StringUtil.isBlank(surveyDetail.getVrRoofThree())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋内部结构图（VR）为空");
                    return result;
                } else if (surveyDetail.getVrRoofThree().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋内部结构图（VR）最少一张");
                    return result;
                } else if (surveyDetail.getVrRoofThree().split(",").length > 9) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋内部结构图（VR）最多九张");
                    return result;
                }
            }
            // 入户全景照片(VR)
            if (CheckMustFillUtil.checkMustFill("vr_roof_four", list)) {
                if (StringUtil.isBlank(surveyDetail.getVrRoofFour())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"入户全景照片(VR)为空");
                    return result;
                } else if (surveyDetail.getVrRoofFour().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"入户全景照片(VR)最少一张");
                    return result;
                } else if (surveyDetail.getVrRoofFour().split(",").length > 9) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"入户全景照片(VR)最多九张");
                    return result;
                }
            }
            // 入户全景照片
            if (CheckMustFillUtil.checkMustFill("vr_roof_four_04", list)) {
                if (StringUtil.isBlank(surveyDetail.getVrRoofFour())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"入户全景照片为空");
                    return result;
                } else if (surveyDetail.getVrRoofFour().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"入户全景照片最少一张");
                    return result;
                } else if (surveyDetail.getVrRoofFour().split(",").length > 9) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"入户全景照片最多九张");
                    return result;
                }
            }
            // 屋顶正南照片
            if (CheckMustFillUtil.checkMustFill("roof_photo_four_04", list)) {
                if (StringUtil.isBlank(surveyDetail.getRoofPhotoFour())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"屋顶正南照片为空");
                    return result;
                } else if (surveyDetail.getRoofPhotoFour().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"屋顶正南照片最少一张");
                    return result;
                } else if (surveyDetail.getRoofPhotoFour().split(",").length > 9) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"屋顶正南照片最多九张");
                    return result;
                }
            }
            // 屋顶西南照片
            if (CheckMustFillUtil.checkMustFill("roof_photo_three_04", list)) {
                if (StringUtil.isBlank(surveyDetail.getRoofPhotoThree())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"屋顶西南照片为空");
                    return result;
                } else if (surveyDetail.getRoofPhotoThree().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"屋顶西南照片最少一张");
                    return result;
                } else if (surveyDetail.getRoofPhotoThree().split(",").length > 9) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"屋顶西南照片最多九张");
                    return result;
                }
            }
            //房屋整体图
            if (CheckMustFillUtil.checkMustFill("fw_img1", list)) {
                if (StringUtil.isBlank(surveyDetail.getFwImg1())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋整体图为空");
                    return result;
                } else if (surveyDetail.getFwImg1().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋整体图最少一张");
                    return result;
                } else if (surveyDetail.getFwImg1().split(",").length > 9) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋整体图最多九张");
                    return result;
                }
            }
            //房屋内部结构图
            if (CheckMustFillUtil.checkMustFill("fw_img2", list)) {
                if (StringUtil.isBlank(surveyDetail.getFwImg2())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋内部结构图为空");
                    return result;
                } else if (surveyDetail.getFwImg2().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋内部结构图最少一张");
                    return result;
                } else if (surveyDetail.getFwImg2().split(",").length > 9) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋内部结构图最多九张");
                    return result;
                }
            }
            //房屋屋顶东南侧图片
            if (CheckMustFillUtil.checkMustFill("fw_img3", list)) {
                if (StringUtil.isBlank(surveyDetail.getFwImg3())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋屋顶东南侧图片为空");
                    return result;
                } else if (surveyDetail.getFwImg3().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋屋顶东南侧图片最少一张");
                    return result;
                } else if (surveyDetail.getFwImg3().split(",").length > 9) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋屋顶东南侧图片最多九张");
                    return result;
                }
            }
            //房屋屋顶西南侧图片
            if (CheckMustFillUtil.checkMustFill("fw_img4", list)) {
                if (StringUtil.isBlank(surveyDetail.getFwImg4())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋屋顶西南侧图片为空");
                    return result;
                } else if (surveyDetail.getFwImg4().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋屋顶西南侧图片最少一张");
                    return result;
                } else if (surveyDetail.getFwImg4().split(",").length > 9) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"房屋屋顶西南侧图片最多九张");
                    return result;
                }
            }
            //遮阴物与房屋距离、高度
            if (CheckMustFillUtil.checkMustFill("fw_img5", list)) {
                if (StringUtil.isBlank(surveyDetail.getFwImg5())) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"遮阴物与房屋距离、高度为空");
                    return result;
                } else if (surveyDetail.getFwImg5().split(",").length < 1) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"遮阴物与房屋距离、高度最少一张");
                    return result;
                } else if (surveyDetail.getFwImg5().split(",").length > 9) {
                    result.setErrMsg(projectMap.get(surveyDetail.getProjectId())+"遮阴物与房屋距离、高度最多九张");
                    return result;
                }
            }
        }
        // 并网电压等级 voltage_classes
        if (surveyRecord.getVoltageClasses() == null
                && CheckMustFillUtil.checkMustFill("voltage_classes", list)) {
            result.setErrMsg("并网电压等级为空");
            return result;
        }
        // 变压器容量 transformer_capacity
        if (surveyRecord.getTransformerCapacity() == null
                && CheckMustFillUtil.checkMustFill("transformer_capacity", list)) {
            result.setErrMsg("变压器容量为空");
            return result;
        }
        // 是否符合变压器容量限制要求 restrict_flag
        if (StringUtil.isBlank(surveyRecord.getRestrictFlag())
                && CheckMustFillUtil.checkMustFill("restrict_flag", list)) {
            result.setErrMsg("是否符合变压器容量限制要求为空");
            return result;
        }
        // 是否封屋顶 seal_roof
        if (StringUtil.isBlank(surveyRecord.getSealRoof())
                && CheckMustFillUtil.checkMustFill("seal_roof", list)) {
            result.setErrMsg("是否封屋顶为空");
            return result;
        }
        // 房屋建成年份 completion_year
        if (StringUtil.isBlank(surveyRecord.getCompletionYear())
                && CheckMustFillUtil.checkMustFill("completion_year", list)) {
            result.setErrMsg("房屋建成年份为空");
            return result;
        }
        // 组件倾角 dip_angle
//        if (surveyRecord.getDipAngle() == null
//                && CheckMustFillUtil.checkMustFill("dip_angle", list)) {
//            result.setErrMsg("组件倾角为空");
//            return result;
//        }
        // 屋面坡度 slope_gradient
        if ("斜屋顶".equals(surveyRecord.getRoofType()) && surveyRecord.getSlopeGradient() == null
                && CheckMustFillUtil.checkMustFill("slope_gradient", list)) {
            result.setErrMsg("屋面坡度为空");
            return result;
        }
        // 檩条间距 purline_interval
        if ("斜屋顶".equals(surveyRecord.getRoofType()) && surveyRecord.getPurlineInterval() == null
                && CheckMustFillUtil.checkMustFill("purline_interval", list)) {
            result.setErrMsg("檩条间距为空");
            return result;
        }
        // 屋顶防水情况 waterproof
        if (StringUtil.isBlank(surveyRecord.getWaterproof())
                && CheckMustFillUtil.checkMustFill("waterproof", list)) {
            result.setErrMsg("屋顶防水情况为空");
            return result;
        }
        // 是否有污染源 source_pollution
        if (StringUtil.isBlank(surveyRecord.getSourcePollution())
                && CheckMustFillUtil.checkMustFill("source_pollution", list)) {
            result.setErrMsg("是否有污染源为空");
            return result;
        }
        // 是否具备运维空间 ops_condition
        if (StringUtil.isBlank(surveyRecord.getOpsCondition())
                && CheckMustFillUtil.checkMustFill("ops_condition", list)) {
            result.setErrMsg("是否具备运维空间为空");
            return result;
        }
        return Result.ok();
    }

    /**
     * 勘测提交设计
     */
    @Transactional(rollbackFor = Exception.class)
    public String surveyToDesign(SurveyEntryReq req, Operator operator) {
        CustomerEntry entry = customerDao.get(req.getId());
        Date now = DateUtils.getNowDate();
        CrmPartner crmPartner = partnerService.getById(entry.getPartnerId());
        // 生成勘测记录
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(req.getId());
        if (surveyRecord == null) {
            surveyRecord = new CustomerEntrySurveyRecord();
        }
        Record pro = null;
        if (StringUtil.isNotBlank(req.getProjectId())) {
            pro = projectDao.getProject(req.getProjectId());
        }
        StringBuilder adSf = new StringBuilder();
        if (!(req.getProvince() + req.getCity() + req.getArea()).equals(entry.getProvince() + entry.getCity() + entry.getArea())) {
            adSf.append("修改地址：修改前：").append(entry.getProvince()).append(entry.getCity()).append(entry.getArea()).append(" ,修改后 ：").
                    append(req.getProvince()).append(req.getCity()).append(req.getArea()).append(";");
            entry.setProvince(StringUtil.isBlank(req.getProvince()) ? "" : req.getProvince());
            entry.setCity(StringUtil.isBlank(req.getCity()) ? "" : req.getCity());
            entry.setArea(StringUtil.isBlank(req.getArea()) ? "" : req.getArea());
            entry.setStreet(StringUtil.isBlank(req.getStreet()) ? "" : req.getStreet());
            entry.setLongitude(req.getLongitude());
            entry.setLatitude(req.getLatitude());
        }
        entry.setWindPressure(req.getWindPressure());
        entry.setSnowPressure(req.getSnowPressure());
        entry.setPressureLevel(req.getPressureLevel());
        if (!Objects.equals(req.getAddress(),entry.getAddress())) {
            if (StringUtil.isBlank(req.getAddress())) {
                adSf.append("清除详细地址信息：修改前：").append(entry.getAddress()).append(";");
            }
            else if (StringUtil.isBlank(entry.getAddress())) {
                adSf.append("填写详细地址：").append(req.getAddress()).append(";");
            }
            else {
                adSf.append("修改详细地址：修改前：").append(entry.getAddress()).append(" ,修改后 ：").
                        append(req.getAddress()).append(";");
            }
            entry.setAddress(StringUtil.isBlank(req.getAddress()) ? "" : req.getAddress().trim());
        }
        //修改项目公司信息
        if (StringUtil.isNotBlank(req.getCompany())){
            ProjectCompanySettings projectCompanySettings = companyDao.get(req.getCompany());
            entry.setProjectCompanyId(projectCompanySettings.getId());
            entry.setProjectCompanyName(projectCompanySettings.getName());
            entry.setManagementType(projectCompanySettings.getCompanyCode());
        } else {
            entry.setProjectCompanyId(null);
            entry.setProjectCompanyName(null);
            entry.setManagementType(null);
        }

        //勘测提交设计校验
        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            throw new IllegalArgumentException(checkApplyResult);
        }
        //产品必填项校验
        String roofType = req.getRoofType();
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            List<ProjectInfoVo> projectList = req.getProjectList();
            if (projectList==null||projectList.isEmpty()) {
                throw new IllegalArgumentException("请选择产品");
            }else {
                StringBuilder roofTypeSb = new StringBuilder();
                Set<String> projectSet = new HashSet<>();
                for (ProjectInfoVo projectInfoVo : projectList) {
                    if (StringUtil.isBlank(projectInfoVo.getProjectId())) {
                        throw new IllegalArgumentException("请选择产品");
                    }
                    if(StringUtil.isBlank(projectInfoVo.getRoofType())){
                        throw new IllegalArgumentException("请选择屋顶类型");
                    }
                    if(!projectSet.add(projectInfoVo.getProjectId())){
                        throw new IllegalArgumentException(projectInfoVo.getProjectName()+"重复");
                    }
                    if(!projectSet.add(projectInfoVo.getRoofType())){
                        throw new IllegalArgumentException(projectInfoVo.getRoofType()+"重复");
                    }
                    roofTypeSb.append(projectInfoVo.getRoofType()+",");
                }
                if(roofTypeSb.length()>0)
                    roofTypeSb.deleteCharAt(roofTypeSb.length()-1);
                roofType= roofTypeSb.toString();
            }
        }else {
            if (StringUtil.isBlank(req.getProjectId())) {
                throw new IllegalArgumentException("请选择产品");
            }
        }
        if (StringUtil.isAnyBlank(entry.getProjectCompanyId())) {
            throw new IllegalArgumentException("项目公司应为必填!");
        }
        if (StringUtil.isAnyBlank(req.getProvince(),req.getCity(),
                req.getArea(), req.getAddress())) {
            throw new IllegalArgumentException("请填写安装地址");
        }
        //校验区域 代理商是否授权
        boolean checkAuth = traderPcdService.checkAuth(entry.getCreateTraderId(),
                req.getProvince(), req.getCity(), req.getArea());
        if (!checkAuth) {
            throw new IllegalArgumentException("代理商区域暂未授权");
        }
        //校验产品区域权限  产品是否授权
        if (pro != null) {
            boolean b = projectDao.checkAuth(req.getProjectId(), req.getProvince(), req.getCity(), req.getArea());
            if (!b) {
                throw new IllegalArgumentException("产品区域暂未授权");
            }
        }
        //校验项目公司区域  产品是否授权
        boolean b1 = companyDao.checkAuth2(entry.getProjectCompanyId(),
                req.getProvince(), req.getCity(), req.getArea());
        if (!b1) {
            throw new IllegalArgumentException("项目公司区域暂未授权");
        }
        String code ="200";
        if (StringUtil.equalsAny(entry.getDesignAuditFlag(),CustomerEntryConstants.DESIGN_AUDIT_FLAG_DZS,
                CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSTG,CustomerEntryConstants.DESIGN_AUDIT_FLAG_SJSHTG,
                CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHZ,CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHTG,
                CustomerEntryConstants.DESIGN_AUDIT_FLAG_DSJ)) {
            throw new IllegalArgumentException("已提交，请先刷新页面");
        }
        entry.setInsuranceFlag(req.getInsuranceFlag());
        entry.setLeaseDate(req.getLeaseDate());
        entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DSJ);
        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_ZC);
        entry.setZsResult("0");//勘测阶段操作进行初始化
        StringBuilder sf = new StringBuilder();
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            StringBuilder projectCode = new StringBuilder();
            StringBuilder projectName = new StringBuilder();
            StringBuilder payCycle = new StringBuilder();
            String productLineId = "";
            String lineName = "";
            String attribute = "";
            BigDecimal epcPrice = new BigDecimal(0);
            StringBuilder sb = new StringBuilder();
            String projectId="";
            for(ProjectInfoVo vo:req.getProjectList()){
                if (StringUtil.isBlank(projectId)){
                    projectId=vo.getProjectId();
                }else {
                    projectId=projectId+","+vo.getProjectId();
                }
                sb.append(vo.getProjectName()+",");
                Record pro1 = projectDao.getProject(vo.getProjectId());
                projectCode.append(pro1.getStr("code")+",") ;
                projectName.append( pro1.getStr("name")+",");
                payCycle.append(pro1.getStr("pay_cycle")+",");
                if (pro1.get("epc_price") != null) {
                    //EPC单价/ 每W定价
                    epcPrice = epcPrice.add(pro1.getBigDecimal("epc_price"));
                }
                //产品线 业务属性取一个
                productLineId= pro1.getStr("product_line_id");
                lineName = pro1.getStr("lineName");
                attribute = pro1.getStr("attribute");

            }
            if(projectName.length()>0)
                projectName.deleteCharAt(projectName.length()-1);
            if (!entry.getProjectName().equals(projectName.toString())){
                sf.append("修改产品：修改前：").append(entry.getProjectName());
                sf.append(" ,修改后 ：").append(projectName.toString()).append(";");
            }
            entry.setProjectName(projectName.toString());
            if(projectCode.length()>0)
                projectCode.deleteCharAt(projectCode.length()-1);
            entry.setProjectCode(projectCode.toString());
            entry.setProjectId(projectId);
            //EPC单价/ 每W定价
            entry.setEpcPrice(epcPrice.divide(new BigDecimal(req.getProjectList().size()), 2, BigDecimal.ROUND_HALF_UP));
            //产品线
            entry.setProductLineId(productLineId);
            entry.setProductLineName(lineName);
            //业务属性 1.纯租25年业务、2.经营性租赁、3.融资租赁、4.光伏贷、5.全款、6.其他
            entry.setProductLine(attribute);
            //租金支付周期 1按月支付 2按季支付 3按年支付
            if(payCycle.length()>0)
                payCycle.deleteCharAt(payCycle.length()-1);
            entry.setPayCycle(payCycle.toString());
            //备案类型
//            entry.setFilingType(req.getFilingType());
            sb.deleteCharAt(sb.length()-1);

        }else {
            if (StringUtil.isBlank(entry.getProjectId()) && StringUtil.isBlank(req.getProjectId())) {
            } else if (StringUtil.isBlank(entry.getProjectId()) || StringUtil.isBlank(req.getProjectId())
                    || !req.getProjectId().equals(entry.getProjectId())) {
                // 修改后 产品被清空
                if (pro == null) {
                    sf.append("修改项目信息,取消选择：").append(entry.getProjectName()).append(";");
                } else {
                    // 修改前 产品未设置
                    if (StringUtil.isBlank(entry.getProjectId())) {
                        sf.append("修改项目信息,修改为：").append(pro.getStr("name")).append(";");
                    }
                    // 修改前与修改后 产品不一样
                    else {
                        sf.append("修改项目信息,修改前：").append(entry.getProjectName()).
                                append(" ,修改后 ：").append(pro.getStr("name")).append(";");
                    }
                    if (!entry.getPartnerId().equals(pro.getStr("management"))) {
                        throw new IllegalArgumentException("选择的产品不属于" + entry.getPartnerName() + ",请重新选择产品");
                    }
                }
                entry.setProjectId(pro == null ? null : req.getProjectId());
                entry.setProjectName(pro == null ? null : pro.getStr("name"));
                entry.setProjectCode(pro == null ? null : pro.getStr("code"));

                //EPC单价/ 每W定价
                entry.setEpcPrice(pro == null ? BigDecimal.ZERO : pro.getBigDecimal("epc_price"));
                //产品线
                entry.setProductLineId(pro == null ? null : pro.getStr("product_line_id"));
                entry.setProductLineName(pro == null ? null : pro.getStr("lineName"));
                //业务属性 1.纯租25年业务、2.经营性租赁、3.融资租赁、4.光伏贷、5.全款、6.其他
                entry.setProductLine(pro == null ? null : pro.getStr("attribute"));
                //租金支付周期 1按月支付 2按季支付 3按年支付
                entry.setPayCycle(pro == null ? null : pro.getStr("pay_cycle"));
                entry.setFilingType(pro == null ? null : pro.getStr("filing_type"));

                //删除旧租金信息
                customerRentVariableService.deleteRentVariable(req.getId());
                //更新租金信息
                if (StringUtil.isNotBlank(req.getProjectId())) {
                    customerRentVariableService.saveEntryComponent(req.getId(), req.getProjectId());
                }
            }
        }
        // 因为广发要求 在勘测时上传房产证明
        // 针对房产证明 做特殊处理，如果资方不是广发时，房产证明不修改
        if (!PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId()) &&
                StringUtil.isNotBlank(surveyRecord.getHouseOwnership())) {
            req.setHouseOwnership(surveyRecord.getHouseOwnership());
        }
        sf.append(adSf);
        // 修改勘测记录
        req.setDistributorId(entry.getDistributorId());
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            surveyRecord = recordDetailService.setBasicInfo(surveyRecord, req.getDistributorId() , req.getAzimuth(), req.getAngle(), req.getBuildingHeight(),
                    req.getRepaymentMethod(),req.getTenantType(), req.getDistance(),
                    req.getVoltageClasses(),req.getTransformerCapacity(),req.getRestrictFlag(),
                    req.getSealRoof(),req.getCompletionYear(),req.getDipAngle(),req.getSlopeGradient(),req.getPurlineInterval(),
                    req.getWaterproof(),req.getSourcePollution(),req.getOpsCondition(),now
                    ,req.getEwLength(),req.getNsWide(),req.getRoofArea(),req.getProjectList(),req.getAddEntryReqSurveyDetails(),req.getId());
            entry.setProjectNum(req.getProjectList().size());
        }else {
            sf = surveyRecordDao.appendMsg(sf, surveyRecord, req.getRoofType(), req.getDistance());
            surveyRecord = surveyRecordDao.setBasicInfo(surveyRecord, req.getDistributorId(), req.getRoofType(),
                    req.getAzimuth(), req.getAngle(), req.getBuildingHeight(), req.getRepaymentMethod(), req.getTenantType(),
                    req.getDistance(), req.getFlyImgs(), req.getRoofPhotoOne(), req.getRoofPhotoTwo(),
                    req.getRoofPhotoThree(), req.getRoofPhotoFour(), req.getRoofPhotoFive(), req.getHouseOwnership(),
                    req.getRoofPhotoFacade(), req.getRoofPhotoInterior(), null, null, req.getHouseSupplementOne(),
                    req.getDetailSupplementOne(), req.getVoltageClasses(), req.getTransformerCapacity(), req.getRestrictFlag(),
                    req.getSealRoof(), req.getCompletionYear(), req.getDipAngle(), req.getSlopeGradient(), req.getPurlineInterval(),
                    req.getWaterproof(), req.getSourcePollution(), req.getOpsCondition(), now, req.getSurveyVideo(), req.getSurveyFiles(),
                    req.getEwLength(), req.getNsWide(), req.getRoofArea(), req.getVrRoofOne(), req.getVrRoofTwo(), req.getVrRoofThree(), req.getVrRoofFour(),
                    req.getHouseOutlinePhoto(), req.getFwImg1(), req.getFwImg2(), req.getFwImg3(), req.getFwImg4(), req.getFwImg5(),req.getRoofFaceThickness()
                    ,req.getStructureType(),req.getSiteSlope(),req.getGroundType(),req.getGeologicalCondition(),req.getFenceHeight());
        }
        entry.setRoofType(roofType);
        surveyRecord.setEntryId(req.getId());
        if (StringUtil.isBlank(surveyRecord.getRepaymentMethod())) {
            // 农户备案 对应 二类卡 ，项目公司备案 对应 其他
            String method = ("1".equals(entry.getFilingType()) ? "1" : "0");
            surveyRecord.setRepaymentMethod(method);
        }
        surveyRecordDao.save(surveyRecord);


        entry.setDesignDrawings(req.getDesignDrawings());

        if (StringUtil.isNotBlank(req.getSchemeId())) {
            CrmPlan plan = planDao.get(req.getSchemeId());
            if (plan != null) {
                entry.setSchemeId(req.getSchemeId());
                entry.setSchemeName(plan.getName());
            }
        }
        String schemeType = "1"; // 设计方案 1.标准方案  2.组合方案 当前只能时标准方案
        entry.setSchemeType(schemeType);

        entry.setSchemeRemarks(req.getSchemeRemarks());
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            if (!CustomerEntryConstants.SCHEME_TYPE_TWO.equals(req.getSchemeType())) {
                entry.setSchemeRemarks(req.getSchemeRemarks());
                entryDesignService.setEntryDesign(req.getAddEntryReqDesignDetails(),req.getItemList(), entry);
            }
        }else {
        if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(schemeType)) {
            entry.setComponentSpec(req.getComponentSpec());
            entry.setSchemeId("");
            entry.setSchemeName("");
        } else {
            //标准方案
            entry.setComponentSpec("");
            entry.setSchemeTypeId(req.getSchemeTypeId());
            if (StringUtil.isNotBlank(req.getSchemeTypeId())){
                CrmProjectInstallWay way = installDao.get(req.getSchemeTypeId());
                if(way!= null){
                    entry.setSchemeTypeName(way.getName());
                }
            }
            if (StringUtil.isNotBlank(req.getSchemeId())) {
                CrmPlan plan = planDao.get(req.getSchemeId());
                if (plan != null) {
                    entry.setSchemeId(req.getSchemeId());
                    entry.setSchemeName(plan.getName());
                }
            }
        }
        }

        // 设计容量 组件类型是'组件'的 规格 × 数量
        int designCapacity = 0;
        if (req.getItemList() != null) {
            for (CustomerEntryComponentVo v : req.getItemList()) {
                if ("3".equals(v.getItemType())) {
                    if(StringUtil.isNotBlank(v.getItemId())){
                        CrmElectricSet crmElectricSet = electricSetDao.get(v.getItemId());
                        if (v.getNum() == null) {
                            continue;
                        }
                        designCapacity = designCapacity + (v.getNum() * Integer.parseInt(crmElectricSet.getModel()));
                    }
                }
            }
        }
        entry.setDesignCapacity(designCapacity);
        // 组件规格
        // 组件类型是'组件'的组件
        List<CustomerEntryComponentVo> zuJianList = new ArrayList<>();
        if (req.getItemList() != null) {
            zuJianList = req.getItemList().stream().filter(v -> "3".equals(v.getItemType())).collect(Collectors.toList());
        }
        if (!CollectionUtils.isEmpty(zuJianList)) {
            List<String> itemIds = zuJianList.stream().filter(e -> !e.getItemId().isEmpty()).map(CustomerEntryComponentVo::getItemId).collect(Collectors.toList());
            List<Record> records = electricSetDao.findByIds(itemIds);
            List<String> specList = records.stream().map(r -> r.getStr("model")).collect(Collectors.toList());
            entry.setComponentSpec(StringUtil.join(specList, ","));
        }

        short msgType=CustomerEntryConstants.ENTRY_SURVEY_DESIGN;
        String str="勘测提交设计";
        entry.setLongitude(req.getLongitude());
        entry.setLatitude(req.getLatitude());
        entry.setZjpbImg(req.getZjpbImg());
        entry.setZjcsImg(req.getZjcsImg());
        entry.setZjzxImg(req.getZjzxImg());
        entry.setZjhsImg(req.getZjhsImg());
        if(!CustomerEntryConstants.AUTHORIZATION_SUCCESS.equals(entry.getAuthorization()) &&
                !CustomerEntryConstants.TENANT_TYPE_COMPANY.equals(entry.getTenantType())){
            throw new IllegalArgumentException("请先完成信息授权!");
        }
        //初勘提交判断有没有开卡
        if ("1".equals(entry.getFilingType())&&"1".equals(crmPartner.getIsOpenBankCard())) {
            CrmTenantYxBankCard bankCard=tenantYxBankCardDao.getByIdCard(entry.getIdCode(),entry.getManagementType(),entry.getPartnerId());
            if (bankCard == null || StringUtil.isBlank(bankCard.getAccountCode())) {
                throw new IllegalArgumentException("请先开通二类卡!");
            }
        }
        if(!StringUtil.equals(entry.getCredit(), CustomerEntryConstants.CREDIT_APPROVED)){
            throw new IllegalArgumentException("预审未通过，不可提交设计!");
        }
        // 校验必填项
        List<Record> checkList = formSetDao.findListByCondition("02", entry.getPartnerId());
        Result result = null;
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            result = requiredCheckForSurvey(entry, surveyRecord,req.getAddEntryReqSurveyDetails(),req.getProjectList(), checkList);
        }else {
            result = requiredCheckForSurvey(entry, surveyRecord, checkList);
        }
        if (!"200".equals(result.getCode())) {
            throw new IllegalArgumentException(result.getErrMsg());
        }
        //越秀汇流箱
        if(PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())){
            combinerBoxGroupService.addNewCombinerBoxGroup(entry,req.getBoxTotalCount(),req.getMergeType(),true,operator,req.getBoxGroupId());
        }
        customerDao.save(entry);
        applicationDao.saveIncomingApplication(entry);
        msgService.saveCustomerEntryMsg(operator, req.getId(), msgType, sf.toString()+str,operator.getUserName());
        // 删除原先方案
        composePlanService.deleteComposePlanByEntryId(req.getId());
        if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(schemeType) && !CollectionUtils.isEmpty(req.getComposePlanLists())) {
            // 处理组合方案
            entry.setComposePlanLists(req.getComposePlanLists());
            composePlanService.saveComposePlan(entry, entry.getId());
        } else {
            if (!PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())&&StringUtil.isNotBlank(req.getSchemeId()) && CustomerEntryConstants.SCHEME_TYPE_ONE.equals(req.getSchemeType())) {
                CrmPlan plan = planDao.get(req.getSchemeId());
                if (plan != null) {
                    entry.setSchemeName(plan.getName());
                }
            }
        }
        // 删除原电器组件
        customerEntryComponentService.deleteEntryComponent(req.getId());
        // 处理电器组件
        List<CustomerEntryComponentVo> itemList = req.getItemList();
        if (itemList != null) {
            customerEntryComponentService.saveEntryComponent(itemList, req.getId(), operator.getUserId());
        }
        return code;
    }

    /**
     * 设计驳回勘测
     */
    @Transactional(rollbackFor = Exception.class)
    public String designBackCustomerEntry(String id, String remarks, Operator operator) {
        CustomerEntry entry = customerDao.get(id);
//        Date now = DateUtils.getNowDate();
        // 待设计状态下，才可操作 设计暂存、设计提交
        if (!CustomerEntryConstants.DESIGN_AUDIT_FLAG_DSJ.equals(entry.getDesignAuditFlag())) {
            throw new IllegalArgumentException("待设计状态才可操作进行驳回勘测操作，请先刷新列表");
        }
        //驳回备注 需要存放到操作日志中
        if (StringUtil.isBlank(remarks)) {
            throw new IllegalArgumentException("请填写撤回原因");
        }
//        entry.setSchemeRemarks(remarks);
        entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
        String code ="200";
        customerDao.save(entry);
        msgService.saveCustomerEntryMsg(operator, id, CustomerEntryConstants.ENTRY_DESIGN_BACK, remarks,operator.getUserName());
        return code;
    }

    /**
     * 设计提交、设计暂存
     */
    @Transactional(rollbackFor = Exception.class)
    public String designCustomerEntry(DesignEntryReq req, Operator operator) {
        CustomerEntry entry = customerDao.get(req.getId());
        Date now = DateUtils.getNowDate();
        CrmPartner crmPartner = partnerService.getById(entry.getPartnerId());
        // 待设计状态下，才可操作 设计暂存、设计提交
        if (!CustomerEntryConstants.DESIGN_AUDIT_FLAG_DSJ.equals(entry.getDesignAuditFlag())) {
            throw new IllegalArgumentException("待设计状态才可操作进行设计操作，请先刷新列表");
        }
        //设计提交、设计暂存 校验
        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            throw new IllegalArgumentException(checkApplyResult);
        }
        String code ="200";
        if (CustomerEntryConstants.ENTRY_STATUS_SHBTG.equals(entry.getStatus())) {
            entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DSJ);
        }
        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_ZC);
        StringBuilder sf = new StringBuilder();
        entry.setDesignDrawings(req.getDesignDrawings());
        //设计方案 1.标准方案  2.组合方案  当前只能为标准方案
        String schemeType = "1";
        if (StringUtil.isNotBlank(req.getSchemeId())) {
            CrmPlan plan = planDao.get(req.getSchemeId());
            if (plan != null) {
                entry.setSchemeId(req.getSchemeId());
                entry.setSchemeName(plan.getName());
            }
        }
        entry.setSchemeType(schemeType);
        //修改备注 需要存放到操作日志中
        String remarks = (StringUtil.isNotBlank(req.getSchemeRemarks())? req.getSchemeRemarks() : "");
        if (StringUtil.isNotBlank(remarks) && !remarks.equals(entry.getSchemeRemarks())) {
            remarks = "，方案备注：" + remarks;
        }
        entry.setSchemeRemarks(req.getSchemeRemarks());
//        if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(schemeType)) {
//            entry.setComponentSpec(req.getComponentSpec());
//            entry.setSchemeId("");
//            entry.setSchemeName("");
//        } else {
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
                entry.setSchemeRemarks(req.getSchemeRemarks());
                entryDesignService.setEntryDesign(req.getAddEntryReqDesignDetails(),req.getItemList(), entry);
        }else {
            //标准方案
            entry.setComponentSpec("");
            entry.setSchemeTypeId(req.getSchemeTypeId());
            if (StringUtil.isNotBlank(req.getSchemeTypeId())) {
                CrmProjectInstallWay way = installDao.get(req.getSchemeTypeId());
                if (way != null) {
                    entry.setSchemeTypeName(way.getName());
                }
            }
            if (StringUtil.isNotBlank(req.getSchemeId())) {
                CrmPlan plan = planDao.get(req.getSchemeId());
                if (plan != null) {
                    entry.setSchemeName(plan.getName());
                }
            }
        }
//        }
        // 设计容量 组件类型是'组件'的 规格 × 数量
        int designCapacity = 0;
        if (req.getItemList() != null) {
            for (CustomerEntryComponentVo v : req.getItemList()) {
                if ("3".equals(v.getItemType())) {
                    if(StringUtil.isNotBlank(v.getItemId())){
                        CrmElectricSet crmElectricSet = electricSetDao.get(v.getItemId());
                        if (v.getNum() == null) {
                            continue;
                        }
                        designCapacity = designCapacity + (v.getNum() * Integer.parseInt(crmElectricSet.getModel()));
                    }
                }
            }
        }
        int oldDesignCapacity = (entry.getDesignCapacity() == null ? 0 : entry.getDesignCapacity());
        if (oldDesignCapacity == 0 && designCapacity != 0) {
            sf.append("填写设计容量：").append(designCapacity).append(";");
        }
        else if (oldDesignCapacity != 0 && designCapacity != oldDesignCapacity) {
            if (designCapacity == 0) {
                sf.append("清除设计容量：").append(oldDesignCapacity).append(";");
            }
            else {
                sf.append("修改设计容量：").append(oldDesignCapacity).
                        append(" ,修改后：").append(designCapacity).append(";");
            }
        }
        entry.setDesignCapacity(designCapacity);
        // 组件规格
        // 组件类型是'组件'的组件
        List<CustomerEntryComponentVo> zuJianList = new ArrayList<>();
        if (req.getItemList() != null) {
            zuJianList = req.getItemList().stream().filter(v -> "3".equals(v.getItemType())).collect(Collectors.toList());
        }
        if (!CollectionUtils.isEmpty(zuJianList)) {
            List<String> itemIds = zuJianList.stream().filter(e -> !e.getItemId().isEmpty()).map(CustomerEntryComponentVo::getItemId).collect(Collectors.toList());
            List<Record> records = electricSetDao.findByIds(itemIds);
            List<String> specList = records.stream().map(r -> r.getStr("model")).collect(Collectors.toList());
            entry.setComponentSpec(StringUtil.join(specList, ","));
        }

        short msgType=CustomerEntryConstants.ENTRY_DESIGN_ZC;
        String str="设计暂存";
        //set新增字段
        entry.setZjpbImg(req.getZjpbImg());
        entry.setZjcsImg(req.getZjcsImg());
        entry.setZjzxImg(req.getZjzxImg());
        entry.setZjhsImg(req.getZjhsImg());
        // 设计提交
        if (CustomerEntryConstants.TYPE_TJ.equals(req.getType())) {
            if(!CustomerEntryConstants.AUTHORIZATION_SUCCESS.equals(entry.getAuthorization()) &&
                    !CustomerEntryConstants.TENANT_TYPE_COMPANY.equals(entry.getTenantType())){
                throw new IllegalArgumentException("请先完成信息授权!");
            }
            //设计提交 判断有没有开卡
            if ("1".equals(entry.getFilingType())&&"".equals(crmPartner.getIsOpenBankCard())) {
                CrmTenantYxBankCard bankCard=tenantYxBankCardDao.getByIdCard(entry.getIdCode(),entry.getManagementType(),entry.getPartnerId());
                if (bankCard == null || StringUtil.isBlank(bankCard.getAccountCode())) {
                    throw new IllegalArgumentException("请先开通二类卡!");
                }
            }

            // 校验必填项
            List<Record> checkList = formSetDao.findListByCondition("02", entry.getPartnerId());
            Result result = null;
            if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())) {
                result = requiredCheckForDesign(entry, req.getItemList(),req.getAddEntryReqDesignDetails(),req.getProjectList(), checkList);
            }else {
                result = requiredCheckForDesign(entry, req.getItemList(), checkList);
            }
            if (!"200".equals(result.getCode())) {
                throw new IllegalArgumentException(result.getErrMsg());
            }
            //判断设计自审是否需要
            if (!FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_SJZS)) {
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DSH);
                entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSTG);
                String stationName = CrmUtils.getStationName(entry);
                itemManageDao.addItem(FormUtils.ENTRY_STATUS_SJSH,entry.getId(),PlantformUtils.getOrderNumber(),"设计审核("+stationName+"-"+entry.getPowerStationCode()+")-"+DateUtils.formatDate(now,"yyyy-MM-dd HH:mm:ss"),now,operator.getUserName());
            } else {
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_KCZS);
                entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DZS);
            }
            if (CustomerEntryConstants.APPLY_STATUS_YSCG.equals(entry.getApplyStatus())) {
                entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_DJJ);
            }
            msgType=CustomerEntryConstants.ENTRY_DESIGN_TJ;
            str="设计提交";
        }
        customerDao.save(entry);
        applicationDao.saveIncomingApplication(entry);
        msgService.saveCustomerEntryMsg(operator, req.getId(), msgType, str +sf.toString()+remarks,operator.getUserName());
        // 删除原先方案
        composePlanService.deleteComposePlanByEntryId(req.getId());
        if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(schemeType) && !CollectionUtils.isEmpty(req.getComposePlanLists())) {
            // 处理组合方案
            entry.setComposePlanLists(req.getComposePlanLists());
            composePlanService.saveComposePlan(entry, entry.getId());
        } else {
            if (StringUtil.isNotBlank(req.getSchemeId()) && CustomerEntryConstants.SCHEME_TYPE_ONE.equals(schemeType)) {
                CrmPlan plan = planDao.get(req.getSchemeId());
                if (plan != null) {
                    entry.setSchemeName(plan.getName());
                }
            }
        }
        // 删除原电器组件
        customerEntryComponentService.deleteEntryComponent(req.getId());
        // 处理电器组件
        List<CustomerEntryComponentVo> itemList = req.getItemList();
        if (itemList != null) {
            customerEntryComponentService.saveEntryComponent(itemList, req.getId(), operator.getUserId());
        }
        //判断是否需要设计审核
        if (CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSTG.equals(entry.getDesignAuditFlag())
                && !FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_SJSH)) {
            toExamine(entry.getId(), entry.getExamineRemarks(), operator, UserUtils.getUser());
        }
        return code;
    }

    public String checkSchMaterial(List<CustomerEntryComponentVo> itemList, List<Record> checkList) {
        List<CustomerEntryComponentVo> nbqList = itemList.stream().filter(v -> "1".equals(v.getItemType())).collect(Collectors.toList());
        List<CustomerEntryComponentVo> bwxList = itemList.stream().filter(v -> "2".equals(v.getItemType())).collect(Collectors.toList());
        List<CustomerEntryComponentVo> zjList = itemList.stream().filter(v -> "4".equals(v.getItemType())).collect(Collectors.toList());
        // 逆变器
        if (nbqList.isEmpty()
                && CheckMustFillUtil.checkMustFill("component1", checkList)) {
            return "请选择逆变器";
        }
        // 并网箱
        if (bwxList.isEmpty()
                && CheckMustFillUtil.checkMustFill("component2", checkList)) {
            return "请选择并网箱";
        }
        // 支架
        if (zjList.isEmpty()
                && CheckMustFillUtil.checkMustFill("component4", checkList)) {
            return "请选择支架";
        }
        for(CustomerEntryComponentVo vc: itemList){
            if(vc.getNum()==null){
                return "物料数量不能为空！";
            }
        }
        return "";
    }

    /**
     * 小程序修改农户信息
     */
    @Transactional(rollbackFor = Exception.class)
    public String editCustomerEntryBy(CustomerEntryVo cus, Operator operator) {
        CustomerEntry entry = customerDao.get(cus.getId());

        StringBuilder sf = new StringBuilder();

        if (!Objects.equals(cus.getBankName(),entry.getBankName())) {
            sf.append("修改开户银行：修改前：").append(entry.getBankName()).append(" ,修改后 ：").append(cus.getBankName()).append(";");
            entry.setBankName(cus.getBankName());
        }
        entry.setBankCode(cus.getBankCode().trim());
        entry.setBankCard(cus.getBankCard());
        entry.setTssBankNum(cus.getTssBankNum());
        entry.setTssBankNumName(cus.getTssBankNumName());
        entry.setBpName(cus.getBpName());
        entry.setBpMobile(cus.getBpMobile());
        entry.setBpCardFront(cus.getBpCardFront());
        entry.setBpCardBack(cus.getBpCardBack());
        entry.setBpFile(cus.getBpFile());
        if (StringUtil.isNotBlank(cus.getBpIdCard()) && cus.getBpIdCard().equals(entry.getIdCode())) {
            throw new IllegalArgumentException("共签人证件号码不能与业主身份证号相同!");
        }
        entry.setBpIdCard(cus.getBpIdCard());
        customerDao.save(entry);
        msgService.saveCustomerEntryMsg(operator, cus.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_AUDIT, sf.toString(),operator.getUserName());
        return "200";
    }


    //设计自审
    @Transactional(rollbackFor = Exception.class)
    public String editCustomerEntryFromPC(AddEntryReq cus, Operator operator) {
        CustomerEntry entry = customerDao.get(cus.getId());
        if (!CustomerEntryConstants.DESIGN_AUDIT_FLAG_DZS.equals(entry.getDesignAuditFlag())
                && !CustomerEntryConstants.DESIGN_AUDIT_FLAG_SJSHBH.equals(entry.getDesignAuditFlag()) ){
            throw new IllegalArgumentException("自审已操作，请先刷新列表");
        }
        Date now = DateUtils.getNowDate();
        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            return checkApplyResult;
        }
        // 勘测记录
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(cus.getId());

//        if (StringUtil.isBlank(cus.getIdCardFront())) {
//            return "身份证正面为空";
//        }
//        if (StringUtil.isBlank(cus.getIdCardBack())) {
//            return "身份证反面为空";
//        }
        //产品必填项校验
        String roofType = cus.getRoofType();
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            List<ProjectInfoVo> projectList = cus.getProjectList();
            if (projectList==null||projectList.isEmpty()) {
                throw new IllegalArgumentException("请选择产品");
            }else {
                StringBuilder roofTypeSb = new StringBuilder();
                Set<String> projectSet = new HashSet<>();
                for(ProjectInfoVo v:projectList){
                    if (StringUtil.isBlank(v.getProjectId())) {
                        throw new IllegalArgumentException("请选择产品");
                    }
                    if(StringUtil.isBlank(v.getRoofType())){
                        throw new IllegalArgumentException("请选择屋顶类型");
                    }
                    if(!projectSet.add(v.getProjectId())){
                        throw new IllegalArgumentException(v.getProjectName()+"重复");
                    }
                    if(!projectSet.add(v.getRoofType())){
                        throw new IllegalArgumentException(v.getRoofType()+"重复");
                    }
                    roofTypeSb.append(v.getRoofType()+",");
                }
                if(roofTypeSb.length()>0)
                    roofTypeSb.deleteCharAt(roofTypeSb.length()-1);
                roofType = roofTypeSb.toString();
            }
        }else {
            if (StringUtil.isBlank(cus.getProjectId())) {
                throw new IllegalArgumentException("请选择产品");
            }
        }

        if (StringUtil.isBlank(cus.getCompany())) {
            return "所属项目公司为空";
        }
        StringBuilder sf = new StringBuilder();
        Record pro = projectDao.getProject(cus.getProjectId());

        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            StringBuilder projectCode = new StringBuilder();
            StringBuilder projectName = new StringBuilder();
            StringBuilder payCycle = new StringBuilder();
            String productLineId = "";
            String lineName = "";
            String attribute = "";
            BigDecimal epcPrice = new BigDecimal(0);
            StringBuilder sb = new StringBuilder();
            String projectId="";
               for(ProjectInfoVo vo:cus.getProjectList()){
                   if (StringUtil.isBlank(projectId)){
                       projectId=vo.getProjectId();
                   }else {
                       projectId=projectId+","+vo.getProjectId();
                   }
                   sb.append(vo.getProjectName()+",");
                   Record pro1 = projectDao.getProject(vo.getProjectId());
                   projectCode.append(pro1.getStr("code")+",") ;
                   projectName.append( pro1.getStr("name")+",");
                   payCycle.append(pro1.getStr("pay_cycle")+",");
                   if (pro1.get("epc_price") != null) {
                       //EPC单价/ 每W定价
                       epcPrice = epcPrice.add(pro1.getBigDecimal("epc_price"));
                   }
                   //产品线 业务属性取一个
                   productLineId= pro1.getStr("product_line_id");
                   lineName = pro1.getStr("lineName");
                   attribute = pro1.getStr("attribute");

               }
               if(projectName.length()>0)
                   projectName.deleteCharAt(projectName.length()-1);
            entry.setProjectId(projectId);
            if (!entry.getProjectName().equals(projectName.toString())){
                sf.append("修改产品：修改前：").append(entry.getProjectName());
                sf.append(" ,修改后 ：").append(projectName.toString()).append(";");
            }
            entry.setProjectName(projectName.toString());
            if(projectCode.length()>0)
                projectCode.deleteCharAt(projectCode.length()-1);
            entry.setProjectCode(projectCode.toString());
            //EPC单价/ 每W定价
            entry.setEpcPrice(epcPrice.divide(new BigDecimal(cus.getProjectList().size()), 2, BigDecimal.ROUND_HALF_UP));
            //产品线
            entry.setProductLineId(productLineId);
            entry.setProductLineName(lineName);
            //业务属性 1.纯租25年业务、2.经营性租赁、3.融资租赁、4.光伏贷、5.全款、6.其他
            entry.setProductLine(attribute);
            //租金支付周期 1按月支付 2按季支付 3按年支付
            if(payCycle.length()>0)
                payCycle.deleteCharAt(payCycle.length()-1);
            entry.setPayCycle(payCycle.toString());
            //备案类型
//            entry.setFilingType(cus.getFilingType());
            sb.deleteCharAt(sb.length()-1);
        }else {
            if (!cus.getProjectId().equals(entry.getProjectId())) {
                sf.append("修改项目信息：修改前：").append(entry.getProjectName()).append(" ,修改后 ：").append(pro.getStr("name")).append(";");
                entry.setProjectId(cus.getProjectId());
                entry.setProjectName(pro.getStr("name"));
                entry.setProjectCode(pro.getStr("code"));
                //EPC单价/ 每W定价
                entry.setEpcPrice(pro.getBigDecimal("epc_price"));

                //产品线
                entry.setProductLineId(pro.getStr("product_line_id"));
                entry.setProductLineName(pro.getStr("lineName"));
                //业务属性 1.纯租25年业务、2.经营性租赁、3.融资租赁、4.光伏贷、5.全款、6.其他
                entry.setProductLine(pro.getStr("attribute"));
                //租金支付周期 1按月支付 2按季支付 3按年支付
                entry.setPayCycle(pro.getStr("pay_cycle"));
                //备案类型
                entry.setFilingType(pro.getStr("filing_type"));
                //删除旧租金信息
                customerRentVariableService.deleteRentVariable(cus.getId());
                //更新租金信息
                customerRentVariableService.saveEntryComponent(cus.getId(), cus.getProjectId());
            }
        }

        //项目公司
        ProjectCompanySettings projectCompanySettings = companyDao.get(cus.getCompany());
        if (!cus.getCompany().equals(entry.getProjectCompanyId())) {
            entry.setProjectCompanyId(projectCompanySettings.getId());
            entry.setProjectCompanyName(projectCompanySettings.getName());
            entry.setManagementType(projectCompanySettings.getCompanyCode());
            if (pro != null) {
                String filingType = pro.getStr("filing_type");
                if (!filingType.equals(projectCompanySettings.getFilingType())) {
                    throw new IllegalArgumentException("选择的产品、项目公司所属备案类型不一致");
                }
            }
            sf.append("修改项目公司信息：修改前：").append(entry.getProjectCompanyName()).append(" ,修改后 ：").append(projectCompanySettings.getName()).append(";");
        }
        // 因为广发要求 在勘测时上传房产证明
        // 针对房产证明 做特殊处理，如果资方不是广发时，房产证明不修改
        if (!PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId()) &&
                StringUtil.isNotBlank(surveyRecord.getHouseOwnership())) {
            cus.setHouseOwnership(surveyRecord.getHouseOwnership());
        }
        // 修改勘测记录
        cus.setDistributorId(entry.getDistributorId());
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            surveyRecord = recordDetailService.setBasicInfo(cus,surveyRecord, now);
            entry.setProjectNum(cus.getProjectList().size());
        }else {
            sf = surveyRecordDao.appendMsg(sf, surveyRecord, cus);
            surveyRecord = surveyRecordDao.setBasicInfo(cus, surveyRecord, now);
        }
        if (StringUtil.isBlank(surveyRecord.getRepaymentMethod())) {
            // 农户备案 对应 二类卡 ，项目公司备案 对应 其他
            String method = ("1".equals(entry.getFilingType()) ? "1" : "0");
            surveyRecord.setRepaymentMethod(method);
        }
        surveyRecordDao.save(surveyRecord);
        entry.setRoofType(roofType);
        //原地址不为空  并且现地址有更改
        if ((StringUtil.isNotBlank(entry.getProvince())  || StringUtil.isNotBlank(entry.getCity()) || StringUtil.isNotBlank(entry.getArea())
                || StringUtil.isNotBlank(entry.getAddress())) &&( !cus.getProvince().equals(entry.getProvince()) || !cus.getCity().equals(entry.getCity())
                || !cus.getArea().equals(entry.getArea()) || !cus.getAddress().equals(entry.getAddress())) ) {
            sf.append("修改安装地址：修改前：").append(entry.getProvince()).append(entry.getCity()).append(entry.getArea())
                    .append(entry.getAddress()).append(" ,修改后 ：").append(cus.getProvince()).append(cus.getCity()).append(cus.getArea()).append(cus.getAddress()).append(";");
            entry.setProvince(cus.getProvince());
            entry.setCity(cus.getCity());
            entry.setArea(cus.getArea());
            entry.setAddress(cus.getAddress().trim());
        } else if (StringUtil.isBlank(entry.getProvince()) && StringUtil.isNotBlank(cus.getProvince())) {
            sf.append("修改安装地址：修改后 ：").append(cus.getProvince()).append(cus.getCity()).append(cus.getArea()).append(cus.getAddress());
            entry.setProvince(cus.getProvince());
            entry.setCity(cus.getCity());
            entry.setArea(cus.getArea());
            entry.setAddress(cus.getAddress().trim());
        }
        entry.setWindPressure(cus.getWindPressure());
        entry.setSnowPressure(cus.getSnowPressure());
        entry.setPressureLevel(cus.getPressureLevel());

        if (StringUtil.isNotBlank(entry.getRemarks()) && !entry.getRemarks().equals(cus.getRemarks())) {
            sf.append("修改备注：修改前：").append(entry.getRemarks()).append(" ,修改后 ：").append(cus.getRemarks()).append(";");
            entry.setRemarks(cus.getRemarks());
        } else if (StringUtil.isBlank(entry.getRemarks()) && StringUtil.isNotBlank(cus.getRemarks())) {
            sf.append("修改备注：修改后 ：").append(cus.getRemarks());
            entry.setRemarks(cus.getRemarks());
        }


//        entry.setBankName(cus.getBankName());
//        entry.setBankCode(cus.getBankCode());
//        entry.setTssBankNum(cus.getTssBankNum());
//        entry.setTssBankNumName(cus.getTssBankNumName());
        entry.setInsuranceFlag(cus.getInsuranceFlag());
        entry.setLeaseDate(cus.getLeaseDate());
//        entry.setBpName(cus.getBpName());
//        entry.setBpMobile(cus.getBpMobile());
//        if (StringUtil.isNotBlank(cus.getBpIdCard()) && cus.getBpIdCard().equals(entry.getIdCode())) {
//            return "共签人证件号码不能与业主身份证号相同";
//        }
//        entry.setBpIdCard(cus.getBpIdCard());
//        entry.setBpCardFront(cus.getBpCardFront());
//        entry.setBpCardBack(cus.getBpCardBack());
//        entry.setBpFile(cus.getBpFile());
//
//        entry.setIdCardBack(cus.getIdCardBack());
//        entry.setIdCardFront(cus.getIdCardFront());
        //entry.setResidenceBooklet(cus.getResidenceBooklet());
//        entry.setBankCard(cus.getBankCard());
        entry.setProvince(cus.getProvince());
        entry.setCity(cus.getCity());
        entry.setArea(cus.getArea());
        entry.setAddress(cus.getAddress().trim());
        if (CustomerEntryConstants.TYPE_TJ.equals(cus.getType())){
            boolean checkAuth = traderPcdService.checkAuth(entry.getCreateTraderId(), entry.getProvince(), entry.getCity(), entry.getArea());
            if (!checkAuth) {
                throw new IllegalArgumentException("代理商区域暂未授权");
            }
            //TODO 校验项目公司区域  产品是否授权
            boolean b1 = companyDao.checkAuth2(cus.getCompany(), entry.getProvince(), entry.getCity(), entry.getArea());
            if (!b1) {
                throw new IllegalArgumentException("项目公司区域暂未授权");
            }
            if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
                    for(ProjectInfoVo vo:cus.getProjectList()){
                        //TODO 校验产品区域权限  产品是否授权
                        boolean b = projectDao.checkAuth(vo.getProjectId(), entry.getProvince(), entry.getCity(), entry.getArea());
                        if (!b) {
                            throw new IllegalArgumentException(vo.getProjectName()+"产品区域暂未授权");
                        }
                    }
            }else {
                //编辑接口
                //TODO 校验产品区域权限  产品是否授权
                boolean b = projectDao.checkAuth(cus.getProjectId(), entry.getProvince(), entry.getCity(), entry.getArea());
                if (!b) {
                    throw new IllegalArgumentException("产品区域暂未授权");
                }
            }
        }

        entry.setSchemeType(cus.getSchemeType());
        entry.setSchemeTypeId(cus.getSchemeTypeId());
        entry.setSchemeId(cus.getSchemeId());
        entry.setExamineRemarks(null);
//        entry.setDzImgs(cus.getDzImgs());

        entry.setDesignDrawings(cus.getDesignDrawings());
//        entry.setDesignDrawingsName(cus.getDesignDrawingsName());

        if (StringUtil.isNotBlank(cus.getSchemeId())) {
            CrmPlan plan = planDao.get(cus.getSchemeId());
            if (plan != null) {
                entry.setSchemeId(cus.getSchemeId());
                entry.setSchemeName(plan.getName());
            }
        }
        entry.setSchemeType(cus.getSchemeType());
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            if (!CustomerEntryConstants.SCHEME_TYPE_TWO.equals(cus.getSchemeType())) {
                entry.setSchemeRemarks(cus.getSchemeRemarks());
                entryDesignService.setEntryDesign(cus.getAddEntryReqDesignDetails(),cus.getItemList(), entry);
            }
        }else {
            if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(cus.getSchemeType())) {
                entry.setComponentSpec(cus.getComponentSpec());
                entry.setSchemeRemarks(cus.getSchemeRemarks());
                entry.setSchemeId("");
                entry.setSchemeName("");
            } else {
                //标准方案
                entry.setComponentSpec("");
                entry.setSchemeRemarks(cus.getSchemeRemarks());
                entry.setSchemeTypeId(cus.getSchemeTypeId());
                if (StringUtil.isNotBlank(cus.getSchemeTypeId())) {
                    CrmProjectInstallWay way = installDao.get(cus.getSchemeTypeId());
                    if (way != null) {
                        entry.setSchemeTypeName(way.getName());
                    }
                }
                if (StringUtil.isNotBlank(cus.getSchemeId())) {
                    CrmPlan plan = planDao.get(cus.getSchemeId());
                    if (plan != null) {
                        entry.setSchemeName(plan.getName());
                    }
                }
            }
        }

        // 设计容量 组件类型是'组件'的 规格 × 数量
        int designCapacity = 0;
        for (CustomerEntryComponentVo v : cus.getItemList()) {
            if ("3".equals(v.getItemType())) {
                CrmElectricSet crmElectricSet = electricSetDao.get(v.getItemId());
                designCapacity = designCapacity + (v.getNum() * Integer.parseInt(crmElectricSet.getModel()));
            }
        }
        entry.setDesignCapacity(designCapacity);
        // 组件规格
        // 组件类型是'组件'的组件
        List<CustomerEntryComponentVo> zuJianList = cus.getItemList().stream().filter(v -> "3".equals(v.getItemType())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(zuJianList)) {
            List<String> itemIds = zuJianList.stream().map(CustomerEntryComponentVo::getItemId).collect(Collectors.toList());
            List<Record> records = electricSetDao.findByIds(itemIds);
            List<String> specList = records.stream().map(r -> r.getStr("model")).collect(Collectors.toList());
            entry.setComponentSpec(StringUtil.join(specList, ","));
        }
        //逆变器 判断不同规格下的逆变器是否有相同品牌的
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            for(ProjectInfoVo vo : cus.getProjectList()){
                List<CustomerEntryComponentVo> nbqList = cus.getItemList().stream().filter(v -> "1".equals(v.getItemType())&&vo.getProjectId().equals(v.getProjectId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(nbqList) && nbqList.size() > 1) {
                    List<String> itemIds = nbqList.stream().map(CustomerEntryComponentVo::getItemId).collect(Collectors.toList());
                    List<Record> records = electricSetDao.findByIds(itemIds);
                    //获取所有逆变器的规格
                    List<String> specList = records.stream().map(r -> r.getStr("model")).collect(Collectors.toList());
                    List<List<String>> lists = new ArrayList<>();
                    for (String spec : specList) {
                        //获取该规格下所有品牌
                        List<Record> brandList = supplyMaterialDao.findBrandBySpec(spec, "1");
                        List<String> list = brandList.stream().map(r -> r.getStr("material_brand")).collect(Collectors.toList());
                        lists.add(list);
                    }
                    //判断是否有相同品牌的逆变器
                    boolean flag = CrmUtils.containsCommonString(lists);
                    if (!flag){
                        throw new BusinessException(vo.getRoofType()+StringUtil.join(specList,",")+"规格下没有相同品牌的逆变器");
                    }
                }
            }
        }else {
            List<CustomerEntryComponentVo> nbqList = cus.getItemList().stream().filter(v -> "1".equals(v.getItemType())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(nbqList) && nbqList.size() > 1) {
                List<String> itemIds = nbqList.stream().map(CustomerEntryComponentVo::getItemId).collect(Collectors.toList());
                List<Record> records = electricSetDao.findByIds(itemIds);
                //获取所有逆变器的规格
                List<String> specList = records.stream().map(r -> r.getStr("model")).collect(Collectors.toList());
                List<List<String>> lists = new ArrayList<>();
                for (String spec : specList) {
                    //获取该规格下所有品牌
                    List<Record> brandList = supplyMaterialDao.findBrandBySpec(spec, "1");
                    List<String> list = brandList.stream().map(r -> r.getStr("material_brand")).collect(Collectors.toList());
                    lists.add(list);
                }
                //判断是否有相同品牌的逆变器
                boolean flag = CrmUtils.containsCommonString(lists);
                if (!flag){
                    throw new BusinessException(StringUtil.join(specList,",")+"规格下没有相同品牌的逆变器");
                }
            }
        }

        User user = UserUtils.getUser();
        String otherName = "";
        if("4".equals(user.getUserType())){
            otherName =user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();;
        }else if("6".equals(user.getUserType())){
            otherName =user.getUserName();
        }else if("7".equals(user.getUserType())){
            otherName = UserUtils.findName(user);
        }
        entry.setZsFlag(cus.getZsFlag());
        entry.setNodeType(cus.getNodeType());
        entry.setZsAuditRemarks(cus.getZsAuditRemarks());
        if("1".equals(cus.getType())){
            String str="";
            String remarks = cus.getZsAuditRemarks();
            if (StringUtil.isBlank(remarks)){
                remarks = cus.getAuditRemarks();
            }
            //审核备注
            entry.setAuditRemarks(remarks);
            entry.setZsFlag("1");
            str="设计自审通过" + (StringUtil.isBlank(remarks) ? "" : (",审核备注：" + remarks) ) + "；";
            msgService.saveCustomerEntryMsg(operator, cus.getId(), CustomerEntryConstants.DESIGN_SELF_AUDIT_PASS, str+sf.toString(),otherName);
        }

        // 删除原先方案
        composePlanService.deleteComposePlanByEntryId(cus.getId());
        if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(cus.getSchemeType()) && !CollectionUtils.isEmpty(cus.getComposePlanLists())) {
            // 处理组合方案
            entry.setComposePlanLists(cus.getComposePlanLists());
            composePlanService.saveComposePlan(entry, entry.getId());
        } else {
            if (!PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())&&StringUtil.isNotBlank(cus.getSchemeId()) && CustomerEntryConstants.SCHEME_TYPE_ONE.equals(cus.getSchemeType())) {
                CrmPlan plan = planDao.get(cus.getSchemeId());
                if (plan != null) {
                    entry.setSchemeName(plan.getName());
                }
            }
        }
        //set新增字段
        entry.setLatitude(cus.getLatitude());
        entry.setLongitude(cus.getLongitude());
        entry.setZjpbImg(cus.getZjpbImg());
        entry.setZjcsImg(cus.getZjcsImg());
        entry.setZjzxImg(cus.getZjzxImg());
        entry.setZjhsImg(cus.getZjhsImg());
        if(CustomerEntryConstants.TYPE_TJ.equals(cus.getType())){
            // 查询项目信息
//            CrmProjectSetting projectSetting = projectDao.get(entry.getProjectId());
            // 校验必填项
            Result result = null;
            List<Record> checkList = formSetDao.findListByCondition("02", entry.getPartnerId());
            if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
                result = requiredCheckForSurvey(entry, surveyRecord,cus.getAddEntryReqSurveyDetails(),cus.getProjectList(), checkList);
            }else {
                result = requiredCheckForSurvey(entry, surveyRecord, checkList);
            }
            if (!"200".equals(result.getCode())) {
                throw new BusinessException(result.getErrMsg());
            }
            if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())) {
                result = requiredCheckForDesign(entry, cus.getItemList(),cus.getAddEntryReqDesignDetails(),cus.getProjectList(), checkList);
            }else {
                result = requiredCheckForDesign(entry, cus.getItemList(), checkList);
            }
            if (!"200".equals(result.getCode())) {
                throw new IllegalArgumentException(result.getErrMsg());
            }
            entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DSH);
            entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSTG);
            entry.setZsResult("1");
        }
        customerDao.save(entry);
        // 删除原电器组件
        customerEntryComponentService.deleteEntryComponent(cus.getId());
        // 处理电器组件
        List<CustomerEntryComponentVo> itemList = cus.getItemList();
        customerEntryComponentService.saveEntryComponent(itemList, cus.getId(), operator.getUserId());
        if(CustomerEntryConstants.TYPE_TJ.equals(cus.getType())) {
            //判断是否需要设计审核
            if (!FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_SJSH)) {
                toExamine(entry.getId(), entry.getExamineRemarks(), operator, UserUtils.getUser());
            } else {  //需要审计审核，生成一个待审批的任务
                Date date = new Date();
                String stationName = CrmUtils.getStationName(entry);
                ItemManage itemManage = itemManageDao.addItem(FormUtils.ENTRY_STATUS_SJSH, entry.getId(), PlantformUtils.getOrderNumber(), "设计审核(" + stationName + '-' + entry.getPowerStationCode() + ")-" + DateUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss"), date, user.getUserName());
                //大代理商优先审核
                String groupName = "设计审核";
                crmPriorReviewSettingService.traderPriorityReview(entry.getCreateTraderId(),itemManage.getId(),groupName);
                //清空设计审核审核备注
                entry.setExamineRemarks("");
                customerDao.save(entry);
            }
        }
        return "200";
    }

    /**
     * 批量删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(BatchOperateReq req) {
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user), user.getUserType());
        for (String id : req.getIds()) {
            deleteCustomerEntry(id, operator);
        }
    }

    /**
     * 批量提交预审
     */
    @Transactional(rollbackFor = Exception.class)
    public Result batchAdmit(BatchOperateReq req,Operator operator) {
        //校验必填是否为空
        for (String id : req.getIds()) {
            CustomerEntry entry = getById(id);
            Result check = checkForBatchAdmit(entry);
            if (check != null) {
                return check;
            }
        }
        for (String id : req.getIds()) {
            CustomerEntry entry = getById(id);
            try {
                Result deal = dealOneForBatchAdmit(entry);
                if (deal != null) {
                    return deal;
                }
            }catch (Exception e){
                Db.update(" insert into crm_customer_entry_msg (id,customer_entry_id,operator,type,operator_id,content,operate_time) values (?,?,?,?,?,?,?)",
                        IdGen.uuid(),entry.getId(),msgService.findName(operator),CustomerEntryConstants.ENTRY_SUBMIT,operator.getUserId(),"提交预审失败，"+e.getMessage(),new Date());
                throw new IllegalArgumentException(e.getMessage());
            }

        }
        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchAdmitForTask(List<String> list) {
        for (String entryId : list) {
            try {
                CustomerEntry entry = getById(entryId);
                Result check = checkForBatchAdmit(entry);
                if (check != null) {
                    logger.info("id:{}, errMsg:{}", entryId, check.getErrMsg());
                    continue;
                }
                Result deal = dealOneForBatchAdmit(entry);
                if (deal != null) {
                    logger.info("id:{}, errMsg:{}", entryId, deal.getErrMsg());
                }
            }catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }

    }

    public Result checkForBatchAdmit(CustomerEntry entry) {
        if(!entry.getPartnerId().equals("03")){
            if (!"3".equals(entry.getAuthorization()) && "1".equals(entry.getTenantType())) {
                return Result.fail("信息使用授权未通过");
            }
        }else{
            if (!"3".equals(entry.getAuthorization()) && "1".equals(entry.getTenantType())) {
                return Result.fail("信息使用授权未通过");
            }
        }
        if ("4".equals(entry.getCredit())) {
            return Result.fail("已预审通过，请刷新列表");
        }
        // 查询项目信息
        String[] idArr = entry.getProjectId().split(",");
        for(String projectId : idArr){
            CrmProjectSetting projectSetting = projectDao.get(projectId);
            if (projectSetting == null) {
                return Result.fail("电站处于暂存状态不满足预审条件");
            }
        }
        List<Record> list = formSetDao.findListByCondition("01", entry.getPartnerId());
        // 资方校验 必须是越秀资方电站

//        if(!PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId()) ||
//                !PartnerConstants.PARTNER_ID_YX.equals(projectSetting.getManagement())) {
//            return Result.fail("越秀电站才可提交预审");
//        }
        // 查询营业执照
        String regnoUrl = null;
        String creditCertificate = null;
//        if (Objects.equals("2", entry.getTenantType())) {
            CustomerEntryOrgFiles orgFiles = orgFilesDao.findOneByEntryId(entry.getId());
            if(orgFiles != null){
                regnoUrl = orgFiles.getRegnoUrl();
                creditCertificate = orgFiles.getCreditCertificate();
            }
//        }
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entry.getId());
        String houseOwnership = null;
        if (surveyRecord!=null){
            houseOwnership = surveyRecord.getHouseOwnership();
        }
        Result result = requiredCheckForRegisterInfo(entry, regnoUrl, list, "2",creditCertificate,houseOwnership);
        if (!"200".equals(result.getCode())) {
            return result;
        }
        return null;
    }

    public Result dealOneForBatchAdmit(CustomerEntry entry) {
        JSONObject resultJson = null;
        if (PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())) {
            String contractPath = getContractPath(entry.getTenantType(), entry.getIdCode(), entry.getPartnerId(),entry.getFilingType());
            resultJson = admittanceHuarongEntry(entry, contractPath);
        }
        else if (PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())) {
            String houseOwnership = "";
            String regnoUrl = "";
            CustomerEntryOrgFiles orgFiles = orgFilesDao.findOneByEntryId(entry.getId());
            CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entry.getId());
            if(StringUtil.isBlank(regnoUrl) &&
                    orgFiles!=null && StringUtil.isNotBlank(orgFiles.getRegnoUrl())){
                regnoUrl = orgFiles.getRegnoUrl();
            }
            if(StringUtil.isBlank(houseOwnership) &&
                    surveyRecord!=null && StringUtil.isNotBlank(surveyRecord.getHouseOwnership())){
                houseOwnership = surveyRecord.getHouseOwnership();
            }
            resultJson = admittanceGuangFaEntry(entry,houseOwnership,regnoUrl);
            if(resultJson == null){
                return Result.fail("代码内部错误请联系管理员");
            }
        }
        else if (PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())) {
            resultJson = operatingLeaseService.admittanceEntry(entry);
        }
        if ("S".equals(resultJson.get("type"))) {
            SQLQuery sqlQuery = customerDao.getSession()
                    .createSQLQuery("update crm_customer_yx_condition set preaudit='2',tenant_code=:tenantCode where id_code=:idCode and partner_id =:partnerId");
            sqlQuery.setParameter("tenantCode", resultJson.getString("businessKey"));
            sqlQuery.setParameter("idCode", entry.getIdCode());
            sqlQuery.setParameter("partnerId", entry.getPartnerId());
            sqlQuery.executeUpdate();
            entry.setCredit(CustomerEntryConstants.CREDIT_SUBMITTED);
            entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);

            if (PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())) {
                //上传信息使用授权书
                updateAuditFile(entry);
            }
            dealHuaRongAdmittance(entry,resultJson);
        } else if ("E".equals(resultJson.get("type"))) {//失败
            return Result.fail(resultJson.getString("message"));
        } else {
            return Result.fail("请勿重复提交");
        }
        customerDao.save(entry);
        return null;
    }


    @Transactional(rollbackFor = Exception.class)
    public Result submitAudit(String id) {
        CustomerEntry entry = getById(id);
        JSONObject resultJson = null;
        if (PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())) {
            String contractPath = getContractPath(entry.getTenantType(), entry.getIdCode(), entry.getPartnerId(),entry.getFilingType());
            resultJson = admittanceHuarongEntry(entry, contractPath);
        }
        else if (PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())) {
            String houseOwnership = "";
            String regnoUrl = "";
            CustomerEntryOrgFiles orgFiles = orgFilesDao.findOneByEntryId(entry.getId());
            CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entry.getId());
            if(StringUtil.isBlank(regnoUrl) &&
                    orgFiles!=null && StringUtil.isNotBlank(orgFiles.getRegnoUrl())){
                regnoUrl = orgFiles.getRegnoUrl();
            }
            if(StringUtil.isBlank(houseOwnership) &&
                    surveyRecord!=null && StringUtil.isNotBlank(surveyRecord.getHouseOwnership())){
                houseOwnership = surveyRecord.getHouseOwnership();
            }
            resultJson = admittanceGuangFaEntry(entry,houseOwnership,regnoUrl);
            if(resultJson == null){
                return Result.fail("代码内部错误请联系管理员");
            }
            logger.info("resultJson:{}", resultJson);
        }
        else if (PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())) {
            resultJson = operatingLeaseService.admittanceEntry(entry);
        }
        if ("S".equals(resultJson.get("type"))) {
            SQLQuery sqlQuery = customerDao.getSession()
                    .createSQLQuery("update crm_customer_yx_condition set preaudit='2',tenant_code=:tenantCode " +
                            "where id_code=:idCode and partner_id =:partnerId");
            sqlQuery.setParameter("tenantCode", resultJson.getString("businessKey"));
            sqlQuery.setParameter("idCode", entry.getIdCode());
            sqlQuery.setParameter("partnerId", entry.getPartnerId());
            sqlQuery.executeUpdate();
            entry.setCredit(CustomerEntryConstants.CREDIT_SUBMITTED);
            entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);

            if (PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())) {
                //上传信息使用授权书
                updateAuditFile(entry);
            }
            dealHuaRongAdmittance(entry,resultJson);
        } else if ("E".equals(resultJson.get("type"))) {//失败
            return Result.fail(resultJson.getString("message"));
        } else {
            return Result.fail("请勿重复提交");
        }
        customerDao.save(entry);
        return Result.ok();
    }

    // 针对华融单位准入申请接口调用之后直接返回预审结果进行逻辑处理
    public void dealHuaRongAdmittance(CustomerEntry entry, JSONObject resultJson) {
        if (!PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())) {
            return;
        }
        String ysResult = resultJson.getString("huarongYsResult");
        if (StringUtil.isNotBlank(ysResult)) {
            String idCode;
            if ("1".equals(entry.getTenantType())) {
                idCode = entry.getIdCode();
            }
            else {
                idCode = entry.getRegno();
            }
            Map<String, String> resultMap = new HashMap<>();
            switch (ysResult) {
                case "1": // 预审通过
                case "3": // 准入重复 表示之前已预审通过
                    resultMap.put("result", "APPROVED");
                    break;
                case "2": // 预审失败
                    resultMap.put("result", "REJECT");
                    resultMap.put("reason", resultJson.getString("message"));
                    break;
                default:
                    throw new BusinessException(resultJson.getString("message"));
            }
            dealYsQueryData(idCode, entry, "资方-华融", resultMap);
        }
    }

    public JSONObject admittanceGuangFaEntry(CustomerEntry entry,String houseOwnership,String regnoUrl) {
        String partnerId = entry.getPartnerId();
//        CrmCustomerIncomingApplication application = incomingApplicationDao.getIncomingApplication(entry);
        CrmCustomerIncomingApplication application = incomingApplicationDao.getNoDeleteApplication(entry.getId());
        if(application==null){
            application=new CrmCustomerIncomingApplication();
            application.setEntryId(entry.getId());
            String tenantStatus=incomingApplicationDao.getTenantStatus(entry.getCredit());
            application.setTenantStatus(tenantStatus);
            if(StringUtil.isNotBlank(entry.getApplyStatus())){
                application.setStatus(entry.getApplyStatus());
            }
            application.setPartnerId(partnerId);
            application.setApplyTime(new Date());
            Long maxVersion=incomingApplicationDao.getMaxVersion(partnerId);
            String numberQZ = CustomerEntryUtil.getJJPrefix(partnerId);
            logger.info(">>>>>>getIncomingApplication  maxVersion:{}",maxVersion);
            //当资方为广发时，进件序号加上NHGF
            String partnersContractNumber = "";
            partnersContractNumber = CustomerEntryUtil.addZero(numberQZ, maxVersion+1);
            logger.info(">>>>>>getIncomingApplication  partnersContractNumber:{}",partnersContractNumber);
            application.setPartnersContractNumber(partnersContractNumber);
            application.setVersion(maxVersion+1);
        }
        if ("a".equals(application.getStatus())){//终止进件的
            application.setStatus("0");
        }
        //广发的进件编号 由广发自己生成
        String numberQZ = CustomerEntryUtil.getJJPrefix(entry.getPartnerId());
        application.setPartnersContractNumber(numberQZ + DateUtils.getNowDate().getTime() + RandomUtil.getPositiveRandomWithRang(2));
        Map<String,Object> params=new HashMap<>();
        params.put("regno_url",regnoUrl);
        params.put("house_ownership",houseOwnership);
        JSONObject resultJson = null;
        try {
            if(CustomerEntryConstants.TENANT_TYPE_PERSON.equals(entry.getTenantType())) {  //个人
                String contractPath = getContractPath(entry);
                if (StringUtil.isBlank(contractPath)) {
                    throw new IllegalArgumentException("提交失败，信息授权书有问题");
                }
                params.put("contractPath", contractPath);
            }
            resultJson = guangfaOperatingService.capitalPreAudit(entry,params,application);
            String inputPieceId=resultJson.getString("inputPieceId");
            resultJson.put("type","S");

            application.setTenantStatus("20");
            application.setInputPieceId(inputPieceId);
            application.setUpdateTime(new Date());
            application.setPartnerId(entry.getPartnerId());
            yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(),application.getPartnersContractNumber(),"0","提交预审 ",null);
            incomingApplicationDao.save(application);
        } catch (IllegalArgumentException | BusinessException e) {
            throw new IllegalArgumentException(e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return resultJson;
    }

    public JSONObject admittanceHuarongEntry(CustomerEntry entry, String contractPath) {
        if (CustomerEntryConstants.FILING_TYPE_FARMER.equals(entry.getFilingType()) && "1".equals(entry.getTenantType())){
            if (StringUtil.isBlank(contractPath)){
                throw new IllegalArgumentException("信息授权书为空！");
            }
        }
        JSONObject resultJson = huaRongApiService.capitalPreAudit(entry, contractPath);
        logger.info("admittanceHuarongEntry.result:{}", resultJson);
        //客户类型：个人 返回成功结果 {"fileSize":202519,"dsc":"上传成功","status":"1"}
        //客户类型：单位 返回成功结果 {"clientCount":1,"dsc":"上传成功","status":"0"}
        if ("2".equals(entry.getTenantType())) {//单位
            String result = resultJson.getString("status");
            switch (result) {
                case "0":
                    resultJson.put("type","S");
                    resultJson.put("huarongYsResult","1");

                    break;
                case "1":
                    resultJson.put("type", "S");
                    resultJson.put("huarongYsResult","2");
                    resultJson.put("message",  resultJson.getString("dsc"));
                    break;
                case "2":
                    resultJson.put("type", "S");
                    resultJson.put("huarongYsResult","3");
                    resultJson.put("message",  resultJson.getString("dsc"));
                    break;
                default:
                    resultJson.put("type", "F");
                    resultJson.put("message",  resultJson.getString("dsc"));
                    break;
            }
        }
        else {
            Integer code = resultJson.getInteger("code");
            switch (code) {
                case 200:
                    resultJson.put("type","S");
                    break;
                default:
                    resultJson.put("type", "E");
                    resultJson.put("message",  resultJson.getString("dsc"));
                    break;
            }
        }
        return resultJson;
    }

    /**
     * 批量提交审核
     *
     */
    @Transactional(rollbackFor = Exception.class)
    public Result batchAudit(BatchOperateReq req) {
        //校验必填是否为空
        for (String id : req.getIds()) {
            CustomerEntry entry = getById(id);
            CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(id);
            // 查询项目信息
            CrmProjectSetting projectSetting = projectDao.get(entry.getProjectId());
            // 校验必填项
            List<Record> checkList = formSetDao.findListByCondition("02", entry.getPartnerId());
            Result result = requiredCheckForSurvey(entry, surveyRecord, checkList);
            if (!"200".equals(result.getCode())) {
                return result;
            }
        }
        for (String id : req.getIds()) {
            CustomerEntry entry = getById(id);
            audit(entry);
        }
        return Result.ok();
    }

    /**
     * 审核
     * 预审通过且征信结果为【通过】时，方可提交到【设计审核】状态
     */
    public void audit(CustomerEntry entry) {
        if (CustomerEntryConstants.CREDIT_APPROVED.equals(entry.getCredit())) {
            throw new IllegalArgumentException("预审未通过");
        }
        if (!CustomerEntryConstants.PRODUCT_ONE.equals(entry.getProductLine()) && !CustomerEntryConstants.CREDIT_APPROVE.equals(entry.getCredit())) {
            throw new IllegalArgumentException("征信未通过");
        }
        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DSH);
        entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSTG);
        entry.setToExamineStatus("1");
        entry.setToExamineTime(new Date());
        customerDao.save(entry);
        User user = UserUtils.getUser();
        //判断是否需要设计审核
        if (!FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_SJSH)) {
            Operator operator = CrmUtils.getOperatorByTwo(user.getId());
            toExamine(entry.getId(), entry.getExamineRemarks(), operator, user);
        }else{  //需要审计审核，生成一个待审批的任务
            Date date=new Date();
            String stationName = CrmUtils.getStationName(entry);
            itemManageDao.addItem(FormUtils.ENTRY_STATUS_SJSH,entry.getId(),PlantformUtils.getOrderNumber(),"设计审核("+stationName+"-"+entry.getPowerStationCode()+")-"+DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss"),date,user.getUserName());
        }
    }

    public void esalesBasisPage(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        List<Record> list = customerDao.esalesBasisList(page, map, operator);
        for(Record rd:list){
            Record de = customerDao.findAccountByentryId(rd.getStr("id"));
            if(de!= null && de.getBigDecimal("jsCount")!= null && de.getBigDecimal("thCount") != null){
                rd.set("setprice",de.getBigDecimal("jsCount").subtract(de.getBigDecimal("thCount")));

            }

        }


        // InformationEncryption(list,operator.getUserType());
        page.setData(list);

        page.setCount(customerDao.countEsalesBasis(map, operator));
    }



    public List<ComposePlan> findByEntryId(String entryId) {

        return composePlanService.findByEntryId(entryId);
    }

    public Record findByEntrySchemeId(String schemeId){
        return composePlanService.findByEntrySchemeId(schemeId);
    }


    public List<Record> findPlanInfoEntryId(String entryId) {
        return composePlanService.findPlanInfoEntryId(entryId);
    }

    public CrmProjectSetting findrojectSettingById(String id) {
        CrmProjectSetting pro = projectDao.get(id);
        if (pro == null) {
            throw new IllegalArgumentException("当前项目不存在");
        }
        return pro;
    }

    /**
     * 手动进行白名单准入
     */
    public Result shoudongCustomerEntry(String id) {
//        CustomerEntry entry = customerDao.get(id);
//        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(id);
//        // 查询项目信息
//        CrmProjectSetting projectSetting = projectDao.get(entry.getProjectId());
//        // 校验必填项
//        List<Record> checkList = formSetDao.findListByCondition("02", projectSetting.getManagement());
//        //校验必填是否为空
//        Result result = requiredCheckForSurvey(entry, surveyRecord, checkList);
//        if (!"200".equals(result.getCode())) {
//            return result;
//        }
//        operatingLeaseService.admittanceEntry(entry);
//        customerDao.save(entry);
        return Result.ok();
    }


    public Record getCustimerByDisId(String distributor_id) {
        return customerDao.getCustimerByDisId(distributor_id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteCustomerEntry(String id, Operator operator) {
        CustomerEntry entry = customerDao.get(id);
        if (!StringUtil.equalsAny(entry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_ZC,
                CustomerEntryConstants.ENTRY_STATUS_KCZS,CustomerEntryConstants.ENTRY_STATUS_SHBTG,
                CustomerEntryConstants.ENTRY_STATUS_DSH)) {
            throw new IllegalArgumentException("进件之后不可操作删除");
        }
        if (PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){
            if (CustomerEntryConstants.CREDIT_APPROVED.equals(entry.getCredit())){
                throw new IllegalArgumentException("预审通过的电站不能删除，请先终止进件");
            }
        }
        if (CustomerEntryConstants.ENTRY_STATUS_ZC.equals(entry.getStatus()) && CustomerEntryConstants.APPLY_CHANGE_APPROVE.equals(entry.getApplyChange())) {
            //申请整改的数据 不可以删除
            throw new IllegalArgumentException("申请整改数据，不可删除");
        }
        String msg = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(msg)) {
            throw new IllegalArgumentException(msg);
        }

        if (!incomingApplicationDao.checkCanDelete(entry.getId())) {
            throw new IllegalArgumentException("进件中或者进件通过之后不可删除电站，请先取消进件");
        }
        // 预审通过之前 同步删除客户记录和预审记录
        // 预审状态 0.暂存 1.待预审 2.预审待审批 3.预审审批中 4.预审通过 5.预审拒绝
//        if (StringUtil.isNotBlank(entry.getTenantId()) &&
//                !CustomerEntryConstants.CREDIT_APPROVED.equals(entry.getCredit())) {
//            // 校验 电站对应的客户 是否录入其他电站
//            long entryNum = customerDao.countByTenantIdExcludeEntry(entry.getTenantId(), entry.getId());
//            if (entryNum == 0) {
//                // 删除客户信息
//                boolean deleteTFlag = tenantDao.updateToDelete(entry.getTenantId());
//                if (!deleteTFlag) {
//                    throw new IllegalArgumentException("当前操作人员过多，请稍后再试");
//                }
                // 删除预审记录
//                String keyInfo;
//                if ("1".equals(entry.getTenantType())) {
//                    keyInfo = entry.getIdCode();
//                }
//                else {
//                    keyInfo = entry.getRegno();
//                }
//                CrmCustomerYxCondition condition = conditionDao.findCustomerYxCondition(keyInfo,entry.getPartnerId());
//                if (condition != null) {
//                    boolean deleteCFlag = conditionDao.updateToDelete(condition.getId());
//                    if (!deleteCFlag) {
//                        throw new IllegalArgumentException("当前操作人员过多，请稍后再试");
//                    }
//                }
//            }
//        }
        if(StringUtil.isNotBlank(entry.getTenantId())){
            long entryNum = customerDao.countByTenantIdExcludeEntry(entry.getTenantId(), entry.getId());
            if (entryNum == 0) {
                // 删除客户信息
                boolean deleteTFlag = tenantDao.updateToDelete(entry.getTenantId());
//                if (!deleteTFlag) {
//                    throw new IllegalArgumentException("当前操作人员过多，请稍后再试");
//                }
                // 删除未授权的预审记录
                String keyInfo;
                if ("1".equals(entry.getTenantType())) {
                    keyInfo = entry.getIdCode();
                }
                else {
                    keyInfo = entry.getRegno();
                }
                CrmCustomerYxCondition condition = conditionDao.findCustomerYxCondition(keyInfo,entry.getPartnerId());
                if (condition != null && !"3".equals(condition.getAuthorization())) {
                    boolean deleteCFlag = conditionDao.updateToDelete(condition.getId());
                    if (!deleteCFlag) {
                        throw new IllegalArgumentException("当前操作人员过多，请稍后再试");
                    }
                }
            }
        }
        // 删除： 电站改为已删除，进件记录改为已删除
        SQLQuery sqlQuery = customerDao.getSession().createSQLQuery("update crm_customer_entry set status='b' where id = :id  ");
        sqlQuery.setParameter("id", id);
        int cou = sqlQuery.executeUpdate();
        if (cou < 1) {
            throw new IllegalArgumentException("当前操作人员过多，请稍后再试");
        }
        //删除未完成的待办事项
        Db.update(" update  crm_item_manage set status = '0'  where form_key>90 and status = '1' and  application_id =  ? ", id);
        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_DELETE);
        incomingApplicationDao.updateToDelete(entry.getId());
    }

    /**
     * 设计审核通过 status 变更为3（待下单）
     */
    @Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
    public void toExamine(String id, String examineRemarks, Operator operator, User user) {

        CustomerEntry entry = customerDao.get(id);
        if (!CustomerEntryConstants.ENTRY_STATUS_DSH.equals(entry.getStatus())) {
            throw new IllegalArgumentException("当前状态发生改变，不可操作");
        }
        if (StringUtil.equalsAny(entry.getDesignAuditFlag(), CustomerEntryConstants.DESIGN_AUDIT_FLAG_SJSHTG,
                CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHZ)) {
            throw new IllegalArgumentException("已提交审核结果，请刷新列表");
        }
        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            throw new IllegalArgumentException(checkApplyResult);
        }

        String otherMsg = user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();
        String msg="设计审核同意；"+(StringUtil.isBlank(examineRemarks)?"": examineRemarks);

        // 设计审核通过 进入进件中
//        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DXD);
        entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_SJSHTG);
        examineService.updateToExamine(entry.getId(),ExamineConstants.TWO,msg,operator.getUserName());

        entry.setExamine(operator.getUserId());
        entry.setExamineName(operator.getUserName());
        entry.setExamineRemarks(examineRemarks);
        entry.setExamineTime(new Date());
        entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_SJSHTG);
        CustomerEntryOrgFiles orgFiles = orgFilesDao.get(entry.getId());
        String firstApplyStatus = entry.getFirstApplyStatus();
        //历史电站标记：0.否 1.是
        boolean hisFlag = true;
        if ("1".equals(entry.getIsHistory()) && PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){
            hisFlag = false;
        }
        if(FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZFSH) && hisFlag) {
            if ((PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())&&!"APPROVING".equals(firstApplyStatus) && !"APPROVED".equals(firstApplyStatus) && !"CLOSED".equals(firstApplyStatus))
                ||(PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())&&!"20".equals(firstApplyStatus) &&  !"30".equals(firstApplyStatus)&& !"60".equals(firstApplyStatus))
                ||(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId()) &&  !"FR".equals(firstApplyStatus)  && !"FT".equals(firstApplyStatus))
               ) {
                CrmTenantYxBankCard card = tenantYxBankCardDao.getByIdCard(entry.getIdCode(), entry.getManagementType(),entry.getPartnerId());
                //先判断档案审核是否通过了
                if (orgFiles != null && "3".equals(orgFiles.getStatus())) {
                    Result result = null;
                    if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId()) && "FS".equals(firstApplyStatus) ){
                        //华融建档待补充资料
                        CrmCustomerIncomingApplication application = applicationDao.getByEntryId(entry.getId());
                        List<HuaRongStatusFormVo> HuaRongStatusFormVos = huaRongApiService.queryRongStatus(PartnerConstants.PARTNER_ID_HR, application.getPartnersContractNumber());
                        HuaRongCustomer customer = HuaRongStatusFormVos.get(0).getCustomerList().get(0);
                        String fileCode = customer.getFileCode().replace(";", ",");
                        result = updateHRFiles(entry,application,operator,fileCode);
                    }else {
                        result = accessProjectApply(entry, card, operator,null);
                    }
                    if (!"200".equals(result.getCode())) {
                        throw new IllegalArgumentException("进件请求失败；" + result.getErrMsg());
                    }
                    entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHZ);
                }
            }
        }else {
            if (orgFiles != null && "3".equals(orgFiles.getStatus())) {
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DAZ);
                entry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_DPG);
                entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_SJSHTG);
            }
            entry.setFirstApplyStatus("APPROVED");
            if (PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
                entry.setFirstApplyStatus("FT");
            }
            if (PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){
                entry.setFirstApplyStatus("30");
            }
//                        entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_JJTG);
            entry.setApplyStatus(null);
        }
        customerDao.save(entry);

        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.DESIGN_AUDIT_PASS,msg,otherMsg);
        //生成审核通过的task
        Date date=new Date();
        ItemManage itemManage= itemManageDao.getItemManagementByEntryId(entry.getId(),FormUtils.ENTRY_STATUS_SJSH);
        if (itemManage != null) {
            itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_STATUS_SJSH, entry.getId(), itemManage.getProcessInstanceId(), itemManage.getProcessInstanceId(), ItemConstants.RESULT_OK, date, operator, "设计审核");
            itemManage.setStatus(ItemConstants.ITEM_STATUS_FINISH);
            itemManage.setEndTime(date);
            itemManageDao.save(itemManage);
            reviewDispatchDao.markDispatchFinish(itemManage);
        }
    }

    public CrmPlanMaterialEntry addCrmPlanMaterialEntry(Record rd, String entryId) {
        CrmPlanMaterialEntry en = new CrmPlanMaterialEntry();
        en.setAmount(rd.getInt("amount") != null ? rd.getInt("amount") : 1);
        en.setPlanId(rd.getStr("plan_id"));
        en.setCode(rd.getStr("code"));
        en.setName(rd.getStr("name"));
        en.setSpec(StringUtil.isNotBlank(rd.getStr("spec")) ? rd.getStr("spec") : rd.getStr("model"));
        en.setUnit(rd.getStr("unit"));
        en.setSort(rd.getInt("sort"));
        en.setEntryId(entryId);
        return en;
    }

    /**
     * 设计审核 审核不通过
     */
    @Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
    public void failedCustomerEntry(String id, String remarks, Operator operator, User user) {
        CustomerEntry entry = customerDao.get(id);

        if (!CustomerEntryConstants.ENTRY_STATUS_DSH.equals(entry.getStatus())) {
            throw new IllegalArgumentException("当前状态发生改变，不可删除");
        }

        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), id);
        if (StringUtil.isNotBlank(checkApplyResult)) {
            throw new IllegalArgumentException(checkApplyResult);
        }
        String msg = "设计审核，驳回" + (StringUtil.isBlank(remarks) ? "" : "；" + remarks);


        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_SHBTG);
        entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
        examineService.updateToExamine(entry.getId(),ExamineConstants.ONE,msg,operator.getUserName());
        entry.setExamine(operator.getUserId());
        entry.setZsResult("4");
        entry.setExamineName(operator.getUserName());
        entry.setExamineRemarks(remarks);
        entry.setExamineTime(new Date());
        if (!FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_SJZS)) { //不需要自审
            entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_ZC);
            entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSBH);
        }
        customerDao.save(entry);

        msgService.saveCustomerEntryMsg(user, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_FAILEDS, msg);

        ItemManage itemManage= itemManageDao.getItemManagementByEntryId(entry.getId(),FormUtils.ENTRY_STATUS_SJSH);
        if (itemManage != null) {
            Date date=new Date();
            itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_STATUS_SJSH, entry.getId(), itemManage.getProcessInstanceId(), itemManage.getProcessInstanceId(), ItemConstants.RESULT_BACK, date, operator, "设计审核");
            itemManage.setStatus(ItemConstants.ITEM_STATUS_FINISH);
            itemManage.setEndTime(date);
            itemManageDao.save(itemManage);
            reviewDispatchDao.markDispatchFinish(itemManage);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void gdtToExamine(String id, String remarks, Operator operator,String type) {
        CustomerEntry entry = customerDao.get(id);


        if(StringUtil.isNotBlank(remarks)){
            entry.setExamineRemarks(entry.getExamineRemarks()+remarks);
        }
        User user = UserUtils.getUser();
        String name = user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();
        if("1".equals(type)){
            //审核通过
            remarks ="  同意；"+ remarks;
            entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DXD);
            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_FIX_ACCEPT_PASSTG,remarks,name);
        }else{
            remarks ="  驳回；"+ remarks;
//            entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_GWSH_NOT);
            entry.setToExamineStatus("1");
            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_FIX_ACCEPT_PASSTG,remarks,name);
        }

        examineService.updateToExamine(entry.getId(),ExamineConstants.THREE,remarks,operator.getUserName());
        customerDao.save(entry);
    }


    /**
     * 申请重审
     */
    public void saveRetrial(String ids, String applyReasonId, String applyReasonName, Operator operator) {

        for (String id : ids.split(",")) {
            CustomerEntry entry = customerDao.get(id);
         /*   if (!CustomerEntryConstants.ADVANCE_STATUS_ONE.equals(entry.getRetrial())) {
                throw new IllegalArgumentException("当前状态发生改变，不可删除");
            }*/
            entry.setRetrial(CustomerEntryConstants.RETRIAL_YES);
            entry.setApplyReasonId(applyReasonId);
            entry.setApplyReasonName(applyReasonName);
            entry.setApplyTime(new Date());
            customerDao.save(entry);

            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_SQCS);
        }
    }

    /**
     * 申请整改
     */
    @Transactional(rollbackFor = Exception.class)
    public Result saveApplyChange(String ids, String applyReasonName, String rectificationId, Operator operator) {
        // 校验变更类型
        Record record = rectificationSettingService.getOneById(rectificationId);
        if (record == null) {
            throw new IllegalArgumentException("申请失败，未查询到变更类型");
        }
        int status = Integer.parseInt(record.getStr("status"));
        Date now = new Date();
        for (String id : ids.split(",")) {
            CustomerEntry entry = customerDao.get(id);
            //判断电站结算明细 是否已请款  已请款不可操作整改
            if(checkIfCashOut(id)){
                throw new IllegalArgumentException("变更失败，电站编码为：" + entry.getPowerStationCode() + " 已请款，不可操作整改！");
            }
            String entryStatus = entry.getStatus();
            int verifyStatus = verifyStatus(entryStatus);
            if (status >= verifyStatus) {
                throw new IllegalArgumentException("变更失败，电站编码为：" + entry.getPowerStationCode() + "只能变更到当前电站状态之前");
            }
            entry.setApplyChange(CustomerEntryConstants.APPLY_CHANGE_YES);
            entry.setRectificationSetId(rectificationId);
            entry.setChangeReason(applyReasonName);
            entry.setChangeTime(now);
            customerDao.save(entry);
            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_SQBG, applyReasonName,operator.getUserName());
        }
        return Result.ok();
    }

    /**
     * 获取电站状态对应的变更状态
     */
    private int verifyStatus(String entryStatus) {
        int verifyStatus;
        switch (entryStatus) {
            case CustomerEntryConstants.ENTRY_STATUS_ZC:
            case CustomerEntryConstants.ENTRY_STATUS_KCZS:
                verifyStatus = 0;
                break;
            case CustomerEntryConstants.ENTRY_STATUS_DSH:
            case CustomerEntryConstants.ENTRY_STATUS_DXD:
            case CustomerEntryConstants.ENTRY_STATUS_SHBTG:
                verifyStatus = 1;
                break;
            case CustomerEntryConstants.ENTRY_STATUS_DAZ:
            case CustomerEntryConstants.ENTRY_STATUS_AZZS:
                verifyStatus = 2;
                break;
            case CustomerEntryConstants.ENTRY_STATUS_DAZYS:
            case CustomerEntryConstants.ENTRY_STATUS_AZYSTH:
                verifyStatus = 3;
                break;
            case CustomerEntryConstants.ENTRY_STATUS_DBW:
                verifyStatus = 4;
                break;
            case CustomerEntryConstants.ENTRY_STATUS_DSCFP:
                verifyStatus = 5;
                break;
            case CustomerEntryConstants.ENTRY_STATUS_DQS:
            case CustomerEntryConstants.ENTRY_STATUS_YSBH:
                verifyStatus = 6;
                break;
            case CustomerEntryConstants.ENTRY_STATUS_DYS:
                verifyStatus = 7;
                break;
            case CustomerEntryConstants.ENTRY_STATUS_YWC:
                verifyStatus = 8;
                break;
            default:
                verifyStatus = 9;
        }
        return verifyStatus;
    }

    public boolean checkIfCashOut(String id){
        Long count=customerDao.checkIfCashOut(id);
        return count>0? true:false;
    }

    /**
     * 获取电站变更后对应状态
     */
    private String reverseVerifyStatus(String status) {
        String entryStatus;
        switch (status) {
            case RectificationSetConstants.STATUS_ZC:
                entryStatus = CustomerEntryConstants.ENTRY_STATUS_ZC;
                break;
            case RectificationSetConstants.STATUS_SJSH:
                entryStatus = CustomerEntryConstants.ENTRY_STATUS_DSH;
                break;
            case RectificationSetConstants.STATUS_DAZ:
                entryStatus = CustomerEntryConstants.ENTRY_STATUS_DAZ;
                break;
            case RectificationSetConstants.STATUS_DAZYS:
                entryStatus = CustomerEntryConstants.ENTRY_STATUS_DAZYS;
                break;
            case RectificationSetConstants.STATUS_DBW:
                entryStatus = CustomerEntryConstants.ENTRY_STATUS_DBW;
                break;
            case RectificationSetConstants.STATUS_DSCFP:
                entryStatus = CustomerEntryConstants.ENTRY_STATUS_DSCFP;
                break;
            case RectificationSetConstants.STATUS_DQSHT:
                entryStatus = CustomerEntryConstants.ENTRY_STATUS_DQS;
                break;
            case RectificationSetConstants.STATUS_DBWYS:
                entryStatus = CustomerEntryConstants.ENTRY_STATUS_DYS;
                break;
            default:
                entryStatus = "";
        }
        return entryStatus;
    }

    /**
     * 审核申请重审
     */
    public void examineRetrial(String id, Operator operator, String type, String examineRemarks, String objType) {


        CustomerEntry entry = customerDao.get(id);

        String otherMsg = "";
        if (StringUtil.isNotBlank(examineRemarks)) {
            otherMsg = examineRemarks;
        }
        User user= UserUtils.getUser();
        String otherName = user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();
        if ("1".equals(objType)) {
            if (!CustomerEntryConstants.ADVANCE_STATUS_TWO.equals(entry.getRetrial())) {
                throw new IllegalArgumentException("当前状态发生改变，不可审核");
            }
            //审核重审
            if ("1".equals(type)) {
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_ZC);
                entry.setRetrial(CustomerEntryConstants.RETRIAL_APPROVE);
                entry.setCheckAcceptImgs("");
                msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_SHSQCHTG, otherMsg,otherName);
            } else {
                //审核不通过
                entry.setRetrial(CustomerEntryConstants.RETRIAL_FAIL);
                msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_SHSQCHBTG, otherMsg,otherName);
            }
        }

        customerDao.save(entry);

    }
    /**
     * 变更申请通过
     */
    @Transactional(rollbackFor = Exception.class)
    public Result approved(String id, Operator operator, String rectificationId, String auditComments) {
        // 查询项目信息
        CustomerEntry entry = customerDao.get(id);

        // 变更类型信息
        Record record = rectificationSettingService.getOneById(rectificationId);
        if (record == null) {
            return Result.fail("审核失败，未查询到变更类型");
        }
        // 校验状态
        if (entry == null) {
            return Result.fail("未查询到项目信息");
        } else if (!CustomerEntryConstants.APPLY_CHANGE_YES.equals(entry.getApplyChange())) {
            throw new IllegalArgumentException("当前状态发生改变，不可审核");
        } else if (!entry.getRectificationSetId().equals(rectificationId)) {
            int status = Integer.parseInt(record.getStr("status"));
            int verifyStatus = verifyStatus(entry.getStatus());
            if (status >= verifyStatus) {
                throw new IllegalArgumentException("变更失败，只能变更到当前电站状态之前");
            }
        }
        User user= UserUtils.getUser();
        String otherName = user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();
        String otherMsg = "";
        if (StringUtil.isNotBlank(auditComments)) {
            otherMsg =  auditComments;
        }

        // 获取变更类型对应的电站状态
        String entryStatus = reverseVerifyStatus(record.getStr("status"));
        if (StringUtil.isBlank(entryStatus)) {
            return Result.fail("变更失败，未查询到变更类型对应的电站状态");
        }

        Date now = new Date();

        // 处理变更逻辑
        // 1.获取电站变更前状态对应的变更类型，转化 待安装、待安装验收、已完成 对应的变更类型
        int beforeStatus = verifyStatus(entry.getStatus());//整改前状态-电站当前状态
        int TobeInstalledAndAcceptedStatus = verifyStatus(CustomerEntryConstants.ENTRY_STATUS_DAZYS);//待安装验收
        int CompletedStatus = verifyStatus(CustomerEntryConstants.ENTRY_STATUS_YWC);//已完成
        int afterStatus = verifyStatus(entryStatus);//整改后状态
        // 2.判断是否要生成 电站整改结算记录
        // 2.1 整改前状态在【待安装验收（不含）】与【已完成（不含）】之间时，且整改后状态在【待安装验收（含）】之前时，需要生成类型为“电站整改”（减法）的结算记录r
        CrmTraderAccountSettleDetail settleDetailYJS=null;
        CrmTraderAccountSettleDetail settleDetailJS = null;
        CrmTraderAccountSettleDetail settleDetailZBJ = null;
        CrmTraderAccountSettleDetail settleDetailCfN = null;
        if (beforeStatus > TobeInstalledAndAcceptedStatus
                && beforeStatus < CompletedStatus
                && afterStatus <= TobeInstalledAndAcceptedStatus) {
            // 查询 预结算记录
            CrmTraderAccountSettleDetail settleDetail = accountSettleDetailDao.findOneByCondition(entry.getDistributorId(),
                    TraderAccountSettleDetailConstants.OBJ_TYPE_DJS, TraderAccountSettleDetailConstants.TYPE_YJS,entry.getId());

            //查询 是否有惩罚记录
            CrmTraderAccountSettleDetail settleDetailCf = accountSettleDetailDao.findOneByCondition(entry.getDistributorId(),
                    TraderAccountSettleDetailConstants.OBJ_TYPE_DJS, TraderAccountSettleDetailConstants.TYPE_PUNISH,entry.getId());
            // 查询账户信息
            CrmTraderAccount traderAccount = accountDao.findByTraderId(entry.getDistributorId());
            if (settleDetail != null) {
                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(), operator.getUserId(), now);

                // 改变账户 预结算金额
                traderAccount.setSettleAmount(traderAccount.getSettleAmount().subtract(settleDetail.getAmount()));
                traderAccount.setSettleAmountYsjs(traderAccount.getSettleAmountYsjs().subtract(settleDetail.getAmount()));
            }
            if(settleDetailCf!=null){
                //判断是否请款了，未请款  直接置为无效， 若已请款，则生成一条原记录的红冲记录
                BigDecimal cFAmount=settleDetailCfN.getAmount().negate();
                if(TraderAccountSettleDetailConstants.FLAG_CAN_CASH_OUT.equals(settleDetailCf.getFlag())){ //未请款
                    settleDetailCf.setFlag(TraderAccountSettleDetailConstants.FLAG_SX);
                    accountSettleDetailDao.save(settleDetailCf);
                }else if(TraderAccountSettleDetailConstants.FLAG_DJ.equals(settleDetailCf.getFlag())){  //已请款
                    settleDetailCfN= accountSettleDetailDao.createOne(settleDetailCfN.getEntryId(), settleDetailCfN.getPowerStationCode(),
                            settleDetailCfN.getTraderId(), settleDetailCfN.getTraderName(), TraderAccountSettleDetailConstants.FLAG_CAN_CASH_OUT, settleDetailCf.getObjType(),
                            TraderAccountSettleDetailConstants.TYPE_DZZG, cFAmount, entry.getRoofType(), entry.getSchemeType(),
                            entry.getSchemeTypeId(), entry.getSchemeTypeName(), entry.getTenantName(), entry.getMobile(),
                            entry.getProjectCode(), entry.getProjectName(),settleDetailCfN.getUnitPrice(),settleDetailCfN.getCapacity(), operator.getUserId(), now);
                }
                traderAccount.setSettleAmount(traderAccount.getSettleAmount().add(cFAmount));
                traderAccount.setSettleRewardsPunishAmount(traderAccount.getSettleRewardsPunishAmount().add(cFAmount));
            }
            accountDao.save(traderAccount);
        } else if (beforeStatus == CompletedStatus) {
            // 2.2 整改前状态在【已完成】时，根据需要最多生成三笔电站整改结算记录，用于平衡之前的电站产生的预结算金额、并网结算金额、质保金结算金额
            // 查询账户信息
            CrmTraderAccount traderAccount = accountDao.findByTraderId(entry.getDistributorId());
            if (afterStatus <= TobeInstalledAndAcceptedStatus) {
                // 查询 预结算记录
                CrmTraderAccountSettleDetail yjsSettleDetail = accountSettleDetailDao.findOneByCondition(entry.getDistributorId(),
                        TraderAccountSettleDetailConstants.OBJ_TYPE_DJS, TraderAccountSettleDetailConstants.TYPE_YJS,entry.getId());
//            BigDecimal mxAmount=BigDecimal.ZERO;
                if (yjsSettleDetail != null) {
                    settleDetailYJS = accountSettleDetailDao.createOne(yjsSettleDetail.getEntryId(), yjsSettleDetail.getPowerStationCode(),
                            yjsSettleDetail.getTraderId(), yjsSettleDetail.getTraderName(), yjsSettleDetail.getFlag(), yjsSettleDetail.getObjType(),
                            TraderAccountSettleDetailConstants.TYPE_DZZG, yjsSettleDetail.getAmount().negate(), yjsSettleDetail.getRoofType(), yjsSettleDetail.getSchemeType(),
                            yjsSettleDetail.getSchemeTypeId(), yjsSettleDetail.getSchemeTypeName(), yjsSettleDetail.getTenantName(), yjsSettleDetail.getMobile(),
                            yjsSettleDetail.getProjectCode(), yjsSettleDetail.getProjectName(),yjsSettleDetail.getUnitPrice(),yjsSettleDetail.getCapacity() ,operator.getUserId(), now);

                    // 改变账户 预结算金额
                    traderAccount.setSettleAmount(traderAccount.getSettleAmount().subtract(yjsSettleDetail.getAmount()));
                    traderAccount.setSettleAmountYsjs(traderAccount.getSettleAmountYsjs().subtract(yjsSettleDetail.getAmount()));
//                mxAmount=mxAmount.add(yjsSettleDetail.getAmount());
                }
            }

            // 查询 并网结算记录
            CrmTraderAccountSettleDetail fbbwjsSettleDetail = accountSettleDetailDao.findOneByCondition(entry.getDistributorId(),
                    TraderAccountSettleDetailConstants.OBJ_TYPE_DJS, TraderAccountSettleDetailConstants.TYPE_FBBWJS,entry.getId());
            if (fbbwjsSettleDetail != null) {
                settleDetailJS = accountSettleDetailDao.createOne(fbbwjsSettleDetail.getEntryId(), fbbwjsSettleDetail.getPowerStationCode(),
                        fbbwjsSettleDetail.getTraderId(), fbbwjsSettleDetail.getTraderName(), fbbwjsSettleDetail.getFlag(), fbbwjsSettleDetail.getObjType(),
                        TraderAccountSettleDetailConstants.TYPE_DZZG, fbbwjsSettleDetail.getAmount().negate(), fbbwjsSettleDetail.getRoofType(),
                        fbbwjsSettleDetail.getSchemeType(), fbbwjsSettleDetail.getSchemeTypeId(), fbbwjsSettleDetail.getSchemeTypeName(),
                        fbbwjsSettleDetail.getTenantName(), fbbwjsSettleDetail.getMobile(), fbbwjsSettleDetail.getProjectCode(), fbbwjsSettleDetail.getProjectName(),
                        fbbwjsSettleDetail.getUnitPrice(),fbbwjsSettleDetail.getCapacity(),operator.getUserId(), now);


                // 改变账户 并网结算金额
                traderAccount.setSettleAmount(traderAccount.getSettleAmount().subtract(fbbwjsSettleDetail.getAmount()));
                traderAccount.setSettleAmountYsjs(traderAccount.getSettleAmountYsjs().subtract(fbbwjsSettleDetail.getAmount()));
            }

            // 查询 质保金记录
            CrmTraderAccountSettleDetail zbjSettleDetail = accountSettleDetailDao.findOneByCondition(entry.getDistributorId(),
                    TraderAccountSettleDetailConstants.OBJ_TYPE_ZBJ, TraderAccountSettleDetailConstants.TYPE_ZBJ,entry.getId());
            if (zbjSettleDetail != null) {
                settleDetailZBJ = accountSettleDetailDao.createOne(zbjSettleDetail.getEntryId(), zbjSettleDetail.getPowerStationCode(),
                        zbjSettleDetail.getTraderId(), zbjSettleDetail.getTraderName(), zbjSettleDetail.getFlag(), zbjSettleDetail.getObjType(),
                        TraderAccountSettleDetailConstants.TYPE_DZZG, zbjSettleDetail.getAmount().negate(), zbjSettleDetail.getRoofType(), zbjSettleDetail.getSchemeType(),
                        zbjSettleDetail.getSchemeTypeId(), zbjSettleDetail.getSchemeTypeName(), zbjSettleDetail.getTenantName(), zbjSettleDetail.getMobile(),
                        zbjSettleDetail.getProjectCode(), zbjSettleDetail.getProjectName(),zbjSettleDetail.getUnitPrice(),zbjSettleDetail.getCapacity(), operator.getUserId(), now);


                // 改变账户 质保金金额
                traderAccount.setQaAmount(traderAccount.getQaAmount().subtract(zbjSettleDetail.getAmount()));
                if (TraderAccountSettleDetailConstants.FLAG_DJ.equals(zbjSettleDetail.getFlag())) {
                    traderAccount.setQaAmountFreeze(traderAccount.getQaAmountFreeze().subtract(zbjSettleDetail.getAmount()));
                } else {
                    traderAccount.setQaAmountUsable(traderAccount.getQaAmountUsable().subtract(zbjSettleDetail.getAmount()));
                }

            }
            //查询 是否有惩罚记录
            CrmTraderAccountSettleDetail settleDetailCf = accountSettleDetailDao.findOneByCondition(entry.getDistributorId(),
                    TraderAccountSettleDetailConstants.OBJ_TYPE_DJS, TraderAccountSettleDetailConstants.TYPE_PUNISH,entry.getId());

            if(settleDetailCf!=null){
                //判断是否请款了，未请款  直接置为无效， 若已请款，则生成一条原记录的红冲记录
                BigDecimal cFAmount=settleDetailCfN.getAmount().negate();
                if(TraderAccountSettleDetailConstants.FLAG_CAN_CASH_OUT.equals(settleDetailCf.getFlag())){ //未请款
                    settleDetailCf.setFlag(TraderAccountSettleDetailConstants.FLAG_SX);
                    accountSettleDetailDao.save(settleDetailCf);
                }else if(TraderAccountSettleDetailConstants.FLAG_DJ.equals(settleDetailCf.getFlag())){  //已请款
                    settleDetailCfN= accountSettleDetailDao.createOne(settleDetailCfN.getEntryId(), settleDetailCfN.getPowerStationCode(),
                            settleDetailCfN.getTraderId(), settleDetailCfN.getTraderName(), TraderAccountSettleDetailConstants.FLAG_CAN_CASH_OUT, settleDetailCf.getObjType(),
                            TraderAccountSettleDetailConstants.TYPE_DZZG, cFAmount, entry.getRoofType(), entry.getSchemeType(),
                            entry.getSchemeTypeId(), entry.getSchemeTypeName(), entry.getTenantName(), entry.getMobile(),
                            entry.getProjectCode(), entry.getProjectName(),settleDetailCfN.getUnitPrice(),settleDetailCfN.getCapacity(), operator.getUserId(), now);
                }
                traderAccount.setSettleAmount(traderAccount.getSettleAmount().add(cFAmount));
                traderAccount.setSettleRewardsPunishAmount(traderAccount.getSettleRewardsPunishAmount().add(cFAmount));
            }
            accountDao.save(traderAccount);
        }

        // 审核通过
        entry.setStatus(entryStatus);
        // 处理整改之后分级状态 当前只有待安装及之后状态才可整改
        switch (entryStatus) {
            case CustomerEntryConstants.ENTRY_STATUS_ZC: // 暂存
                entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
                entry.setInstallFlag(CustomerEntryConstants.FLAG_INIT);
                entry.setCheckAcceptFlag(CustomerEntryConstants.FLAG_INIT);
                entry.setMergeFlag(CustomerEntryConstants.FLAG_INIT);
                break;
            case CustomerEntryConstants.ENTRY_STATUS_DSH:// 待设计审核
                entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSTG);
                entry.setInstallFlag(CustomerEntryConstants.FLAG_INIT);
                entry.setCheckAcceptFlag(CustomerEntryConstants.FLAG_INIT);
                entry.setMergeFlag(CustomerEntryConstants.FLAG_INIT);
                break;
            case CustomerEntryConstants.ENTRY_STATUS_DAZ:// 待安装
                if ("0".equals(entry.getDispatchStatus())) {
                    entry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_DPG);
                }
                else {
                    entry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_DAZ);
                }
                entry.setCheckAcceptFlag(CustomerEntryConstants.FLAG_INIT);
                entry.setMergeFlag(CustomerEntryConstants.FLAG_INIT);
                break;
            case CustomerEntryConstants.ENTRY_STATUS_DAZYS:// 待安装验收
                entry.setCheckAcceptFlag(CustomerEntryConstants.CHECK_ACCEPT_FLAG_ZSTG);
                entry.setMergeFlag(CustomerEntryConstants.FLAG_INIT);
                break;
            case CustomerEntryConstants.ENTRY_STATUS_DBW:// 待并网
                entry.setMergeFlag(CustomerEntryConstants.FLAG_INIT);
                break;
            case CustomerEntryConstants.ENTRY_STATUS_DYS:// 待并网验收
                entry.setMergeFlag(CustomerEntryConstants.MERGE_FLAG_DBW);
                break;

        }
        if ("1".equals(entryStatus)) {
            entry.setToExamineStatus("1");
        } else if ("5".equals(entryStatus)) {
            entry.setToExamineStatus("3");
        } else if ("7".equals(entryStatus)) {
            entry.setToExamineStatus("5");
        }
        entry.setApplyChange(CustomerEntryConstants.APPLY_CHANGE_APPROVE);
        if (StringUtil.isNotBlank(auditComments)) {
            entry.setAuditComments(auditComments);
        }

        // 添加记录
        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_TWENTY, otherMsg, otherName);

        // 变更状态到赊销下单及之前 ，那么要重新签约
        if (afterStatus <= verifyStatus(CustomerEntryConstants.ENTRY_STATUS_DXD)) {
            //那么要重新签合同
            entry.setSignStatus(CustomerEntryConstants.SIGN_STATUS_UNSTART);
        }
        // 保存更新
        customerDao.save(entry);
        //将预结算明细推入金蝶  待结算账户的
        CrmTrader trader = traderDao.get(entry.getDistributorId());
        if (settleDetailYJS != null) {
            logger.info(">>>>>>>>>>>>approved settleDetailNumber1:{},objType1:{},amount1:{}",settleDetailYJS.getNumber(),settleDetailYJS.getObjType(),settleDetailYJS.getAmount());
            //保存预结算明细
            accountSettleDetailDao.save(settleDetailYJS);
        }
        if(settleDetailJS!=null){
            //保存结算明细
            accountSettleDetailDao.save(settleDetailJS);
        }
        if (settleDetailZBJ != null) {

            accountSettleDetailDao.save(settleDetailZBJ);
        }
        if(settleDetailCfN !=null){
            accountSettleDetailDao.save(settleDetailCfN);
        }

        // 变更状态到待下单之前，删除电站物料清单中状态为 "1"(已删除) 的记录
        if (afterStatus < verifyStatus(CustomerEntryConstants.ENTRY_STATUS_DXD)) {
            customerEntryComponentService.deleteComponentByEntryId(entry.getId());
        }
        return Result.ok();
    }

    /**
     * 变更申请不通过
     */
    @Transactional(rollbackFor = Exception.class)
    public Result auditFailed(String id, Operator operator, String auditComments) {
        // 查询项目信息
        CustomerEntry entry = customerDao.get(id);

        // 校验状态和数据
        if (entry == null) {
            return Result.fail("未查询到项目信息");
        } else if (!CustomerEntryConstants.APPLY_CHANGE_YES.equals(entry.getApplyChange())) {
            return Result.fail("当前状态发生改变，不可审核");
        } else if (StringUtil.isBlank(auditComments)) {
            return Result.fail("备注不能为空");
        }

        String otherMsg = "";
        if (StringUtil.isNotBlank(auditComments)) {
            otherMsg = auditComments;
        }
        User user= UserUtils.getUser();
        String otherName = user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();
        // 审核不通过
        entry.setApplyChange(CustomerEntryConstants.APPLY_CHANGE_FAIL);
        entry.setAuditComments(auditComments);

        // 添加记录
        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_TWENTY_ONE, otherMsg,otherName);

        // 保存更新
        customerDao.save(entry);
        return Result.ok();
    }



    public void listWaitOrder(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        List<Record> list = customerDao.selectWaitOrders(page, map, operator);
        if("all".equals(map.get("entryPage"))) {  //电站档案列表
            for (Record r : list) {
                CustomerEntryOrgFiles orgFiles = orgFilesDao.findOneByEntryId(r.getStr("id"));
                if (orgFiles != null) {
                   r.set("org_files_time",orgFiles.getAuditTime());
                }
                Record materialRecord=entryDao.getEntryMaterial(r.getStr("id"));
               if(materialRecord!=null){
                   r.set("nbqSpec",materialRecord.getStr("nbqSpec"));
                   r.set("nbqNum",materialRecord.getStr("nbqNum"));
                   r.set("bwxSpec",materialRecord.getStr("bwxSpec"));
                   r.set("bwxNum",materialRecord.getStr("bwxNum"));
                   r.set("zjBrand",materialRecord.getStr("zjBrand"));//组件品牌
                   r.set("nbqBrand",materialRecord.getStr("nbqBrand"));//逆变器品牌
               }

            }
        }
        InformationEncryption(list,operator.getUserType());
        page.setData(list);
        page.setCount(customerDao.countWaitOrders(map, operator));
    }
    public void ajaxForInfoAuthorizationData(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        List<Record> list = customerYxAuthorizationDao.ajaxForInfoAuthorizationData(page, map, operator);
        page.setData(list);
        page.setCount(customerYxAuthorizationDao.countInfoAuthorizationData(map, operator));
    }
    @Transactional(rollbackFor = Exception.class)
    public Result reAuthorization(String idCode ,String mobile,String patnerId,String id){
        String entryId = Db.queryStr("select id from crm_customer_entry " +
                        "where id_code=? AND mobile=? AND tenant_type = '1' and authorization = '3' and partner_id=? and status!='b' order by create_time desc limit 1",
                idCode,mobile, patnerId);
        CustomerEntry entry = customerDao.get(entryId);
        String address=entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress();
        String signFlowId = askAuthContractService.createAskAuthContract(idCode, mobile,address,patnerId);
        CrmCustomerYxAuthorization oldAuthorization = customerYxAuthorizationDao.get(id);
        oldAuthorization.setOldFlag("1");
        customerYxAuthorizationDao.save(oldAuthorization);
        CrmCustomerYxAuthorization customerYxAuthorization = new CrmCustomerYxAuthorization();
        customerYxAuthorization.setName(entry.getTenantName());
        customerYxAuthorization.setMobile(mobile);
        customerYxAuthorization.setIdCode(idCode);
        customerYxAuthorization.setAuthorization("2");
        customerYxAuthorization.setPartnerId(patnerId);
        customerYxAuthorization.setSignFlowId(signFlowId);
        customerYxAuthorization.setCreateTime(new Date());
        customerYxAuthorization.setOldFlag("0");
        customerYxAuthorizationDao.save(customerYxAuthorization);
        Record record = Db.findFirst(" select id from crm_customer_yx_condition where  id_code=? AND mobile=? and authorization = '3' and partner_id=?  limit 1 ",
                idCode, mobile, patnerId);
        CrmCustomerYxCondition condition = conditionDao.get(record.getStr("id"));
        condition.setSignFlowId(signFlowId);
        conditionDao.save(condition);
        return Result.ok();
    }

    public void outConfirmData(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        List<Record> list = customerDao.selectOutConfirmData(page, map, operator);
        InformationEncryption(list,operator.getUserType());
        page.setData(list);
        page.setCount(customerDao.countOutConfirmData(map, operator));
    }

    public void InformationEncryption(List<Record> list,String userType){
        /*if(!User.USER_TYPE_YYS.equals(userType)){
            for(Record rd:list){
                if(StringUtil.isNotBlank(rd.getStr("id_code"))){
                    rd.set("id_code",EncryptionUtils.encryptIDCardNum(rd.getStr("id_code")));
                }
                if(StringUtil.isNotBlank(rd.getStr("mobile"))){
                    rd.set("mobile",EncryptionUtils.encryptIDCardNum(rd.getStr("mobile")));
                }
            }
        }*/
    }

    public void listWaitOrderFromSmallP(LayuiPage<Record> page, Map<String, String> map, Operator operator) {

        List<Record> list = customerDao.selectWaitOrdersFromSmallP(page, map, operator);
//        InformationEncryption(list,operator.getUserType());
        page.setData(list);
        page.setCount(customerDao.countWaitOrdersFromSmallP(map, operator));
    }

    public void queryInverterList(LayuiPage<Record> page, Map<String, String> map, Operator operator) {

        List<Record> list = customerDao.queryInverterList(page, map, operator);
//        InformationEncryption(list,operator.getUserType());
        page.setData(list);
        page.setCount(customerDao.countInverterList(map, operator));
    }

    public void findRecycleBinOrders(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        List<Record> list = customerDao.findRecycleBinOrders(page, map, operator);
        InformationEncryption(list,operator.getUserType());
        page.setData(list);

        page.setCount(customerDao.countRecycleBinOrders(map, operator));
    }

    public void findRetrialPage(LayuiPage<Record> page, Map<String, String> map, Operator operator, String objType) {
        List<Record> list = customerDao.findRetrialOrders(page, map, operator, objType);
        InformationEncryption(list,operator.getUserType());
        page.setData(list);
        page.setCount(customerDao.countRetrialOrders(map, operator, objType));
    }

    public  List<Record>  nbqInsertDetail(String entryId){
        StringBuilder querySql=new StringBuilder();
        querySql.append(" select m.id,m.powerStationCode,m.materialBrand,concat(m.materialBrand,'','云') as yun,m.tenantName,m.tenantType,m.mobile,m.province,m.city,m.area,m.address, ")
                .append(" m.actualCapacity,m.detailsAddress,m.sn,m.nbqsn,m.nbqType,m.poweyType,m.longitude,m.latitude,m.traderTel,m.materialName,m.price,m.component_spec,m.regionalismCode from ")
                .append(" (SELECT a.id,a.power_station_code as powerStationCode,(SELECT c.material_brand  FROM crm_supply_material as c  ")
                .append(" WHERE c.`code` in(SELECT b.code FROM crm_plan_material_entry as b WHERE b.`entry_id` = a.id AND b.`type` = '逆变器')) as materialBrand,a.tenant_name as tenantName, ")
                .append(" (SELECT c.material_name  FROM crm_supply_material as c WHERE c.`code` in(SELECT b.code FROM crm_plan_material_entry as b WHERE b.`entry_id` = a.id AND b.`type` = '逆变器')) as materialName, ")
                .append(" (case a.tenant_type when '1' then '个人' else '单位' end ) tenantType,a.mobile,a.province,a.city,a.area,concat(a.province,a.city,a.area,a.address) as address, ")
                .append(" a.actual_capacity as actualCapacity,a.address as detailsAddress,b.sn as sn,b.nbq_sn as nbqsn,b.spec as nbqType,'家庭户用' as poweyType,a.longitude,a.latitude,a.trader_tel as traderTel, ")
                .append(" (select bb.regionalism_code from s_province as aa  left join s_city as bb on aa.ProvinceID=bb.ProvinceId  ")
                .append(" where  aa.ProvinceName=a.province and bb.CityName=a.city ) as regionalismCode,a.actual_capacity ,a.component_spec, ")
                .append(" (select product_para_value from crm_customer_incoming_product_para where project_code=a.project_code and product_para_code='ELE_PRICE' order by lease_term_from asc limit 1) as price ")
                .append(" FROM crm_customer_entry as a  ")
                .append(" left join crm_plan_material_entry as b on a.id=b.entry_id ")
                .append(" WHERE a.`status` = '6' AND a.nbq_dz_id = '' AND a.nbq_factory != '00' and b.type='逆变器' ")
                .append(" and a.id=?) as m ");
        List<Record> records = Db.find(querySql.toString(), entryId);
        return records;
    }

    public Result insertInterFace(String id) {
        CustomerEntry entry = customerDao.get(id);
        boolean checked = checkEntryJrInterface(id);
        if (checked) {
            throw new IllegalArgumentException("已接入逆变器平台");
        }
        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            return Result.fail(checkApplyResult);
        }
        Record city = AddressUtils.getCityByCityName(entry.getProvince(), entry.getCity());
        String regionalismCode = String.valueOf(city.getLong("regionalism_code"));

        StringBuilder zjNumSql = new StringBuilder();
        zjNumSql.append(" SELECT count(1) ");
        zjNumSql.append(" FROM crm_plan_material_entry b ");
        zjNumSql.append(" WHERE b.type = '组件' and b.status = '0' and b.entry_id = ? ");
        Long zjNum = Db.queryLong(zjNumSql.toString(), id); //TODO 当前组件记录 是一个组件一条记录

        StringBuilder querySql=new StringBuilder();
        querySql.append(" SELECT b.id,c.material_brand as materialBrand, ")
                .append(" c.material_name as materialName,concat(c.material_brand,'','云') as yun, ")
                .append(" b.sn as sn,b.nbq_sn as nbqsn,b.spec as nbqType, b.yz_code ")
                .append(" FROM crm_plan_material_entry b ")
                .append(" left join crm_supply_material c on c.`code` = b.code and c.status != '2' ")
                .append(" WHERE b.type='逆变器' and b.status = '0' ")
                .append(" and b.entry_id=? ");
        List<Record> records = Db.find(querySql.toString(), id);
//        int jlFlag = 0;//锦浪标记：0.未接入 1.待接入
//        int gwFlag = 0;//固德威标记：0.未接入 1.待接入
        Map<String, Integer>  faFlag = new HashMap<>();
        for(Record rd:records){
            String materialBrand=rd.get("materialBrand");
            BrandFactInfo info = BrandFactInfo.externalOf(materialBrand);
            if (info == null) {
                continue;
            }
            faFlag.put(info.getBrandType(), 1);
        }
        if (!faFlag.isEmpty()) {
            for (String type : faFlag.keySet()) {
                String stationId = getJlStationId(type, id);
                if (StringUtil.isNotBlank(stationId)) {
                    BrandFactInfo info = BrandFactInfo.matchType(type);
                    return Result.fail("已接入" + info.getFactoryName() + "平台，请先刷新列表");
                }
            }
        }
        if (entry.getEpcPrice() == null) {
            throw new IllegalArgumentException("电价信息有误");
        }
        String ginLangSn = ""; //锦浪
        List<Map> goodWList=new ArrayList<>(); // 固德威
        List<Map<String,String>> aisweiList=new ArrayList<>(); // 爱士惟
        for(Record rd:records){
            String materialBrand=rd.get("materialBrand");
            BrandFactInfo info = BrandFactInfo.externalOf(materialBrand);
            if (info == null) {
                continue;
            }
            if (info == BrandFactInfo.Jinlang) {
                ginLangSn = ginLangSn + rd.getStr("sn") + ",";
            }
            else if(info == BrandFactInfo.GoodW){
                Map map=new HashMap();
                String materialName =  rd.getStr("materialName");//逆变器名称
                map.put("it_name", materialName);
                if(StringUtil.isBlank(materialName)){
                    throw new IllegalArgumentException("逆变器名称不能为空");
                }
                String nbqsn = rd.getStr("nbqsn"); //逆变器序列号 SN码
                map.put("it_sn",nbqsn);
                if(StringUtil.isBlank(nbqsn)){
                    throw new IllegalArgumentException("逆变器sn序列号不能为空");
                }
                String yzCode = rd.getStr("yz_code"); //逆变器校验码
                map.put("it_checkcode",yzCode);
                if(StringUtil.isBlank(yzCode)){
                    throw new IllegalArgumentException("逆变器校验码不能为空");
                }
                goodWList.add(map);
            }
            else if (info == BrandFactInfo.Aiswei){
                Map<String,String> map=new HashMap();
                String materialName =  rd.getStr("materialName");//逆变器名称
                map.put("it_name", materialName);
                if(StringUtil.isBlank(materialName)){
                    throw new IllegalArgumentException("逆变器名称不能为空");
                }
                String sn = rd.getStr("sn"); //采集器 SN码
                map.put("psno",sn);
                if(StringUtil.isBlank(sn)){
                    throw new IllegalArgumentException("采集器sn序列号不能为空");
                }
                String yzCode = rd.getStr("yz_code"); //采集器注册码
                map.put("registno",yzCode);
                if(StringUtil.isBlank(yzCode)){
                    throw new IllegalArgumentException("采集器注册码不能为空");
                }
                aisweiList.add(map);
            }
        }
        if (StringUtil.isNotBlank(ginLangSn)) {
            ginLangSn = ginLangSn.substring(0,ginLangSn.length()-1);
            insertGinLang(entry, ginLangSn);
        }
        if (!goodWList.isEmpty()) {
            insertGoodW(entry, goodWList, regionalismCode, zjNum);
        }
        if (!aisweiList.isEmpty()) {
            insertAiswei(entry, aisweiList);
        }

        return Result.ok();
    }

    /**
     * 获取电站已接入的云平台电站id
     * @param entryId 系统电站id
     * @param type 01.锦浪 02.固德威 03.爱士惟
     * @return
     */
    public String getJlStationId(String type, String entryId) {
        //判断是否接入逆变器平台
        String jlJrSql = "select a.brand_id " +
                "from crm_customer_interface a " +
                "where a.status = '0' and a.brand = ? and a.entry_id = ? " +
                "order by a.create_time desc limit 1";
        return Db.queryStr(jlJrSql, type, entryId);
    }

    /**
     * 校验电站是否接入逆变器平台
     * @param entryId 系统电站id
     * @return
     */
    public boolean checkEntryJrInterface(String entryId) {
        //判断是否接入逆变器平台
        String jlJrSql = "select count(1) " +
                "from crm_customer_interface a " +
                "where a.status = '0' and a.entry_id = ? ";
        return Db.queryLong(jlJrSql, entryId) > 0;
    }

    /**
     * 校验电站是否接入逆变器平台
     * @param entryId 系统电站id
     * @return
     */
    public boolean deleteEntryJrInterface(String entryId) {
        //判断是否接入逆变器平台
        String jlJrSql = "update crm_customer_interface a " +
                "set a.status = '1' " +
                "where a.status = '0' and a.entry_id = ? ";
        return Db.update(jlJrSql, entryId) > 0;
    }
    /**
     *固德威新增设备
     */
    public void addInverterGoodW(String entryId,String nbqName,String nbqSn,String yzCode,String partnerId){
        Map<String,Object> body=new HashMap<>();
        body.put("pw_id",entryId);//电站id
        body.put("it_name",nbqName);//逆变器名称
        body.put("it_sn",nbqSn);//逆变器sn
        body.put("it_checkcode",yzCode);//验证码
        String url = GuDeConstan.url+GuDeConstan.addInverter_url;
        //获取账号密码
        Record record = customerDao.findAccountById(partnerId, "02");
        String account = record.getStr("login_name");
        String password = record.getStr("password");
        String result= GuDeUtils.request(url,body,account,password);
        String status = "1";
        Map parse=(Map) JSONObject.parse(result);
        if(parse.containsKey("code") && parse.containsKey("data")){
            if("0".equals(String.valueOf(parse.get("code"))) && parse.get("data") != null){
                status = "0";
            }
            if("100000".equals(String.valueOf(parse.get("code")))){
                saveSysRecord(entryId,url,new Gson().toJson(body), result, "1");
                throw new IllegalArgumentException(String.valueOf(parse.get("msg")));
            }
        }
        saveSysRecord(entryId,url,new Gson().toJson(body), result, status);
    }

    /**
     *固德威删除设备
     */
    public void removeInverterGoodW(String entryId,String gdwStationId ,String nbqSn,String partnerId){
        Map<String,String> body=new HashMap<>();
        body.put("pwId",gdwStationId);//固德威电站id
        body.put("sn",nbqSn);//逆变器sn
        String url = GuDeConstan.url+GuDeConstan.removeInverter_url;
        //获取账号密码
        Record record = customerDao.findAccountById(partnerId, "02");
        String account = record.getStr("login_name");
        String password = record.getStr("password");
        String result= GuDeUtils.requestForGet(GuDeConstan.url,GuDeConstan.removeInverter_url,body,account,password);
        System.out.println("固德威删除设备接口返回----->"+result);
        Map parse=(Map) JSONObject.parse(result);
        String status = "1";
        if(parse.containsKey("code") && parse.containsKey("data")){
            if("0".equals(String.valueOf(parse.get("code")))){
                status = "0";
            }
            if("100000".equals(String.valueOf(parse.get("code")))){
                saveSysRecord(entryId,url,new Gson().toJson(body), result, "1");
                throw new IllegalArgumentException(String.valueOf(parse.get("msg")));
            }
        }
        saveSysRecord(entryId,url,new Gson().toJson(body), result, status);
    }

    /**
     * 新增固德威电站
     */
    public String insertGoodW(CustomerEntry rd, List<Map> snList, String regionalismCode, Long zjNum){
        String address=rd.getProvince() + rd.getCity() + rd.getArea() + rd.getAddress();
        String longitude=GaodeUtil.getLonLat(address);
        if(StringUtil.isBlank(longitude)){
            longitude="100.0000,10.00";
        }
        Map<String,Object> body=new HashMap<>();
        String tenantName = StringUtil.getStationName(rd.getTenantName(), rd.getPowerStationCode()); //电站名称
        body.put("pw_name", tenantName);
        if(StringUtil.isBlank(tenantName)){
            throw new IllegalArgumentException("电站名称不能为空");
        }
        body.put("conn_date",DateUtil.today());//接入时间
        body.put("pw_yieldrate", rd.getEpcPrice());//收益率 范围 0~10
        if(rd.getEpcPrice() == null){
            throw new IllegalArgumentException("收益率不能为空");
        }
        body.put("pw_inventersnum", zjNum);//组件数量
        if(zjNum == null){
            throw new IllegalArgumentException("组件数量不能为空");
        }
        // 系统存的Wp 需要转化成kWp
        if(rd.getActualCapacity() == null){
            throw new IllegalArgumentException("电站容量不能为空");
        }
        BigDecimal actualCapacity = rd.getActualCapacity().divide(new BigDecimal(1000), 3, RoundingMode.HALF_UP);
        body.put("pw_capacity", actualCapacity);//电站容量
        body.put("pw_address", address);//所在地区
        if(StringUtil.isBlank(address)){
            throw new IllegalArgumentException("所在地区不能为空");
        }
        body.put("pw_areacode", regionalismCode);//区域编码
        if(StringUtil.isBlank(regionalismCode)){
            throw new IllegalArgumentException("区域编码不能为空");
        }
        body.put("pw_type",0); // 电站类型：0:家庭户用
        Map m=new HashMap();
        List<Map> list=new ArrayList<>();
        m.put("owner_phone", rd.getMobile());
        if(StringUtil.isBlank(rd.getMobile())){
            throw new IllegalArgumentException("手机号不能为空");
        }
        String ownerName = rd.getTenantName();
        if (StringUtil.isNotBlank(ownerName) && ownerName.length() > 10) {
            ownerName = ownerName.substring(0,10);
        }
        m.put("owner_name", ownerName);
        if(StringUtil.isBlank(ownerName)){
            throw new IllegalArgumentException("用户名不能为空");
        }
        m.put("is_first_owner",true);
        list.add(m);
        body.put("list_pwowner",list);
        body.put("list_attachment",null);
        body.put("pw_synopsis","接口创建电站");
        body.put("pw_longitude",longitude.split(",")[0]);//经度
        body.put("pw_latitude",longitude.split(",")[1]);//纬度
        body.put("pw_synopsishide",true);
        body.put("list_inverters", snList); // 新增逆变器
        String url = GuDeConstan.url+GuDeConstan.add_url;
        //获取账号密码
        Record record = customerDao.findAccountById(rd.getPartnerId(), "02");
        String account = record.getStr("login_name");
        String password = record.getStr("password");
        String result= GuDeUtils.request(url,body,account,password);
        Map parse=(Map) JSONObject.parse(result);
        String status = "1";
        if(parse.containsKey("code") && parse.containsKey("data")){
            if("0".equals(String.valueOf(parse.get("code"))) && parse.get("data") != null){
                Map SS=(Map) JSONObject.parse(String.valueOf(parse.get("data")));
                insertSql(rd.getId(),String.valueOf(SS.get("id")),"02");
                status = "0";
            }
            // {"code":100041,"msg":"当前设备被添加到其他电站，不允许再使用！:4050KMTW241G0130","data":null}
//            else if("100041".equals(String.valueOf(parse.get("code")))){
//                insertSql(rd.getId(),String.valueOf(000),"02");
//                status = "0";
//            }
            else{
                saveSysRecord(rd.getId(),url,new Gson().toJson(body), result, "1");
                throw new IllegalArgumentException("固德威" + String.valueOf(parse.get("msg")));
            }
        }
        saveSysRecord(rd.getId(),url,new Gson().toJson(body), result, status);
        return String.valueOf(parse.get("code"));
    }

    /**
     * 新增爱士惟电站
     */
    public void insertAiswei(CustomerEntry rd, List<Map<String,String>> snList){

        String tenantName = StringUtil.getStationName(rd.getTenantName(), rd.getPowerStationCode()); //电站名称
        if(StringUtil.isBlank(tenantName)){
            throw new IllegalArgumentException("电站名称不能为空");
        }
        String address=rd.getProvince() + rd.getCity() + rd.getArea() + rd.getAddress();
        // 系统存的Wp 需要转化成kWp
        if (rd.getActualCapacity() == null || rd.getActualCapacity().compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("电站容量不能为空,且容量必填大于0");
        }
        BigDecimal actualCapacity = rd.getActualCapacity().divide(new BigDecimal(1000), 3, RoundingMode.HALF_UP);

        //获取账号密码
        Record record = customerDao.findAccountById(rd.getPartnerId(), "03");
        String key = record.getStr("login_name");
        String secret = record.getStr("password");
        String token = record.getStr("keyword3");
        int sucess = 0;
        String errorMsg = "";
        for (Map<String,String> map : snList) {
            CreateStationProReq req = new CreateStationProReq();
            req.setEntryId(rd.getId());
            req.setName(tenantName);
            if (rd.getLatitude() != null && rd.getLongitude() != null) {
                req.setJd(rd.getLongitude().stripTrailingZeros().toPlainString()); // 经度
                req.setWd(rd.getLatitude().stripTrailingZeros().toPlainString());//纬度
            }
            else {
                String longitude=GaodeUtil.getLonLat(address);
                if(StringUtil.isNotBlank(longitude)){
                    req.setJd(longitude.split(",")[0]);//经度
                    req.setWd(longitude.split(",")[1]);//纬度
                }
            }
            req.setTotalpower(actualCapacity.stripTrailingZeros().toPlainString());
            req.setProvince(rd.getProvince());
            req.setCity(rd.getCity());
            req.setStreet(address);
            req.setPsno(map.get("psno"));
            req.setRegistno(map.get("registno"));
            req.setToken(token);
            req.setKey(key);
            req.setSecret(secret);
            AisweiRet<CreateStationProR> pro = aisweiApi.createStation(req);
            if (Objects.equals(pro.getStatus(), 200)) {
                CreateStationProR data = pro.getData();
                if (data != null) {
                    insertSql(rd.getId(), data.getApikey(),"03");
                    logger.info("同步爱士惟电站成功,psno:{},registno:{}", req.getPsno(), req.getRegistno());
                    sucess ++;
                }
            }
            else {
                errorMsg = errorMsg + req.getPsno() + " " + pro.getInfo() + ",";
            }
            logger.info("同步爱士惟电站失败,psno:{},registno:{}", req.getPsno(), req.getRegistno());
        }
        if (sucess < 1) {
            throw new IllegalArgumentException("爱士惟" + errorMsg);
        }
    }

    /**
     * 新增锦浪电站并绑定采集器
     */
    public String addCollectorGinLang(String entryId, String sn, String mobile, String traderTel, String installTime,
                                          String price, String province, String city, String address, String stationName,String capacity,String partnerId){
        Map<String,Object> map = new HashMap<>();

        map.put("sn",sn);//通讯棒sn
        map.put("stationName",stationName);//电站名称
        map.put("capacity",capacity);//装机容量必填（单位 kWp）
        map.put("money","CNY");//货币种类
        map.put("addr", address);//电站详细地址
        map.put("countryStr","中国");//国家名称
        map.put("regionStr", province);//区域名称
        map.put("cityStr", city);//城市名称
        map.put("price", price);//每度电收益
        map.put("installTime", installTime);//安装时间
        map.put("mobile", mobile);//手机号
        map.put("installerMobile", traderTel);//安装商电话
        String url = GinLangConstan.addStationBindCollectorUrl;
        //获取账号密码
        Record record = customerDao.findAccountById(partnerId, "01");
        String apiId = record.getStr("login_name");
        String apiSecret = record.getStr("password");
        String result= GinLangUtils.HttpRequest(map, url,apiSecret,apiId);
        Map parse=(Map) JSONObject.parse(result);
        if (!"0".equals(String.valueOf(parse.get("code")))){
            saveSysRecord(entryId,url,new Gson().toJson(map), result, "1");
            throw new BusinessException("推送采集器信息至锦浪平台失败："+parse.get("msg"));
        }
        String data = "";
        if ("true".equals(String.valueOf(parse.get("success"))) && "0".equals(String.valueOf(parse.get("code")))) {
            if (parse.get("data") != null) {
                data = String.valueOf(parse.get("data"));
            }
            insertSql(entryId, data,"01");
        }
        saveSysRecord(entryId,url,new Gson().toJson(map), result, "0");
        return data;
    }

    /**
     * 锦浪绑定采集器
     * 即是新增电站
     */
    public String editCollectorGinLang(String entryId, String sn, String stationId,String partnerId){
        Map<String,Object> map = new HashMap<>();

        map.put("sn",sn);//通讯棒sn
        map.put("stationId",stationId);//电站id
        String url = GinLangConstan.addStationBindCollectorUrl;
        //获取账号密码
        Record record = customerDao.findAccountById(partnerId, "01");
        String apiId = record.getStr("login_name");
        String apiSecret = record.getStr("password");
        String result= GinLangUtils.HttpRequest(map, url,apiSecret,apiId);
        Map parse=(Map) JSONObject.parse(result);
        if (!"0".equals(String.valueOf(parse.get("code")))){
            saveSysRecord(entryId,url,new Gson().toJson(map), result, "1");
            throw new BusinessException("更换新的采集器至锦浪平台失败："+parse.get("msg"));
        }
        String data = "";
        if ("true".equals(String.valueOf(parse.get("success"))) && "0".equals(String.valueOf(parse.get("code")))) {
            if (parse.get("data") != null) {
                data = String.valueOf(parse.get("data"));
            }
        }
        saveSysRecord(entryId,url,new Gson().toJson(map), result, "0");
        return data;
    }

    /**
     * 锦浪换绑采集器
     */
    public String editCollectorGinLang(String entryId, String oldSn, String newSn, String stationId,String partnerId){
        delCollectorGinLang(entryId, oldSn, 0,partnerId);
        String data = editCollectorGinLang(entryId, newSn, stationId,partnerId);
        return data;
    }
    /**
     * 已存在锦浪电站 绑定逆变器
     */
    public  void addNbqGinLang(String entryId, String sn, String stationId,String partnerId){
        Map<String,Object> map = new HashMap<>();
        map.put("sn",sn);//通讯棒sn
        map.put("id",stationId);//锦浪系统电站id

        String url = GinLangConstan.addDeviceUrl;
        //获取账号密码
        Record record = customerDao.findAccountById(partnerId, "01");
        String apiId = record.getStr("login_name");
        String apiSecret = record.getStr("password");
        String result= GinLangUtils.HttpRequest(map, url,apiSecret,apiId);
        Map parse=(Map) JSONObject.parse(result);
        if (!"0".equals(String.valueOf(parse.get("code")))){
            saveSysRecord(entryId,url,new Gson().toJson(map), result, "1");
            throw new BusinessException("推送逆变器平台失败："+parse.get("msg"));
        }
        saveSysRecord(entryId,url,new Gson().toJson(map), result, "0");
    }

    /**
     * 锦浪解绑采集器
     */
    public void delCollectorGinLang(String entryId, String sn,Integer deleteInvert,String partnerId){
        Map<String,Object> map = new HashMap<>();
        map.put("sn",sn);
        map.put("deleteInvert",deleteInvert);
        String url = GinLangConstan.delCollectorUrl;
        //获取账号密码
        Record record = customerDao.findAccountById(partnerId, "01");
        String apiId = record.getStr("login_name");
        String apiSecret = record.getStr("password");
        String result= GinLangUtils.HttpRequest(map, url,apiSecret,apiId);
        Map parse=(Map) JSONObject.parse(result);
        if (!"0".equals(String.valueOf(parse.get("code")))){
            saveSysRecord(entryId,url,new Gson().toJson(map), result, "1");
            throw new BusinessException("推送逆变器平台失败："+parse.get("msg"));
        }
        saveSysRecord(entryId,url,new Gson().toJson(map), result, "0");
    }


    /**
     * 锦浪添加变电站信息
     * @param rd
     * @param sn
     */
    public String insertGinLang(CustomerEntry rd, String sn) {
//        Map<String,Object> req=new HashMap<>();
        String stationName = StringUtil.getStationName(rd.getTenantName(), rd.getPowerStationCode());//电站名称+电站编码
        String azTime = DateUtils.formatDate(rd.getInstallTime(),"yyyy-MM-dd HH:mm:ss");
//        req.put("stationName", stationName);
        if(StringUtil.isBlank(stationName)){
            throw  new IllegalArgumentException("电站名称不能为空");
        }
        BigDecimal actualCapacity = rd.getActualCapacity();
        if (actualCapacity == null || actualCapacity.compareTo(BigDecimal.ZERO) <= 0) {
            throw  new IllegalArgumentException("装机容量必填（单位 kWp）");
        }
        // 系统存的Wp 需要转化成kWp
        actualCapacity = actualCapacity.divide(new BigDecimal(1000), 3, RoundingMode.HALF_UP);
//        req.put("capacity",actualCapacity);//装机容量必填（单位 kWp）
//        req.put("money","CNY");//货币种类
        //电站详细地址
        String address = rd.getProvince() + rd.getCity() + rd.getArea() + rd.getAddress();
//        req.put("addr", address);
        if(StringUtil.isBlank(address)){
            throw  new IllegalArgumentException("电站详细地址不能为空");
        }
//        req.put("price",rd.get("price"));//每度电收益
        if (rd.getEpcPrice() == null) {
            throw  new IllegalArgumentException("每度电收益不能为空");
        }
        String price = rd.getEpcPrice().toPlainString();
//        req.put("inverterSn",rd.get("nbqsn"));//逆变器 SN 填写即可绑定
//        if(StringUtil.isBlank(rd.get("nbqsn"))){
//            throw  new IllegalArgumentException("逆变器SN不能为空");
//        }
//        req.put("collectorSn",rd.get("sn"));//采集器 SN 填写即可绑定
        if(StringUtil.isBlank(sn)){
            throw  new IllegalArgumentException("采集器SN不能为空");
        }
        String mobile = rd.getMobile();
//        req.put("mobile", mobile);//手机号
        if(StringUtil.isBlank(mobile)){
            throw new IllegalArgumentException("手机号不能为空");
        }
//        req.put("latitude",rd.get("longitude"));//纬度
//
//        req.put("Integeritude",rd.get("latitude"));//经度
//        req.put("countryStr","中国");//国家名称
        String traderTel = rd.getTraderTel();
//        req.put("installerMobile",traderTel);//安装商电话
        if(StringUtil.isBlank(traderTel)){
            throw  new IllegalArgumentException("安装商电话不能为空");
        }
        String province = rd.getProvince();
//        req.put("regionStr", province);//区域名称
        if(StringUtil.isBlank(province)){
            throw  new IllegalArgumentException("区域名称不能为空");
        }
        String city = rd.getCity();
//        req.put("cityStr", city);//城市名称
        if(StringUtil.isBlank(city)){
            throw  new IllegalArgumentException("城市名称不能为空");
        }
//        String url = GinLangConstan.addUrl;
//        String result= GinLangUtils.HttpRequest(req, url);
//        logger.info("----->锦浪接口返回:{}",result);
//        Map parse=(Map) JSONObject.parse(result);
//        String status = "1";
//        if(parse.containsKey("success") && parse.containsKey("data")){
//            if("true".equals(String.valueOf(parse.get("success"))) && "0".equals(String.valueOf(parse.get("code")))){
//                String data = "";
//                if (parse.get("data") != null){
//                    data = String.valueOf(parse.get("data"));
//                }
//                insertSql(id, data,"01");
//                status = "0";
//                addCollectorGinLang(data, rd.get("sn"), mobile, traderTel, province, city,
//                        address, rd.get("tenantName"), actualCapacity.toPlainString());
//            }
//        }
//        saveSysRecord(id,url,new Gson().toJson(req), result, status);

        addCollectorGinLang(rd.getId(), sn, mobile, traderTel, azTime, rd.getEpcPrice().toPlainString(),
                province, city, address, stationName, actualCapacity.toPlainString(),rd.getPartnerId());

//        if(parse.get("success") != null && "true".equals(String.valueOf(parse.get("success")))){
//            return "200";
//        }
        return "200";
    }

    /**
     * 变电站信息插入中间表
     * @param id
     * @param stationId
     * @param type
     */
    public static void insertSql(String id,String stationId,String type){
        String insertSql="INSERT INTO crm_customer_interface(`id`, `entry_id`, `brand`, `brand_id`, `status`, `create_time`) VALUES (?,?,?,?,'0',?)";
        Db.update(insertSql,IdGen.uuid(),id,type,stationId, DateUtil.now());

        String saveSatationSql="UPDATE crm_customer_entry a SET a.`nbq_dz_id` = ? WHERE a.`id` = ? AND a.`nbq_factory` = ?";
        Db.update(saveSatationSql,stationId,id,type);
    }

    /**
     * 生成逆变器接入同步日志
     * status 状态 0 成功 1失败
     */
    public static int saveSysRecord(String entryId, String url, String requestParam,
                                    String responseParam, String status){
        StringBuilder insertSql=new StringBuilder();
        insertSql.append(" INSERT INTO crm_customer_interface_process(id,entry_id,url,create_time,request_param, response_param, status) ");
        insertSql.append(" VALUES (MD5(UUID()), ?,?,NOW(),?,?,?)");
        int result=Db.update(insertSql.toString(), entryId,url,requestParam, responseParam, status);
        return result;
    }





    public Result flagCustomerEntry(String id, String flag) {
        CustomerEntry entry = customerDao.get(id);
        entry.setFlag(flag);
        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchOrder(List<String> ids, Operator operator, String warehouseId, String remark) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new BusinessException("下单信息不能为空");
        }
        if (StringUtil.isBlank(warehouseId)) {
            throw new BusinessException("仓库信息不能为空");
        }

        // 获取代理商信息
        User user =UserUtils.getUser();// userDao.getById(operator.getUserId());

        Ascription ascription = CrmUtils.getAscription(user);

        // User currentUser = UserUtils.getUser();
        Record res = CrmUtils.getByUserId(user);
        String traderId = res.getStr("parent_id");

        Date now = new Date();
        CrmCustomerOrder customerOrder = new CrmCustomerOrder();
        customerOrder.setOrderNumber(PlantformUtils.getOrderNumber());
        customerOrder.setCreateBy(operator.getUserId());
        customerOrder.setCreateTime(now);
        customerOrderDao.save(customerOrder);
        StringBuilder projectCode = new StringBuilder();
        StringBuilder relateNo = new StringBuilder();
        List<Record> oldComponentList = new ArrayList<>();
        for (String id : ids) {
            CustomerEntry customerEntry = customerDao.get(id);
            if (!CustomerEntryConstants.ENTRY_STATUS_DXD.equals(customerEntry.getStatus())) {
                throw new BusinessException("信息状态发生变化，请刷新后再试");
            }
          /*  if (StringUtil.isNotBlank(customerEntry.getManagementType())) {
                if (StringUtil.isNotBlank(customerEntry.getApplyStatus()) && !StringUtil.equalsAny(customerEntry.getApplyStatus(), "QY", "PR")) {
                    throw new IllegalArgumentException("进件申请未通过，不可操作");
                }
            }*/
            if("1".equals(customerEntry.getProductLine()) && !CustomerEntryConstants.SIGN_STATUS_COMPLETED.equals(customerEntry.getSignStatus())){
                throw new IllegalArgumentException(customerEntry.getPowerStationCode()+",该项目没完成合同签署，不可操作下单!");
            }
            customerEntry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DAZ);
            customerEntry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_DPG);
            customerEntry.setAcceptFlag("1");//已下单
            customerDao.save(customerEntry);
            msgService.saveCustomerEntryMsg(operator, id, CustomerEntryConstants.ADVANCE_TYPE_OPT_XIADAN);
            // 如果已经下过单，判断是否需要生成待审批订单
            if (StringUtil.isNotBlank(customerEntry.getOrderBy())) {
                boolean againFlag = true;
                Date oldDate = entryComponentDao.findOldDate(customerEntry.getId());
                List<Record> componentList = entryComponentDao.findByEntryId(customerEntry.getId());
                for (Record r : componentList) {
                    int oldNum = entryComponentDao.findOldNumByEntryIdAndItemId(r.getStr("entry_id"), r.getStr("item_id"),oldDate);
                    logger.info("获取历史数据 {} ,{},{},{}",oldNum,r.getStr("entry_id"), r.getStr("item_id"),r.getInt("num"));

                    if (r.getInt("num") > oldNum) {
                        r.set("num", oldNum);
                        againFlag = false;
                    }
                    oldComponentList.add(r);
                }
                if (againFlag) {
                    continue;
                }
            }
            if (projectCode.length() > 0) {
                projectCode.append(",");
            }
            projectCode.append(customerEntry.getProjectCode());
            if (relateNo.length() > 0) {
                relateNo.append(",");
            }
            relateNo.append(customerEntry.getPowerStationCode());
            customerEntry.setOrderBy(operator.getUserId());
            customerEntry.setOrderName(operator.getUserName());
            customerEntry.setOrderTime(now);
            customerDao.save(customerEntry);
            customerOrderRelDao.createOrderRel(customerOrder.getId(), customerEntry.getId());
        }
        // 创建待审批订单
        CrmSupplyMaterialDeliverOrder deliverOrder = new CrmSupplyMaterialDeliverOrder();
        deliverOrder.setId(IdGen.uuid());
        deliverOrder.setType(DeliverOrderConstants.TYPE_PROJECT);
        deliverOrder.setNumber(PlantformUtils.findOrderNumber("XM"));
        deliverOrder.setProjectCode(projectCode.toString());
        deliverOrder.setTraderId(traderId);
        deliverOrder.setRelateNo(relateNo.toString());
        deliverOrder.setInWarehouseId(warehouseId);
        deliverOrder.setRemarks(remark);
        deliverOrder.setPlaceBy(ascription.getAscriptionId());
        deliverOrder.setPlaceName(ascription.getAscriptionName());
        deliverOrder.setPlaceTime(now);
        deliverOrder.setCreateBy(operator.getUserId());
        deliverOrder.setCreator(operator.getUserName());
        deliverOrder.setCreateTime(now);
        deliverOrder.setStatus(DeliverOrderConstants.STATUS_WAIT_AUDIT);
        deliverOrder.setOrderExamineStatus(BondApplyConstant.APPLYSTATUS_ONE);
        // 创建待审批订单物料详情
        List<Record> list = customerEntryComponentService.findByEntryIds(ids);
        if (oldComponentList.size() > 0) {
            for (Record r : list) {
                for (Record re : oldComponentList) {
                    if (Objects.equals(re.getStr("item_id"), r.getStr("item_id"))) {
                        BigDecimal subtractNum = new BigDecimal(re.getInt("num").toString());
                        r.set("num", r.getBigDecimal("num").subtract(subtractNum));
                    }
                }
            }
        }
        String currentTraderId = CrmUtils.getCurrentTraderId(user);
        CrmTrader trader = traderService.getById(currentTraderId);
        String qqProjectCode = trader.getQqProjectCode();
        int i = 0;
        BigDecimal total = BigDecimal.ZERO;
        boolean deliverDetailFlag = true;
        BigDecimal predictAmount=BigDecimal.ZERO; //预估授信额度
        for (Record r : list) {
            if (r.getBigDecimal("num").compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            deliverDetailFlag = false;
            deliverDetailDao.createOne(deliverOrder.getId(), null, r.getStr("type"),
                    r.getStr("model"), r.getBigDecimal("num"), i);
            total = total.add(r.getBigDecimal("num"));
            i++;
            //按照申请物料规格的最高价判断代理商授信额度
            BigDecimal maxPrice=supplyMaterialDao.getMaxPriceBySpec2(r.getStr("type"),r.getStr("model"),qqProjectCode);
            logger.info(">>>>>>>>赊销下单 获取单个物料的最大价格:{},{},{},{}",r.getStr("type"),r.getStr("model"),r.getBigDecimal("num"),maxPrice);
            predictAmount=predictAmount.add(maxPrice.multiply(r.getBigDecimal("num")));
        }
        if (deliverDetailFlag) {
            return;
        }
        logger.info(">>>>>>>>>>>赊销下单 获取物料的授信额度 predictAmount：{}",predictAmount);
        //获取订单在过程中的，还未发货的，计算他的授信额
        BigDecimal ztPridictAmount=supplyMaterialDao.getTotalAmountNotReduceAmount(deliverOrder.getTraderId(),"");
        logger.info(">>>>>>>>>>>赊销下单 获取在途的物料授信额度 ztPridictAmount：{}",ztPridictAmount);
        predictAmount=predictAmount.add(ztPridictAmount); //总的授信额度
        CrmTraderAccount account = accountDao.findByTraderId(deliverOrder.getTraderId());
        if (account == null) {
            throw new BusinessException("请新增代理商的可授信额度!");
        }
        logger.info(">>>>>>>>>>>赊销下单 获取账户的授信额度 zhAmount：{}",account.getBasicQuotaAmountBalance());
        if (account.getBasicQuotaAmountBalance().compareTo(predictAmount) < 0) {
            throw new BusinessException("代理商标准授信额不足，不能下单!");
        }

        deliverOrder.setMaterialTypeAmount(new BigDecimal(i));
        deliverOrder.setTotalApplyAmount(total);

        // 创建待审批订单操作日志
        deliverOrderMsgDao.saveOptMsg(deliverOrder.getId(), DeliverOrderConstants.OPT_CREATE, null, operator);

        //启动流程
        Record rd = FormUtils.getdefLatest(FormUtils.SUPPLY_ORDER_APPLICATION);
        if(rd == null){
            throw  new BusinessException("订单审批流程未定义，不可发布申请");
        }
        String processName="订单申请-"+operator.getUserName()+'-'+DateUtils.formatDate(now,"yyyy-MM-dd HH:mm:ss")+"("+ascription.getAscriptionName()+")";
        String processInstanceId=flowableService.startProcessFlowable(user,deliverOrder.getId(),rd,FormUtils.SUPPLY_ORDER_APPLICATION,now,ascription.getAscriptionName(),remark,processName,deliverOrder.getTraderId());
        logger.info(">>>>>>>>>>>>>savePurchaseOrder processInstanceId:{} ",processInstanceId);
        deliverOrder.setProcessInstanceId(processInstanceId);
        deliverOrder.setProcessDefId(rd.getStr("id"));
        String taskName=FormUtils.getOneStepTaskName(rd.getStr("id"));
        deliverOrder.setTaskName(taskName);
        logger.info(">>>>>>>>>>>>>>savePurchaseOrder>>>>>>>>>taskId:{},taskName:{}",deliverOrder.getId(),taskName);

        deliverDao.save(deliverOrder);
    }

    /**
     * 批量收货
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchReceive(List<String> ids, Operator operator) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new BusinessException("收货信息不能为空");
        }
        for (String id : ids) {
            CustomerEntry customerEntry = customerDao.get(id);
            if (!CustomerEntryConstants.ENTRY_STATUS_SH.equals(customerEntry.getStatus())) {
                throw new BusinessException("信息状态发生变化，请刷新后再试");
            }
            customerEntry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DAZ);
            customerEntry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_DPG);
            customerEntry.setReceiveBy(operator.getUserId());
            customerEntry.setReceiveName(operator.getUserName());
            customerEntry.setReceiveTime(new Date());
            customerDao.save(customerEntry);
            msgService.saveCustomerEntryMsg(operator, id, CustomerEntryConstants.ADVANCE_TYPE_OPT_SHOUHUO);
        }
    }

    /**
     * 安装完成
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchInstall(AddReportReq req, Operator operator) {
        CustomerEntry customerEntry = customerDao.get(req.getEntryId());
//        customerEntry.setLongitude(req.getLongitude());
//        customerEntry.setLatitude(req.getLatitude());
        logger.info("batchInstall customerEntry={}",JSONObject.toJSONString(customerEntry));
        if (customerEntry == null) {
            throw new BusinessException("订单不存在或状态异常");
        } else if (!CustomerEntryConstants.ENTRY_STATUS_DAZ.equals(customerEntry.getStatus()) && !CustomerEntryConstants.ENTRY_STATUS_AZYSTH.equals(customerEntry.getStatus())) {
            throw new BusinessException("信息状态发生变化，请刷新后再试");
        }
        if(StringUtil.isBlank(customerEntry.getInstallBy())){
            throw new BusinessException("请先电站安装!");
        }
        //项目公司备案 判断备案文件必填,项目备案代码必填
        if (CustomerEntryConstants.FILING_TYPE_COMPANY.equals(customerEntry.getFilingType())) {
            GuardUtils.notBlank(req.getFilingDocumentCode(), "项目备案代码不能为空");
            GuardUtils.notBlank(req.getFilingDocumentPhoto(), "备案证不能为空");
        }
        //广发存量电站合同必填
        if(PartnerConstants.PARTNER_ID_GF.equals(customerEntry.getPartnerId()) && "1".equals(customerEntry.getIsHistory())){
            GuardUtils.notBlank(req.getContractUrl(), "合同不能为空");
        }
        //租户类型是单位
        if (CustomerEntryConstants.TENANT_TYPE_COMPANY.equals(customerEntry.getTenantType()) && "01".equals(customerEntry.getPartnerId())) {
            GuardUtils.notBlank(req.getOtherImgs1(), "银行印鉴留样不能为空");
            GuardUtils.notBlank(req.getOtherImgs2(), "签约现场照片不能为空");
            GuardUtils.notBlank(req.getOtherImgs3(), "约现场照片-正脸照片不能为空");
            GuardUtils.notBlank(req.getOtherImgs4(), "签署完成照片不能为空");
            GuardUtils.notBlank(req.getOtherFiles(), "其他资料不能为空");
        }
        /*if ("1".equals(customerEntry.getTenantType()) && !StringUtil.equalsAny(customerEntry.getSignStatus(),"2","3","5","g","e")
                &&FormSetUtils.processSetEnable(customerEntry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZFSH)) {
            throw new BusinessException("当前电站未签约《农户合同》，请在签约后再提交完工!");
        }*/

        // 查询项目信息
        //CrmProjectSetting projectSetting = projectDao.get(customerEntry.getProjectId());
        // 校验必填项
        List<Record> checkList = formSetDao.findListByCondition("03", customerEntry.getPartnerId());
        Result result = null;
        if(PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
            if (req.getCompleteList() == null || req.getCompleteList().isEmpty()) {
                throw new BusinessException("请先上传完工资料");
            }
            result = requiredCheckForInstallHr(req, checkList);
        }else{
            result = requiredCheckForInstall(req, checkList);
        }
        if (!"200".equals(result.getCode())) {
            throw new BusinessException(result.getErrMsg());
        }
        // 查询使用的新物料
        List<Record> list = entryDao.findNewMostSpecByEntryId(customerEntry.getId());
        /*Long oldCount = entryDao.getOldMostSpecCnt(customerEntry.getId());
        if ((list == null || list.isEmpty()) && oldCount == 0) {
            throw new BusinessException("完工前请先安装");
        }*/
        long snCount = entryDao.findMaterialSnByEntryId(customerEntry.getId());
        if (snCount == 0) {
            throw new BusinessException("sn码为空");
        }
        String checkApplyResult = CrmUtils.checkExistApply(customerEntry.getStatus(), customerEntry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            throw new BusinessException(checkApplyResult);
        }

        // 获取实际安装容量
        List<CrmPlanMaterialEntry> materialEntries = entryDao.findByEntryId(customerEntry.getId());
        BigDecimal total = BigDecimal.ZERO;
        int nbqNum = 0;//实际安装逆变器数量
        List<String> actualSpecList = new ArrayList<>();//实际安装逆变器规格集合
        String actualZjSpec = "";//实际安装组件规格
        int i = 0;
        for (CrmPlanMaterialEntry materialEntry : materialEntries) {
            if ("组件".equals(materialEntry.getType())) {
                total = total.add(new BigDecimal(materialEntry.getSpec()));
                actualZjSpec=materialEntry.getSpec();
                i++;
            }
            if ("逆变器".equals(materialEntry.getType())) {
                actualSpecList.add(materialEntry.getSpec());
                nbqNum += materialEntry.getAmount();
            }
        }
        //判断安装组件数量和设计方案是否一致
        Integer designCapacity = customerEntry.getDesignCapacity();
        BigDecimal bigDecimal = new BigDecimal(designCapacity);
        if (bigDecimal.compareTo(total)!=0){
            throw new BusinessException("安装组件数量和设计方案不一致，请确认后再提交！");
        }
        //判断逆变器数量和设计方案是否一致
        List<Record> records = customerEntryComponentService.findByEntryId(customerEntry.getId());
        int nbq = 0;//逆变器设计数量
        List<String> designSpecList = new ArrayList<>();//设计逆变器规格集合
        String designZjSpec = "";
        for (Record record : records) {
            //逆变器
            if ("1".equals(record.getStr("item_type"))){
                nbq += record.getInt("num");
                designSpecList.add(record.getStr("specs"));
            }
            if ("3".equals(record.getStr("item_type"))){
                if(StringUtil.isBlank(designZjSpec)){
                    designZjSpec=record.getStr("specs");
                }
            }
        }
        //判断安装组件规格和设计方案是否一致
        if (!designZjSpec.equals(actualZjSpec)){
            throw new BusinessException("安装组件规格和设计方案不一致，请确认后再提交！");
        }
        //判断安装逆变器规格和设计方案是否一致
        for (String actualSpec : actualSpecList) {
            if (!designSpecList.contains(actualSpec)){
                throw new BusinessException("安装逆变器规格和设计方案不一致，请确认后再提交！");
            }
        }
        if (nbq != nbqNum){
            throw new BusinessException("安装逆变器数量和设计方案不一致，请确认后再提交！");
        }
        customerEntry.setActualCapacity(total);
        Date now = new Date();
        CrmAcceptingReport report = null;
        if(PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
            report = saveReportHr(customerEntry, req, operator, now, i);
        }else{
            report = saveReport(customerEntry, req, operator, now, i);
        }
        if ( PartnerConstants.PARTNER_ID_GF.equals(customerEntry.getPartnerId())  && "1".equals(customerEntry.getIsHistory())) {
            if (StringUtil.isNotBlank(report.getContractUrl())){
                customerEntry.setSignStatus(ESignConstants.GF_CONTRACT_STATUS_YSC);
            }else {
                customerEntry.setSignStatus(ESignConstants.GF_CONTRACT_STATUS_DSC);
            }
        }
        customerEntry.setReceivingReportId(report.getId());
        customerEntry.setInstallBy(operator.getUserId());
        customerEntry.setInstallTime(now);

        String confirmId = IdGen.uuid();
        String oldConfirmId = Db.queryStr("select id from crm_customer_entry_out_confirm where entry_id=?",customerEntry.getId());
        if (StringUtil.isNotBlank(oldConfirmId)) {
            confirmId = oldConfirmId;
        }

        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(customerEntry.getId());
        if (surveyRecord != null) {
            surveyRecord.setFilingDocumentCode(req.getFilingDocumentCode());
            surveyRecord.setFilingDocumentPhoto(req.getFilingDocumentPhoto());
            surveyRecordDao.save(surveyRecord);
        }


        //是否有新物料安装
        if (!(list == null || list.isEmpty())) {
            // 出库
            // 查询代理商仓库
            String warehouseId = customerEntry.getWarehouseId();
            if (StringUtil.isBlank(warehouseId)) {
//            List<Record> warehouseList = supplyWarehouseDao.findByTypeAndAscriptionId(WarehouseConstants.WAREHOUSE_TYPE_JXS, customerEntry.getDistributorId());
//            warehouseId = warehouseList.get(0).getStr("id");
                throw new BusinessException("请选择安装仓库");
            }

            boolean hasBwx = false;
            // 获取仓库库存
            for (Record re : list) {
                if (StringUtil.isBlank(re.getStr("material_id"))) {
                    continue;
                }
                // 查询物料信息
                SupplyMaterial material = supplyMaterialDao.get(re.getStr("material_id"));
                MaterialWarehouseStocks warehouseStocks = materialStockDao.findByWarehouse(re.getStr("material_id"), warehouseId);
                if (warehouseStocks == null) {
                    throw new BusinessException(String.format("物料编号【%s】库存不足", material.getCode()));
                } else if (re.getBigDecimal("amount").compareTo(warehouseStocks.getWarning()) > 0) {
                    throw new BusinessException(String.format("物料编号【%s】库存不足", material.getCode()));
                }
                warehouseStocks.setWarning(warehouseStocks.getWarning().subtract(re.getBigDecimal("amount")));
                warehouseStocks.setRealNum(warehouseStocks.getRealNum().subtract(re.getBigDecimal("amount")));
                warehouseStocks.setNewestKeepTime(new Date());
                materialStockDao.save(warehouseStocks);
                // 按库存批次先进先出出库
                StockUnit stockUnit = new StockUnit(material.getId(), warehouseId);
//            String keepId = IdGen.uuid();
                KeepUnit keepUnit = new KeepUnit(operator.getUserId(), operator.getUserName(), "2", "5", customerEntry.getId(),
                        customerEntry.getPowerStationCode(), customerEntry.getRemarks(), material.getId(), material.getCode(), re.getStr("type"),
                        material.getRemarks(), null, null, re.getBigDecimal("amount"),
                        warehouseId, "",material.getUnitName());
                keepUnit.setProjectCode(customerEntry.getProjectCode());
                fifoStock.deliverForBatch(stockUnit, keepUnit, re.getBigDecimal("amount"),"");

                if ("并网箱".equals(re.getStr("type"))) {
                    hasBwx = true;
                }
                //出库确认明细
                Db.update("INSERT INTO `crm_customer_entry_out_confirm_detail`(id,main_id,`num`,material_id,create_time) VALUES(?,?,?,?,NOW())",
                        IdGen.uuid(),confirmId,re.getBigDecimal("amount"), re.getStr("material_id"));
            }

            //未使用系统提供的并网箱标记
            if (!hasBwx) {
                customerEntry.setFlag("1");
            }

            //将物料置为旧物料
            SQLQuery sqlQuery = entryDao.getSession().createSQLQuery("update crm_plan_material_entry set old_flag='2' where entry_id = :id and material_id <> ''");
            sqlQuery.setParameter("id", customerEntry.getId());
            sqlQuery.executeUpdate();
        }

        //判断是否需要安装自审
        if (!FormSetUtils.processSetEnable(customerEntry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_AZJS)) {
            customerEntry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DAZYS);
            customerEntry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_AZWC);
            customerEntry.setCheckAcceptFlag(CustomerEntryConstants.CHECK_ACCEPT_FLAG_ZSTG);
        } else {
            customerEntry.setStatus(CustomerEntryConstants.ENTRY_STATUS_AZZS);
            customerEntry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_AZWC);
            customerEntry.setCheckAcceptFlag(CustomerEntryConstants.CHECK_ACCEPT_FLAG_DZS);
        }

        customerDao.save(customerEntry);
        msgService.saveCustomerEntryMsg(operator, customerEntry.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_CANCEL_AUDIT,req.getCompleteRemark(),null);

        //生成待出库确认单
        if (StringUtil.isBlank(oldConfirmId)) {
            Db.update("INSERT INTO `crm_customer_entry_out_confirm`(id,entry_id,`status`,create_time) VALUES(?,?,'1',NOW())",
                    confirmId, customerEntry.getId());
        }

        //判断是否需要安装验收
        if (!FormSetUtils.processSetEnable(customerEntry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_AZYS)
                && CustomerEntryConstants.ENTRY_STATUS_DAZYS.equals(customerEntry.getStatus())) {
            toNetAcceptPass(customerEntry.getId(), "1", null, CustomerEntryConstants.FIX_FLAG_FINISH, operator, UserUtils.getUser());
        }
        if(CustomerEntryConstants.ENTRY_STATUS_DAZYS.equals(customerEntry.getStatus())){
            //需要安装验收 ，那么生成安装验收的任务
            String stationName = CrmUtils.getStationName(customerEntry);
            itemManageDao.addItem(FormUtils.ENTRY_STATUS_AZYS,customerEntry.getId(), PlantformUtils.getOrderNumber(),"安装验收("+stationName+"-"+customerEntry.getPowerStationCode()+")-"+DateUtils.formatDate(now,"yyyy-MM-dd HH:mm:ss"),now,operator.getUserName());
        }
    }

    /**
     * 安装完成
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchHrInstall(AddReportReq req, Operator operator) {
        CustomerEntry customerEntry = customerDao.get(req.getEntryId());
//        customerEntry.setLongitude(req.getLongitude());
//        customerEntry.setLatitude(req.getLatitude());
        logger.info("batchInstall customerEntry={}",JSONObject.toJSONString(customerEntry));
        if (customerEntry == null) {
            throw new BusinessException("订单不存在或状态异常");
        } else if (!CustomerEntryConstants.ENTRY_STATUS_DAZ.equals(customerEntry.getStatus()) && !CustomerEntryConstants.ENTRY_STATUS_AZYSTH.equals(customerEntry.getStatus())) {
            throw new BusinessException("信息状态发生变化，请刷新后再试");
        }
        if(StringUtil.isBlank(customerEntry.getInstallBy())){
            throw new BusinessException("请先电站安装!");
        }
        //项目公司备案 判断备案文件必填,项目备案代码必填
        if (CustomerEntryConstants.FILING_TYPE_COMPANY.equals(customerEntry.getFilingType())) {
            GuardUtils.notBlank(req.getFilingDocumentCode(), "项目备案代码不能为空");
            GuardUtils.notBlank(req.getFilingDocumentPhoto(), "备案证不能为空");
        }
        //广发存量电站合同必填
        if(PartnerConstants.PARTNER_ID_GF.equals(customerEntry.getPartnerId()) && "1".equals(customerEntry.getIsHistory())){
            GuardUtils.notBlank(req.getContractUrl(), "合同不能为空");
        }
        //租户类型是单位
        if (CustomerEntryConstants.TENANT_TYPE_COMPANY.equals(customerEntry.getTenantType()) && "01".equals(customerEntry.getPartnerId())) {
            GuardUtils.notBlank(req.getOtherImgs1(), "银行印鉴留样不能为空");
            GuardUtils.notBlank(req.getOtherImgs2(), "签约现场照片不能为空");
            GuardUtils.notBlank(req.getOtherImgs3(), "约现场照片-正脸照片不能为空");
            GuardUtils.notBlank(req.getOtherImgs4(), "签署完成照片不能为空");
            GuardUtils.notBlank(req.getOtherFiles(), "其他资料不能为空");
        }
        /*if ("1".equals(customerEntry.getTenantType()) && !StringUtil.equalsAny(customerEntry.getSignStatus(),"2","3","5","g","e")
                &&FormSetUtils.processSetEnable(customerEntry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZFSH)) {
            throw new BusinessException("当前电站未签约《农户合同》，请在签约后再提交完工!");
        }*/

        // 查询项目信息
        //CrmProjectSetting projectSetting = projectDao.get(customerEntry.getProjectId());
        // 校验必填项
        List<Record> checkList = formSetDao.findListByCondition("03", customerEntry.getPartnerId());
        Result result = null;
        if(PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
            if (req.getCompleteList() == null || req.getCompleteList().isEmpty()) {
                throw new BusinessException("请先上传完工资料");
            }
            result = requiredCheckForInstallHr(req, checkList);
        }else{
            result = requiredCheckForInstall(req, checkList);
        }
        if (!"200".equals(result.getCode())) {
            throw new BusinessException(result.getErrMsg());
        }
        // 查询使用的新物料
        List<Record> list = entryDao.findNewMostSpecByEntryId(customerEntry.getId());
        /*Long oldCount = entryDao.getOldMostSpecCnt(customerEntry.getId());
        if ((list == null || list.isEmpty()) && oldCount == 0) {
            throw new BusinessException("完工前请先安装");
        }*/
        long snCount = entryDao.findMaterialSnByEntryId(customerEntry.getId());
        if (snCount == 0) {
            throw new BusinessException("sn码为空");
        }
        String checkApplyResult = CrmUtils.checkExistApply(customerEntry.getStatus(), customerEntry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            throw new BusinessException(checkApplyResult);
        }

        // 获取实际安装容量
        List<CrmPlanMaterialEntry> materialEntries = entryDao.findByEntryId(customerEntry.getId());
        Map<String,List<CrmPlanMaterialEntry>> map = materialEntries.stream().collect(Collectors.groupingBy(CrmPlanMaterialEntry::getProjectId));
        Set ketSet = map.keySet();
        int i = 0;
        BigDecimal total = BigDecimal.ZERO;
        for (Object key : ketSet){
            String roofType = crmCustomerEntryProjectDao.getRoofTypeByProjectId(customerEntry.getId(), (String) key);
            List<CrmPlanMaterialEntry> mList = map.get(key);

            int nbqNum = 0;//实际安装逆变器数量
            List<String> actualSpecList = new ArrayList<>();//实际安装逆变器规格集合
            String actualZjSpec = "";//实际安装组件规格

            for (CrmPlanMaterialEntry materialEntry : mList) {
                if ("组件".equals(materialEntry.getType())) {
                    total = total.add(new BigDecimal(materialEntry.getSpec()));
                    actualZjSpec=materialEntry.getSpec();
                    i++;
                }
                if ("逆变器".equals(materialEntry.getType())) {
                    actualSpecList.add(materialEntry.getSpec());
                    nbqNum += materialEntry.getAmount();
                }
            }


            //判断逆变器数量和设计方案是否一致
            List<Record> records = customerEntryComponentService.findByEntryIdByProjectId(customerEntry.getId(),(String) key);
            int nbq = 0;//逆变器设计数量
            List<String> designSpecList = new ArrayList<>();//设计逆变器规格集合
            String designZjSpec = "";
            for (Record record : records) {
                //逆变器
                if ("1".equals(record.getStr("item_type"))){
                    nbq += record.getInt("num");
                    designSpecList.add(record.getStr("specs"));
                }
                if ("3".equals(record.getStr("item_type"))){
                    if(StringUtil.isBlank(designZjSpec)){
                        designZjSpec=record.getStr("specs");
                    }
                }
            }
            //判断安装组件规格和设计方案是否一致
            if (!designZjSpec.equals(actualZjSpec)){
                throw new BusinessException(roofType+"安装组件规格和设计方案不一致，请确认后再提交！");
            }
            //判断安装逆变器规格和设计方案是否一致
            for (String actualSpec : actualSpecList) {
                if (!designSpecList.contains(actualSpec)){
                    throw new BusinessException(roofType+"安装逆变器规格和设计方案不一致，请确认后再提交！");
                }
            }
            if (nbq != nbqNum){
                throw new BusinessException(roofType+"安装逆变器数量和设计方案不一致，请确认后再提交！");
            }

        }
        //判断安装组件数量和设计方案是否一致
        Integer designCapacity = customerEntry.getDesignCapacity();
        BigDecimal bigDecimal = new BigDecimal(designCapacity);
        if (bigDecimal.compareTo(total)!=0){
            throw new BusinessException("安装组件数量和设计方案不一致，请确认后再提交！");
        }
        customerEntry.setActualCapacity(total);

        Date now = new Date();
        CrmAcceptingReport report = null;
        if(PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
            report = saveReportHr(customerEntry, req, operator, now, i);
        }else{
            report = saveReport(customerEntry, req, operator, now, i);
        }
        customerEntry.setReceivingReportId(report.getId());
        customerEntry.setInstallBy(operator.getUserId());
        customerEntry.setInstallTime(now);

        String confirmId = IdGen.uuid();
        String oldConfirmId = Db.queryStr("select id from crm_customer_entry_out_confirm where entry_id=?",customerEntry.getId());
        if (StringUtil.isNotBlank(oldConfirmId)) {
            confirmId = oldConfirmId;
        }

        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(customerEntry.getId());
        if (surveyRecord != null) {
            surveyRecord.setFilingDocumentCode(req.getFilingDocumentCode());
            surveyRecord.setFilingDocumentPhoto(req.getFilingDocumentPhoto());
            surveyRecordDao.save(surveyRecord);
        }


        //是否有新物料安装
        if (!(list == null || list.isEmpty())) {
            // 出库
            // 查询代理商仓库
            String warehouseId = customerEntry.getWarehouseId();
            if (StringUtil.isBlank(warehouseId)) {
//            List<Record> warehouseList = supplyWarehouseDao.findByTypeAndAscriptionId(WarehouseConstants.WAREHOUSE_TYPE_JXS, customerEntry.getDistributorId());
//            warehouseId = warehouseList.get(0).getStr("id");
                throw new BusinessException("请选择安装仓库");
            }

            boolean hasBwx = false;
            // 获取仓库库存
            for (Record re : list) {
                if (StringUtil.isBlank(re.getStr("material_id"))) {
                    continue;
                }
                // 查询物料信息
                SupplyMaterial material = supplyMaterialDao.get(re.getStr("material_id"));
                MaterialWarehouseStocks warehouseStocks = materialStockDao.findByWarehouse(re.getStr("material_id"), warehouseId);
                if (warehouseStocks == null) {
                    throw new BusinessException(String.format("物料编号【%s】库存不足", material.getCode()));
                } else if (re.getBigDecimal("amount").compareTo(warehouseStocks.getWarning()) > 0) {
                    throw new BusinessException(String.format("物料编号【%s】库存不足", material.getCode()));
                }
                warehouseStocks.setWarning(warehouseStocks.getWarning().subtract(re.getBigDecimal("amount")));
                warehouseStocks.setRealNum(warehouseStocks.getRealNum().subtract(re.getBigDecimal("amount")));
                warehouseStocks.setNewestKeepTime(new Date());
                materialStockDao.save(warehouseStocks);
                // 按库存批次先进先出出库
                StockUnit stockUnit = new StockUnit(material.getId(), warehouseId);
//            String keepId = IdGen.uuid();
                KeepUnit keepUnit = new KeepUnit(operator.getUserId(), operator.getUserName(), "2", "5", customerEntry.getId(),
                        customerEntry.getPowerStationCode(), customerEntry.getRemarks(), material.getId(), material.getCode(), re.getStr("type"),
                        material.getRemarks(), null, null, re.getBigDecimal("amount"),
                        warehouseId, "",material.getUnitName());
                keepUnit.setProjectCode(customerEntry.getProjectCode());
                fifoStock.deliverForBatch(stockUnit, keepUnit, re.getBigDecimal("amount"),"");

                if ("并网箱".equals(re.getStr("type"))) {
                    hasBwx = true;
                }
                //出库确认明细
                Db.update("INSERT INTO `crm_customer_entry_out_confirm_detail`(id,main_id,`num`,material_id,create_time) VALUES(?,?,?,?,NOW())",
                        IdGen.uuid(),confirmId,re.getBigDecimal("amount"), re.getStr("material_id"));
            }

            //未使用系统提供的并网箱标记
            if (!hasBwx) {
                customerEntry.setFlag("1");
            }

            //将物料置为旧物料
            SQLQuery sqlQuery = entryDao.getSession().createSQLQuery("update crm_plan_material_entry set old_flag='2' where entry_id = :id and material_id <> ''");
            sqlQuery.setParameter("id", customerEntry.getId());
            sqlQuery.executeUpdate();
        }

        //判断是否需要安装自审
        if (!FormSetUtils.processSetEnable(customerEntry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_AZJS)) {
            customerEntry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DAZYS);
            customerEntry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_AZWC);
            customerEntry.setCheckAcceptFlag(CustomerEntryConstants.CHECK_ACCEPT_FLAG_ZSTG);
        } else {
            customerEntry.setStatus(CustomerEntryConstants.ENTRY_STATUS_AZZS);
            customerEntry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_AZWC);
            customerEntry.setCheckAcceptFlag(CustomerEntryConstants.CHECK_ACCEPT_FLAG_DZS);
        }

        customerDao.save(customerEntry);
        msgService.saveCustomerEntryMsg(operator, customerEntry.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_CANCEL_AUDIT,req.getCompleteRemark(),null);

        //生成待出库确认单
        if (StringUtil.isBlank(oldConfirmId)) {
            Db.update("INSERT INTO `crm_customer_entry_out_confirm`(id,entry_id,`status`,create_time) VALUES(?,?,'1',NOW())",
                    confirmId, customerEntry.getId());
        }

        //判断是否需要安装验收
        if (!FormSetUtils.processSetEnable(customerEntry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_AZYS)
                && CustomerEntryConstants.ENTRY_STATUS_DAZYS.equals(customerEntry.getStatus())) {
            toNetAcceptPass(customerEntry.getId(), "1", null, CustomerEntryConstants.FIX_FLAG_FINISH, operator, UserUtils.getUser());
        }
        if(CustomerEntryConstants.ENTRY_STATUS_DAZYS.equals(customerEntry.getStatus())){
            //需要安装验收 ，那么生成安装验收的任务
            String stationName = CrmUtils.getStationName(customerEntry);
            itemManageDao.addItem(FormUtils.ENTRY_STATUS_AZYS,customerEntry.getId(), PlantformUtils.getOrderNumber(),"安装验收("+stationName+"-"+customerEntry.getPowerStationCode()+")-"+DateUtils.formatDate(now,"yyyy-MM-dd HH:mm:ss"),now,operator.getUserName());
        }
    }


    //完工暂存
    @Transactional(rollbackFor = Exception.class)
    public void batchInstallZc(AddReportZcReq req, Operator operator) {

        CustomerEntry customerEntry = customerDao.get(req.getEntryId());
        if (customerEntry == null) {
            throw new BusinessException("订单不存在或状态异常");
        } else if (!CustomerEntryConstants.ENTRY_STATUS_DAZ.equals(customerEntry.getStatus()) && !CustomerEntryConstants.ENTRY_STATUS_AZYSTH.equals(customerEntry.getStatus())) {
            throw new BusinessException("信息状态发生变化，请刷新后再试");
        }
        logger.info("batchInstall customerEntry={}",JSONObject.toJSONString(customerEntry));
        // 获取实际安装容量
        List<CrmPlanMaterialEntry> materialEntries = entryDao.findByEntryId(customerEntry.getId());
        BigDecimal total = BigDecimal.ZERO;
        int i = 0;
        for (CrmPlanMaterialEntry materialEntry : materialEntries) {
            if ("组件".equals(materialEntry.getType())) {
                total = total.add(new BigDecimal(materialEntry.getSpec()));
                i++;
            }
        }
        customerEntry.setActualCapacity(total);
        Date now = new Date();
        CrmAcceptingReport report = saveReportZc(customerEntry, req, operator, now, i);
        if ( PartnerConstants.PARTNER_ID_GF.equals(customerEntry.getPartnerId())  && "1".equals(customerEntry.getIsHistory())) {
            if (StringUtil.isNotBlank(report.getContractUrl())){
                customerEntry.setSignStatus(ESignConstants.GF_CONTRACT_STATUS_YSC);
            }else {
                customerEntry.setSignStatus(ESignConstants.GF_CONTRACT_STATUS_DSC);
            }
        }
        customerEntry.setReceivingReportId(report.getId());
        if (StringUtil.isNotBlank(req.getMobile())) {
            customerEntry.setMobile(req.getMobile().trim());
        }
        if (StringUtil.isNotBlank(req.getTenantName())) {
            customerEntry.setTenantName(req.getTenantName());
        }
        if (StringUtil.isNotBlank(req.getAddress())) {
            customerEntry.setAddress(req.getAddress().trim());
        }
//        customerEntry.setInstallBy(operator.getUserId());
//        customerEntry.setInstallTime(now);
        customerDao.save(customerEntry);
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(customerEntry.getId());
        if (surveyRecord != null) {
            surveyRecord.setFilingDocumentCode(req.getFilingDocumentCode());
            surveyRecord.setFilingDocumentPhoto(req.getFilingDocumentPhoto());
            surveyRecordDao.save(surveyRecord);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchInstallZcHr(AddReportZcReq req, Operator operator) {
            CustomerEntry customerEntry = customerDao.get(req.getEntryId());
            if (customerEntry == null) {
                throw new BusinessException("订单不存在或状态异常");
            } else if (!CustomerEntryConstants.ENTRY_STATUS_DAZ.equals(customerEntry.getStatus()) && !CustomerEntryConstants.ENTRY_STATUS_AZYSTH.equals(customerEntry.getStatus())) {
                throw new BusinessException("信息状态发生变化，请刷新后再试");
            }
            logger.info("batchInstall customerEntry={}",JSONObject.toJSONString(customerEntry));
            // 获取实际安装容量
            List<CrmPlanMaterialEntry> materialEntries = entryDao.findByEntryId(customerEntry.getId());
            BigDecimal total = BigDecimal.ZERO;
            int i = 0;
            for (CrmPlanMaterialEntry materialEntry : materialEntries) {
                if ("组件".equals(materialEntry.getType())) {
                    total = total.add(new BigDecimal(materialEntry.getSpec()));
                    i++;
                }
            }
            customerEntry.setActualCapacity(total);
            Date now = new Date();
            CrmAcceptingReport report = saveReportZcHr(customerEntry, req, operator, now, i);
            customerEntry.setReceivingReportId(report.getId());
            if (StringUtil.isNotBlank(req.getMobile())) {
                customerEntry.setMobile(req.getMobile().trim());
            }
            if (StringUtil.isNotBlank(req.getTenantName())) {
                customerEntry.setTenantName(req.getTenantName());
            }
            if (StringUtil.isNotBlank(req.getAddress())) {
                customerEntry.setAddress(req.getAddress().trim());
            }
//        customerEntry.setInstallBy(operator.getUserId());
//        customerEntry.setInstallTime(now);
            customerDao.save(customerEntry);
            CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(customerEntry.getId());
            if (surveyRecord != null) {
                surveyRecord.setFilingDocumentCode(req.getFilingDocumentCode());
                surveyRecord.setFilingDocumentPhoto(req.getFilingDocumentPhoto());
                surveyRecordDao.save(surveyRecord);
            }

    }

    @Transactional(rollbackFor = Exception.class)
    public void batchMerge(List<String> ids, Operator operator) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new BusinessException("安装信息不能为空");
        }
        for (String id : ids) {
            CustomerEntry customerEntry = customerDao.get(id);
            if (!CustomerEntryConstants.ENTRY_STATUS_DBW.equals(customerEntry.getStatus())) {
                throw new BusinessException("信息状态发生变化，请刷新后再试");
            }
            customerEntry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DYS);
            customerEntry.setMergeBy(operator.getUserId());
            customerEntry.setMergeTime(new Date());
            customerEntry.setMergeName(operator.getUserName());
            customerDao.save(customerEntry);
            msgService.saveCustomerEntryMsg(operator, id, CustomerEntryConstants.ADVANCE_TYPE_OPT_BINGW);
        }
    }
    /**
     *
     */
    public List<Record> findMaterialListByEntryId(String entryId){
        return entryDao.findMaterialListByEntryId(entryId);
    }



    /**
     * 并网
     */
    @Transactional(rollbackFor = Exception.class)
    public void accept(AddReportSecondReq req, Operator operator) {
        CustomerEntry customerEntry = customerDao.get(req.getEntryId());
        if (customerEntry == null) {
            throw new BusinessException("订单不存在或状态异常");
        } else if (!CustomerEntryConstants.ENTRY_STATUS_DBW.equals(customerEntry.getStatus())) {
            throw new BusinessException("信息状态发生变化，请刷新后再试");
        }
        Date now = new Date();
        customerEntry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DYS);
        customerEntry.setGeneratorNo(req.getGeneratorNo());
//        customerEntry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DAZYS);
        customerEntry.setMergeBy(operator.getUserId());
        customerEntry.setMergeName(operator.getUserName());
        customerEntry.setMergeTime(now);
        customerDao.save(customerEntry);

        CrmAcceptingReport report = reportDao.get(customerEntry.getReceivingReportId());
        report.setYxImg(req.getYxImg());
        report.setGebImg(req.getGebImg());
        report.setGebImg2(req.getGebImg2());
        report.setMergeAcceptBy(operator.getUserId());
        report.setMergeAcceptName(operator.getUserName());
        report.setMergeAcceptTime(now);
        reportDao.save(report);

        msgService.saveCustomerEntryMsg(operator, customerEntry.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_BINGW);
    }

    /**
     * 获取token --只有浙银的才会获取
     */
    public String findZypubKey(String type) {
        if (StringUtil.isNotBlank(type)) {
            cacheService.del("findZypubKey");
        }
        String zypubKey;
        String url = "/api/public/pub-key";
        Map<String, Object> jieMap = gwEzTemplate.postForm(url, SourceConstants.TYPR_ZY, null, new ParameterizedTypeReference<Map<String, Object>>() {
        });
        logger.info("findZypubKey --------------  :{}", jieMap);
        Object pubKey = jieMap.get("PUB_KEY");
        zypubKey = pubKey.toString();
        logger.info("findZypubKey --------------zypubKey  :{}", pubKey);

        return zypubKey;
    }







    @Transactional(rollbackFor = Exception.class)
    public void returnEntry(String id) {
        CustomerEntry customerEntry = customerDao.get(id);
        if (!CustomerEntryConstants.ENTRY_STATUS_DZF.equals(customerEntry.getStatus()) && !CustomerEntryConstants.ENTRY_STATUS_GDBH.equals(customerEntry.getStatus())) {
            throw new BusinessException("信息状态发生变化，请刷新后再试");
        }
        User currentUser = UserUtils.getUser();
        customerEntry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DYS);
        customerEntry.setCheckAcceptImgs("");
        customerDao.save(customerEntry);
        //更改验收报告状态
        CrmAcceptingReport report = reportDao.get(customerEntry.getReceivingReportId());
        report.setStatus(CustomerEntryConstants.REPORT_STATUS_DYS);
        reportDao.save(report);
        msgService.saveCustomerEntryMsg(currentUser, id, CustomerEntryConstants.ADVANCE_TYPE_OPT_DJFRETURN, "");
    }



    /**
     * 提交验收报告
     */
    /*@Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public void tempSaveReport(addReportReq req, Operator operator) {
        CustomerEntry customerEntry = customerDao.get(req.getEntryId());
        if (customerEntry == null || !(CustomerEntryConstants.ENTRY_STATUS_DBW.equals(customerEntry.getStatus()) || CustomerEntryConstants.ENTRY_STATUS_YSBH.equals(customerEntry.getStatus()))) {
            throw new BusinessException("订单不存在或状态异常");
        }
        customerEntry.setGeneratorNo(req.getGeneratorNo());
        CrmAcceptingReport report = saveReport(customerEntry, req, operator);
        customerEntry.setReceivingReportId(report.getId());
        if (StringUtil.isNotBlank(req.getMobile())) {
            customerEntry.setMobile(req.getMobile());
        }
        if (StringUtil.isNotBlank(req.getTenantName())) {
            customerEntry.setTenantName(req.getTenantName());
        }
        if (StringUtil.isNotBlank(req.getAddress())) {
            customerEntry.setAddress(req.getAddress());
        }
        customerDao.save(customerEntry);
    }*/

    private CrmAcceptingReport saveReport(CustomerEntry customerEntry, AddReportReq req, Operator operator,
                                          Date time, int i) {
        CrmAcceptingReport report;
        if (StrKit.notBlank(customerEntry.getReceivingReportId())) {
            report = reportDao.get(customerEntry.getReceivingReportId());
        } else {
            report = new CrmAcceptingReport();
            report.setCreateBy(operator.getUserId());
            report.setCreator(operator.getUserName());
            report.setCreateTime(time);
            report.setStatus(CustomerEntryConstants.REPORT_STATUS_DYS);
        }
        report.setComponentSpec(customerEntry.getComponentSpec());
        report.setComponentNum(i);
        report.setCapacity(customerEntry.getActualCapacity());
        report.setOtherImgs1(req.getOtherImgs1());
        report.setOtherImgs2(req.getOtherImgs2());
        report.setOtherImgs3(req.getOtherImgs3());
        report.setOtherImgs4(req.getOtherImgs4());
        report.setDzjc1(req.getDzjc1());
        report.setDzjc2(req.getDzjc2());
        report.setZjImg1(req.getZjImg1());
        report.setZjImg2(req.getZjImg2());
        report.setZjImg3(req.getZjImg3());
        report.setZjImg4(req.getZjImg4());
        report.setZjImg5(req.getZjImg5());
        report.setComponentImg1(req.getComponentImg1());
        report.setComponentImg2(req.getComponentImg2());
        report.setSizeMeasureImgs(req.getSizeMeasureImgs());
        report.setFixOtherImg(req.getFixOtherImg());
        report.setTotalImgs(req.getTotalImgs());
        report.setBwInnerImg(req.getBwInnerImg());
        report.setDcImgs(req.getDcImgs());
        report.setNbqZbImg(req.getNbqZbImg());
        report.setNbqPlateImg(req.getNbqPlateImg());
        report.setDqsbAnImgOne(req.getDqsbAnImgOne());
        report.setZjPlateImg(req.getZjPlateImg());
        report.setOpenWayVoltageImgs(req.getOpenWayVoltageImgs());
        report.setJdImg1(req.getJdImg1());
        report.setJdImg2(req.getJdImg2());
        report.setOtherFiles(req.getOtherFiles());
        report.setJdImg3(req.getJdImg3());
        report.setJdImg4(req.getJdImg4());
        report.setJdImg5(req.getJdImg5());
        report.setJdImg6(req.getJdImg6());
        report.setZjReport(req.getZjReport());
        report.setFixAcceptBy(operator.getUserId());
        report.setFixAcceptName(operator.getUserName());
        report.setFixAcceptTime(time);
        report.setStatus(CustomerEntryConstants.REPORT_STATUS_DYS);
        report.setSupplementVideoUrl(req.getSupplementVideoUrl());
        report.setCompleteRemark(req.getCompleteRemark());
        //广发新增字段
        report.setSafetyDiscloseDocImg(req.getSafetyDiscloseDocImg());
        report.setComponentImg3(req.getComponentImg3());
        report.setTotalImgs(req.getTotalImgs());
        report.setSafetyWarningImg(req.getSafetyWarningImg());
        report.setSafetyWarningImg2(req.getSafetyWarningImg2());
        report.setSafetyWarningImg3(req.getSafetyWarningImg3());
        report.setNbqZlcImg(req.getNbqZlcImg());
        report.setBwJdImg(req.getBwJdImg());
        report.setZjImg8(req.getZjImg8());
        report.setZjImg9(req.getZjImg9());
        report.setZjImg10(req.getZjImg10());
        report.setZjImg11(req.getZjImg11());
        report.setZjImg12(req.getZjImg12());
        report.setZjImg13(req.getZjImg13());
        report.setZjImg14(req.getZjImg14());
        report.setZjImg15(req.getZjImg15());
        report.setBkImg1(req.getBkImg1());
        report.setBkImg2(req.getBkImg2());
        report.setBkImg3(req.getBkImg3());
        report.setYkImg1(req.getYkImg1());
        report.setJdImg8(req.getJdImg8());
        report.setJdImg9(req.getJdImg9());
        report.setJdImg10(req.getJdImg10());
        report.setJdImg11(req.getJdImg11());
        report.setJdImg12(req.getJdImg12());
        report.setFsImg1(req.getFsImg1());
        report.setFsImg2(req.getFsImg2());
        report.setFsImg3(req.getFsImg3());
        report.setComponentImg4(req.getComponentImg4());
        report.setContractUrl(req.getContractUrl());
        report.setSignDate(new Date());
        report.setWaterMudClampImgs(req.getWaterMudClampImgs());
        //华融新增字段
        report.setOtherImgs5(req.getOtherImgs5());
        report.setOtherImgs6(req.getOtherImgs6());
        report.setOtherImgs7(req.getOtherImgs7());
        report.setOtherImgs8(req.getOtherImgs8());
        report.setKgConditionFiles(req.getKgConditionFiles());
        reportDao.save(report);
        return report;
    }

    @Transactional(rollbackFor = Exception.class)
    public CrmAcceptingReport saveReportHr(CustomerEntry customerEntry, AddReportReq req, Operator operator,
                                          Date time, int i) {
        CrmAcceptingReport acceptingReport;
        if (StrKit.notBlank(customerEntry.getReceivingReportId())) {
            reportDetailDao.deleteReportDetailByEntryId(customerEntry.getId());
            acceptingReport = reportDao.get(customerEntry.getReceivingReportId());
        } else {
            acceptingReport = new CrmAcceptingReport();
            acceptingReport.setCreateBy(operator.getUserId());
            acceptingReport.setCreator(operator.getUserName());
            acceptingReport.setCreateTime(time);
            acceptingReport.setStatus(CustomerEntryConstants.REPORT_STATUS_DYS);
        }
        acceptingReport.setComponentNum(i);
        acceptingReport.setCapacity(customerEntry.getActualCapacity());
        acceptingReport.setComponentSpec(customerEntry.getComponentSpec());
        List<CrmAcceptingReportDetail> completeList = req.getCompleteList();
        for(CrmAcceptingReportDetail reportDetail : completeList){
            CrmAcceptingReportDetail report = new CrmAcceptingReportDetail();
            String projectId = reportDetail.getProjectId();
            Record record = entryDao.countByEntryProjectId(customerEntry.getId(), projectId);
            if (record == null || record.get("total") == null || record.get("spec") == null ||
                    record.get("num") == null) {
                throw new BusinessException("安装组件数量和设计方案不一致，请确认后再提交！");
            }
            report.setEntryId(req.getEntryId());
            report.setProjectId(projectId);
            report.setCreateBy(operator.getUserId());
            report.setCreator(operator.getUserName());
            report.setCreateTime(time);
            report.setStatus(CustomerEntryConstants.REPORT_STATUS_DYS);
            report.setComponentSpec(record.getStr("spec"));
            report.setComponentNum(record.getLong("num").intValue());
            report.setCapacity(BigDecimal.valueOf(record.getDouble("total")));
            report.setOtherImgs1(reportDetail.getOtherImgs1());
            report.setOtherImgs2(reportDetail.getOtherImgs2());
            report.setOtherImgs3(reportDetail.getOtherImgs3());
            report.setOtherImgs4(reportDetail.getOtherImgs4());
            report.setDzjc1(reportDetail.getDzjc1());
            report.setDzjc2(reportDetail.getDzjc2());
            report.setZjImg1(reportDetail.getZjImg1());
            report.setZjImg2(reportDetail.getZjImg2());
            report.setZjImg3(reportDetail.getZjImg3());
            report.setZjImg4(reportDetail.getZjImg4());
            report.setZjImg5(reportDetail.getZjImg5());
            report.setComponentImg1(reportDetail.getComponentImg1());
            report.setComponentImg2(reportDetail.getComponentImg2());
            report.setSizeMeasureImgs(reportDetail.getSizeMeasureImgs());
            report.setFixOtherImg(reportDetail.getFixOtherImg());
            report.setTotalImgs(reportDetail.getTotalImgs());
            report.setBwInnerImg(reportDetail.getBwInnerImg());
            report.setDcImgs(reportDetail.getDcImgs());
            report.setNbqZbImg(reportDetail.getNbqZbImg());
            report.setNbqPlateImg(reportDetail.getNbqPlateImg());
            report.setDqsbAnImgOne(reportDetail.getDqsbAnImgOne());
            report.setNbqPlateImg(reportDetail.getNbqPlateImg());
            report.setZjPlateImg(reportDetail.getZjPlateImg());
            report.setOpenWayVoltageImgs(reportDetail.getOpenWayVoltageImgs());
            report.setJdImg1(reportDetail.getJdImg1());
            report.setJdImg2(reportDetail.getJdImg2());
            report.setJdImg3(reportDetail.getJdImg3());
            report.setJdImg4(reportDetail.getJdImg4());
            report.setJdImg5(reportDetail.getJdImg5());
            report.setOtherFiles(reportDetail.getOtherFiles());
            report.setJdImg6(reportDetail.getJdImg6());
            report.setZjReport(reportDetail.getZjReport());
            report.setFixAcceptBy(operator.getUserId());
            report.setFixAcceptName(operator.getUserName());
            report.setFixAcceptTime(time);
            report.setStatus(CustomerEntryConstants.REPORT_STATUS_DYS);
            report.setSupplementVideoUrl(reportDetail.getSupplementVideoUrl());
            report.setCompleteRemark(reportDetail.getCompleteRemark());
            //广发新增字段
            report.setSafetyDiscloseDocImg(reportDetail.getSafetyDiscloseDocImg());
            report.setComponentImg3(reportDetail.getComponentImg3());
            report.setTotalImgs(reportDetail.getTotalImgs());
            report.setSafetyWarningImg(reportDetail.getSafetyWarningImg());
            report.setSafetyWarningImg2(req.getSafetyWarningImg2());
            report.setSafetyWarningImg3(reportDetail.getSafetyWarningImg3());
            report.setNbqZlcImg(reportDetail.getNbqZlcImg());
            report.setBwJdImg(reportDetail.getBwJdImg());
            report.setZjImg8(reportDetail.getZjImg8());
            report.setZjImg9(reportDetail.getZjImg9());
            report.setZjImg10(reportDetail.getZjImg10());
            report.setZjImg11(reportDetail.getZjImg11());
            report.setZjImg12(reportDetail.getZjImg12());
            report.setZjImg13(reportDetail.getZjImg13());
            report.setZjImg14(reportDetail.getZjImg14());
            report.setZjImg15(reportDetail.getZjImg15());
            report.setBkImg1(reportDetail.getBkImg1());
            report.setBkImg2(reportDetail.getBkImg2());
            report.setBkImg3(reportDetail.getBkImg3());
            report.setYkImg1(reportDetail.getYkImg1());
            report.setJdImg8(reportDetail.getJdImg8());
            report.setJdImg9(reportDetail.getJdImg9());
            report.setJdImg10(reportDetail.getJdImg10());
            report.setJdImg11(reportDetail.getJdImg11());
            report.setJdImg12(reportDetail.getJdImg12());
            report.setFsImg1(reportDetail.getFsImg1());
            report.setFsImg2(reportDetail.getFsImg2());
            report.setFsImg3(reportDetail.getFsImg3());
            report.setComponentImg4(reportDetail.getComponentImg4());
            report.setContractUrl(reportDetail.getContractUrl());
            //华融新增字段
            report.setOtherImgs5(reportDetail.getOtherImgs5());
            report.setOtherImgs6(reportDetail.getOtherImgs6());
            report.setOtherImgs7(reportDetail.getOtherImgs7());
            report.setOtherImgs8(reportDetail.getOtherImgs8());
            report.setKgConditionFiles(req.getKgConditionFiles());
            reportDetailDao.save(report);
        }
        reportDao.save(acceptingReport);
        return acceptingReport;
    }

    public void createEntryPdf(CrmAcceptingReport report, CustomerEntry entry, String type,CustomerEntryToExamine examine,Map<String,Object> map,List<Record> list) {
        if (report == null) {
            report = reportDao.get(entry.getReceivingReportId());
        }
        String fileName = entry.getTraderName() + "-户用电站验收报告";
        String fileName1 = entry.getTraderName() + "-户用电站验收报告";

        String fileUrl = String.format(FILE_PATH_TEMPLATE, IdGen.uuid()) + "/" + fileName + ".pdf";
        //压缩有的文件路劲
        String filenewUrl = String.format(FILE_PATH_TEMPLATE, IdGen.uuid()) + "/" + fileName1 + ".pdf";
        File file = null;
        File newfile = null;
        try {
            file = new File(fileUrl);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            newfile = new File(filenewUrl);
            if (!newfile.getParentFile().exists()) {
                newfile.getParentFile().mkdirs();
            }
            file.createNewFile();
            //生成pdf文件
            PdfReport.createBusinessInfoPDF(new FileOutputStream(file), report, entry,examine,map,list);
            logger.info("createEntryPdf 电站编码：{} 生成pdf文件 文件大小魏：{}", entry.getPowerStationCode(), FileUtils.sizeOf(file));
            //压缩pdf
            new ReduceSize().manipulatePdf(fileUrl, filenewUrl);
            logger.info("createEntryPdf 电站编码：{} 生成pdf文件 压缩后文件大小：{}", entry.getPowerStationCode(), FileUtils.sizeOf(newfile));
            //上传
            byte[] buffer = PdfReport.File2byte(newfile);
            String fileInfo = AliyunOSSClientUtil.uploadImage(buffer, "pdf", fileName);
            logger.info("返回路径信息" + fileInfo + fileInfo);

            String sql = "UPDATE crm_customer_entry SET check_accept_imgs=? WHERE id=?";
            Db.update(sql, com.sifang.modules.sys.common.utils.StringUtil.convertBackSlant(fileInfo), entry.getId());
            cacheService.hset("entryIdFileSize", entry.getId(), String.valueOf(FileUtils.sizeOf(file)));
            cacheService.hset("entryIdFileName", entry.getId(), fileName + ".pdf");
            if ("1".equals(type)) {
                uploadAttachment(entry.getId(), fileInfo);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("生成 PDF文件推送验收报告至浙银失败 generatePdf Exception：{}", e);
            throw new BusinessException("交付失败,推送验收报告至浙银失败");
        } finally {
            file.delete();
            newfile.delete();
        }
    }


    public void uploadAttachment(String id, String fileUr) {
        CrmCustomerIncomingApplication application = null;
        if (StringUtil.isBlank(fileUr)) {
            fileUr = Db.queryStr("select check_accept_imgs from crm_customer_entry where id =?", id);
            application = applicationDao.getIncomingByEntryId(id);
        } else {
            application = applicationDao.getByEntryId(id);
        }
        String sileSize = cacheService.hget("entryIdFileSize", id);
        String fileName = cacheService.hget("entryIdFileName", id);

        if (StringUtil.isBlank(fileName)) {
            fileName = fileUr.substring(fileUr.lastIndexOf("/") + 1);
        }
        String fileUrl = String.format(FILE_PATH_TEMPLATE, IdGen.uuid() + "/" + fileName);
        File file = new File(fileUrl);
        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            new ReduceSize().manipulatePdf(commonStaticImgPath + fileUr, fileUrl);
            byte[] buffer = FileUtils.readFileToByteArray(file);

            logger.info("压缩文件： 压缩前 size:{},---- 压缩后路劲 url: {}, -----压缩后文件大小： {}", sileSize, fileUrl, FileUtils.sizeOf(file));
            operatingLeaseService.uploadCheckProject(application, fileName, fileUrl, String.valueOf(FileUtils.sizeOf(file)), buffer);
        } catch (Exception e) {
            logger.error("uploadAttachment 压缩文件失败=------- ：", e);
        } finally {
            file.delete();
        }

    }

    @Transactional(readOnly = true)
    public void uploadTwoAttachmentTh(String id, String type, String managementType) {
        if (StringUtil.isBlank(managementType)) {
            CustomerEntry customerEntry = customerDao.get(id);
            if (!"2".equals(customerEntry.getNextApplyStatus())) {
                throw new BusinessException("不满足上传附件的条件");
            }
            managementType = customerEntry.getManagementType();
        }
        logger.info("uploadTwoAttachment-----上传附件  id:{},type:{}, managementType:{},tiaojain:{}", id, type, managementType, CustomerEntryConstants.TYPE_ZJYL.equals(managementType));
        if (CustomerEntryConstants.TYPE_ZJYL.equals(managementType)) {
            logger.info("uploadTwoAttachment-----上传附件 two ");
            CrmCustomerIncomingApplication application = applicationDao.getByEntryId(id);
            logger.info("uploadTwoAttachment-----上传附件 {}", application);
            if (application != null) {

            }
        }

        //uploadCheckProject(application,fileName,customerEntry.getCheckAcceptImgs(),sileSize);
    }

    @Transactional(readOnly = true)
    public void uploadTwoAttachmentNot(String powerStationCode, String type, String managementType) {
        String id = null;
        if (StringUtil.isBlank(managementType)) {
            Record rd = Db.findFirst("select * from crm_customer_entry where power_station_code=?", powerStationCode);
            managementType = rd.getStr("management_type");
            id = rd.getStr("id");
        }
        logger.info("uploadTwoAttachment-----上传附件  id:{},tyoe:{},tiaojain:{}", id, type, CustomerEntryConstants.TYPE_ZJYL.equals(managementType));
        if (CustomerEntryConstants.TYPE_ZJYL.equals(managementType)) {
            CrmCustomerIncomingApplication application = applicationDao.getByEntryId(id);
            if (application != null) {

            }
        }

        //uploadCheckProject(application,fileName,customerEntry.getCheckAcceptImgs(),sileSize);
    }


    @Transactional(rollbackFor = Exception.class)
    public void sureInDoc(String id, Operator operator) {
        CustomerEntry customerEntry = customerDao.get(id);
        //9.待归档
        if (!CustomerEntryConstants.ENTRY_STATUS_DGD.equals(customerEntry.getStatus())) {
            throw new BusinessException("信息状态发生变化，请刷新后再试");
        }
        //a.已完成
        customerEntry.setStatus(CustomerEntryConstants.ENTRY_STATUS_YWC);
        customerEntry.setIndocBy(operator.getUserId());
        customerEntry.setIndocName(operator.getUserName());
        customerEntry.setIndocTime(new Date());
        customerDao.save(customerEntry);
        msgService.saveCustomerEntryMsg(operator, id, CustomerEntryConstants.ADVANCE_TYPE_OPT_GUIDANG);
    }

    @Transactional(rollbackFor = Exception.class)
    public void refuseInDoc(String id, String reason, Operator operator) {
        CustomerEntry customerEntry = customerDao.get(id);
        //9.待归档
        if (!CustomerEntryConstants.ENTRY_STATUS_DGD.equals(customerEntry.getStatus())) {
            throw new BusinessException("信息状态发生变化，请刷新后再试");
        }
        //11.归档退回
        customerEntry.setStatus(CustomerEntryConstants.ENTRY_STATUS_GDBH);
        customerDao.save(customerEntry);
        String msg = "退回原因：" + reason;
        msgService.saveCustomerEntryMsg(operator, id, CustomerEntryConstants.ADVANCE_TYPE_OPT_IN_DOC_BACK, msg,operator.getUserName());
    }

    public Record statisticForPCTrader() {
        Record dspRecord = materialApplyDao.statisticOrderForTraderDsp();
        Record yxdRecord = materialApplyDao.statisticOrderForTraderDfh();
        Record drkRecord = deliverDao.statisticOrderForTraderDrk();
        Record dshRecord = deliverDao.statisticOrderForTraderDsh();
        return new Record().setColumns(dspRecord).setColumns(yxdRecord).setColumns(drkRecord).setColumns(dshRecord);
    }

    public Record statisticForTrader(String traderId, String userId) {
        return customerDao.statisticForTrader(traderId, userId);
    }

    public Record statisticForPlaft(Map<String, String> map) {
        return customerDao.statisticForPlaft(map);
    }

    public Record statisticForSupply(List<String> ascriptionId) {
        Record purchaseOrderRecord = purchaseOrderDao.statisticOrder(ascriptionId);
        Record deliverOrderRecord = deliverDao.statisticOrder(ascriptionId);
        Record ret = new Record();
        ret.setColumns(purchaseOrderRecord).setColumns(deliverOrderRecord);
        return ret;
    }

    public Record statisticForSupplyChain() {
        Record ret = new Record();
        Record dspRecord = materialApplyDao.statisticOrderForSupplyChain();// 待审批
        Record dgylfhRecord = deliverDao.statisticOrderForSupplyChainDgylfh();// 待供应链发货
        Record dgysfhRecord = deliverDao.statisticOrderForSupplyChainDgysfh();// 待供应商发货
        Record djxsrkRecord = deliverDao.statisticOrderForSupplyChainDjxsrk();// 待代理商入库
        Record dgylrkRecord = deliverDao.statisticOrderForSupplyChainDgylrk();// 待供应链入库
        Record dshRecord = checkPendingOrderDao.statisticOrderForSupplyChainDsh();// 待审核
        return ret.setColumns(dspRecord).setColumns(dgylfhRecord).setColumns(dgysfhRecord).setColumns(djxsrkRecord)
                .setColumns(dgylrkRecord).setColumns(dshRecord);
    }

    /**
     * 匹配合同
     */
    @Transactional(rollbackFor = Exception.class)
    public void matchingContract() {
        //获取所有未匹配的合同
        List<CrmProjectContract> lists = contractService.findCrmProjectContractList();

        //去除所有未匹配合同的项目信息
        List<Record> pros = customerDao.findCustomerEntryListNot();
        List<String> ids = Lists.newArrayList();
        List<CrmProjectContract> proLists = Lists.newArrayList();
        for (Record rd : pros) {
            String id = rd.getStr("id");
            String projcetInfo = rd.getStr("projcetInfo");
            System.out.println("projcetInfo : " + projcetInfo);
            if (lists.size() < 1) {
                break;
            }
            Iterator<CrmProjectContract> iterator = lists.iterator();
            while (iterator.hasNext()) {
                CrmProjectContract con = iterator.next();
                String contract = con.getCustomerName().trim() + con.getIdCode().trim() + con.getAssemblySpecs() + con.getAssemblyNum();
                System.out.println("contract : " + contract);
                if (contract.equals(projcetInfo)) {
                    ids.add(id);
                    con.setCustomerEntryId(id);
                    con.setStatus(CustomerEntryConstants.CONTRACT_STATUS_PP);
                    proLists.add(con);
                    iterator.remove();
                }
            }
            //for(CrmProjectContract con:lists){
            //    String contract = con.getCustomerName().trim()+con.getIdCode().trim()+con.getAssemblySpecs()+con.getAssemblyNum();
            //    System.out.println("contract : "+contract);
            //    if (contract.equals(projcetInfo)) {
            //        ids.add(id);
            //        con.setCustomerEntryId(id);
            //        con.setStatus("2");
            //        proLists.add(con);
            //        lists.remove(con);
            //    }
            //}
        }
        if (ids.size() > 0) {
            UpdateCustomerEntry(ids);
            contractService.addContractList(proLists);
        } else {
            throw new BusinessException("匹配失败，暂无可匹配信息");
        }

    }

    public void UpdateCustomerEntry(List<String> ids) {
        SQLQuery sqlQuery = customerDao.getSession().createSQLQuery("UPDATE crm_customer_entry SET uniformity='2'  WHERE uniformity='1' and  id IN (" + SqlUtils.inParam(ids) + ")");
        sqlQuery.executeUpdate();
    }


    public Record findCustomerEntryGeneratorNo(String generator_no, String powerStationCode) {
        return customerDao.findCustomerEntryGeneratorNo(generator_no, powerStationCode);
    }


    /**
     * 校验导入物料数据
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> checkImportPowerStationCode(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "check");
        CustomerEntryCodeImportHandler handler = new CustomerEntryCodeImportHandler();
        handler.setStartSheet(1);
        handler.setStartRow(1);
        try {
            new ExcelReader().check(in, params.get("extName"), handler);
            Map<String, Object> map = (Map<String, Object>) handler.getHandlerResult();
            String templateError = (String) map.get("TemplateError");
            if (!handler.isCheckFlag()) {
                handler.appendErrorDetail("<p>未填充数据</p>");
            }
            String hanl = handler.getErrorDetail();
            if (StrKit.notBlank(templateError)) {
                retMap.put("errorDetail", templateError);
                retMap.put("errorMessage", "y");
            } else if (StringUtils.isNotBlank(hanl)) {
                retMap.put("errorDetail", hanl);
                retMap.put("errorMessage", "y");
            } else if ("overLimit".equalsIgnoreCase((String) map.get("overLimit"))) {
                retMap.put("overLimit", "y");
            } else {
                retMap.put("pass", "y");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return retMap;
    }

    /**
     * 导入物料数据
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importPowerStationCode(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "import");
        CustomerEntryCodeImportHandler handler = new CustomerEntryCodeImportHandler();
        handler.setStartSheet(1);
        handler.setStartRow(2);

        try {
            new ExcelReader().readExcel(in, params.get("fileName"), handler);

            List<String> codeList = handler.getRetList();
            long count = Db.update("UPDATE crm_customer_entry SET whether_to_pay='2' WHERE power_station_code IN(" + SqlUtils.inParam(codeList) + ") AND status IN('8','9','11','a')");
            retMap.put("successCount", count);
            retMap.put("pass", "y");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return retMap;
    }

    //修改方案明细为空的数据
    public void updateCustomerPlanEntry(String id, String code) {

        CustomerEntry entry;
        if (StringUtil.isNotBlank(id)) {
            entry = customerDao.get(id);
        } else {
            entry = customerDao.getByHql("from CustomerEntry where powerStationCode =:p1 ", new Parameter(code));
        }

        List<CrmPlanMaterialEntry> entrys = Lists.newArrayList();
        String planName = "";
        if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(entry.getSchemeType())) {
            //获取方案

            List<Record> plans = Db.find("SELECT * FROM crm_compose_plan WHERE customer_entry_id=?", id);

            //   List<ComposePlan> planents = Lists.newArrayList();
            List<String> planids = Lists.newArrayList();
            List<String> chongfuplanids = Lists.newArrayList();
            for (Record job : plans) {
               /* ComposePlan plan = new ComposePlan();
                plan.setCode(job.getStr("code"));
                plan.setName(job.getStr("name"));
                plan.setPlanType(job.getStr("plan_type"));
                plan.setComponentNum(job.getInt("component_num"));
                plan.setPlanId(job.getStr("plan_id"));
                planents.add(plan);*/
                if (planids.contains(job.getStr("plan_id"))) {
                    chongfuplanids.add(job.getStr("plan_id"));
                } else {
                    planids.add(job.getStr("plan_id"));
                }
                if (StringUtil.isNotBlank(planName)) {
                    planName = planName + " / " + job.getStr("name");
                } else {
                    planName = job.getStr("name");
                }
            }
            entry.setSchemeName(planName);

            //   composePlanService.saveComposePlan(planents,entry.getId());
            //获取方案中的物料明细
            List<Record> lists = materialDao.listMaterialByPlanIds(planids);
            if (chongfuplanids.size() > 0) {
                List<Record> rdss = materialDao.listMaterialByPlanIds(chongfuplanids);
                lists.addAll(rdss);
            }

            for (Record rd : lists) {
                entrys.add(addCrmPlanMaterialEntry(rd, entry.getId()));
            }

            Record replan = materialDao.findElectricPlan(entry.getComponentSpec(), entry.getDesignCapacity().toString());
            if (replan != null) {


                Map<String, Record> nbqMap = materialDao.findElectric("1");
                Map<String, Record> bwxMap = materialDao.findElectric("2");
                //获取逆变器和并网箱
                if (StringUtil.isNotBlank(replan.getStr("inverter1"))) {
                    if (nbqMap.containsKey(replan.getStr("inverter1"))) {
                        CrmPlanMaterialEntry es = addCrmPlanMaterialEntry(nbqMap.get(replan.getStr("inverter1")), entry.getId());
                        es.setPlanId(replan != null ? replan.getStr("id") : "1");
                        entrys.add(es);
                    }
                }
                if (StringUtil.isNotBlank(replan.getStr("inverter2"))) {
                    if (nbqMap.containsKey(replan.getStr("inverter2"))) {
                        CrmPlanMaterialEntry es = addCrmPlanMaterialEntry(nbqMap.get(replan.getStr("inverter2")), entry.getId());
                        es.setPlanId(replan != null ? replan.getStr("id") : "1");
                        entrys.add(es);
                    }
                }
                if (StringUtil.isNotBlank(replan.getStr("inverter3"))) {
                    if (nbqMap.containsKey(replan.getStr("inverter3"))) {
                        CrmPlanMaterialEntry es = addCrmPlanMaterialEntry(nbqMap.get(replan.getStr("inverter3")), entry.getId());
                        es.setPlanId(replan != null ? replan.getStr("id") : "1");
                        entrys.add(es);
                    }
                }
                if (StringUtil.isNotBlank(replan.getStr("box1"))) {
                    if (bwxMap.containsKey(replan.getStr("box1"))) {
                        CrmPlanMaterialEntry es = addCrmPlanMaterialEntry(bwxMap.get(replan.getStr("box1")), entry.getId());
                        es.setPlanId(replan != null ? replan.getStr("id") : "1");
                        entrys.add(es);
                    }
                }
                if (StringUtil.isNotBlank(replan.getStr("box2"))) {
                    if (bwxMap.containsKey(replan.getStr("box2"))) {
                        CrmPlanMaterialEntry es = addCrmPlanMaterialEntry(bwxMap.get(replan.getStr("box2")), entry.getId());
                        es.setPlanId(replan != null ? replan.getStr("id") : "1");
                        entrys.add(es);
                    }
                }
                if (StringUtil.isNotBlank(replan.getStr("box3"))) {
                    if (bwxMap.containsKey(replan.getStr("box3"))) {
                        CrmPlanMaterialEntry es = addCrmPlanMaterialEntry(bwxMap.get(replan.getStr("box3")), entry.getId());
                        es.setPlanId(replan != null ? replan.getStr("id") : "1");
                        entrys.add(es);
                    }
                }
            }

            //关联电器设备--根据组件规格  和组件块数 获取
            List<Record> dianqilist = materialDao.listMaterialByAssembly(entry.getComponentSpec(), entry.getDesignCapacity().toString());
            for (Record rd : dianqilist) {
                entrys.add(addCrmPlanMaterialEntry(rd, entry.getId()));
            }

        } else {
            CrmPlan plan = planDao.get(entry.getSchemeId());
            if (plan == null) {
                throw new IllegalArgumentException("当前方案不存在");
            }
            List<Record> lists = materialDao.listMaterialByPlanId(entry.getSchemeId());
            for (Record rd : lists) {
                CrmPlanMaterialEntry en = new CrmPlanMaterialEntry();
                en.setAmount(rd.getInt("amount"));
                en.setPlanId(entry.getSchemeId());
                en.setCode(rd.getStr("code"));
                en.setName(rd.getStr("name"));
                en.setSpec(rd.getStr("spec"));
                en.setUnit(rd.getStr("unit"));
                en.setSort(rd.getInt("sort"));
                en.setEntryId(entry.getId());
                entrys.add(en);
            }
        }
        if (entrys.size() == 0) {
            throw new IllegalArgumentException("当前方案没有物料明细");
        }
        entryDao.save(entrys);
        customerDao.save(entry);
    }


    public List<Record> findCustomerEntryList(LayuiPage<Record> page, Map<String, String> map) {
        return customerDao.findCustomerEntryList(page, map);
    }

    public List<Record> findCustomerEntryCount(Map<String, String> map, Operator operator) {
        return customerDao.findCustomerEntryCount(map, operator);
    }

    public List<Record> findCustomerEntryGroupProvince(Map<String, String> map, Operator operator) {
        return customerDao.findCustomerEntryGroupProvince(map, operator);
    }

    @Transactional(rollbackFor = Exception.class)
    public void doReceive(String ids) {
        User user = UserUtils.getUser();
        Date now = new Date();
        List<String> dataList = Arrays.asList(ids.split(","));
        for (String entryId : dataList) {
            CustomerEntry entry = customerDao.get(entryId);
            if (!StrKit.notNull(entry)) {
                throw new BusinessException("项目不存在");
            }
            if ("b".equals(entry.getStatus())) {
                throw new BusinessException("项目" + entry.getProjectCode() + "已删除");
            }
            if ("1".equals(entry.getAcceptFlag())) {
                throw new BusinessException("项目" + entry.getProjectCode() + "已接收");
            }
            Record par = partnerDao.findByProjectId(entry.getProjectId());
            if (par != null) {
                entry.setPartnerId(par.getStr("id"));
                entry.setPartnerName(par.getStr("name"));
            }
            entry.setAcceptBy(user.getId());
            entry.setAcceptFlag("1");
            entry.setAcceptor(CrmUtils.getUserXM(user));
            entry.setAcceptTime(now);
            customerDao.save(entry);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void uploadContract(String entryId, String path, Operator operator){
        CustomerEntry entry = customerDao.get(entryId);
        if (entry == null) {
            throw new BusinessException("登记信息不存在");
        }
        if (!StrKit.isBlank(entry.getContract())) {
            throw new BusinessException("合同已上传，不可再次上传");
        }
        User user= UserUtils.getUser();
        String otherName = user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();
        entry.setContract(path);
        customerDao.save(entry);
        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_UPLOAD_CONTRACT, null,otherName);
    }

    @Transactional(rollbackFor = Exception.class)
    public void signFinish(String entryId, Operator operator){
        CustomerEntry entry = customerDao.get(entryId);
        if (StrKit.isBlank(entry.getContract())) {
            throw new BusinessException("发电用合同未上传!");
        }
        User user = UserUtils.getUser();
        String otherMsg = "";
        if("4".equals(user.getUserType())){
            otherMsg =user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();;
        }else if("6".equals(user.getUserType())){
            otherMsg =user.getUserName();
        }else if("7".equals(user.getUserType())){
            otherMsg = UserUtils.findName(user);
        }
        //状态改为待并网验收
        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DYS);
        if (Integer.valueOf(entry.getApplyStatus()) < 17) {
            entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_DBWTJ);
        }
        customerDao.save(entry);
        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_QSWC, null,otherMsg);
    }

    @Transactional(rollbackFor = Exception.class)
    public void uploadBillAndNo(UploadBillReq req, Operator operator){
        CustomerEntry entry = customerDao.get(req.getId());
        entry.setBill(req.getBill());
        entry.setBillNumber(req.getBillNumber());
        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DQS);
        User user = UserUtils.getUser();
        String otherMsg = "";
        if("4".equals(user.getUserType())){
            otherMsg =user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();;
        }else if("6".equals(user.getUserType())){
            otherMsg =user.getUserName();
        }else if("7".equals(user.getUserType())){
            otherMsg = UserUtils.findName(user);
        }

        if (!StrKit.isBlank(req.getBillNumber())) {
            otherMsg += "发票号：" + req.getBillNumber();
        }
        customerDao.save(entry);
        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_UPLOAD_BILL, "", otherMsg);
    }

    /**
     * 安装验收通过
     *  @param id entryid
     *  @param fixConclusion 安装验收意见
     */
    @Transactional(rollbackFor = Exception.class)
    public void fixAcceptPass(String id, String fixConclusion, Operator operator,String zfFixConclusion) {
        CustomerEntry entry = customerDao.get(id);
        if (!CustomerEntryConstants.ENTRY_STATUS_DAZYS.equals(entry.getStatus())) {
            throw new BusinessException("仅待安装验收状态可操作验收");
        }
        User user = UserUtils.getUser();
        CrmAcceptingReport report = getReportById(entry.getReceivingReportId());
        report.setFixConclusion(fixConclusion);
        report.setFixAcceptBy(operator.getUserId());
        report.setFixAcceptName(operator.getUserName());
        report.setFixAcceptTime(new Date());
        report.setFixConclusion(fixConclusion);
        report.setUpdateBy(operator.getUserId());
        report.setUpdateTime(new Date());
        report.setUpdater(operator.getUserName());
        report.setZfFixConclusion(zfFixConclusion);
        reportDao.save(report);
        entry.setToExamineStatus("4");
        customerDao.save(entry);
        //部门名称+岗位名称+姓名
        String otherMsg = user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();
        //StringUtil.isBlank(fixConclusion)?"":" 备注：" + fixConclusion;
        zfFixConclusion="同意；"+zfFixConclusion;
        examineService.updateToExamine(entry.getId(),ExamineConstants.FOUR,zfFixConclusion,operator.getUserName());

        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_FIX_ACCEPT_PASSTG, zfFixConclusion,otherMsg);
    }

    public String findRoleName(String roleRds){
        List<Record> list  = FormUtils.getPlatformRoleNameByIds(roleRds);
        StringBuilder roleSb = new StringBuilder("");
        for(Record rd: list){
            roleSb.append(",").append(rd.getStr("name"));
        }
        if(StrKit.notBlank(roleSb.toString())){
            roleSb.toString().substring(1);
        }
        return roleSb.toString();
    }

    @Autowired
    CustomerEntrySurveyChangeRecordDao surveyChangeRecordDao;

    /**
     * 安装审核
     */
    @Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
    public void toNetAcceptPass(String id, String type, String fixConclusion, String materialFixFlag, Operator operator, User user){
        CustomerEntry entry = customerDao.get(id);
        if (CustomerEntryConstants.ENTRY_STATUS_DBW.equals(entry.getStatus())) {
            throw new BusinessException("电站已验收通过，请先刷新列表");
        }
        if (!CustomerEntryConstants.ENTRY_STATUS_DAZYS.equals(entry.getStatus())) {
            throw new BusinessException("仅待安装验收状态可操作验收");
        }
        if (surveyChangeRecordDao.selectNoAudited(id, null) > 0) {
            throw new BusinessException("操作失败，有勘测变更申请信息未审核");
        }
        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            throw new BusinessException(checkApplyResult);
        }

        String otherName = user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();
        if("1".equals(type)){
            //通过
            if (!Objects.equals(CustomerEntryConstants.FIX_FLAG_FINISH, materialFixFlag)) {
                throw new BusinessException("审核通过需物料安装完成");
            }
            if( (!"APPROVED".equals(entry.getFirstApplyStatus()) && PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId()))
                ||(!"30".equals(entry.getFirstApplyStatus()) && PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId()) && !"1".equals(entry.getIsHistory()))
                ||(!"FT".equals(entry.getFirstApplyStatus()) && PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId()))
            ){
                throw new BusinessException("第一次进件未通过，不支持安装验收！");
            }
            CrmAcceptingReport report = getReportById(entry.getReceivingReportId());
            if(entry.getProjectId().split(",").length == 1){
                //安装验收成功后，生成代理商的“预结算金额”，公式：预结算金额=分包结算金额*预结算比例；
                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"));
                //预结算比例，取系统设置下的值，未设置时，不可验收
                BigDecimal proportion = accountSetService.findYjsProportion(entry.getDistributorId());
                if (proportion == null) {
                    throw new BusinessException("未设置预结算比例，不可操作验收");
                }
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DBW);
                entry.setCheckAcceptFlag(CustomerEntryConstants.CHECK_ACCEPT_FLAG_YSTG);
                entry.setMaterialFixFlag(materialFixFlag);
                report.setMaterialFixFlag(materialFixFlag);
                report.setFixConclusion(fixConclusion);
                report.setFixAcceptTime(new Date());
                entry.setInstallAcceptTime(new Date());//安装验收时间
                reportDao.save(report);
                BigDecimal yjsAmount = fbAmount.multiply(proportion).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                //代理商待结算账户下，生成变动明细，增加【分包款余额】的值
                CrmTraderAccountSettleDetail settleDetail=createSettleDetail(map,entry, yjsAmount, operator, "0", "0",settleNumber);

                //释放标准授信额度余额、增加分包款余额、增加验收结算总额、增加质保金总额，增加冻结金额
                CrmTraderAccount account = accountDao.findByTraderId(entry.getDistributorId());
                BigDecimal totalAmount = getTotalAmount(entry.getId(),"0");
                if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) {
                    accountDao.updateBasicQuotaAmountBalance(totalAmount,account.getId());
//                account.setBasicQuotaAmountBalance(account.getBasicQuotaAmountBalance().add(totalAmount));
                }
                BigDecimal cfAmount2=BigDecimal.ZERO;
                //获取惩罚政策 单户装机容量≤10千瓦，基础结算价格每瓦减少0.15元
                CrmRewardsPunishWay rewardsPunishWay3=rewardsPunishWayDao.getRewardsPunishWay("3");
                if(rewardsPunishWay3!=null){
                    BigDecimal cap= report.getCapacity().divide(new BigDecimal("1000"),2, BigDecimal.ROUND_HALF_UP); //运算后不要四舍五入
                    logger.info("...单户装机容量 cap：{}",cap);
                    if(cap.compareTo(new BigDecimal(rewardsPunishWay3.getHighData()))<=0){
                        //生成一条惩罚结算记录
                        cfAmount2=report.getCapacity().multiply(new BigDecimal(rewardsPunishWay3.getRatioData())).multiply(proportion).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                        CrmTraderAccountSettleDetail cfSettleDetail2 =createSettleCfDetail(map,entry, cfAmount2.negate(), operator, "5", "0",rewardsPunishWay3.getNumber(),rewardsPunishWay3.getRatioData());
                        logger.info("..生成第二种惩罚记录金额 cfSettleDetail2:{},entryId:{}",cfSettleDetail2,entry.getId());
                        accountSettleDetailDao.save(cfSettleDetail2);
                    }
                }
                BigDecimal settleAmount = yjsAmount.subtract(cfAmount2);
                BigDecimal settleAmountYsjs = yjsAmount;
                BigDecimal settleRewardsPunishAmount = cfAmount2;
                accountDao.updateAccountSettleAmount(settleAmount, settleAmountYsjs, settleRewardsPunishAmount,account.getId());
//            account.setSettleAmount(account.getSettleAmount().add(yjsAmount).subtract(cfAmount2));
//            account.setSettleAmountYsjs(account.getSettleAmountYsjs().add(yjsAmount));
//            account.setSettleRewardsPunishAmount(account.getSettleRewardsPunishAmount().subtract(cfAmount2));
                accountDao.save(account);

                materialKeepDao.update("update CrmSupplyMaterialKeep set accountFlag='1' where sourceId=:p1 and type = '2' and accountFlag='0' ",
                        new Parameter(entry.getId()));

                if(settleDetail!=null){
                    //保存结算明细
                    accountSettleDetailDao.save(settleDetail);
                }
            }else{
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DBW);
                entry.setCheckAcceptFlag(CustomerEntryConstants.CHECK_ACCEPT_FLAG_YSTG);
                entry.setMaterialFixFlag(materialFixFlag);
                report.setMaterialFixFlag(materialFixFlag);
                report.setFixConclusion(fixConclusion);
                report.setFixAcceptTime(new Date());
                entry.setInstallAcceptTime(new Date());//安装验收时间
                reportDao.save(report);
            }
            //广发保存项目公司上传的保单
            insuranceBizService.saveInsurance(entry,user);
            boolean hisFlag = true;
            if ("1".equals(entry.getIsHistory()) && PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){
                hisFlag = false;
            }
            //第二次进件
           if (FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_WGZLTS) && hisFlag) {
            if ((PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())&&!"APPROVED".equals(entry.getNextApplyStatus()) && !"WAITING".equals(entry.getNextApplyStatus()))
            || (PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())
                    && !"25".equals(entry.getNextApplyStatus()) && !"30".equals(entry.getNextApplyStatus()) && !"60".equals(entry.getNextApplyStatus()) )) {
                if(entry.getProjectId().split(",").length == 1){
                    CrmInsuranceList insuranceSetting = insuranceBizService.getInsuranceSetting(entry);
                    if (insuranceSetting != null && !Objects.equals(InsuranceConstants.STATUS_NORMAL, insuranceSetting.getStatus())) {
                        throw new BusinessException("保险设置被禁用");
                    }
                }
                Result result = accessProjectApplySec(entry,operator);
                if (!"200".equals(result.getCode())) {
                    throw new IllegalArgumentException("农户投放审查信息同步失败；"+result.getErrMsg());
                }
            }
            }else {
               if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
                   entry.setNextApplyStatus("DS");
               }else {
                   entry.setNextApplyStatus("WAITING");
                   entry.setApplyStatus(null);
               }
           }

            fixConclusion ="安装验收 同意；"+fixConclusion;

            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_FIX_ACCEPT_PASS, fixConclusion,otherName);
            examineService.updateToExamine(entry.getId(),ExamineConstants.FIVE,fixConclusion,operator.getUserName());


            String nbqCode="00";
            String nbqName="";
            String querySql="SELECT c.material_brand as materialBrand FROM crm_supply_material as c " +
                    "WHERE c.`code` in (SELECT b.code FROM crm_plan_material_entry as b WHERE b.`entry_id` = ? AND b.`type` = '逆变器') limit 1";
            List<Record> records = Db.find(querySql,id);
            for(Record rd:records){
                nbqName=rd.get("materialBrand");
            }
            BrandFactInfo info = BrandFactInfo.externalOf(nbqName);
            if (info != null) {
                nbqCode = info.getBrandType();
            }
            entry.setNbqFactory(nbqCode);
            if(entry.getProjectId().split(",").length == 1){
                CrmInsuranceList insuranceSetting = insuranceBizService.getInsuranceSetting(entry);
                if (insuranceSetting != null && !Objects.equals(InsuranceConstants.STATUS_NORMAL, insuranceSetting.getStatus())) {
                    throw new BusinessException("保险设置被禁用");
                }
                if (insuranceSetting != null) {
                    // 深圳市慧择保险经纪有限公司，公司id必须为0，如果以后改了，那要同步修改这个地方
                    if (Objects.equals("0", insuranceSetting.getCompanyId())) {
                        insuranceBizService.push(entry, null, null, user,"0");
                    }
                }
            }else{
                CrmInsuranceList insuranceSetting = null;
                String[] arr = entry.getProjectId().split(",");
                for(String projectId : arr){
                    insuranceSetting = insuranceBizService.getInsuranceSettingList(projectId);
                    if (insuranceSetting != null && !Objects.equals(InsuranceConstants.STATUS_NORMAL, insuranceSetting.getStatus())) {
                        throw new BusinessException("保险设置被禁用");
                    }
                }
                if (insuranceSetting != null) {
                    // 深圳市慧择保险经纪有限公司，公司id必须为0，如果以后改了，那要同步修改这个地方
                    if (Objects.equals("0", insuranceSetting.getCompanyId())) {
                        insuranceBizService.push(entry, null, null, user,"0");
                    }
                }
            }

            if(PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())){
                //生成一条安装验收通过待生成巡检单的记录
                CrmEntryQualitySeekEntry seek = qualitySeekEntryDao.findInfoByEntryId(entry.getId());
                if (seek == null){
                    qualitySeekEntryDao.saveSeekEntry(entry.getId(),entry.getDistributorId(),entry.getInstallAcceptTime());
                }
            }

        }else{   //不通过
            fixConclusion ="安装验收 驳回；"+fixConclusion;
            entry.setCheckAcceptFlag(CustomerEntryConstants.CHECK_ACCEPT_FLAG_YSBH);
            entry.setMaterialFixFlag(materialFixFlag);
            CrmAcceptingReport report = getReportById(entry.getReceivingReportId());
            report.setMaterialFixFlag(materialFixFlag);
            report.setFixConclusion(fixConclusion);
            reportDao.save(report);
            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_FIX_ACCEPT_REFUSE, fixConclusion,otherName);
            examineService.updateToExamine(entry.getId(),ExamineConstants.FIVE,fixConclusion,operator.getUserName());
        }
        //生成审核的task
        Date date=new Date();
        String itemStatus="1".equals(type)?ItemConstants.RESULT_OK:ItemConstants.RESULT_BACK;
        ItemManage itemManage= itemManageDao.getItemManagementByEntryId(entry.getId(),FormUtils.ENTRY_STATUS_AZYS);
        if (itemManage != null) {
            itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_STATUS_AZYS, entry.getId(), itemManage.getProcessInstanceId(), itemManage.getProcessInstanceId(), itemStatus, date, operator, "安装验收");
            itemManage.setStatus(ItemConstants.ITEM_STATUS_FINISH);
            itemManage.setEndTime(date);
            itemManageDao.save(itemManage);
            reviewDispatchDao.markDispatchFinish(itemManage);
        }
        if(Objects.equals(CustomerEntryConstants.FIX_FLAG_FINISH, materialFixFlag) && entry.getMaterialFixFinishTime()==null){
            entry.setMaterialFixFinishTime(new Date());
        }
        customerDao.save(entry);
    }



    /**
     * 资方审核
     */
    @Transactional(rollbackFor = Exception.class)
    public void GdtMergeAccept(String id, String fixConclusion, Operator operator,String type){
        CustomerEntry entry = customerDao.get(id);

        User user= UserUtils.getUser();
        String otherName = user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();
        entry.setGdtRemarks(fixConclusion);
        if("1".equals(type)){

            CrmAcceptingReport report = 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"));
            //预结算比例，取系统设置下的值，未设置时，不可验收
            BigDecimal proportion = accountSetService.findYjsProportion(entry.getDistributorId());
            if (proportion == null) {
                throw new BusinessException("未设置预结算比例，不可操作验收");
            }
            entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DBW);
            entry.setMergeFlag(CustomerEntryConstants.MERGE_FLAG_DBW);
            BigDecimal yjsAmount = fbAmount.multiply(proportion).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
            //代理商待结算账户下，生成变动明细，增加【分包款余额】的值
            CrmTraderAccountSettleDetail settleDetail=createSettleDetail(map,entry, yjsAmount, operator, "0", "0",settleNumber);

            //释放标准授信额度余额、增加分包款余额、增加验收结算总额、增加质保金总额，增加冻结金额
            CrmTraderAccount account = accountDao.findByTraderId(entry.getDistributorId());
            if (account == null) {
                throw new BusinessException("请先设置代理商可授信额");
            }
            BigDecimal totalAmount = getTotalAmount(entry.getId(),"0");
            if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) {
                account.setBasicQuotaAmountBalance(account.getBasicQuotaAmountBalance().add(totalAmount));
            }
            account.setSettleAmount(account.getSettleAmount().add(yjsAmount));
            account.setSettleAmountYsjs(account.getSettleAmountYsjs().add(yjsAmount));
            accountDao.save(account);


            customerDao.save(entry);
//            String otherMsg = StrKit.isBlank(fixConclusion) ? "" : "验收意见：" + fixConclusion;
//            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_FIX_ACCEPT_PASS, otherMsg,otherName);
            if("1".equals(entry.getProductLine())){
                //纯租25年业务是产生租金
                CustomerEntryRent rent  = new CustomerEntryRent();
                rent.setId(IdGen.uuid());
                rent.setEntryId(entry.getId());
                rent.setRentStaus("0");
                rent.setPowerStationCode(entry.getPowerStationCode());
                customerEntryRentService.save(rent);
            }

            if(settleDetail!=null){
                //保存结算明细
                accountSettleDetailDao.save(settleDetail);
            }
            fixConclusion="同意；"+fixConclusion;
        }else{
            entry.setToExamineStatus("3");
//            entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_GWAZNOT);
            fixConclusion="驳回；"+fixConclusion;
        }

        String otherMsg = StrKit.isBlank(fixConclusion) ? "" :  fixConclusion;
        examineService.updateToExamine(entry.getId(), ExamineConstants.SIX,fixConclusion,operator.getUserName());
        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_FIX_ACCEPT_PASSTG, otherMsg,otherName);
    }

    /**
     * 资方并网审核
     */
    @Transactional(rollbackFor = Exception.class)
    public void GdtBwMergeAccept(String id, String fixConclusion, Operator operator,String type){
        CustomerEntry entry = customerDao.get(id);

        User user= UserUtils.getUser();
        String otherName = user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();
        CrmAcceptingReport report = getReportById(entry.getReceivingReportId());
        entry.setGdtRemarks(StringUtil.isNotBlank(entry.getGdtRemarks())?entry.getGdtRemarks()+"资方安装验收："+fixConclusion:fixConclusion);
        if("1".equals(type)){
            entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_YWC);
            //并网验收生成代理商的分包并网结算金额，分包并网结算额=分包结算额*（1-预结算比例A）-质保金，质保金=组件单瓦数*数量*质保金结算单价
            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:{}",id,fbAmount);
            BigDecimal proportion = accountSetService.findYjsProportion(entry.getDistributorId());
            Record set = accountSetService.findZBJSinglePrice();;
            String way = set.getStr("way");//结算方式1.按瓦数 2.按组件块数 3.按结算比例（质保金账户使用
            BigDecimal propor=set.getBigDecimal("proportion");
            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);
            if(fbbwAmount.compareTo(BigDecimal.ZERO)<0){
                //分包结算金额小于0
                logger.info(">>>>>>>>>>>>>>>>分包结算金额为负数 proportion :{},zbjSinglePrice:{}",proportion,zbjSinglePrice);
            }
            //生成待结算账户分包并网结算记录
            CrmTraderAccountSettleDetail settleDetail= createSettleDetail(map,entry, fbbwAmount, operator, "1", "0",settleNumber);
            //生成质保金账户结算记录
            CrmTraderAccountSettleDetail settleDetail2=createSettleDetail(map,entry, zbjSinglePrice, operator, "3", "1",settleNumber);
            accountSettleDetailDao.save(settleDetail2);
            //释放授信额上限余额、增加分包款余额、增加验收结算总额、增加质保金总额，增加冻结金额
            CrmTraderAccount account = accountDao.findByTraderId(entry.getDistributorId());
            BigDecimal totalAmount = getTotalAmount(entry.getId(),"1");
            if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) {
                account.setMaxQuotaAmountBalance(account.getMaxQuotaAmountBalance().add(totalAmount));
            }
            account.setSettleAmount(account.getSettleAmount().add(fbbwAmount));
            account.setSettleAmountYsjs(account.getSettleAmountYsjs().add(fbbwAmount));
            account.setQaAmount(account.getQaAmount().add(zbjSinglePrice));
            account.setQaAmountFreeze(account.getQaAmountFreeze().add(zbjSinglePrice));
            accountDao.save(account);

            if(settleDetail!=null){
                //保存结算明细
                accountSettleDetailDao.save(settleDetail);
            }
            fixConclusion = " 同意；"+fixConclusion;
        }else{
//            entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_GWBWNOT);
            entry.setToExamineStatus("5");
            fixConclusion = " 驳回；"+fixConclusion;
        }
        customerDao.save(entry);

        examineService.updateToExamine(entry.getId(),ExamineConstants.NINE,fixConclusion,operator.getUserName());

        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_OPT_GWBWSH, fixConclusion,otherName);
    }


    //获取使用的物料总额
    public BigDecimal getTotalAmount(String id, String accountFlag) {
        return customerDao.getTotalAmount(id, accountFlag);
    }

    //代理商待结算账户下，生成变动明细
    public CrmTraderAccountSettleDetail createSettleDetail(Map<String ,String> map,CustomerEntry entry, BigDecimal yjsAmount, Operator operator, String type, String objType,String settleNumber) {
        CrmTraderAccountSettleDetail settleDetail = new CrmTraderAccountSettleDetail();
        settleDetail.setEntryId(entry.getId());
        settleDetail.setPowerStationCode(entry.getPowerStationCode());
        settleDetail.setTraderId(entry.getDistributorId());
        settleDetail.setTraderName(entry.getTraderName());
        //0.待结算账户
        settleDetail.setObjType(objType);
        //0.预结算 1.分包并网结算 2.电站整改(减) 3.质保金
        settleDetail.setType(type);
        settleDetail.setAmount(yjsAmount);
        settleDetail.setRoofType(entry.getRoofType());
        settleDetail.setSchemeType(entry.getSchemeType());
        settleDetail.setSchemeTypeId(entry.getSchemeId());
        settleDetail.setSchemeTypeName(entry.getSchemeName());
        settleDetail.setTenantName(entry.getTenantName());
        settleDetail.setMobile(entry.getMobile());
        settleDetail.setProjectCode(entry.getProjectCode());
        settleDetail.setProjectName(entry.getProjectName());
        settleDetail.setCreateBy(operator.getUserId());
        settleDetail.setCreateTime(new Date());
        settleDetail.setNumber("JS"+PlantformUtils.getOrderNumber());
        settleDetail.setUnitPrice(new BigDecimal(map.get("amount")));// 结算单价
        settleDetail.setCapacity(new BigDecimal(map.get("actual_capacity")));//
        if ("3".equals(type)) {
            //请款标记:0.可请款 1.冻结
            settleDetail.setFlag("1");
            //质保金到期时间
            settleDetail.setEndTime(DateUtils.yearSub(settleDetail.getCreateTime(),1));
        }
        settleDetail.setSettleNumber(settleNumber);
        return settleDetail;
    }

    public CrmTraderAccountSettleDetail createSettleCfDetail(Map<String ,String> map,CustomerEntry entry, BigDecimal yjsAmount, Operator operator, String type, String objType,String settleNumber,String number) {
        CrmTraderAccountSettleDetail settleDetail = new CrmTraderAccountSettleDetail();
        settleDetail.setEntryId(entry.getId());
        settleDetail.setPowerStationCode(entry.getPowerStationCode());
        settleDetail.setTraderId(entry.getDistributorId());
        settleDetail.setTraderName(entry.getTraderName());
        //0.待结算账户
        settleDetail.setObjType(objType);
        //0.预结算 1.分包并网结算 2.电站整改(减) 3.质保金
        settleDetail.setType(type);
        settleDetail.setAmount(yjsAmount);
        settleDetail.setRoofType(entry.getRoofType());
        settleDetail.setSchemeType(entry.getSchemeType());
        settleDetail.setSchemeTypeId(entry.getSchemeId());
        settleDetail.setSchemeTypeName(entry.getSchemeName());
        settleDetail.setTenantName(entry.getTenantName());
        settleDetail.setMobile(entry.getMobile());
        settleDetail.setProjectCode(entry.getProjectCode());
        settleDetail.setProjectName(entry.getProjectName());
        settleDetail.setCreateBy(operator.getUserId());
        settleDetail.setCreateTime(new Date());
        settleDetail.setNumber("JS"+PlantformUtils.getOrderNumber());
        settleDetail.setUnitPrice(new BigDecimal(number));// 结算单价
        settleDetail.setCapacity(new BigDecimal(map.get("actual_capacity")));//
        if ("3".equals(type)) {
            //请款标记:0.可请款 1.冻结
            settleDetail.setFlag("1");
            //质保金到期时间
            settleDetail.setEndTime(DateUtils.yearSub(settleDetail.getCreateTime(),1));
        }
        settleDetail.setSettleNumber(settleNumber);
        return settleDetail;
    }

    /**
     * 平台安装验收退回
     * @param id entryid
     * @param fixConclusion 安装验收意见
     */
    @Transactional(rollbackFor = Exception.class)
    public void fixAcceptRefuse(String id, String fixConclusion, String materialFixFlag, Operator operator, User user){
        CustomerEntry entry = customerDao.get(id);
        if (!CustomerEntryConstants.ENTRY_STATUS_DAZYS.equals(entry.getStatus())) {
            throw new BusinessException("仅待安装验收状态可操作退回");
        }
        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            throw new BusinessException(checkApplyResult);
        }
        String otherName = user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();
        CrmAcceptingReport report = getReportById(entry.getReceivingReportId());
        report.setFixAcceptBy(operator.getUserId());
        report.setFixAcceptName(operator.getUserName());
        report.setFixAcceptTime(new Date());
        report.setFixConclusion(fixConclusion);
        report.setUpdateBy(operator.getUserId());
        report.setUpdateTime(new Date());
        report.setUpdater(operator.getUserName());

        entry.setMaterialFixFlag(materialFixFlag);
        report.setMaterialFixFlag(materialFixFlag);

        reportDao.save(report);

        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_AZYSTH);
        entry.setCheckAcceptFlag(CustomerEntryConstants.CHECK_ACCEPT_FLAG_YSBH);
        //判断是否需要安装自审
        if (!FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_AZJS)) {
            entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DAZ);
            entry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_ZSBH);
            entry.setCheckAcceptFlag(CustomerEntryConstants.FLAG_INIT);
        }

        if (Objects.equals(CustomerEntryConstants.FIX_FLAG_FINISH, materialFixFlag) && entry.getMaterialFixFinishTime() == null) {
            entry.setMaterialFixFinishTime(new Date());
        }

        customerDao.save(entry);

        String otherMsg = "安装验收驳回；" + fixConclusion;

        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_FIX_ACCEPT_REFUSE, otherMsg, otherName);
        examineService.updateToExamine(entry.getId(), ExamineConstants.FIVE, otherMsg, operator.getUserName());
        Date date = new Date();
        String itemStatus = ItemConstants.RESULT_BACK;
        ItemManage itemManage = itemManageDao.getItemManagementByEntryId(entry.getId(), FormUtils.ENTRY_STATUS_AZYS);
        if (itemManage != null) {
            itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_STATUS_AZYS, entry.getId(), itemManage.getProcessInstanceId(), itemManage.getProcessInstanceId(), itemStatus, date, operator, "安装验收");
            itemManage.setStatus(ItemConstants.ITEM_STATUS_FINISH);
            itemManage.setEndTime(date);
            itemManageDao.save(itemManage);
            reviewDispatchDao.markDispatchFinish(itemManage);
        }
    }




    /**
     * 并网提交
     */
    @Transactional(rollbackFor = Exception.class)
    public void merge(AddReportSecondReq req, Operator operator, boolean temp) {
        CustomerEntry entry = customerDao.get(req.getEntryId());
        if (!StringUtil.equalsAny(entry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_DBW, CustomerEntryConstants.ENTRY_STATUS_YSBH)) {
            throw new BusinessException("仅待并网状态可操作并网提交");
        }
        if (FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZFSH)) {
            if ("1".equals(entry.getTenantType()) && !StringUtil.equalsAny(entry.getSignStatus(),"2","3","5","g","e")) {
            throw new BusinessException("当前电站未签约《农户合同》，请在签约后再操作并网");
        }
        }
        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            throw new BusinessException(checkApplyResult);
        }
        // 校验发电户号格式
        if (StringUtil.isBlank(req.getGeneratorNo())) {
            throw new BusinessException("发电户号不能为空");
        } /*else if (req.getGeneratorNo().length() != 13 && req.getGeneratorNo().length() != 16) {
            throw new BusinessException("发电户号格式不正确");
        }*/
        CrmAcceptingReport report = getReportById(entry.getReceivingReportId());
        //安装验收时间
//        Date fixAcceptTime = report.getFixAcceptTime();
        Date fixAcceptTime = entry.getInstallAcceptTime();
        Date now = new Date();
        //计算时间差
//        long diff = (now.getTime() - fixAcceptTime.getTime())/(1000 * 60 * 60 * 24);
//        System.out.println("相差天数："+diff);
//        if(diff>120){
//            throw new BusinessException("超期三十天不能提交并网");
//        }
//        if(!temp && !"0".equals(entry.getRepaymentMethod())){
//            GuardUtils.notBlank(gebImg, "划转截图不能为空");
//        }
        // 校验保险信息
        //  checkInsurance(req.getApplication());
        if (!temp) {
            if (PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())) {
                CrmCustomerIncomingApplication application = incomingApplicationDao.getByEntryId(entry.getId());
                if (!StringUtil.equalsAny(application.getStatus(),"15","17","18","19","20","21")){
                   throw new BusinessException("二次进件未审核通过，不能提交并网！");
                }
            }
            // 查询项目信息
            //CrmProjectSetting projectSetting = projectDao.get(entry.getProjectId());
            // 校验必填项
            List<Record> checkList = formSetDao.findListByCondition("04", entry.getPartnerId());
            Result result = requiredCheckForMerge(req, checkList);
            if (!"200".equals(result.getCode())) {
                throw new BusinessException(result.getErrMsg());
            }
        }
        entry.setAddressConsistent(req.getAddressConsistent());
        boolean consistent = CustomerEntryConstants.ADDESS_CONSISTENT_YES.equals(req.getAddressConsistent());
        if (consistent) {
            req.setProvince(entry.getProvince());
            req.setCity(entry.getCity());
            req.setArea(entry.getArea());
            req.setAddress(entry.getAddress());
        }
        entry.setElectricProvince(req.getProvince());
        entry.setElectricCity(req.getCity());
        entry.setElectricArea(req.getArea());
        entry.setElectricAddress(req.getAddress());
        entry.setContract(req.getContractFile());
        entry.setContractFilename(req.getContractFilename());
        entry.setContractVideoUrl(req.getContractVideoUrl());
        entry.setContractVideoName(req.getContractVideoName());
        entry.setOtherAttachment(req.getOtherAttachment());
        String otherName = "";
        User user= UserUtils.getUser();
        if("7".equals(operator.getUserType())){
            otherName= operator.getRoleName() +","+operator.getUserName();
        }else if("6".equals(operator.getUserType())){
            otherName= operator.getUserName();
        }else{
            otherName = user.getDepartmentName() +" " +findRoleName(user.getRoleIds()) +" "+operator.getUserName();
        }

        //判断发电户号是否存在
        List<String> ifSameBoxGroup = Db.query("SELECT id FROM crm_customer_entry WHERE generator_no=? AND status !='b' and id != ?", req.getGeneratorNo(), entry.getId());
        if (ifSameBoxGroup !=null && ifSameBoxGroup.size()>0) {
            //判断是否是一个汇流组
            long count2= Db.queryLong(" SELECT COUNT(*) FROM crm_entry_combiner_box_group_detail d WHERE d.entry_id IN (" +StringUtil.joinInSql(ifSameBoxGroup)+
                    ") AND d.box_group_id<>(SELECT d1.box_group_id FROM crm_entry_combiner_box_group_detail d1 WHERE d1.entry_id=? ) ",entry.getId());
            if(count2>=1){
                throw new BusinessException("并网失败，发电户号已存在");
            }
        }

        if ("1".equals(req.getBwInstitution()) && StringUtil.isNotBlank(req.getPowerPlantCode())){
            long count2 = Db.queryLong("SELECT COUNT(*) FROM crm_customer_entry WHERE power_plant_code=? AND status !='b' and id != ?", req.getPowerPlantCode(), entry.getId());
            if (count2 > 0) {
                throw new BusinessException("并网失败，电厂编码已存在");
            }
        }
        entry.setGridInstitution(req.getBwInstitution());
        if ("0".equals(req.getBwInstitution())){
            entry.setGeneratorNo(req.getGeneratorNo());
            entry.setProvinceCode(req.getProvinceCode());
            entry.setPowerPlantCode("");
            report.setArchivesImg("");
        }else {
            entry.setPowerPlantCode(req.getPowerPlantCode());
            entry.setGeneratorNo(req.getGeneratorNo());
            report.setArchivesImg(req.getArchivesImg());
            entry.setProvinceCodeHand(req.getProvinceCodeHand());
        }
        if (!temp) {
            //并网验收打回进入并网验收状态
            // if (CustomerEntryConstants.ENTRY_STATUS_YSBH.equals(entry.getStatus())) {
            entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DYS);
            entry.setOnGridFlag(CustomerEntryConstants.ON_GRID_FLAG_YBW);
            entry.setMergeFlag(CustomerEntryConstants.MERGE_FLAG_DBW);

            // }
            //待并网状态进入发票上传状态

            //整改过来的  如果已经上传过发票 或者签署过合同 那么就不用在继续这些操作
       /*     if(StringUtil.isNotBlank(entry.getContract())){
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DYS);
            }else if(StringUtil.isNotBlank(entry.getBill())){
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DQS);
            }*/
        }
        Record par = partnerDao.findByProjectId(entry.getProjectId());
        if (par != null) {
            entry.setPartnerId(par.getStr("id"));
            entry.setPartnerName(par.getStr("name"));
        }
        //提交并网验收时间(操作并网提交的时间)
        if (!temp){
            entry.setMergeTime(new Date());
        }
        customerDao.save(entry);

//        CrmAcceptingReport report = getReportById(entry.getReceivingReportId());
        report.setYxImg(req.getYxImg());
        report.setGebImg(req.getGebImg());
        report.setGebImg2(req.getGebImg2());
        report.setUpdateBy(operator.getUserId());
        report.setUpdateTime(new Date());
        report.setUpdater(operator.getUserName());
        report.setDbImgs(req.getDbImgs());
        report.setDbxImgs(req.getDbxImgs());
        report.setTlzhjkImgs(req.getTlzhjkImgs());
        report.setPowerCapacityUrl(req.getPowerCapacityUrl());
        reportDao.save(report);

        msgService.saveCustomerEntryMsg(operator, entry.getId(), temp ?
                CustomerEntryConstants.ADVANCE_TYPE_MERGE_TEMP :
                CustomerEntryConstants.ADVANCE_TYPE_MERGE_SUBMIT, null, otherName);

        if ("0".equals(entry.getProductLine()) && !temp) {//纯租25年业务
            customerEntryRentService.updateMeetTime(entry, report);
        }
        //去除保存保险信息
        customerEntryExtraService.addIncomingApplicationSec(req.getApplication(), operator, temp);
//        CrmInsuranceList insuranceSetting = insuranceBizService.getInsuranceSetting(entry);
//        if (insuranceSetting != null && !Objects.equals(InsuranceConstants.STATUS_NORMAL, insuranceSetting.getStatus())) {
//            throw new BusinessException("保险设置被禁用");
//        }
//        if (insuranceSetting != null) {
//            if (Objects.equals("0", insuranceSetting.getCompanyId()) && !temp) { // 深圳市慧择保险经纪有限公司
//                insuranceBizService.push(entry, null, null);
//            }
//        }
        //提交国网授权 只有农户备案才需要国网授权
        if("0".equals(req.getIsEmpower()) && "0".equals(entry.getIfStateGridStatus()) && "1".equals(entry.getFilingType())){
            if (PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())){//暂时只有越秀需要提交国网授权
                Result result = stateGridService.addUserInfoArriveStateGrid(req.getGeneratorNo(),entry);
                if("200".equals(result.getCode())){
                    entry.setIfStateGridStatus("1");
                }else{
                    entry.setIfStateGridStatus("0");
                    String otherMsg = "提交国网授权失败" + (StringUtil.isBlank(result.getErrMsg()) ? "" : "，" +result.getErrMsg());
                    msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_MERGE_SUBMIT, otherMsg, otherName);
                }
                customerDao.save(entry);
            }
        }
        if (!temp) {
            //判断是否需要并网验收
            if (!FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_BWYS)) {
                twoMergeAcceptRefuse(entry.getId(), "1", null, CustomerEntryConstants.MERGE_FLAG_FINISH,
                        null, operator, user);
            } else {//需要并网验收，那么生成并网验收的任务
                //创建档案审核的任务
                Date date = new Date();
                String stationName = CrmUtils.getStationName(entry);
                ItemManage itemManage = itemManageDao.addItem(FormUtils.ENTRY_STATUS_BWYS, entry.getId(), PlantformUtils.getOrderNumber(), "并网验收(" + stationName + "-" + entry.getPowerStationCode() + ")-" + DateUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss"), date, operator.getUserName());
                //大代理商优先审核
                String groupName = "并网审核";
                crmPriorReviewSettingService.traderPriorityReview(entry.getCreateTraderId(),itemManage.getId(),groupName);
                //清空安装验收审核备注
                report.setMergeConclusion("");
                reportDao.save(report);
            }
        }
    }

    private void checkInsurance(AddIncomingApplication app) {
        if (app == null) {
            throw new BusinessException("保险信息不能为空");
        }
        CrmCustomerIncomingApplicationInsurance insurance = app.getInsurance();
        if (insurance == null) {
            throw new BusinessException("保险信息不能为空");
        }
    }

    /**
     * 并网验收驳回
     */
    @Transactional(rollbackFor = Exception.class)
    public void mergeAcceptRefuse(String id, String mergeConclusion, Operator operator, String zfMergeConclusion) {
        CustomerEntry entry = customerDao.get(id);
        if (!CustomerEntryConstants.ENTRY_STATUS_DYS.equals(entry.getStatus())) {
            throw new BusinessException("仅待并网验收状态可操作验收");
        }
        User user = UserUtils.getUser();
        String otherName = user.getDepartmentName() + " " + findRoleName(user.getRoleIds()) + " " + operator.getUserName();
        //状态变为并网验收驳回
        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_YSBH);
        entry.setMergeFlag(CustomerEntryConstants.CREDIT_MOREN);
        entry.setOnGridFlag(CustomerEntryConstants.ON_GRID_FLAG_BWYSBH);
        customerDao.save(entry);

        CrmAcceptingReport report = getReportById(entry.getReceivingReportId());
        report.setMergeConclusion(mergeConclusion);
        report.setMergeAcceptBy(operator.getUserId());
        report.setMergeAcceptName(operator.getUserName());
        report.setMergeAcceptTime(new Date());
        report.setUpdateBy(operator.getUserId());
        report.setUpdateTime(new Date());
        report.setUpdater(operator.getUserName());
        report.setZfMergeConclusion(zfMergeConclusion);
        reportDao.save(report);

        String otherMsg = "驳回；" + mergeConclusion;

        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ACCEPTANCE_REVIEW_REFUSE, otherMsg, otherName);
        examineService.updateToExamine(entry.getId(), ExamineConstants.SIX, otherMsg, operator.getUserName());

        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_FIX_ACCEPT_PASSTG, otherMsg, otherName);
    }

    /**
     * 并网验收通过
     */
    @Transactional(rollbackFor = Exception.class)
    public void mergeAcceptPass(String id, String mergeConclusion, String finalConclusion, Operator operator, String zfMergeConclusion) {
        CustomerEntry entry = customerDao.get(id);

        //查询是否有保单
        List<CrmCustomerEntryInsurance> entryInsuranceList = entryInsuranceDao.findByEntryId(id);
        if (entryInsuranceList != null) {
            for (CrmCustomerEntryInsurance entryInsurance : entryInsuranceList) {
                if (!InsuranceOrderConstants.STATUS_SUCCESS.equals(entryInsurance.getStatus())) {
                    throw new BusinessException("投保状态未完成，不允许并网验收通过");
                } else if (!"工程安装一切险".equals(entryInsurance.getInsuranceName())&&StringUtil.isAnyBlank(entryInsurance.getNumber(), entryInsurance.getInsuranceType()
                        , entryInsurance.getInsuranceCompanyName(), entryInsurance.getPolicyholder(), entryInsurance.getInsurant()
                        , entryInsurance.getDownUrl()) || (entryInsurance.getInsuranceMoney() == null && !"工程安装一切险".equals(entryInsurance.getInsuranceName()))) {
                    throw new BusinessException("投保单数据不完善，不允许并网验收通过");
                }
            }
        }

        //并网验收完成后，项目自动进入到【项目归档】阶段
//        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_YWC);
        entry.setMergeFlag(CustomerEntryConstants.MERGE_FLAG_ZFSHZ);
        entry.setCheckAcceptTime(new Date());
        entry.setCheckAcceptBy(operator.getUserId());
        entry.setCheckAcceptName(operator.getUserName());
        entry.setToExamineStatus("6");
        customerDao.save(entry);

        CrmAcceptingReport report = getReportById(entry.getReceivingReportId());
        report.setMergeConclusion(mergeConclusion);
        report.setFinalConclusion(finalConclusion);
        report.setMergeAcceptBy(operator.getUserId());
        report.setMergeAcceptName(operator.getUserName());
        report.setMergeAcceptTime(new Date());
        report.setUpdateBy(operator.getUserId());
        report.setUpdateTime(new Date());
        report.setUpdater(operator.getUserName());
//        report.setStatus(CustomerEntryConstants.ENTRY_STATUS_GWBW);
        report.setZfMergeConclusion(zfMergeConclusion);
        reportDao.save(report);
        User user = UserUtils.getUser();
        String otherName = user.getDepartmentName() + " " + findRoleName(user.getRoleIds()) + " " + operator.getUserName();
        //并网验收生成代理商的分包并网结算金额，分包并网结算额=分包结算额*（1-预结算比例A）-质保金，质保金=组件单瓦数*数量*质保金结算单价
//        BigDecimal fbAmount = settlementSchemeService.calcPriceByProjectId(entry.getProjectId(), report.getComponentNum(), report.getCapacity());
//        logger.info(">>>>>>>>>>>>>>>>>>>>>>>mergeAcceptPass id :{},fbAmount:{}",id,fbAmount);
//        BigDecimal proportion = accountSetService.findYjsProportion(entry.getDistributorId());
//        BigDecimal zbjSinglePrice = accountSetService.findZBJSinglePrice();
//        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.multiply(report.getCapacity()));
//        //生成待结算账户分包并网结算记录
//        createSettleDetail(entry, fbbwAmount, operator, "1", "0");
//        //生成质保金账户结算记录
//        createSettleDetail(entry, zbjSinglePrice.multiply(report.getCapacity()), operator, "3", "1");
//
//        //释放授信额上限余额、增加分包款余额、增加验收结算总额、增加质保金总额，增加冻结金额
//        CrmTraderAccount account = accountDao.findByTraderId(entry.getDistributorId());
//        BigDecimal totalAmount = getTotalAmount(entry.getId());
//        if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) {
//            account.setMaxQuotaAmountBalance(account.getMaxQuotaAmountBalance().add(totalAmount));
//        }
//        account.setSettleAmount(account.getSettleAmount().add(fbbwAmount));
//        account.setSettleAmountYsjs(account.getSettleAmountYsjs().add(fbbwAmount));
//        account.setQaAmount(account.getQaAmount().add(zbjSinglePrice.multiply(report.getCapacity())));
//        account.setQaAmountFreeze(account.getQaAmountFreeze().add(zbjSinglePrice.multiply(report.getCapacity())));
//        accountDao.save(account);

        String otherMsg = " 同意；" + mergeConclusion;

        examineService.updateToExamine(entry.getId(), ExamineConstants.SEVEN, otherMsg, operator.getUserName());
        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_MERGE_ACCEPT_PASS, otherMsg, otherName);
    }

    /**
     * 并网验收二次审核
     */
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public void twoMergeAcceptRefuse(String id, String type, String fixConclusion, String materialMergeFlag,
                                     String powerCapacityUrl, Operator operator, User user) {
        CustomerEntry entry = customerDao.get(id);
        if (!CustomerEntryConstants.ENTRY_STATUS_DYS.equals(entry.getStatus())) {
            throw new BusinessException("当前状态下不可操作，请刷新页面");
        }
        if (materialInformationChangeApplyDao.checkRepeatByEntryId(entry.getId())) {
            throw new BusinessException("操作失败，有物料变更变更申请信息未审核");
        }

        if (completionInfoChangeDao.selectNoAudited(id, null) > 0) {
            throw new BusinessException("操作失败，有完工信息变更信息未审核");
        }

        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            throw new BusinessException(checkApplyResult);
        }

        String otherName = user.getDepartmentName() + " " + findRoleName(user.getRoleIds()) + " " + operator.getUserName();
        short typesh = CustomerEntryConstants.MERGE_ACCEPTANCE_PASS;
        String otherMsg = "";
        if ("1".equals(type)) {
            //查询是否有保单
            List<CrmCustomerEntryInsurance> entryInsuranceList = entryInsuranceDao.findByEntryId(id);
            if (entryInsuranceList != null) {
                for (CrmCustomerEntryInsurance entryInsurance : entryInsuranceList) {
                    if (!InsuranceOrderConstants.STATUS_SUCCESS.equals(entryInsurance.getStatus())) {
                        throw new BusinessException("投保状态未完成，不允许并网验收通过");
                    } else if (!"工程安装一切险".equals(entryInsurance.getInsuranceName())&&!"4".equals(entryInsurance.getInsuranceType())&&StringUtil.isAnyBlank(entryInsurance.getNumber(), entryInsurance.getInsuranceType()
                            , entryInsurance.getInsuranceCompanyName(), entryInsurance.getPolicyholder(), entryInsurance.getInsurant()
                            , entryInsurance.getDownUrl()) || (entryInsurance.getInsuranceMoney() == null && !"工程安装一切险".equals(entryInsurance.getInsuranceName())) ) {
                        throw new BusinessException("投保单数据不完善，不允许并网验收通过");
                    }
                    if(PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())
                    &&!StringUtils.equalsAny(entryInsurance.getInsuranceType(),"0","4")){
                        throw new BusinessException("保单类型必须是财产险、工程险");
                    }
                }
            }

            if (!Objects.equals(CustomerEntryConstants.MERGE_FLAG_FINISH, materialMergeFlag)) {
                throw new BusinessException("审核通过需物料并网完成");
            }
            boolean hisFlag = true;
            if ("1".equals(entry.getIsHistory()) && PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){
                hisFlag = false;
            }
            //BT业务进入资方审核，其他业务变为已完成
            if ("1".equals(entry.getProductLine())) {
                entry.setToExamineStatus("7");//审核完成
                // entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_GWBW);
            } else if (!FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_TFZLTS) || !hisFlag) {
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_YWC);
                entry.setMergeFlag(CustomerEntryConstants.MERGE_FLAG_ZFSHTG);
                if (PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())){
                    //生成结算记录
                    customerEntryExtraService.bwSettle(entry);
                    accountSettleDetailDao.changeRewardSettleStatus(entry.getId());
                }
                //广发存量电站，并网验收通过后，自动推送电站客户信息
                if(!hisFlag){
                    CrmAcceptingReport report = getReportById(entry.getReceivingReportId());
                    entry.setMergeFlag(CustomerEntryConstants.MERGE_FLAG_ZFSHZ);
                    entry.setCheckAcceptName(user.getUserName());
                    entry.setCheckAcceptTime(new Date());
                    report.setMaterialMergeFlag(materialMergeFlag);
//                    report.setPowerCapacityUrl(powerCapacityUrl);
                    report.setMergeConclusion(fixConclusion);
                    reportDao.save(report);
                    CrmCustomerIncomingApplication application = incomingApplicationDao.getIncomingApplication(entry);
                    if (application==null || StringUtil.equalsAny(application.getTenantStatus(),"10","40","50")){
                        nhPowerStationService.customerEntryPush(entry.getId(),operator);
                    }
                }
            } else {
                CrmAcceptingReport report = getReportById(entry.getReceivingReportId());
                // entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_YWC);
                entry.setMergeFlag(CustomerEntryConstants.MERGE_FLAG_ZFSHZ);
                entry.setCheckAcceptName(user.getUserName());
                entry.setCheckAcceptTime(new Date());
                report.setMaterialMergeFlag(materialMergeFlag);
//                report.setPowerCapacityUrl(powerCapacityUrl);
                report.setMergeConclusion(fixConclusion);
                reportDao.save(report);
                //并网结算 放到了 越秀投放款付款申请状态 审核通过后
               /* //并网验收生成代理商的分包并网结算金额，分包并网结算额=分包结算额*（1-预结算比例A）-质保金，质保金=组件单瓦数*数量*质保金结算单价
                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:{}",id,fbAmount);
                BigDecimal proportion = accountSetService.findYjsProportion(entry.getDistributorId());
                Record set=accountSetService.findZBJSinglePrice();//质保金设置规则
                String way = set.getStr("way");//结算方式1.按瓦数 2.按组件块数 3.按结算比例（质保金账户使用
                BigDecimal propor=set.getBigDecimal("proportion");
                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);
                //生成待结算账户分包并网结算记录
                CrmTraderAccountSettleDetail settleDetail= createSettleDetail(entry, fbbwAmount, operator, "1", "0",settleNumber);
                //生成质保金账户结算记录
                CrmTraderAccountSettleDetail settleDetail2 =createSettleDetail(entry, zbjSinglePrice, operator, "3", "1",settleNumber);
                accountSettleDetailDao.save(settleDetail2);
                //释放授信额上限余额、增加分包款余额、增加验收结算总额、增加质保金总额，增加冻结金额
                CrmTraderAccount account = accountDao.findByTraderId(entry.getDistributorId());
                BigDecimal totalAmount = getTotalAmount(entry.getId(),"1");
                if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) {
                    account.setMaxQuotaAmountBalance(account.getMaxQuotaAmountBalance().add(totalAmount));
                }
                account.setSettleAmount(account.getSettleAmount().add(fbbwAmount));
                account.setSettleAmountYsjs(account.getSettleAmountYsjs().add(fbbwAmount));
                account.setQaAmount(account.getQaAmount().add(zbjSinglePrice));
                account.setQaAmountFreeze(account.getQaAmountFreeze().add(zbjSinglePrice));
                accountDao.save(account);

                if(settleDetail!=null){
                    //保存结算明细
                    accountSettleDetailDao.save(settleDetail);
                }*/
                //查询有没有变更记录
                CustomerEntrySupplementDetail changeRecordDetail = supplementDetailDao.getLatestChangeRecordDetail(entry.getId());
                CrmCustomerIncomingApplication application = applicationDao.getByEntryId(entry.getId());
                //推送进件信息
                switch (entry.getPartnerId()){
                    case PartnerConstants.PARTNER_ID_YX:
                        extraService.addIncomingApplicationSec(entry, operator, changeRecordDetail);
                        break;
                    case PartnerConstants.PARTNER_ID_GF:
                        guangFaManagemnetService.gridIncomingApplication(entry,application,report,operator);
                        break;
                    case PartnerConstants.PARTNER_ID_HR:
                        huaRongManagementService.accessProjectApplyTwo(entry, application,operator);
                        break;
                }
            }

            otherMsg = " 并网验收通过；";

        } else {
            // 查询验收报告
            CrmAcceptingReport report = getReportById(entry.getReceivingReportId());
            report.setMaterialMergeFlag(materialMergeFlag);
//            report.setPowerCapacityUrl(powerCapacityUrl);
            report.setMergeConclusion(fixConclusion);
            reportDao.save(report);
            //状态变为并网验收驳回
            entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_YSBH);
            entry.setMergeFlag(CustomerEntryConstants.CREDIT_MOREN);
            entry.setOnGridFlag(CustomerEntryConstants.ON_GRID_FLAG_ZFSHBH);
            typesh = CustomerEntryConstants.MERGE_ACCEPTANCE_REFUSE;
            otherMsg = " 并网验收驳回；";
        }
        entry.setMaterialMergeFlag(materialMergeFlag);
        customerDao.save(entry);

        if (!StrKit.isBlank(fixConclusion)) {
            otherMsg = otherMsg + fixConclusion;
        }
        examineService.updateToExamine(entry.getId(), ExamineConstants.EIGHT, otherMsg, operator.getUserName());
        msgService.saveCustomerEntryMsg(operator, entry.getId(), typesh, otherMsg, otherName);

        //生成审核的task
        Date date = new Date();
        String itemStatus = "1".equals(type) ? ItemConstants.RESULT_OK : ItemConstants.RESULT_BACK;
        ItemManage itemManage = itemManageDao.getItemManagementByEntryId(entry.getId(), FormUtils.ENTRY_STATUS_BWYS);
        if (itemManage != null) {
            itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_STATUS_BWYS, entry.getId(), itemManage.getProcessInstanceId(), itemManage.getProcessInstanceId(), itemStatus, date, operator, "并网验收");
            itemManage.setStatus(ItemConstants.ITEM_STATUS_FINISH);
            itemManage.setEndTime(date);
            itemManageDao.save(itemManage);
            reviewDispatchDao.markDispatchFinish(itemManage);
        }
    }

    /**
     * 小程序操作派工
     */
    @Transactional(rollbackFor = Exception.class)
    public void dispatch(DispatchReq req, Operator operator) {
        List<String> engineerIds = req.getEngineerIds();
        List<String> engineerNames = new ArrayList<>();
        for (String engineerId : engineerIds) {
            CrmTraderEmploye employe = traderEmployeService.getById(engineerId);
            if ("1".equals(employe.getStatus())) {
                throw new IllegalArgumentException("工程师【" + employe.getName() + "】已删除");
            }
            engineerNames.add(employe.getName());
        }
        GuardUtils.notBlank(req.getEntryId(), "电站参数不能为空");
        Date time = new Date();
        CustomerEntry entry = getById(req.getEntryId());
        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            throw new IllegalArgumentException(checkApplyResult);
        }

        entry.setDispatchStatus("1");
        entry.setEngineerId(StringUtil.join(engineerIds, ","));
        entry.setEngineerName(StringUtil.join(engineerNames, ","));
        entry.setDispatchTime(time);
        entry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_DAZ);
        saveByUpdate(entry);
        // 过程记录
        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ENTRY_DISPATCH, "已确认领料，执行派工；", "");
    }


    /**
     * 批量派工
     * 只要有分配权限就可以分配待办事项，不一定需要组长，但是改派必须由组长进行。
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchDispatch(BatchDispatchReq req) {
        User user = UserUtils.getUser();
       /* if (!UserConstants.TYPE_TRADER.equals(user.getUserType())) {
            throw new BusinessException("暂无权限操作");
        }*/
        // 操作人
        Operator operator = Operator.of(user);
        List<String> engineerIds = req.getEngineerIds();
        List<String> engineerNames = new ArrayList<>();
        for (String engineerId : engineerIds) {
            CrmTraderEmploye employe = traderEmployeService.getById(engineerId);
            if ("1".equals(employe.getStatus())) {
                throw new IllegalArgumentException("工程师【" + employe.getName() + "】已删除");
            }
            engineerNames.add(employe.getName());
        }
        GuardUtils.notBlank(req.getEntryIds(), "请选择电站");
        Date time = new Date();
        List<String> entryList = Arrays.asList(req.getEntryIds().split(","));
        for (String s : entryList) {
            CustomerEntry entry = getById(s);
            String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
            if (StringUtil.isNotBlank(checkApplyResult)) {
                throw new BusinessException("电站【" + entry.getPowerStationCode() + "】" + checkApplyResult);
            }
//            if ("1".equals(entry.getDispatchStatus())) {
//                throw new BusinessException("电站【"+entry.getPowerStationCode()+"】已派工");
//            }
            entry.setDispatchStatus("1");
            entry.setEngineerId(StringUtil.join(engineerIds, ","));
            entry.setEngineerName(StringUtil.join(engineerNames, ","));
            entry.setDispatchTime(time);
            entry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_DAZ);
            saveByUpdate(entry);
            // 过程记录
            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ENTRY_DISPATCH, "已确认领料，执行派工；", "");
        }
    }

    /**
     * 撤销派工
     */
    @Transactional(rollbackFor = Exception.class)
    public void turnbackDispatch(String ids) {
        User user = UserUtils.getUser();
//        if (!UserConstants.TYPE_TRADER.equals(user.getUserType())) {
//            throw new BusinessException("暂无权限操作");
//        }
        // 操作人
        Operator operator = Operator.of(user);
        if (StringUtil.isBlank(ids)) {
            throw new BusinessException("请选择数据");
        }
        List<String> entryList = Arrays.asList(ids.split(","));
        for (String s : entryList) {
            CustomerEntry entry = getById(s);
            String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
            if (StringUtil.isNotBlank(checkApplyResult)) {
                throw new BusinessException(String.format("电站【%s】%s", entry.getPowerStationCode(), checkApplyResult));
            }

            entry.setDispatchStatus("0");
            entry.setEngineerId(null);
            entry.setEngineerName(null);
            entry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_DPG);
            saveByUpdate(entry);
            // 过程记录
            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ENTRY_DISPATCH_QUASH, "撤销派工；", "");
        }

    }

    /**
     * 查询首页统计
     */
    public Record homeStatistics(Map<String, String> map, User user, boolean isShow, Operator operator) {
        return customerDao.homeStatistics(map, user, isShow, operator);
    }

    public List<CrmPlanMaterialEntry> findUsedByEntryId(String entryId) {
        return entryDao.findByEntryId(entryId);
    }

    public List<CrmPlanMaterialEntry> findByEntryProjectId(String entryId, String[] projectId) {
        return entryDao.findByEntryProjectId(entryId,projectId);
    }



    public String findVoByEntryId(String code) {
        String sql = "select material_brand as materialBrand from crm_supply_material where code =?";

        return Db.queryStr(sql, code);
    }

    /**
     * 删除使用物料
     */
    @Transactional(rollbackFor = Exception.class)
    public Result deleteUsedRecord(String ids) {
        List<CrmPlanMaterialEntry> list = entryDao.findByIds(ids);
        for (CrmPlanMaterialEntry materialEntry : list) {
            if (StringUtil.isNotBlank(materialEntry.getBarcode())) {
                // 查询条码库数据
                CrmSupplyBarcode oneByBarcode = barcodeDao.findOneByBarcode(materialEntry.getBarcode());
                oneByBarcode.setBarcodeStatus("2");
                barcodeDao.save(oneByBarcode);
            }
            entryDao.deletePlanMaterialById(materialEntry.getId());
            if (StringUtil.isNotBlank(materialEntry.getSn())) {
                CustomerEntry entry = customerDao.get(materialEntry.getEntryId());
                if (StringUtil.isNotBlank(entry.getSn())) {
                    List<String> snList = new ArrayList<>(Arrays.asList(entry.getSn().split(",")));
                    snList.remove(materialEntry.getSn());
                    entry.setSn(StringUtil.join(snList, ","));
                    List<String> nbqSnList = new ArrayList<>(Arrays.asList(entry.getNbqSn().split(",")));
                    nbqSnList.remove(materialEntry.getNbqSn());
                    entry.setNbqSn(StringUtil.join(nbqSnList, ","));
                    customerDao.save(entry);
                }
            }
        }
        return Result.ok();
    }

    //校验物料条码是否有效
    public Result checkMaterialCode(UsedMaterialReq req) {
        Result result = new Result<>();
        if (StringUtil.isBlank(req.getBarcode())) {
            result.setCode("205");
            result.setMsg("扫码结果：" + req.getBarcode() + "，未查询到该条码");
            return result;
        }
        String barcode = req.getBarcode().trim();
        CustomerEntry entry = customerDao.get(req.getEntryId());
        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            result = Result.fail(checkApplyResult);
            return result;
        }
        if ("0".equals(req.getFlag())) {
            result.setOk();
        }
        else {
            CrmSupplyBarcode oneByBarcode = barcodeDao.findOneByBarcode(barcode);
            if (oneByBarcode == null) {
                result.setCode("205");
                result.setMsg("扫码结果：" + barcode + "，未查询到该条码，请联系仓库导入条码");
                return result;
            } else if ("1".equals(oneByBarcode.getStatus())) {
                result.setCode("202");
                result.setMsg("扫码结果：" + barcode + "，该条码已被删除");
                return result;
            } else if ("1".equals(oneByBarcode.getBarcodeStatus())) {
                result.setCode("201");
                result.setMsg("扫码结果：" + barcode + "，该物料已被使用");
                return result;
            }
            // 查询物料id
            SupplyMaterial material = supplyMaterialDao.get(oneByBarcode.getMaterialId());
            if (material == null) {
                result.setCode("205");
                result.setMsg("扫码结果：" + barcode + "，未查询到该物料");
                return result;
            }
            if (!material.getMaterialSpecs().equals(req.getSpec())) {
                result.setCode("205");
                result.setMsg("扫码结果：" + barcode + "，扫码识别的物料规格和设计规格不匹配");
                return result;
            }
            if (StringUtil.isNotBlank(req.getMaterialModel()) && !material.getMaterialModel().equals(req.getMaterialModel())) {
                result.setCode("205");
                result.setMsg("扫码结果：" + barcode + "，扫码识别的物料型号和设计型号不匹配");
                return result;
            }
            BigDecimal warning = materialStockDao.getWarning(req.getWarehouseId(), material.getId());
            if (warning == null || warning.compareTo(BigDecimal.ZERO) == 0) {
                result.setCode("205");
                result.setMsg("扫码结果：" + barcode + "，该物料库存不足，请联系仓库核实是否有库存");
                return result;
            }

            // 查询物料类型
            CrmSupplyMaterialType materialType = materialTypeDao.get(material.getMaterialTypeId());
            if (StringUtil.isNotBlank(req.getMaterialType()) && !req.getMaterialType().equals(materialType.getId())) {
                result.setCode("205");
                result.setMsg("扫码结果：" + barcode + "，物料不存在");
                return result;
            }
            String brand = "";

            List<Record> materialList;
            if("04".equals(entry.getPartnerId())){
                materialList = entryDao.findMaterialListByEntryProjectId(entry.getId(),req.getProjectId());
            }else{
                materialList = entryDao.findMaterialListByEntryId(entry.getId());
            }
            List<Record> nbqList = materialList.stream().filter(r -> "逆变器".equals(r.getStr("type"))).collect(Collectors.toList());
            if (nbqList.size() > 0 && "逆变器".equals(materialType.getName())) {
                for (Record record : nbqList) {
                    brand = record.getStr("material_brand");
                    break;
                }
                if (!brand.equals(material.getMaterialBrand())) {
                    result.setCode("205");
                    result.setMsg("扫码结果：" + barcode + "，请使用相同品牌的物料");
                    return result;
                }
            }
        }
        result.setCode("200");
        result.setMsg("可以使用");
        result.setData(barcode);
        return result;
    }

    /**
     * 使用物料
     */
    public Result usedMaterial(UsedMaterialReq req) {
        Result result = new Result<>();
        if (StringUtil.isBlank(req.getBarcode())) {
            result.setCode("205");
            result.setMsg("扫码结果：" + req.getBarcode() + "，未查询到该条码");
            return result;
        }
        CustomerEntry entry = customerDao.get(req.getEntryId());
        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            result = Result.fail(checkApplyResult);
            return result;
        }
        Date now = new Date();
        if ("0".equals(req.getFlag())) {
            if (StringUtil.isBlank(req.getType())) {
                result.setCode("201");
                result.setMsg("物料类型不能为空");
                return result;
            } else if (StringUtil.isBlank(req.getCode())) {
                result.setCode("202");
                result.setMsg("物料号不能为空");
                return result;
            } else if (StringUtil.isBlank(req.getSpec())) {
                result.setCode("203");
                result.setMsg("物料规格不能为空");
                return result;
            } else if (StringUtil.isBlank(req.getName())) {
                result.setCode("204");
                result.setMsg("物料名称不能为空");
                return result;
            } else if (StringUtil.isBlank(req.getMaterialModel())){
                result.setCode("205");
                result.setMsg("物料型号不能为空");
                return result;
            }
            if("04".equals(entry.getPartnerId())){
                    entryDao.createOne("", req.getType(), req.getCode(), req.getName(), req.getSpec(), "", req.getBarcode().trim(), 1
                            , now, req.getEntryId(),req.getMaterialModel(),req.getProjectId());
            }else{
                entryDao.createOne("", req.getType(), req.getCode(), req.getName(), req.getSpec(), "", req.getBarcode().trim(), 1
                        , now, req.getEntryId(),req.getMaterialModel(),entry.getProjectId());
            }
        } else {
            CrmSupplyBarcode oneByBarcode = barcodeDao.findOneByBarcode(req.getBarcode().trim());
            if (oneByBarcode == null) {
                result.setCode("205");
                result.setMsg("扫码结果：" + req.getBarcode() + "，未查询到该条码，请联系仓库导入条码");
                return result;
            } else if ("1".equals(oneByBarcode.getStatus())) {
                result.setCode("202");
                result.setMsg("扫码结果：" + req.getBarcode() + "，该条码已被删除");
                return result;
            } else if ("1".equals(oneByBarcode.getBarcodeStatus())) {
                result.setCode("201");
                result.setMsg("扫码结果：" + req.getBarcode() + "，该物料已被使用");
                return result;
            }
            // 查询物料id
            SupplyMaterial material = supplyMaterialDao.get(oneByBarcode.getMaterialId());
            if (material == null) {
                result.setCode("205");
                result.setMsg("扫码结果：" + req.getBarcode() + "，未查询到该物料");
                return result;
            }
            if (!material.getMaterialSpecs().equals(req.getSpec())) {
                result.setCode("205");
                result.setMsg("扫码结果：" + req.getBarcode() + "，扫码识别的物料规格和设计规格不匹配");
                return result;
            }
            if (StringUtil.isNotBlank(req.getMaterialModel()) && !material.getMaterialModel().equals(req.getMaterialModel())) {
                result.setCode("205");
                result.setMsg("扫码结果：" + req.getBarcode() + "，扫码识别的物料型号和设计型号不匹配");
                return result;
            }
            BigDecimal warning = materialStockDao.getWarning(req.getWarehouseId(), material.getId());
            if (warning == null || warning.compareTo(BigDecimal.ZERO) == 0) {
                result.setCode("205");
                result.setMsg("扫码结果：" + req.getBarcode() + "，该物料库存不足，请联系仓库核实是否有库存");
                return result;
            }

            // 查询物料类型
            CrmSupplyMaterialType materialType = materialTypeDao.get(material.getMaterialTypeId());
            if (StringUtil.isNotBlank(req.getMaterialType()) && !req.getMaterialType().equals(materialType.getId())) {
                result.setCode("205");
                result.setMsg("扫码结果：" + req.getBarcode() + "，物料不存在");
                return result;
            }
            String brand = "";
            List<Record> materialList;
            if("04".equals(entry.getPartnerId())){
                materialList = entryDao.findMaterialListByEntryProjectId(entry.getId(),req.getProjectId());
            }else{
                materialList = entryDao.findMaterialListByEntryId(entry.getId());
            }
            List<Record> nbqList = materialList.stream().filter(r -> "逆变器".equals(r.getStr("type"))).collect(Collectors.toList());
            if (nbqList.size() > 0 && "逆变器".equals(materialType.getName())) {
                for (Record record : nbqList) {
                    brand = record.getStr("material_brand");
                    break;
                }
                if (!brand.equals(material.getMaterialBrand())) {
                    result.setCode("205");
                    result.setMsg("扫码结果：" + req.getBarcode() + "，请使用相同品牌的物料");
                    return result;
                }
            }

            if("04".equals(entry.getPartnerId())){
                entryDao.createOne(material.getId(), materialType.getName(), material.getCode(), material.getMaterialName(),
                        material.getMaterialSpecs(), material.getUnitName(), oneByBarcode.getMaterialBarcode(),
                        1, now, req.getEntryId(),material.getMaterialModel(),req.getProjectId());
            }else{
                entryDao.createOne(material.getId(), materialType.getName(), material.getCode(), material.getMaterialName(),
                        material.getMaterialSpecs(), material.getUnitName(), oneByBarcode.getMaterialBarcode(),
                        1, now, req.getEntryId(),material.getMaterialModel(),entry.getProjectId());
            }
            oneByBarcode.setBarcodeStatus("1");
            barcodeDao.save(oneByBarcode);
        }
        result.setOk();
        return result;
    }

    /**
     * 电站退回待安装
     * step : 1.清除结算 2.退回库存 3.清除使用物料
     */
    @Transactional(rollbackFor = Exception.class)
    public Result backAzForEntry(String entryId, User user, int step, String remarks) throws IllegalAccessException {
        CustomerEntry entry = customerDao.get(entryId);
        if (entry == null || "b".equals(entry.getStatus())) {
            return Result.fail("电站已删除");
        }
        CrmCustomerIncomingApplication application = applicationDao.getByEntryId(entry.getId());
        if (application != null && StringUtil.equalsAny(application.getStatus(),"15","17","18","19","20","23","31")) {
            return Result.fail("已提交完工/并网进件，不支持退回待安装");
        }
        if (PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId()) ||  PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId()) ){
            if (application != null && StringUtil.equalsAny(application.getStatus(),"21")) {
                return Result.fail("已提交完工/并网进件，不支持退回待安装");
            }
        }
        if (PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId()) &&
                !StringUtil.equalsAny(entry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_AZZS,CustomerEntryConstants.ENTRY_STATUS_DAZ,
                CustomerEntryConstants.ENTRY_STATUS_AZYSTH, CustomerEntryConstants.ENTRY_STATUS_DBW,
                CustomerEntryConstants.ENTRY_STATUS_YSBH)) {
            return Result.fail("当前状态不支持退回安装操作，华融电站待并网/安装阶段才可操作");
        }
        else if ( (PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())  || PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())) && !StringUtil.equalsAny(entry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_AZZS,CustomerEntryConstants.ENTRY_STATUS_DAZ,
                CustomerEntryConstants.ENTRY_STATUS_AZYSTH)) {
            return Result.fail("当前状态不支持退回安装操作，广发越秀电站安装阶段才可操作");
        }
        List<CrmPlanMaterialEntry> usedMaterials = findUsedByEntryId(entry.getId());
        if (usedMaterials.isEmpty()) {
            return Result.fail("当前状态不需要退回操作");
        }
        String content = null;
        if (step > 0 && StringUtil.equalsAny(entry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_DBW,
                CustomerEntryConstants.ENTRY_STATUS_YSBH)) {
            removeEntrySettle(entry, application);
            content = "并网退回安装,清除结算记录";
        }
        if (step > 1 && StringUtil.equalsAny(entry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_DAZ,
                CustomerEntryConstants.ENTRY_STATUS_AZZS, CustomerEntryConstants.ENTRY_STATUS_AZYSTH)) {
            if (PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())) {
                delInterfaceRecord(entry.getId(), usedMaterials);
            }
            backStockForEntry(entry, application);
            if (StringUtil.isBlank(content)) {
                content = "安装验收退回待安装,将物料退回仓库";
            }
            else {
                content = content + ",将物料退回仓库";
            }
        }
        if (step > 2 && CustomerEntryConstants.ENTRY_STATUS_DAZ.equals(entry.getStatus())) {
            removeUsedMaterial(entry);
            content = content + ",清除电站物料使用记录";
        }
        if (StringUtil.isBlank(content)) {
            return Result.fail("当前状态不需要退回待安装");
        }

        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user), user.getUserType());
        msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.BACK_DAZ,
                content + (StringUtil.isNotBlank(remarks) ? ("," + remarks) : ""),"");
        return Result.ok();
    }


    /**
     * 并网退回安装时，删除结算记录
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeEntrySettle(CustomerEntry entry, CrmCustomerIncomingApplication application) throws IllegalAccessException {
        if (entry == null) {
            return;
        }
        if (!PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())) {
            throw new IllegalAccessException("暂时只支持资方华融电站进行退回操作");
        }
        // 待并网状态才可操作
        if (!StringUtil.equalsAny(entry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_DBW,
                CustomerEntryConstants.ENTRY_STATUS_YSBH)) {
            throw new IllegalAccessException("当前状态不支持退回安装操作，待并网才可操作");
        }

        // 删除结算记录
        List<CrmTraderAccountSettleDetail> settleDetails = accountSettleDetailDao.findListByEntry(entry.getId(), null);
        if (settleDetails.isEmpty()) {
            throw new IllegalAccessException("操作失败，未查询到结算记录");
        }
        BigDecimal yjsAmount = BigDecimal.ZERO;
        BigDecimal cfAmount = BigDecimal.ZERO;
        List<CrmTraderAccountSettleDetail> yjsDetails = new ArrayList<>();
        List<CrmTraderAccountSettleDetail> cfDetails = new ArrayList<>();
        for (CrmTraderAccountSettleDetail settleDetail : settleDetails) {
            //结算类型:0.预结算 1.分包并网结算 2.电站整改(减) 3.质保金 4.奖励政策 5.并网惩罚政策(减)
            if (StringUtil.equalsAny(settleDetail.getType(),"1","3")) {
                throw new IllegalAccessException("电站已生成并网结算不支持退回安装操作");
            }
            if ("2".equals(settleDetail.getType())) {
                throw new IllegalAccessException("电站已生成整改结算记录不支持退回安装操作");
            }
            if ("0".equals(settleDetail.getType())) {
                yjsAmount = yjsAmount.add(settleDetail.getAmount());
                yjsDetails.add(settleDetail);
            }
            if ("5".equals(settleDetail.getType())) {
                cfAmount = cfAmount.add(settleDetail.getAmount().negate());
                cfDetails.add(settleDetail);
            }
        }
        //释放标准授信额度余额、增加分包款余额、增加验收结算总额、增加质保金总额，增加冻结金额
        CrmTraderAccount account = accountDao.findByTraderId(entry.getDistributorId());

        // 删除结算明细
        for (CrmTraderAccountSettleDetail detail : yjsDetails) {
            boolean deleted;
            try {
                deleted = accountSettleDetailDao.deleteDetail(detail);
            }catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new IllegalAccessException("已退回，请勿重复操作");
            }
            if (!deleted) {
                throw new IllegalAccessException("已退回，请勿重复操作");
            }
        }
        // 删除结算明细
        for (CrmTraderAccountSettleDetail detail : cfDetails) {
            boolean deleted;
            try {
                deleted = accountSettleDetailDao.deleteDetail(detail);
            }catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new IllegalAccessException("已退回，请勿重复操作");
            }
            if (!deleted) {
                throw new IllegalAccessException("已退回，请勿重复操作");
            }
        }

        // 结算账户余额退回
        // basic_quota_amount_balance -,settle_amount -,settle_amount_ysjs -, settle_rewards_punish_amount +
        BigDecimal settleAmount = yjsAmount.subtract(cfAmount);
        BigDecimal settleAmountYsjs = yjsAmount;
        BigDecimal settleRewardsPunishAmount = cfAmount;
        accountDao.updateAccountSettleAmount(settleAmount.negate(), settleAmountYsjs.negate(), settleRewardsPunishAmount.negate(),account.getId());
        // basic_quota_amount_balance -
        BigDecimal totalAmount = getTotalAmount(entry.getId(),"1");
        if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) {
            accountDao.updateBasicQuotaAmountBalance(totalAmount.negate(),account.getId());
        }

        // 物料出库记录 结算标记 改成未生成结算记录
        materialKeepDao.update("update CrmSupplyMaterialKeep set accountFlag='0' where sourceId=:p1 and type = '2' and accountFlag='1' ",
                new Parameter(entry.getId()));

        entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DAZ);
        entry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_ZSBH);
        entry.setCheckAcceptFlag(CustomerEntryConstants.FLAG_INIT);
        entry.setOnGridFlag(CustomerEntryConstants.FLAG_INIT);
        customerDao.save(entry);

        //TODO 保单记录无法删除

    }

    /**
     * 清除逆变器平台、监控系统数据
     * @param entryId
     */
    public void delInterfaceRecord(String entryId, List<CrmPlanMaterialEntry> usedMaterials) {
        //TODO 需要删除监控系统数据 需要手动在监控系统删除电站及设备
        NhPowerStationService.backSysRecord(entryId);
        boolean checked = checkEntryJrInterface(entryId);
        //TODO 有接入逆变器厂商 需要手动删除逆变器平台的电站设备数据
        if (checked) {
            // 固德威逆变器 可直接通过接口删除逆变器平台的数据 其他品牌不行
            String gdwStationId = getJlStationId("02", entryId);
            if (StringUtil.isNotBlank(gdwStationId)) {
                for (CrmPlanMaterialEntry me : usedMaterials) {
                    if ("逆变器".equals(me.getType())) {
                        removeInverterGoodW(entryId, gdwStationId, me.getNbqSn(), PartnerConstants.PARTNER_ID_HR);
                    }
                }
            }
            deleteEntryJrInterface(entryId);
        }
    }

    /**
     * 物料退回仓库
     */
    @Transactional(rollbackFor = Exception.class)
    public void backStockForEntry(CustomerEntry entry, CrmCustomerIncomingApplication application) throws IllegalAccessException {
        if (entry == null) {
            return;
        }
//        if (!PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())) {
//            throw new IllegalAccessException("暂时只支持资方华融电站进行退回物料操作");
//        }
        if (!StringUtil.equalsAny(entry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_DAZ,
                CustomerEntryConstants.ENTRY_STATUS_AZZS, CustomerEntryConstants.ENTRY_STATUS_AZYSTH)) {
            throw new IllegalAccessException("当前状态不支持退回物料操作，安装阶段才可操作");
        }
        List<CrmPlanMaterialEntry> usedMaterials = findUsedByEntryId(entry.getId());
        if (usedMaterials.isEmpty()) {
            return;
        }
        // 要求
        // 1.清理掉结算信息
        List<CrmTraderAccountSettleDetail> settleDetails = accountSettleDetailDao.findListByEntry(entry.getId(), "0,1,2,3,5");
        if (!settleDetails.isEmpty()) {
            throw new IllegalAccessException("电站已生成结算记录不支持退回物料操作");
        }
        // 2.清理逆变器平台数据、监控运维数据
        if (checkEntryJrInterface(entry.getId())) {
            throw new IllegalAccessException("电站已推送给逆变器平台不支持退回物料操作");
        }

        List<CrmSupplyMaterialKeep> keeps = materialKeepDao.getListByEntryId(entry.getId());
        // 退库存
        for (CrmSupplyMaterialKeep keep : keeps) {
            // MaterialWarehouseStocks  warning +，real_num +
            materialStockDao.backStock(keep.getMaterialId(), keep.getWarehouseId(), keep.getAmount());
            // SupplyMaterialBatch sold_num -， remaining +
            batchDao.backStock(keep.getBatchId(), keep.getAmount());

            // 使用记录 old_flag出库标记改成1
            for (CrmPlanMaterialEntry me : usedMaterials) {
                if (me.getMaterialId().equals(keep.getMaterialId()) && "2".equals(me.getOldFlag())) {
                    me.setOldFlag("1");
                    entryDao.save(me);
                }
            }
            // 删除出库记录
            boolean deleted;
            try {
                deleted = materialKeepDao.deleteKeep(keep);
            }catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new IllegalAccessException("已退回，请勿重复操作");
            }
            if (!deleted) {
                throw new IllegalAccessException("已退回，请勿重复操作");
            }
        }
        //删除出库确认明细
        StringBuilder sql = new StringBuilder();
        sql.append(" DELETE FROM crm_customer_entry_out_confirm_detail WHERE main_id in ( ");
        sql.append(" SELECT c.`id` FROM crm_customer_entry_out_confirm c WHERE c.`entry_id` = ? )");
        Db.update(sql.toString(), entry.getId());
        if (StringUtil.equalsAny(entry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_AZZS,
                CustomerEntryConstants.ENTRY_STATUS_AZYSTH)) {
            entry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_ZSBH);
            entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DAZ);
            customerDao.save(entry);
        }
    }

    /**
     * 删除电站的物料使用记录
     * 前提不存在已出库的物料
     */
    public void removeUsedMaterial(CustomerEntry entry) throws IllegalAccessException {
        if (!CustomerEntryConstants.ENTRY_STATUS_DAZ.equals(entry.getStatus())) {
            throw new IllegalAccessException("安装状态下 才可删除物料记录");
        }
        List<CrmSupplyMaterialKeep> keeps = materialKeepDao.getListByEntryId(entry.getId());
        if (!keeps.isEmpty()) {
            throw new IllegalAccessException("需要先将已出库的物料退回仓库");
        }
        List<CrmPlanMaterialEntry> usedMaterials = findUsedByEntryId(entry.getId());
        for (CrmPlanMaterialEntry me : usedMaterials) {
            if ("2".equals(me.getOldFlag())) {
                throw new IllegalAccessException("需要先将已出库的物料退回仓库");
            }

            boolean deleted;
            try {
                deleted = entryDao.deleteDetail(me);
            }catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new IllegalAccessException("已删除物料，请勿重复操作");
            }
            if (!deleted) {
                throw new IllegalAccessException("已删除物料，请勿重复操作");
            }
            if (StringUtil.equalsAny(me.getType(),"组件","逆变器")){
                CrmSupplyBarcode barcode = barcodeDao.findOneByBarcode(me.getBarcode());
                barcode.setBarcodeStatus("2");
                barcodeDao.save(barcode);
            }
        }
    }

    public Result saveWarehouse(String entryId, String warehouseId) {
        SQLQuery sqlQuery = customerDao.getSession()
                .createSQLQuery("update crm_customer_entry set warehouse_id=:warehouseId where id = :id ");
        sqlQuery.setParameter("warehouseId", warehouseId);
        sqlQuery.setParameter("id", entryId);
        sqlQuery.executeUpdate();

        return Result.ok();
    }

    /**
     * 查询安装组件信息：使用最多的规格，数量 ，实际安装容量
     */
    public Result findActualCapacity(String entryId) {
        List<CrmPlanMaterialEntry> materialEntries = entryDao.findByEntryId(entryId);
        List<Record> mostSpecList = entryDao.findMostSpecByEntryId(entryId);
        int total = 0;
        int nbqTotal = 0;
        for (CrmPlanMaterialEntry materialEntry : materialEntries) {
            if ("组件".equals(materialEntry.getType())) {
                total = total + Integer.parseInt(materialEntry.getSpec());
            } else if ("逆变器".equals(materialEntry.getType())) {
                nbqTotal = nbqTotal + materialEntry.getAmount();
            }
        }
        Record record = new Record();
        BigDecimal i = BigDecimal.ZERO;
        String componentSpec = "";
        int componentNum = 0;
        for (Record r : mostSpecList) {
            if ("组件".equals(r.getStr("type"))) {
                componentNum = componentNum + Integer.parseInt(r.getBigDecimal("amount").toString());
                if (StringUtil.isBlank(componentSpec)) {
                    componentSpec = r.getStr("spec");
                } else {
                    componentSpec = componentSpec + "," + r.getStr("spec");
                }
                if (r.getBigDecimal("amount").compareTo(i) > 0) {
                    i = r.getBigDecimal("amount");
                    record.set("spec", r.getStr("spec"));
                    record.set("amount", Integer.parseInt(r.getBigDecimal("amount").toString()));
                }
            }
        }

        // 实际安装容量
        record.set("total", total);
        record.set("nbqTotal", nbqTotal);
        record.set("componentSpec", componentSpec);
        record.set("componentNum", componentNum);
        Result result = new Result<>();
        result.setOk();
        result.setData(new Gson().toJson(record));
        return result;
    }

    private Pattern dhpattern = Pattern.compile("^(\\+\\d{1,3})?\\s?\\(?\\d{1,4}\\)?[-.\\s]?\\d{1,4}[-.\\s]?\\d{4}$");
    private Pattern sfzPattern = Pattern.compile("(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)");

    //业主信息必填校验
    public Result requiredCheckTJ(CustomerEntry entry, CrmPartner partner) {
        Result result = new Result();
        result.setCode("205");
        if (StringUtil.isBlank(entry.getProjectId())) {
            result.setErrMsg("项目名称为空");
            return result;
        }
        if (StringUtil.isBlank(entry.getTenantName())) {
            result.setErrMsg("业主姓名为空");
            return result;
        }
        if (StringUtil.isBlank(entry.getIdCode())) {
            result.setErrMsg("身份证号为空");
            return result;
        }
        if (StringUtil.isNotBlank(entry.getIdCode()) && !sfzPattern.matcher(entry.getIdCode()).matches()) {
            result.setErrMsg("身份证号格式不正确！");
            return result;
        }
        if (StringUtil.isBlank(entry.getGender())) {
            result.setErrMsg("性别为空");
            return result;
        }
        if (entry.getAge() == null) {
            result.setErrMsg("年龄为空");
            return result;
        }
        if (StringUtil.isBlank(entry.getMobile())) {
            result.setErrMsg("联系电话为空");
            return result;
        }
        if (StringUtil.isNotBlank(entry.getMobile()) && !dhpattern.matcher(entry.getMobile()).matches()) {
            result.setErrMsg("联系电话格式不正确！");
            return result;
        }
        //身份证
        if (StringUtil.isBlank(entry.getIdCardFront())) {
            result.setErrMsg("身份证正面为空");
            return result;
        }
        if (StringUtil.isBlank(entry.getIdCardBack())) {
            result.setErrMsg("身份证反面为空");
            return result;
        }
        if (Objects.equals("1", partner.getOverageFlag()) && entry.getAge() >= partner.getNeedSignerAge()) {
            if (StringUtil.isBlank(entry.getBpName())) {
                result.setErrMsg("共签人名称为空");
                return result;
            }
            if (StringUtil.isBlank(entry.getBpIdCard())) {
                result.setErrMsg("共签人证件号码为空");
                return result;
            }
            if (StringUtil.isBlank(entry.getBpMobile())) {
                result.setErrMsg("共签人手机号为空");
                return result;
            }
            if (StringUtil.isBlank(entry.getBpCardFront())) {
                result.setErrMsg("共签人身份证正面为空");
                return result;
            }
            if (StringUtil.isBlank(entry.getBpCardBack())) {
                result.setErrMsg("共签人身份证反面为空");
                return result;
            }
            if (StringUtil.isBlank(entry.getBpFile())) {
                result.setErrMsg("共签人子女证明材料为空");
                return result;
            }
        }

        //安装地址
        if (StringUtil.isBlank(entry.getProvince()) || StringUtil.isBlank(entry.getCity())
                || StringUtil.isBlank(entry.getArea()) || StringUtil.isBlank(entry.getAddress())) {
            result.setErrMsg("请补全安装地址");
            return result;
        }
        return Result.ok();
    }

    // 信息登记必填校验 step=1为信息录入的提交 step=2为提交预审
    public Result requiredCheckForRegisterInfo(CustomerEntry entry, String regnoUrl, List<Record> list, String step, String creditCertificate, String houseOwnership) {
        Result result = new Result();
        result.setCode("205");
        if (CheckMustFillUtil.checkMustFill("project_name", list) &&
                StringUtil.isBlank(entry.getProjectId())) {
            result.setErrMsg("请选择产品");
            return result;
        }
        if (StringUtil.isBlank(entry.getTenantType())) {
            result.setErrMsg("客户类型为空");
            return result;
        }
        if (StringUtil.isBlank(entry.getProvince())) {
            result.setErrMsg("请选择业主地址-省");
            return result;
        }
        if (StringUtil.isBlank(entry.getCity())) {
            result.setErrMsg("请选择业主地址-市");
            return result;
        }
        if (StringUtil.isBlank(entry.getArea())) {
            result.setErrMsg("请选择业主地址-区县");
            return result;
        }
        if (StringUtil.isBlank(entry.getAddress())) {
            result.setErrMsg("请填写业主详细地址");
            return result;
        }
        if (StringUtil.isBlank(entry.getProjectCompanyId())) {
            result.setErrMsg("请选择项目公司");
            return result;
        }
        if (StringUtil.isBlank(entry.getTenantName())
                && CheckMustFillUtil.checkMustFill("tenant_name", list)) {
            if (Objects.equals("1", entry.getTenantType())) {
                result.setErrMsg("业主姓名为空");
            } else {
                result.setErrMsg("单位名称为空");
            }
            return result;
        }
        // 信用代码
        if (StringUtil.isBlank(entry.getRegno())
                && Objects.equals("2", entry.getTenantType())
                && CheckMustFillUtil.checkMustFill("regno", list)) {
            result.setErrMsg("统一社会信用代码为空");
            return result;
        }
        if (StringUtil.isBlank(entry.getIdCode())
                && CheckMustFillUtil.checkMustFill("id_code", list)) {
            result.setErrMsg("身份证号为空");
            return result;
        }
        if (StringUtil.isNotBlank(entry.getIdCode()) && !sfzPattern.matcher(entry.getIdCode()).matches()) {
            result.setErrMsg("身份证号格式不正确！");
            return result;
        }
        if (StringUtil.isBlank(entry.getGender())
                && Objects.equals("1", entry.getTenantType())
                && CheckMustFillUtil.checkMustFill("gender", list)) {
            result.setErrMsg("性别为空");
            return result;
        }
        CrmPartner partner = partnerService.getById(entry.getPartnerId());
        if("1".equals(entry.getTenantType())) {
            if (entry.getAge() == null
                    && Objects.equals("1", entry.getTenantType())
                    && CheckMustFillUtil.checkMustFill("age", list)) {
                result.setErrMsg("年龄为空");
                return result;
            } else if (entry.getAge() != null) {
                if (partner.getFailCreateAge() != null && entry.getAge() > partner.getFailCreateAge()) {
                    result.setErrMsg("年龄超过建站要求");
                    return result;
                }
            }
        }
        if (StringUtil.isBlank(entry.getMobile())
                && CheckMustFillUtil.checkMustFill("mobile", list)) {
            result.setErrMsg("联系电话为空");
            return result;
        }
        if (StringUtil.isNotBlank(entry.getMobile()) && !dhpattern.matcher(entry.getMobile()).matches()) {
            result.setErrMsg("联系电话格式不正确！");
            return result;
        }
        //身份证
        if (StringUtil.isBlank(entry.getIdCardFront())
                && CheckMustFillUtil.checkMustFill("id_card_front", list)) {
            result.setErrMsg("身份证正面为空");
            return result;
        }
        if (StringUtil.isBlank(entry.getIdCardBack())
                && CheckMustFillUtil.checkMustFill("id_card_back", list)) {
            result.setErrMsg("身份证反面为空");
            return result;
        }
        //安装地址
        if (StringUtil.isBlank(entry.getProvince()) || StringUtil.isBlank(entry.getCity())
                || StringUtil.isBlank(entry.getArea()) || StringUtil.isBlank(entry.getAddress())) {
            result.setErrMsg("请补全安装地址");
            return result;
        }
        // 账户名称
        if (StringUtil.isBlank(entry.getBankName())
                && CheckMustFillUtil.checkMustFill("bank_name", list)) {
            result.setErrMsg("账户名称为空");
            return result;
        }
        // 银行账号
        if (StringUtil.isBlank(entry.getBankCode())
                && CheckMustFillUtil.checkMustFill("bank_code", list)) {
            result.setErrMsg("银行账号为空");
            return result;
        }
        // 开户行
        if (StringUtil.isBlank(entry.getTssBankNumName())
                && CheckMustFillUtil.checkMustFill("tss_bank_num_name", list)) {
            result.setErrMsg("开户行为空");
            return result;
        }
        // 银行卡照片
        if (StringUtil.isBlank(entry.getBankCard())
                && CheckMustFillUtil.checkMustFill("bank_card", list)) {
            result.setErrMsg("银行卡照片为空");
            return result;
        }
        // 户口本复印件
        if (StringUtil.isBlank(entry.getResidenceBooklet())
                && Objects.equals("1", entry.getTenantType())
                && CheckMustFillUtil.checkMustFill("residence_booklet", list)) {
            result.setErrMsg("户口本复印件为空");
            return result;
        }
        // 负责人姓名
        if (StringUtil.isBlank(entry.getCorp())
                && Objects.equals("2", entry.getTenantType())
                && CheckMustFillUtil.checkMustFill("corp", list)) {
            result.setErrMsg("负责人姓名为空");
            return result;
        }
        // 营业执照
        if (StringUtil.isBlank(regnoUrl)
                && Objects.equals("2", entry.getTenantType())
                && CheckMustFillUtil.checkMustFill("regno_url", list)) {
            result.setErrMsg("营业执照为空");
            return result;
        }
        if (StringUtil.isBlank(houseOwnership)
                && Objects.equals("1", entry.getTenantType())
                && CheckMustFillUtil.checkMustFill("house_ownership", list)) {
            result.setErrMsg("房产证为空");
            return result;
        }
        if (StringUtil.isBlank(creditCertificate)
                && Objects.equals("1", entry.getTenantType())
                && CheckMustFillUtil.checkMustFill("credit_certificate", list)) {
            result.setErrMsg("信誉凭证为空");
            return result;
        }
        if (StringUtil.isBlank(entry.getExigenceName()) && CheckMustFillUtil.checkMustFill("exigence_name", list)) {
            result.setErrMsg("紧急联系人为空");
            return result;
        }
        if (StringUtil.isBlank(entry.getExigencePhone()) && CheckMustFillUtil.checkMustFill("exigence_phone", list)) {
            result.setErrMsg("紧急联系人电话为空");
            return result;
        }
        if ("1".equals(entry.getTenantType())) {
            if (Objects.equals("1", partner.getOverageFlag()) && entry.getAge() >= partner.getNeedSignerAge()) {
                if (StringUtil.isBlank(entry.getBpName()) && CheckMustFillUtil.checkMustFill("bp_name", list)) {
                    result.setErrMsg("共签人名称为空");
                    return result;
                }
                if (StringUtil.isBlank(entry.getBpRelation()) && CheckMustFillUtil.checkMustFill("bp_relation", list)) {
                    result.setErrMsg("共签人与业主关系为空");
                    return result;
                }
                if (StringUtil.isBlank(entry.getBpIdCard()) && CheckMustFillUtil.checkMustFill("bp_id_card", list)) {
                    result.setErrMsg("共签人证件号码为空");
                    return result;
                }
                if (StringUtil.isBlank(entry.getBpMobile()) && CheckMustFillUtil.checkMustFill("bp_mobile", list)) {
                    result.setErrMsg("共签人手机号为空");
                    return result;
                }
                if (StringUtil.isBlank(entry.getBpCardFront()) && CheckMustFillUtil.checkMustFill("bp_card_front", list)) {
                    result.setErrMsg("共签人身份证正面为空");
                    return result;
                }
                if (StringUtil.isBlank(entry.getBpCardBack()) && CheckMustFillUtil.checkMustFill("bp_card_back", list)) {
                    result.setErrMsg("共签人身份证反面为空");
                    return result;
                }
                if (StringUtil.isBlank(entry.getBpFile()) && CheckMustFillUtil.checkMustFill("bp_file", list)) {
                    result.setErrMsg("共签人子女证明材料为空");
                    return result;
                }
            }
        }


        return Result.ok();
    }

    //必填校验
//    public Result requiredCheck(CustomerEntry entry, CustomerEntrySurveyRecord surveyRecord) {
//        Result result = new Result();
//        result.setCode("205");
//       /* if (StringUtil.isBlank(entry.getResidenceBooklet())) {
//            result.setErrMsg("户口本复印件为空");
//            return result;
//        }*/
//        if (StringUtil.isBlank(entry.getFilingType())) {
//            result.setErrMsg("备案类型为空");
//            return result;
//        }
//        if (StringUtil.isBlank(entry.getInsuranceFlag())) {
//            result.setErrMsg("保险购买情况为空");
//            return result;
//        }
//        if (entry.getLeaseDate() == null) {
//            result.setErrMsg("预计投放日为空");
//            return result;
//        }
//        if (StringUtil.isBlank(entry.getBankName())) {
//            result.setErrMsg("银行账户名称为空");
//            return result;
//        }
//
//        if (StringUtil.isBlank(entry.getBankCode())) {
//            result.setErrMsg("银行账号为空");
//            return result;
//        }
//        if (StringUtil.isBlank(entry.getTssBankNum())) {
//            result.setErrMsg("联行号为空");
//            return result;
//        }
//        if (StringUtil.isBlank(entry.getBankCard())) {
//            result.setErrMsg("银行卡照片为空");
//            return result;
//        }
//
//        if (entry.getAge() >= 65) {
//            if (StringUtil.isBlank(entry.getBpName())) {
//                result.setErrMsg("共签人名称为空");
//                return result;
//            }
//            if (StringUtil.isBlank(entry.getBpIdCard())) {
//                result.setErrMsg("共签人证件号码为空");
//                return result;
//            }
//            if (StringUtil.isBlank(entry.getBpMobile())) {
//                result.setErrMsg("共签人手机号为空");
//                return result;
//            }
//            if (StringUtil.isBlank(entry.getBpCardFront())) {
//                result.setErrMsg("共签人身份证正面为空");
//                return result;
//            }
//            if (StringUtil.isBlank(entry.getBpCardBack())) {
//                result.setErrMsg("共签人身份证反面为空");
//                return result;
//            }
//            if (StringUtil.isBlank(entry.getBpFile())) {
//                result.setErrMsg("共签人子女证明材料为空");
//                return result;
//            }
//        }
//
//        //屋顶类型
//        if (StringUtil.isBlank(surveyRecord.getRoofType())) {
//            result.setErrMsg("屋顶类型为空");
//            return result;
//        }
//
//        //并网距离
//        if (surveyRecord.getDistance() == null) {
//            result.setErrMsg("并网距离为空");
//            return result;
//        }
//        //方位角
//        if (StringUtil.isBlank(surveyRecord.getAzimuth())) {
//            result.setErrMsg("方位角为空");
//            return result;
//        }
//        //建筑高度
//        if (surveyRecord.getBuildingHeight() == null) {
//            result.setErrMsg("建筑高度");
//            return result;
//        }
//        //还款方式
//        if (StringUtil.isBlank(surveyRecord.getRepaymentMethod()) && "1".equals(entry.getTenantType())) {
//            result.setErrMsg("划转方式为空");
//            return result;
//        }
//        if (StringUtil.isBlank(surveyRecord.getRoofPhotoOne())) {
//            result.setErrMsg("房屋正面照片为空");
//            return result;
//        }
//        if (StringUtil.isBlank(surveyRecord.getRoofPhotoTwo())) {
//            result.setErrMsg("东南角照片为空");
//            return result;
//        }
//        if (StringUtil.isBlank(surveyRecord.getRoofPhotoThree())) {
//            result.setErrMsg("西南角照片为空");
//            return result;
//        }
//        if (StringUtil.isBlank(surveyRecord.getRoofPhotoFour())) {
//            result.setErrMsg("正南侧照片为空");
//            return result;
//        }
//        if (StringUtil.isBlank(surveyRecord.getRoofPhotoFacade())) {
//            result.setErrMsg("生活气息照1照片为空");
//            return result;
//        }
//        if (StringUtil.isBlank(surveyRecord.getRoofPhotoInterior())) {
//            result.setErrMsg("生活气息照2照片为空");
//            return result;
//        }
//        if (StringUtil.isBlank(surveyRecord.getRoofPhotoFive())) {
//            result.setErrMsg("必填补充1照片为空");
//            return result;
//        }
//        //房产证
//        if (StringUtil.isBlank(surveyRecord.getHouseOwnership())) {
//            result.setErrMsg("房产证为空");
//            return result;
//        }
//
//        if ("1".equals(entry.getSchemeType())) {
//            //方案类型
//            if (StringUtil.isBlank(entry.getSchemeTypeId())) {
//                result.setErrMsg("方案类型为空");
//                return result;
//            }
//        } else {
//            List<ComposePlan> composePlanList = findByEntryId(entry.getId());
//            if (CollectionUtils.isEmpty(composePlanList)) {
//                result.setErrMsg("方案类型为空");
//                return result;
//            }
//            boolean detailFlag = false;
//            for (ComposePlan plan : composePlanList) {
//                if (!StrKit.notNull(plan.getPlanId())) {
//                    detailFlag = true;
//                    break;
//                }
//            }
//            if (detailFlag) {
//                result.setErrMsg("方案为空");
//                return result;
//            }
//        }
//
//        //设计图纸
//        if (StringUtil.isBlank(entry.getDesignDrawings())) {
//            result.setErrMsg("设计图纸为空");
//            return result;
//        }
////        if (StringUtil.isBlank(entry.getZjpbImg())) {
////            result.setErrMsg("组件排布图为空");
////            return result;
////        }
////        if (StringUtil.isBlank(entry.getZjzxImg())) {
////            result.setErrMsg("组件走线图为空");
////            return result;
////        }
////        if (StringUtil.isBlank(entry.getZjcsImg())) {
////            result.setErrMsg("支架侧视图为空");
////            return result;
////        }
////        if (StringUtil.isBlank(entry.getZjhsImg())) {
////            result.setErrMsg("支架后视图为空");
////            return result;
////        }
////        if (StringUtil.isBlank(entry.getNbqwzImg())) {
////            result.setErrMsg("逆变器位置为空");
////            return result;
////        }
////        if (StringUtil.isBlank(entry.getPdxwzImg())) {
////            result.setErrMsg("配电箱位置为空");
////            return result;
////        }
//        //组件
//        if (StringUtil.isBlank(entry.getComponentSpec())) {
//            result.setErrMsg("组件为空");
//            return result;
//        }
//        return Result.ok();
//    }

    // 勘测必填校验
    public Result requiredCheckForSurvey(CustomerEntry entry, CustomerEntrySurveyRecord surveyRecord, List<Record> list) {
        Result result = new Result();
        result.setCode("205");

        if (StringUtil.isBlank(entry.getFilingType())
                && CheckMustFillUtil.checkMustFill("filing_type", list)) {
            result.setErrMsg("备案类型为空");
            return result;
        }
        if (StringUtil.isBlank(entry.getInsuranceFlag())
                && CheckMustFillUtil.checkMustFill("insurance_flag", list)) {
            result.setErrMsg("保险购买情况为空");
            return result;
        }
        if (entry.getLeaseDate() == null
                && CheckMustFillUtil.checkMustFill("lease_date", list)) {
            result.setErrMsg("预计投放日为空");
            return result;
        }

        //屋顶类型
        if (StringUtil.isBlank(surveyRecord.getRoofType())
                && CheckMustFillUtil.checkMustFill("roof_type", list)) {
            result.setErrMsg("房屋类型为空");
            return result;
        }

        //校验广发必填项
        String GfNotEmptyFormSet="";
        if(PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){
            GfNotEmptyFormSet=FormSetService.getNotEmptyForm(surveyRecord.getRoofType());
        }


        //并网距离
        if (surveyRecord.getDistance() == null
                && CheckMustFillUtil.checkMustFill("distance", list)) {
            result.setErrMsg("并网距离为空");
            return result;
        }
        //方位角
        if (StringUtil.isBlank(surveyRecord.getAzimuth())
                && CheckMustFillUtil.checkMustFill("angle_azimuth", list)) {
            result.setErrMsg("方位角为空");
            return result;
        }
        //东西长
        if (surveyRecord.getEwLength() == null
                && (CheckMustFillUtil.checkMustFill("ew_length", list) || GfNotEmptyFormSet.contains("ew_length"))) {
            result.setErrMsg("东西长为空");
            return result;
        }
        //南北宽
        if (surveyRecord.getNsWide() == null
                && (CheckMustFillUtil.checkMustFill("ns_wide", list) ||  GfNotEmptyFormSet.contains("ns_wide"))) {
            result.setErrMsg("南北宽为空");
            return result;
        }
        //屋顶面积
        if (surveyRecord.getRoofArea() == null
                && (CheckMustFillUtil.checkMustFill("roof_area", list) || GfNotEmptyFormSet.contains("roof_area"))) {
            result.setErrMsg("屋顶面积为空");
            return result;
        }
        //房产证明
        if (CheckMustFillUtil.checkMustFill("house_ownership", list)) {
            if( StringUtil.isBlank(surveyRecord.getHouseOwnership())){
                result.setErrMsg("房产证明图片为空");
                return result;
            } else if (surveyRecord.getHouseOwnership().split(",").length > 8) {
                result.setErrMsg("房产证明图片最多八张");
                return result;
            }
        }
        //经度
        if (entry.getLongitude() == null
                && CheckMustFillUtil.checkMustFill("longitude", list)) {
            result.setErrMsg("经度为空");
            return result;
        }
        //纬度
        if (entry.getLatitude() == null
                && CheckMustFillUtil.checkMustFill("latitude", list)) {
            result.setErrMsg("纬度为空");
            return result;
        }
        if ( entry.getLatitude()!=null && entry.getLatitude().compareTo(new BigDecimal(90))>0
                && CheckMustFillUtil.checkMustFill("latitude", list)){
            result.setErrMsg("纬度数据不合法:"+entry.getLatitude()+"，请检查后重新提交");
            return result;
        }
        //建筑高度
        if (surveyRecord.getBuildingHeight() == null
                && (CheckMustFillUtil.checkMustFill("building_height", list) ||  GfNotEmptyFormSet.contains("building_height"))) {
            result.setErrMsg("建筑高度为空");
            return result;
        }
        //还款方式
        if (StringUtil.isBlank(surveyRecord.getRepaymentMethod())
                && CheckMustFillUtil.checkMustFill("repayment_method", list) && "1".equals(entry.getTenantType())) {
            result.setErrMsg("划转方式为空");
            return result;
        }
        if (CheckMustFillUtil.checkMustFill("fly_imgs", list)) {
            if (StringUtil.isBlank(surveyRecord.getFlyImgs())) {
                result.setErrMsg("无人机航拍图为空");
                return result;
            } else if (surveyRecord.getFlyImgs().split(",").length < 3) {
                result.setErrMsg("无人机航拍图至少三张");
                return result;
            }
        }
        if (CheckMustFillUtil.checkMustFill("fly_imgs_04", list)) {
            if (StringUtil.isBlank(surveyRecord.getFlyImgs())) {
                result.setErrMsg("屋顶高空俯视照片为空");
                return result;
            } else if (surveyRecord.getFlyImgs().split(",").length < 3) {
                result.setErrMsg("屋顶高空俯视照片至少三张");
                return result;
            }
        }
        if (CheckMustFillUtil.checkMustFill("roof_photo_one", list)) {
            if (StringUtil.isBlank(surveyRecord.getRoofPhotoOne())) {
                result.setErrMsg("安装区域整体照片为空");
                return result;
            } else if (surveyRecord.getRoofPhotoOne().split(",").length < 2) {
                result.setErrMsg("安装区域整体照片至少两张");
                return result;
            }
        }
        if (CheckMustFillUtil.checkMustFill("roof_photo_one_03", list)) {
            if (StringUtil.isBlank(surveyRecord.getRoofPhotoOne())) {
                result.setErrMsg("房屋屋顶照片为空");
                return result;
            } else if (surveyRecord.getRoofPhotoOne().split(",").length < 2) {
                result.setErrMsg("房屋屋顶照片至少两张");
                return result;
            }
        }
        if (StringUtil.isBlank(surveyRecord.getRoofPhotoTwo())
                && CheckMustFillUtil.checkMustFill("roof_photo_two", list)) {
            result.setErrMsg("安装区域东南角照片为空");
            return result;
        }
        if (CheckMustFillUtil.checkMustFill("roof_photo_two_04", list)){
            if (StringUtil.isBlank(surveyRecord.getRoofPhotoTwo())) {
                result.setErrMsg("屋顶东南照片为空");
                return result;
            }else if (surveyRecord.getRoofPhotoTwo().split(",").length > 9){
                result.setErrMsg("屋顶东南照片最多九张");
                return result;
            }
        }
        if (CheckMustFillUtil.checkMustFill("roof_photo_two_03", list)){
            if (StringUtil.isBlank(surveyRecord.getRoofPhotoTwo())) {
                result.setErrMsg("房屋屋顶东侧图片为空");
                return result;
            }else if (surveyRecord.getRoofPhotoTwo().split(",").length > 9){
                result.setErrMsg("房屋屋顶东侧图片最多九张");
                return result;
            }
        }

        if (StringUtil.isBlank(surveyRecord.getRoofPhotoThree())
                && CheckMustFillUtil.checkMustFill("roof_photo_three", list)) {
            result.setErrMsg("安装区域西南角照片为空");
            return result;
        }
        if (StringUtil.isBlank(surveyRecord.getRoofPhotoThree())
                && CheckMustFillUtil.checkMustFill("roof_photo_three_03", list)) {
            result.setErrMsg("房屋屋顶西侧图片为空");
            return result;
        }
        if (StringUtil.isBlank(surveyRecord.getRoofPhotoThree())
                && CheckMustFillUtil.checkMustFill("roof_photo_three_04", list)) {
            result.setErrMsg("屋顶西南照片为空");
            return result;
        }
        if (StringUtil.isBlank(surveyRecord.getRoofPhotoFour())
                && CheckMustFillUtil.checkMustFill("roof_photo_four", list)) {
            result.setErrMsg("安装区域正南照片为空");
            return result;
        }
        if (StringUtil.isBlank(surveyRecord.getRoofPhotoFour())
                && CheckMustFillUtil.checkMustFill("roof_photo_four_04", list)) {
            result.setErrMsg("屋顶正南照片为空");
            return result;
        }
        if (StringUtil.isBlank(surveyRecord.getRoofPhotoFour())
                && CheckMustFillUtil.checkMustFill("roof_photo_four_03", list)) {
            result.setErrMsg("房屋屋顶南侧图片为空");
            return result;
        }
        if (CheckMustFillUtil.checkMustFill("roof_photo_facade", list)) {
            if (StringUtil.isBlank(surveyRecord.getRoofPhotoFacade())) {
                result.setErrMsg("房屋内部结构照片为空");
                return result;
            } else if (surveyRecord.getRoofPhotoFacade().split(",").length < 2) {
                result.setErrMsg("房屋内部结构照片至少两张");
                return result;
            }
        }
        if (CheckMustFillUtil.checkMustFill("roof_photo_interior", list)) {
            if (StringUtil.isBlank(surveyRecord.getRoofPhotoInterior())) {
                result.setErrMsg("房屋内部环境照片为空");
                return result;
            } else if (surveyRecord.getRoofPhotoInterior().split(",").length < 2) {
                result.setErrMsg("房屋内部环境照片至少两张");
                return result;
            }
        }
        if (StringUtil.isBlank(surveyRecord.getRoofPhotoFive())
                && CheckMustFillUtil.checkMustFill("roof_photo_five", list)) {
            result.setErrMsg("安装区域细节照片为空");
            return result;
        }
        if (StringUtil.isBlank(surveyRecord.getHouseSupplementOne())
                && CheckMustFillUtil.checkMustFill("house_supplement_one", list)) {
            result.setErrMsg("房屋其他障碍物照片为空");
            return result;
        }
        // detail_supplement_one
        if (StringUtil.isBlank(surveyRecord.getDetailSupplementOne())
                && CheckMustFillUtil.checkMustFill("detail_supplement_one", list)) {
            result.setErrMsg("逆变器、配电箱预安装位置照片为空");
            return result;
        }
        // house_outline_photo
        if (StringUtil.isBlank(surveyRecord.getHouseOutlinePhoto())
                && CheckMustFillUtil.checkMustFill("house_outline_photo", list)) {
            result.setErrMsg("房屋轮廓照片为空");
            return result;
        }
        // 并网电压等级 voltage_classes
        if (surveyRecord.getVoltageClasses() == null
                && CheckMustFillUtil.checkMustFill("voltage_classes", list)) {
            result.setErrMsg("并网电压等级为空");
            return result;
        }
        // 变压器容量 transformer_capacity
        if (surveyRecord.getTransformerCapacity() == null
                && CheckMustFillUtil.checkMustFill("transformer_capacity", list)) {
            result.setErrMsg("变压器容量为空");
            return result;
        }
        // 是否符合变压器容量限制要求 restrict_flag
        if (StringUtil.isBlank(surveyRecord.getRestrictFlag())
                && CheckMustFillUtil.checkMustFill("restrict_flag", list)) {
            result.setErrMsg("是否符合变压器容量限制要求为空");
            return result;
        }
        // 是否封屋顶 seal_roof
        if (StringUtil.isBlank(surveyRecord.getSealRoof())
                && CheckMustFillUtil.checkMustFill("seal_roof", list)) {
            result.setErrMsg("是否封屋顶为空");
            return result;
        }
        // 房屋建成年份 completion_year
        if (StringUtil.isBlank(surveyRecord.getCompletionYear())
                && CheckMustFillUtil.checkMustFill("completion_year", list)) {
            result.setErrMsg("房屋建成年份为空");
            return result;
        }
        // 组件倾角 dip_angle
        if (surveyRecord.getDipAngle() == null
                && (CheckMustFillUtil.checkMustFill("dip_angle", list) || GfNotEmptyFormSet.contains("dip_angle")) ) {
            result.setErrMsg("组件倾角为空");
            return result;
        }
        // 屋面坡度 slope_gradient
        if ("斜屋顶".equals(surveyRecord.getRoofType()) && surveyRecord.getSlopeGradient() == null
                && CheckMustFillUtil.checkMustFill("slope_gradient", list)) {
            result.setErrMsg("屋面坡度为空");
            return result;
        }
        // 檩条间距 purline_interval
        if ("斜屋顶".equals(surveyRecord.getRoofType()) && surveyRecord.getPurlineInterval() == null
                && CheckMustFillUtil.checkMustFill("purline_interval", list)) {
            result.setErrMsg("檩条间距为空");
            return result;
        }
        // 屋顶防水情况 waterproof
        if (StringUtil.isBlank(surveyRecord.getWaterproof())
                && CheckMustFillUtil.checkMustFill("waterproof", list)) {
            result.setErrMsg("屋顶防水情况为空");
            return result;
        }
        // 是否有污染源 source_pollution
        if (StringUtil.isBlank(surveyRecord.getSourcePollution())
                && CheckMustFillUtil.checkMustFill("source_pollution", list)) {
            result.setErrMsg("是否有污染源为空");
            return result;
        }
        // 是否具备运维空间 ops_condition
        if (StringUtil.isBlank(surveyRecord.getOpsCondition())
                && CheckMustFillUtil.checkMustFill("ops_condition", list)) {
            result.setErrMsg("是否具备运维空间为空");
            return result;
        }
        // 踏勘补充证明视频
        if (StringUtil.isBlank(surveyRecord.getSurveyVideo())
                && CheckMustFillUtil.checkMustFill("survey_video", list)) {
            result.setErrMsg("踏勘补充证明视频为空");
            return result;
        }
        // 踏勘记录表文件
        if (CheckMustFillUtil.checkMustFill("survey_files", list)) {
            if (StringUtil.isBlank(surveyRecord.getSurveyFiles())) {
                result.setErrMsg("踏勘记录表文件为空");
                return result;
            } else if (surveyRecord.getSurveyFiles().split(",").length < 1) {
                result.setErrMsg("踏勘记录表文件最少一张");
                return result;
            } else if (surveyRecord.getSurveyFiles().split(",").length > 4) {
                result.setErrMsg("踏勘记录表文件最多四张");
                return result;
            }
        }
        // 户用勘察记录表（1-9张）
        if (CheckMustFillUtil.checkMustFill("survey_files_03", list)) {
            if (StringUtil.isBlank(surveyRecord.getSurveyFiles())) {
                result.setErrMsg("户用勘察记录表为空");
                return result;
            } else if (surveyRecord.getSurveyFiles().split(",").length < 1) {
                result.setErrMsg("户用勘察记录表最少一张");
                return result;
            } else if (surveyRecord.getSurveyFiles().split(",").length > 9) {
                result.setErrMsg("户用勘察记录表最多九张");
                return result;
            }
        }
        // 现场踏勘表
        if (CheckMustFillUtil.checkMustFill("survey_files_04", list)) {
            if (StringUtil.isBlank(surveyRecord.getSurveyFiles())) {
                result.setErrMsg("现场踏勘表为空");
                return result;
            } else if (surveyRecord.getSurveyFiles().split(",").length < 1) {
                result.setErrMsg("现场踏勘表最少一张");
                return result;
            } else if (surveyRecord.getSurveyFiles().split(",").length > 4) {
                result.setErrMsg("现场踏勘表最多四张");
                return result;
            }
        }
        // 房屋整体图（VR全景）
        if (CheckMustFillUtil.checkMustFill("vr_roof_one", list)) {
            if (StringUtil.isBlank(surveyRecord.getVrRoofOne())) {
                result.setErrMsg("房屋整体图（VR全景）为空");
                return result;
            } else if (surveyRecord.getVrRoofOne().split(",").length < 1) {
                result.setErrMsg("房屋整体图（VR全景）最少一张");
                return result;
            } else if (surveyRecord.getVrRoofOne().split(",").length > 9) {
                result.setErrMsg("房屋整体图（VR全景）最多九张");
                return result;
            }
        }
        // 房屋整体俯视图（无人机）
        if (CheckMustFillUtil.checkMustFill("vr_roof_two", list)) {
            if (StringUtil.isBlank(surveyRecord.getVrRoofTwo())) {
                result.setErrMsg("房屋整体俯视图（无人机）为空");
                return result;
            } else if (surveyRecord.getVrRoofTwo().split(",").length < 1) {
                result.setErrMsg("房屋整体俯视图（无人机）最少一张");
                return result;
            } else if (surveyRecord.getVrRoofTwo().split(",").length > 9) {
                result.setErrMsg("房屋整体俯视图（无人机）最多九张");
                return result;
            }
        }
        // 房屋内部结构图（VR）
        if (CheckMustFillUtil.checkMustFill("vr_roof_three", list)) {
            if (StringUtil.isBlank(surveyRecord.getVrRoofThree())) {
                result.setErrMsg("房屋内部结构图（VR）为空");
                return result;
            } else if (surveyRecord.getVrRoofThree().split(",").length < 1) {
                result.setErrMsg("房屋内部结构图（VR）最少一张");
                return result;
            } else if (surveyRecord.getVrRoofThree().split(",").length > 9) {
                result.setErrMsg("房屋内部结构图（VR）最多九张");
                return result;
            }
        }
        // 入户全景照片(VR)
        if (CheckMustFillUtil.checkMustFill("vr_roof_four", list)) {
            if (StringUtil.isBlank(surveyRecord.getVrRoofFour())) {
                result.setErrMsg("入户全景照片(VR)为空");
                return result;
            } else if (surveyRecord.getVrRoofFour().split(",").length < 1) {
                result.setErrMsg("入户全景照片(VR)最少一张");
                return result;
            } else if (surveyRecord.getVrRoofFour().split(",").length > 9) {
                result.setErrMsg("入户全景照片(VR)最多九张");
                return result;
            }
        }
        // 入户全景照片
        if (CheckMustFillUtil.checkMustFill("vr_roof_four_04", list)) {
            if (StringUtil.isBlank(surveyRecord.getVrRoofFour())) {
                result.setErrMsg("入户全景照片为空");
                return result;
            } else if (surveyRecord.getVrRoofFour().split(",").length < 1) {
                result.setErrMsg("入户全景照片最少一张");
                return result;
            } else if (surveyRecord.getVrRoofFour().split(",").length > 9) {
                result.setErrMsg("入户全景照片最多九张");
                return result;
            }
        }
        // 屋顶正南照片
        if (CheckMustFillUtil.checkMustFill("roof_photo_four_04", list)) {
            if (StringUtil.isBlank(surveyRecord.getRoofPhotoFour())) {
                result.setErrMsg("屋顶正南照片为空");
                return result;
            } else if (surveyRecord.getRoofPhotoFour().split(",").length < 1) {
                result.setErrMsg("屋顶正南照片最少一张");
                return result;
            } else if (surveyRecord.getRoofPhotoFour().split(",").length > 9) {
                result.setErrMsg("屋顶正南照片最多九张");
                return result;
            }
        }
        // 屋顶西南照片
        if (CheckMustFillUtil.checkMustFill("roof_photo_three_04", list)) {
            if (StringUtil.isBlank(surveyRecord.getRoofPhotoThree())) {
                result.setErrMsg("屋顶西南照片为空");
                return result;
            } else if (surveyRecord.getRoofPhotoThree().split(",").length < 1) {
                result.setErrMsg("屋顶西南照片最少一张");
                return result;
            } else if (surveyRecord.getRoofPhotoThree().split(",").length > 9) {
                result.setErrMsg("屋顶西南照片最多九张");
                return result;
            }
        }
        //房屋整体图
        if (CheckMustFillUtil.checkMustFill("fw_img1", list)) {
            if (StringUtil.isBlank(surveyRecord.getFwImg1())) {
                result.setErrMsg("房屋整体图为空");
                return result;
            } else if (surveyRecord.getFwImg1().split(",").length < 1) {
                result.setErrMsg("房屋整体图最少一张");
                return result;
            } else if (surveyRecord.getFwImg1().split(",").length > 9) {
                result.setErrMsg("房屋整体图最多九张");
                return result;
            }
        }
        //房屋内部结构图
        if (CheckMustFillUtil.checkMustFill("fw_img2", list)) {
            if (StringUtil.isBlank(surveyRecord.getFwImg2())) {
                result.setErrMsg("房屋内部结构图为空");
                return result;
            } else if (surveyRecord.getFwImg2().split(",").length < 1) {
                result.setErrMsg("房屋内部结构图最少一张");
                return result;
            } else if (surveyRecord.getFwImg2().split(",").length > 9) {
                result.setErrMsg("房屋内部结构图最多九张");
                return result;
            }
        }
        //房屋屋顶东南侧图片
        if (CheckMustFillUtil.checkMustFill("fw_img3", list)) {
            if (StringUtil.isBlank(surveyRecord.getFwImg3())) {
                result.setErrMsg("房屋屋顶东南侧图片为空");
                return result;
            } else if (surveyRecord.getFwImg3().split(",").length < 1) {
                result.setErrMsg("房屋屋顶东南侧图片最少一张");
                return result;
            } else if (surveyRecord.getFwImg3().split(",").length > 9) {
                result.setErrMsg("房屋屋顶东南侧图片最多九张");
                return result;
            }
        }
        //房屋屋顶西南侧图片
        if (CheckMustFillUtil.checkMustFill("fw_img4", list)) {
            if (StringUtil.isBlank(surveyRecord.getFwImg4())) {
                result.setErrMsg("房屋屋顶西南侧图片为空");
                return result;
            } else if (surveyRecord.getFwImg4().split(",").length < 1) {
                result.setErrMsg("房屋屋顶西南侧图片最少一张");
                return result;
            } else if (surveyRecord.getFwImg4().split(",").length > 9) {
                result.setErrMsg("房屋屋顶西南侧图片最多九张");
                return result;
            }
        }
        //遮阴物与房屋距离、高度
        if (CheckMustFillUtil.checkMustFill("fw_img5", list)) {
            if (StringUtil.isBlank(surveyRecord.getFwImg5())) {
                result.setErrMsg("遮阴物与房屋距离、高度为空");
                return result;
            } else if (surveyRecord.getFwImg5().split(",").length < 1) {
                result.setErrMsg("遮阴物与房屋距离、高度最少一张");
                return result;
            } else if (surveyRecord.getFwImg5().split(",").length > 9) {
                result.setErrMsg("遮阴物与房屋距离、高度最多九张");
                return result;
            }
        }

        if (StringUtil.isBlank(surveyRecord.getRoofFaceThickness())
                && (CheckMustFillUtil.checkMustFill("roof_face_thickness", list) || GfNotEmptyFormSet.contains("roof_face_thickness")) ) {
            result.setErrMsg("屋面板厚度为空");
            return result;
        }
        if (StringUtil.isBlank(surveyRecord.getStructureType())
                && (CheckMustFillUtil.checkMustFill("structure_type", list) || GfNotEmptyFormSet.contains("structure_type")) ) {
            result.setErrMsg("结构类型不能为空");
            return result;
        }

        if (StringUtil.isBlank(surveyRecord.getSiteSlope())
                && (CheckMustFillUtil.checkMustFill("site_slope", list) || GfNotEmptyFormSet.contains("site_slope")) ) {
            result.setErrMsg("场地坡度不能为空");
            return result;
        }
        if (StringUtil.isBlank(surveyRecord.getGroundType())
                && (CheckMustFillUtil.checkMustFill("ground_type", list) || GfNotEmptyFormSet.contains("ground_type")) ) {
            result.setErrMsg("地面类型不能为空");
            return result;
        }
        if (StringUtil.isBlank(surveyRecord.getGeologicalCondition())
                && (CheckMustFillUtil.checkMustFill("geological_condition", list) || GfNotEmptyFormSet.contains("geological_condition")) ) {
            result.setErrMsg("地质情况不能为空");
            return result;
        }
        if (StringUtil.isBlank(surveyRecord.getFenceHeight())
                && (CheckMustFillUtil.checkMustFill("fence_height", list) || GfNotEmptyFormSet.contains("fence_height")) ) {
            result.setErrMsg("围墙高度不能为空");
            return result;
        }

        return Result.ok();
    }

    // 设计必填校验
    public Result requiredCheckForDesign(CustomerEntry entry, List<CustomerEntryComponentVo> itemList, List<Record> list) {
        Result result = new Result();
        result.setCode("205");
        if ("1".equals(entry.getSchemeType())) {
            //方案类型
            if (StringUtil.isBlank(entry.getSchemeTypeId())) {
                result.setErrMsg("方案类型为空");
                return result;
            }
            if (StringUtil.isBlank(entry.getSchemeId())) {
                result.setErrMsg("方案名称为空");
                return result;
            }
        } else {
            List<ComposePlan> composePlanList = findByEntryId(entry.getId());
            if (CollectionUtils.isEmpty(composePlanList)) {
                result.setErrMsg("方案类型为空");
                return result;
            }
            boolean detailFlag = false;
            for (ComposePlan plan : composePlanList) {
                if (!StrKit.notNull(plan.getPlanId())) {
                    detailFlag = true;
                    break;
                }
            }
            if (detailFlag) {
                result.setErrMsg("方案为空");
                return result;
            }
        }
        //设计图纸
        if (StringUtil.isBlank(entry.getDesignDrawings())
                && CheckMustFillUtil.checkMustFill("design_drawings", list)) {
            result.setErrMsg("设计图纸为空");
            return result;
        } else if (entry.getDesignDrawings().split(",").length > 4
                && CheckMustFillUtil.checkMustFill("design_drawings", list)) {
            result.setErrMsg("设计图纸最多四张");
            return result;
        }
        // 组件排布图
        if (CheckMustFillUtil.checkMustFill("zjpb_img_03", list)) {
            if (StringUtil.isBlank(entry.getZjpbImg())) {
                result.setErrMsg("组件排布图为空");
                return result;
            } else if (entry.getZjpbImg().split(",").length < 1) {
                result.setErrMsg("组件排布图最少一张");
                return result;
            } else if (entry.getZjpbImg().split(",").length > 6) {
                result.setErrMsg("组件排布图最多六张");
                return result;
            }
        }
        // 组件接线图
        if (CheckMustFillUtil.checkMustFill("zjzx_img_03", list)) {
            if (StringUtil.isBlank(entry.getZjzxImg())) {
                result.setErrMsg("组件接线图为空");
                return result;
            } else if (entry.getZjzxImg().split(",").length < 1) {
                result.setErrMsg("组件接线图最少一张");
                return result;
            } else if (entry.getZjzxImg().split(",").length > 6) {
                result.setErrMsg("组件接线图最多六张");
                return result;
            }
        }
        // 组件支架图
        if (CheckMustFillUtil.checkMustFill("zjcs_img_03", list)) {
            if (StringUtil.isBlank(entry.getZjcsImg())) {
                result.setErrMsg("组件支架图为空");
                return result;
            } else if (entry.getZjcsImg().split(",").length < 1) {
                result.setErrMsg("组件支架图最少一张");
                return result;
            } else if (entry.getZjcsImg().split(",").length > 6) {
                result.setErrMsg("组件支架图最多六张");
                return result;
            }
        }
        // 一次接线图/电气图
        if (CheckMustFillUtil.checkMustFill("zjhs_img_03", list)) {
            if (StringUtil.isBlank(entry.getZjhsImg())) {
                result.setErrMsg("一次接线图/电气图为空");
                return result;
            } else if (entry.getZjhsImg().split(",").length < 1) {
                result.setErrMsg("一次接线图/电气图最少一张");
                return result;
            } else if (entry.getZjhsImg().split(",").length > 6) {
                result.setErrMsg("一次接线图/电气图最多六张");
                return result;
            }
        }
//        if (StringUtil.isBlank(entry.getZjpbImg())
//                && CheckMustFillUtil.checkMustFill("zjpb_img", list)) {
//            result.setErrMsg("组件排布图为空");
//            return result;
//        }
//        if (StringUtil.isBlank(entry.getZjzxImg())
//                && CheckMustFillUtil.checkMustFill("zjzx_img", list)) {
//            result.setErrMsg("组件走线图为空");
//            return result;
//        }
//        if (StringUtil.isBlank(entry.getZjcsImg())
//                && CheckMustFillUtil.checkMustFill("zjcs_img", list)) {
//            result.setErrMsg("支架侧视图为空");
//            return result;
//        }
//        if (StringUtil.isBlank(entry.getZjhsImg())
//                && CheckMustFillUtil.checkMustFill("zjhs_img", list)) {
//            result.setErrMsg("支架后视图为空");
//            return result;
//        }
//        if (StringUtil.isBlank(entry.getNbqwzImg())
//                && CheckMustFillUtil.checkMustFill("nbqwz_img", list)) {
//            result.setErrMsg("逆变器位置为空");
//            return result;
//        }
//        if (StringUtil.isBlank(entry.getPdxwzImg())
//                && CheckMustFillUtil.checkMustFill("pdxwz_img", list)) {
//            result.setErrMsg("配电箱位置为空");
//            return result;
//        }
        // 组件校验
        if (StringUtil.isBlank(entry.getComponentSpec())
                && CheckMustFillUtil.checkMustFill("component3", list)) {
            result.setErrMsg("组件为空");
            return result;
        }
        //其他物料校验
        String checkResult = checkSchMaterial(itemList, list);
        if (StringUtil.isNotBlank(checkResult)) {
            result.setErrMsg(checkResult);
            return result;
        }
        return Result.ok();
    }

    // 安装必填校验
    public Result requiredCheckForInstall(AddReportReq req, List<Record> list) {
        Result result = new Result();
        result.setCode("205");
        if (StringUtil.isBlank(req.getDzjc1())
                && CheckMustFillUtil.checkMustFill("dzjc1", list)) {
            result.setErrMsg("电站基础-主屋照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getDzjc2())
                && CheckMustFillUtil.checkMustFill("dzjc2", list)) {
            result.setErrMsg("电站基础-副屋照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjImg1())
                && CheckMustFillUtil.checkMustFill("zj_img1", list)) {
            result.setErrMsg("支架正面照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjImg2())
                && CheckMustFillUtil.checkMustFill("zj_img2", list)) {
            result.setErrMsg("支架侧视图照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjImg3())
                && CheckMustFillUtil.checkMustFill("zj_img3", list)) {
            result.setErrMsg("支架北侧图照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjImg4())
                && CheckMustFillUtil.checkMustFill("zj_img4", list)) {
            result.setErrMsg("基座安装固定为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjImg3())
                && CheckMustFillUtil.checkMustFill("zj_img3", list)) {
            result.setErrMsg("底座防水为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjImg4())
                && CheckMustFillUtil.checkMustFill("zj_img4", list)) {
            result.setErrMsg("支架型号照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjImg5())
                && CheckMustFillUtil.checkMustFill("zj_img5", list)) {
            result.setErrMsg("航拍图照片不能为空");
            return result;
        }
        if (StringUtil.isBlank(req.getComponentImg1())
                && CheckMustFillUtil.checkMustFill("component_img1", list)) {
            result.setErrMsg("组件倾角照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getComponentImg2())
                && CheckMustFillUtil.checkMustFill("component_img2", list)) {
            result.setErrMsg("组件方位角照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getSizeMeasureImgs())
                && CheckMustFillUtil.checkMustFill("size_measure_imgs", list)) {
            result.setErrMsg("屋顶线缆安装照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getFixOtherImg())
                && CheckMustFillUtil.checkMustFill("fix_other_img", list)) {
            result.setErrMsg("线缆下墙照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getTotalImgs())
                && CheckMustFillUtil.checkMustFill("total_imgs", list)) {
            result.setErrMsg("逆变器组串接入照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getBwInnerImg())
                && CheckMustFillUtil.checkMustFill("bw_inner_img", list)) {
            result.setErrMsg("并网箱内部照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getDcImgs())
                && CheckMustFillUtil.checkMustFill("dc_imgs", list)) {
            result.setErrMsg("逆变器安装照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getNbqZbImg())
                && CheckMustFillUtil.checkMustFill("nbq_zb_img", list)) {
            result.setErrMsg("并网箱逆变器整体照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getDqsbAnImgOne())
                && CheckMustFillUtil.checkMustFill("dqsb_an_img_one", list)) {
            result.setErrMsg("逆变器注册截图照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getNbqPlateImg())
                && CheckMustFillUtil.checkMustFill("nbq_plate_img", list)) {
            result.setErrMsg("逆变器铭牌照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjPlateImg())
                && CheckMustFillUtil.checkMustFill("zj_plate_img", list)) {
            result.setErrMsg("组件铭牌照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getOpenWayVoltageImgs())
                && CheckMustFillUtil.checkMustFill("open_way_voltage_imgs", list)) {
            result.setErrMsg("开路电压图为空");
            return result;
        }
        if (StringUtil.isBlank(req.getJdImg1())
                && CheckMustFillUtil.checkMustFill("jd_img1", list)) {
            result.setErrMsg("组件与组件之间接地照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getJdImg2())
                && CheckMustFillUtil.checkMustFill("jd_img2", list)) {
            result.setErrMsg("组件与支架接地照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getJdImg3())
                && CheckMustFillUtil.checkMustFill("jd_img3", list)) {
            result.setErrMsg("支架与接地扁铁连接照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getJdImg4())
                && CheckMustFillUtil.checkMustFill("jd_img4", list)) {
            result.setErrMsg("接地扁铁下墙照片空");
            return result;
        }
        if (StringUtil.isBlank(req.getJdImg5())
                && CheckMustFillUtil.checkMustFill("jd_img5", list)) {
            result.setErrMsg("支架接地电阻照片为空");
            return result;
        }
        // 东向西航拍 direction_air_img1
        if (StringUtil.isBlank(req.getJdImg6())
                && CheckMustFillUtil.checkMustFill("jd_img6", list)) {
            result.setErrMsg("电气接地电阻照片为空");
            return result;
        }
        // 西向东航拍 direction_air_img2
        if (StringUtil.isBlank(req.getZjReport())
                && CheckMustFillUtil.checkMustFill("zj_report", list)) {
            result.setErrMsg("自检记录报告为空");
            return result;
        }
        if (StringUtil.isBlank(req.getOtherFiles())
                && CheckMustFillUtil.checkMustFill("other_files", list)) {
            result.setErrMsg("其他资料为空");
            return result;
        }

        //广发新增字段校验
        if (StringUtil.isBlank(req.getZjImg5())
                && CheckMustFillUtil.checkMustFill("zj_img5_03", list)) {
            result.setErrMsg("支架安装图-支架安装完成VR图为空");
            return result;
        }
        if (StringUtil.isBlank(req.getSafetyWarningImg2())
                && CheckMustFillUtil.checkMustFill("safety_warning_img2_03", list)) {
            result.setErrMsg("施工安全图-三级安全教育为空");
            return result;
        }
        if (StringUtil.isBlank(req.getSafetyWarningImg2())
                && CheckMustFillUtil.checkMustFill("safety_warning_img2", list)) {
            result.setErrMsg("三级安全教育卡为空");
            return result;
        }
        if (StringUtil.isBlank(req.getSafetyWarningImg3())
                && CheckMustFillUtil.checkMustFill("safety_warning_img3", list)) {
            result.setErrMsg("施工安全图-开工前站班会（施工安全用品：安全帽、安全绳、反光衣、工作鞋）为空");
            return result;
        }
        if (StringUtil.isBlank(req.getSafetyWarningImg())
                && CheckMustFillUtil.checkMustFill("safety_warning_img", list)) {
            result.setErrMsg("施工安全图-安全警示牌为空");
            return result;
        }
        if (StringUtil.isBlank(req.getSafetyDiscloseDocImg())
                && CheckMustFillUtil.checkMustFill("safety_disclose_doc_img", list)) {
            result.setErrMsg("施工安全图-安全技术交底书为空");
            return result;
        }
        if (StringUtil.isBlank(req.getComponentImg3())
                && CheckMustFillUtil.checkMustFill("component_img3", list)) {
            result.setErrMsg("组件航拍俯视照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getDcImgs())
                && CheckMustFillUtil.checkMustFill("dc_imgs_03", list)) {
            result.setErrMsg("逆变器安装图-整体外观及走线及采集器（离地高度）为空");
            return result;
        }
        if (StringUtil.isBlank(req.getNbqPlateImg())
                && CheckMustFillUtil.checkMustFill("nbq_plate_img_03", list)) {
            result.setErrMsg("逆变器安装图-铭牌为空");
            return result;
        }
        if (StringUtil.isBlank(req.getTotalImgs())
                && CheckMustFillUtil.checkMustFill("total_imgs_03", list)) {
            result.setErrMsg("逆变器安装图-接地情况为空");
            return result;
        }
        if (StringUtil.isBlank(req.getNbqZlcImg())
                && CheckMustFillUtil.checkMustFill("nbq_zlc_img", list)) {
            result.setErrMsg("逆变器安装图-逆变器交流侧为空");
            return result;
        }
        if (StringUtil.isBlank(req.getOpenWayVoltageImgs())
                && CheckMustFillUtil.checkMustFill("open_way_voltage_imgs_03", list)) {
            result.setErrMsg("逆变器安装图-组串开路电压照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getNbqZbImg())
                && CheckMustFillUtil.checkMustFill("nbq_zb_img_03", list)) {
            result.setErrMsg("并网箱安装图-外观及走线（离地高度）为空");
            return result;
        }
        if (StringUtil.isBlank(req.getBwInnerImg())
                && CheckMustFillUtil.checkMustFill("bw_inner_img_03", list)) {
            result.setErrMsg("并网箱安装图-并网箱内部全景为空");
            return result;
        }
        if (StringUtil.isBlank(req.getBwJdImg())
                && CheckMustFillUtil.checkMustFill("bw_jd_img", list)) {
            result.setErrMsg("并网箱安装图-接地情况为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjImg8())
                && CheckMustFillUtil.checkMustFill("zj_img8", list)) {
            result.setErrMsg("支架安装图-支架方阵（东向西完工照）为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjImg9())
                && CheckMustFillUtil.checkMustFill("zj_img9", list)) {
            result.setErrMsg("支架安装图-支架方阵（北向南完工照）为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjImg4())
                && CheckMustFillUtil.checkMustFill("zj_img4_03", list)) {
            result.setErrMsg("支架安装图-立柱东西间距、南北间距（带尺寸）为空");
            return result;
        }
        if (CheckMustFillUtil.checkMustFill("zj_img10", list)){
            if (StringUtil.isBlank(req.getZjImg10())){
                result.setErrMsg("基础安装-螺栓孔洞防水图(不少于3张)为空");
                return result;
            }
            if (req.getZjImg10().split(",").length < 3){
                result.setErrMsg("基础安装-螺栓孔洞防水图(不少于3张)至少三张");
                return result;
            }
        }
        if (StringUtil.isBlank(req.getZjImg11())
                && CheckMustFillUtil.checkMustFill("zj_img11", list)) {
            result.setErrMsg("基础安装-柱脚防水完工图为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjImg12())
                && CheckMustFillUtil.checkMustFill("zj_img12", list)) {
            result.setErrMsg("支架安装图-斜梁悬挑（南）为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjImg13())
                && CheckMustFillUtil.checkMustFill("zj_img13", list)) {
            result.setErrMsg("支架安装图-斜梁悬挑（北）为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjImg14())
                && CheckMustFillUtil.checkMustFill("zj_img14", list)) {
            result.setErrMsg("支架安装图-檀条悬挑（东）为空");
            return result;
        }
        if (StringUtil.isBlank(req.getZjImg15())
                && CheckMustFillUtil.checkMustFill("zj_img15", list)) {
            result.setErrMsg("支架安装图-檀条悬挑（西）为空");
            return result;
        }
        if (StringUtil.isBlank(req.getJdImg4())
                && CheckMustFillUtil.checkMustFill("jd_img4_03", list)) {
            result.setErrMsg("支架接地图-支架接地为空");
            return result;
        }
        if (StringUtil.isBlank(req.getBkImg1())
                && CheckMustFillUtil.checkMustFill("bk_img1", list)) {
            result.setErrMsg("边框接地图-边框与边框接地为空");
            return result;
        }
        if (StringUtil.isBlank(req.getComponentImg1())
                && CheckMustFillUtil.checkMustFill("component_img1_03", list)) {
            result.setErrMsg("边框接地图-组件安装倾角为空");
            return result;
        }
        if (StringUtil.isBlank(req.getBkImg2())
                && CheckMustFillUtil.checkMustFill("bk_img2", list)) {
            result.setErrMsg("边框接地图-边框与支架接地为空");
            return result;
        }
        if (StringUtil.isBlank(req.getBkImg3())
                && CheckMustFillUtil.checkMustFill("bk_img3", list)) {
            result.setErrMsg("边框接地图-其他图片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getYkImg1())
                && CheckMustFillUtil.checkMustFill("yk_img1", list)) {
            result.setErrMsg("压块或背压板照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getFixOtherImg())
                && CheckMustFillUtil.checkMustFill("fix_other_img_03", list)) {
            result.setErrMsg("线缆走向（屋顶、下墙）、线缆保护管（或桥架）敷设及固定照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getSizeMeasureImgs())
                && CheckMustFillUtil.checkMustFill("size_measure_imgs_03", list)) {
            result.setErrMsg("电缆桥架内部电缆照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getJdImg8())
                && CheckMustFillUtil.checkMustFill("jd_img8", list)) {
            result.setErrMsg("接地极图-并网箱、逆变器安装接地极为空");
            return result;
        }
        if (StringUtil.isBlank(req.getJdImg5())
                && CheckMustFillUtil.checkMustFill("jd_img5_03", list)) {
            result.setErrMsg("接地极图-支架接地电阻阻值（近景）为空");
            return result;
        }
        if (StringUtil.isBlank(req.getJdImg9())
                && CheckMustFillUtil.checkMustFill("jd_img9", list)) {
            result.setErrMsg("接地极图-并网箱、逆变器安装接地电阻阻值（近景）为空");
            return result;
        }
        if (StringUtil.isBlank(req.getJdImg10())
                && CheckMustFillUtil.checkMustFill("jd_img10", list)) {
            result.setErrMsg("接地极图-接地引下线警示做法为空");
            return result;
        }
        if (StringUtil.isBlank(req.getJdImg11())
                && CheckMustFillUtil.checkMustFill("jd_img11", list)) {
            result.setErrMsg("接地极图-支架接地电阻测量照片（远景）为空");
            return result;
        }
        if (StringUtil.isBlank(req.getJdImg12())
                && CheckMustFillUtil.checkMustFill("jd_img12", list)) {
            result.setErrMsg("接地极图-并网箱、逆变器安装接地电阻测量照片（远景）为空");
            return result;
        }
        if (StringUtil.isBlank(req.getFsImg1())
                && CheckMustFillUtil.checkMustFill("fs_img1", list)) {
            result.setErrMsg("防水措施图-横竖向水槽为空");
            return result;
        }
        if (StringUtil.isBlank(req.getFsImg2())
                && CheckMustFillUtil.checkMustFill("fs_img2", list)) {
            result.setErrMsg("防水措施图-落水管走向及其固定为空");
            return result;
        }
        if (StringUtil.isBlank(req.getFsImg3())
                && CheckMustFillUtil.checkMustFill("fs_img3", list)) {
            result.setErrMsg("防水措施图-其他图片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getComponentImg4())
                && CheckMustFillUtil.checkMustFill("component_img4", list)) {
            result.setErrMsg("组件安装完成VR视图为空");
            return result;
        }
        if (StringUtil.isBlank(req.getOtherImgs5())
                && CheckMustFillUtil.checkMustFill("other_imgs5", list)) {
            result.setErrMsg("水槽细节照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getOtherImgs6())
                && CheckMustFillUtil.checkMustFill("other_imgs6", list)) {
            result.setErrMsg("落水管照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getOtherImgs7())
                && CheckMustFillUtil.checkMustFill("other_imgs7", list)) {
            result.setErrMsg("假梁-斜梁方向为空");
            return result;
        }
        if (StringUtil.isBlank(req.getOtherImgs8())
                && CheckMustFillUtil.checkMustFill("other_imgs8", list)) {
            result.setErrMsg("并网箱逆变器防雨罩照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getKgConditionFiles())
                && CheckMustFillUtil.checkMustFill("kg_condition_files", list)) {
            result.setErrMsg("安全防护措施合照照片为空");
            return result;
        }
        if (StringUtil.isBlank(req.getSupplementVideoUrl())
                && CheckMustFillUtil.checkMustFill("supplement_video_url", list)) {
            result.setErrMsg("补充视频为空");
            return result;
        }
        if (StringUtil.isBlank(req.getCompleteRemark())
                && CheckMustFillUtil.checkMustFill("complete_remark", list)) {
            result.setErrMsg("完工备注为空");
            return result;
        }
        if (StringUtil.isBlank(req.getWaterMudClampImgs())
                && CheckMustFillUtil.checkMustFill("water_mud_clamp_imgs", list)) {
            result.setErrMsg("导水排泥夹照片为空");
            return result;
        }
        return Result.ok();
    }

    public Result requiredCheckForInstallHr(AddReportReq req, List<Record> list) {
        Result result = new Result();
        result.setCode("205");
        if(req.getCompleteList().size() > 0){
            for(CrmAcceptingReportDetail reportDetail :  req.getCompleteList()){
                if (StringUtil.isBlank(reportDetail.getDzjc1())
                        && CheckMustFillUtil.checkMustFill("dzjc1", list)) {
                    result.setErrMsg("电站基础-主屋照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getDzjc2())
                        && CheckMustFillUtil.checkMustFill("dzjc2", list)) {
                    result.setErrMsg("电站基础-副屋照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjImg1())
                        && CheckMustFillUtil.checkMustFill("zj_img1", list)) {
                    result.setErrMsg("支架正面照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjImg2())
                        && CheckMustFillUtil.checkMustFill("zj_img2", list)) {
                    result.setErrMsg("支架侧视图照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjImg3())
                        && CheckMustFillUtil.checkMustFill("zj_img3", list)) {
                    result.setErrMsg("支架北侧图照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjImg4())
                        && CheckMustFillUtil.checkMustFill("zj_img4", list)) {
                    result.setErrMsg("基座安装固定为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjImg3())
                        && CheckMustFillUtil.checkMustFill("zj_img3", list)) {
                    result.setErrMsg("底座防水为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjImg4())
                        && CheckMustFillUtil.checkMustFill("zj_img4", list)) {
                    result.setErrMsg("支架型号照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjImg5())
                        && CheckMustFillUtil.checkMustFill("zj_img5", list)) {
                    result.setErrMsg("航拍图照片不能为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getComponentImg1())
                        && CheckMustFillUtil.checkMustFill("component_img1", list)) {
                    result.setErrMsg("组件倾角照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getComponentImg2())
                        && CheckMustFillUtil.checkMustFill("component_img2", list)) {
                    result.setErrMsg("组件方位角照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getSizeMeasureImgs())
                        && CheckMustFillUtil.checkMustFill("size_measure_imgs", list)) {
                    result.setErrMsg("屋顶线缆安装照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getFixOtherImg())
                        && CheckMustFillUtil.checkMustFill("fix_other_img", list)) {
                    result.setErrMsg("线缆下墙照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getTotalImgs())
                        && CheckMustFillUtil.checkMustFill("total_imgs", list)) {
                    result.setErrMsg("逆变器组串接入照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getBwInnerImg())
                        && CheckMustFillUtil.checkMustFill("bw_inner_img", list)) {
                    result.setErrMsg("并网箱内部照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getDcImgs())
                        && CheckMustFillUtil.checkMustFill("dc_imgs", list)) {
                    result.setErrMsg("逆变器安装照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getNbqZbImg())
                        && CheckMustFillUtil.checkMustFill("nbq_zb_img", list)) {
                    result.setErrMsg("并网箱逆变器整体照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getDqsbAnImgOne())
                        && CheckMustFillUtil.checkMustFill("dqsb_an_img_one", list)) {
                    result.setErrMsg("逆变器注册截图照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getNbqPlateImg())
                        && CheckMustFillUtil.checkMustFill("nbq_plate_img", list)) {
                    result.setErrMsg("逆变器铭牌照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjPlateImg())
                        && CheckMustFillUtil.checkMustFill("zj_plate_img", list)) {
                    result.setErrMsg("组件铭牌照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getOpenWayVoltageImgs())
                        && CheckMustFillUtil.checkMustFill("open_way_voltage_imgs", list)) {
                    result.setErrMsg("开路电压图为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getJdImg1())
                        && CheckMustFillUtil.checkMustFill("jd_img1", list)) {
                    result.setErrMsg("组件与组件之间接地照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getJdImg2())
                        && CheckMustFillUtil.checkMustFill("jd_img2", list)) {
                    result.setErrMsg("组件与支架接地照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getJdImg3())
                        && CheckMustFillUtil.checkMustFill("jd_img3", list)) {
                    result.setErrMsg("支架与接地扁铁连接照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getJdImg4())
                        && CheckMustFillUtil.checkMustFill("jd_img4", list)) {
                    result.setErrMsg("接地扁铁下墙照片空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getJdImg5())
                        && CheckMustFillUtil.checkMustFill("jd_img5", list)) {
                    result.setErrMsg("支架接地电阻照片为空");
                    return result;
                }
                // 东向西航拍 direction_air_img1
                if (StringUtil.isBlank(reportDetail.getJdImg6())
                        && CheckMustFillUtil.checkMustFill("jd_img6", list)) {
                    result.setErrMsg("电气接地电阻照片为空");
                    return result;
                }
                // 西向东航拍 direction_air_img2
                if (StringUtil.isBlank(reportDetail.getZjReport())
                        && CheckMustFillUtil.checkMustFill("zj_report", list)) {
                    result.setErrMsg("自检记录报告为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getOtherFiles())
                        && CheckMustFillUtil.checkMustFill("other_files", list)) {
                    result.setErrMsg("其他资料为空");
                    return result;
                }

                //广发新增字段校验
                if (StringUtil.isBlank(reportDetail.getZjImg5())
                        && CheckMustFillUtil.checkMustFill("zj_img5_03", list)) {
                    result.setErrMsg("支架安装图-支架安装完成VR图为空");
                    return result;
                }
                if (StringUtil.isBlank(req.getSafetyWarningImg2())
                        && CheckMustFillUtil.checkMustFill("safety_warning_img2_03", list)) {
                    result.setErrMsg("施工安全图-三级安全教育为空");
                    return result;
                }
                if (StringUtil.isBlank(req.getSafetyWarningImg2())
                        && CheckMustFillUtil.checkMustFill("safety_warning_img2", list)) {
                    result.setErrMsg("三级安全教育卡为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getSafetyWarningImg3())
                        && CheckMustFillUtil.checkMustFill("safety_warning_img3", list)) {
                    result.setErrMsg("施工安全图-开工前站班会（施工安全用品：安全帽、安全绳、反光衣、工作鞋）为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getSafetyWarningImg())
                        && CheckMustFillUtil.checkMustFill("safety_warning_img", list)) {
                    result.setErrMsg("施工安全图-安全警示牌为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getSafetyDiscloseDocImg())
                        && CheckMustFillUtil.checkMustFill("safety_disclose_doc_img", list)) {
                    result.setErrMsg("施工安全图-安全技术交底书为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getComponentImg3())
                        && CheckMustFillUtil.checkMustFill("component_img3", list)) {
                    result.setErrMsg("组件航拍俯视照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getDcImgs())
                        && CheckMustFillUtil.checkMustFill("dc_imgs_03", list)) {
                    result.setErrMsg("逆变器安装图-整体外观及走线及采集器（离地高度）为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getNbqPlateImg())
                        && CheckMustFillUtil.checkMustFill("nbq_plate_img_03", list)) {
                    result.setErrMsg("逆变器安装图-铭牌为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getTotalImgs())
                        && CheckMustFillUtil.checkMustFill("total_imgs_03", list)) {
                    result.setErrMsg("逆变器安装图-接地情况为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getNbqZlcImg())
                        && CheckMustFillUtil.checkMustFill("nbq_zlc_img", list)) {
                    result.setErrMsg("逆变器安装图-逆变器交流侧为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getOpenWayVoltageImgs())
                        && CheckMustFillUtil.checkMustFill("open_way_voltage_imgs_03", list)) {
                    result.setErrMsg("逆变器安装图-组串开路电压照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getNbqZbImg())
                        && CheckMustFillUtil.checkMustFill("nbq_zb_img_03", list)) {
                    result.setErrMsg("并网箱安装图-外观及走线（离地高度）为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getBwInnerImg())
                        && CheckMustFillUtil.checkMustFill("bw_inner_img_03", list)) {
                    result.setErrMsg("并网箱安装图-并网箱内部全景为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getBwJdImg())
                        && CheckMustFillUtil.checkMustFill("bw_jd_img", list)) {
                    result.setErrMsg("并网箱安装图-接地情况为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjImg8())
                        && CheckMustFillUtil.checkMustFill("zj_img8", list)) {
                    result.setErrMsg("支架安装图-支架方阵（东向西完工照）为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjImg9())
                        && CheckMustFillUtil.checkMustFill("zj_img9", list)) {
                    result.setErrMsg("支架安装图-支架方阵（北向南完工照）为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjImg4())
                        && CheckMustFillUtil.checkMustFill("zj_img4_03", list)) {
                    result.setErrMsg("支架安装图-立柱东西间距、南北间距（带尺寸）为空");
                    return result;
                }
                if (CheckMustFillUtil.checkMustFill("zj_img10", list)){
                    if (StringUtil.isBlank(reportDetail.getZjImg10())){
                        result.setErrMsg("基础安装-螺栓孔洞防水图(不少于3张)为空");
                        return result;
                    }
                    if (reportDetail.getZjImg10().split(",").length < 3){
                        result.setErrMsg("基础安装-螺栓孔洞防水图(不少于3张)至少三张");
                        return result;
                    }
                }
                if (StringUtil.isBlank(reportDetail.getZjImg11())
                        && CheckMustFillUtil.checkMustFill("zj_img11", list)) {
                    result.setErrMsg("基础安装-柱脚防水完工图为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjImg12())
                        && CheckMustFillUtil.checkMustFill("zj_img12", list)) {
                    result.setErrMsg("支架安装图-斜梁悬挑（南）为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjImg13())
                        && CheckMustFillUtil.checkMustFill("zj_img13", list)) {
                    result.setErrMsg("支架安装图-斜梁悬挑（北）为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjImg14())
                        && CheckMustFillUtil.checkMustFill("zj_img14", list)) {
                    result.setErrMsg("支架安装图-檀条悬挑（东）为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getZjImg15())
                        && CheckMustFillUtil.checkMustFill("zj_img15", list)) {
                    result.setErrMsg("支架安装图-檀条悬挑（西）为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getJdImg4())
                        && CheckMustFillUtil.checkMustFill("jd_img4_03", list)) {
                    result.setErrMsg("支架接地图-支架接地为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getBkImg1())
                        && CheckMustFillUtil.checkMustFill("bk_img1", list)) {
                    result.setErrMsg("边框接地图-边框与边框接地为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getComponentImg1())
                        && CheckMustFillUtil.checkMustFill("component_img1_03", list)) {
                    result.setErrMsg("边框接地图-组件安装倾角为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getBkImg2())
                        && CheckMustFillUtil.checkMustFill("bk_img2", list)) {
                    result.setErrMsg("边框接地图-边框与支架接地为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getBkImg3())
                        && CheckMustFillUtil.checkMustFill("bk_img3", list)) {
                    result.setErrMsg("边框接地图-其他图片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getYkImg1())
                        && CheckMustFillUtil.checkMustFill("yk_img1", list)) {
                    result.setErrMsg("压块或背压板照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getFixOtherImg())
                        && CheckMustFillUtil.checkMustFill("fix_other_img_03", list)) {
                    result.setErrMsg("线缆走向（屋顶、下墙）、线缆保护管（或桥架）敷设及固定照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getSizeMeasureImgs())
                        && CheckMustFillUtil.checkMustFill("size_measure_imgs_03", list)) {
                    result.setErrMsg("电缆桥架内部电缆照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getJdImg8())
                        && CheckMustFillUtil.checkMustFill("jd_img8", list)) {
                    result.setErrMsg("接地极图-并网箱、逆变器安装接地极为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getJdImg5())
                        && CheckMustFillUtil.checkMustFill("jd_img5_03", list)) {
                    result.setErrMsg("接地极图-支架接地电阻阻值（近景）为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getJdImg9())
                        && CheckMustFillUtil.checkMustFill("jd_img9", list)) {
                    result.setErrMsg("接地极图-并网箱、逆变器安装接地电阻阻值（近景）为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getJdImg10())
                        && CheckMustFillUtil.checkMustFill("jd_img10", list)) {
                    result.setErrMsg("接地极图-接地引下线警示做法为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getJdImg11())
                        && CheckMustFillUtil.checkMustFill("jd_img11", list)) {
                    result.setErrMsg("接地极图-支架接地电阻测量照片（远景）为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getJdImg12())
                        && CheckMustFillUtil.checkMustFill("jd_img12", list)) {
                    result.setErrMsg("接地极图-并网箱、逆变器安装接地电阻测量照片（远景）为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getFsImg1())
                        && CheckMustFillUtil.checkMustFill("fs_img1", list)) {
                    result.setErrMsg("防水措施图-横竖向水槽为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getFsImg2())
                        && CheckMustFillUtil.checkMustFill("fs_img2", list)) {
                    result.setErrMsg("防水措施图-落水管走向及其固定为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getFsImg3())
                        && CheckMustFillUtil.checkMustFill("fs_img3", list)) {
                    result.setErrMsg("防水措施图-其他图片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getComponentImg4())
                        && CheckMustFillUtil.checkMustFill("component_img4", list)) {
                    result.setErrMsg("组件安装完成VR视图为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getOtherImgs5())
                        && CheckMustFillUtil.checkMustFill("other_imgs5", list)) {
                    result.setErrMsg("水槽细节照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getOtherImgs6())
                        && CheckMustFillUtil.checkMustFill("other_imgs6", list)) {
                    result.setErrMsg("落水管照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getOtherImgs7())
                        && CheckMustFillUtil.checkMustFill("other_imgs7", list)) {
                    result.setErrMsg("假梁-斜梁方向为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getOtherImgs8())
                        && CheckMustFillUtil.checkMustFill("other_imgs8", list)) {
                    result.setErrMsg("并网箱逆变器防雨罩照片为空");
                    return result;
                }
                if (StringUtil.isBlank(req.getKgConditionFiles())
                        && CheckMustFillUtil.checkMustFill("kg_condition_files", list)) {
                    result.setErrMsg("安全防护措施合照照片为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getSupplementVideoUrl())
                        && CheckMustFillUtil.checkMustFill("supplement_video_url", list)) {
                    result.setErrMsg("补充视频为空");
                    return result;
                }
                if (StringUtil.isBlank(reportDetail.getCompleteRemark())
                        && CheckMustFillUtil.checkMustFill("complete_remark", list)) {
                    result.setErrMsg("完工备注为空");
                    return result;
                }
            }
        }


        return Result.ok();
    }

    // 并网必填校验
    public Result requiredCheckForMerge(AddReportSecondReq req, List<Record> list) {
        Result result = new Result();
        result.setCode("205");
        // 购售电地址是否一致 address_consistent
        if (StringUtil.isBlank(req.getAddressConsistent())
                && CheckMustFillUtil.checkMustFill("address_consistent", list)) {
            result.setErrMsg("购售电地址是否一致为空");
            return result;
        }
        // 购售电地址 electric_pca_address
        boolean consistent = CustomerEntryConstants.ADDESS_CONSISTENT_YES.equals(req.getAddressConsistent());
        if (!consistent && CheckMustFillUtil.checkMustFill("address_consistent", list) ) {
            if (StringUtil.isBlank(req.getProvince()) || StringUtil.isBlank(req.getCity())
                    || StringUtil.isBlank(req.getArea()) || StringUtil.isBlank(req.getAddress())) {
                result.setErrMsg("购售电地址不能为空");
                return result;
            }
        }
        // 发电户号 generator_no
        if (StringUtil.isBlank(req.getGeneratorNo())
                && CheckMustFillUtil.checkMustFill("generator_no", list)) {
            result.setErrMsg("发电户号为空");
            return result;
        }

        // 电力公司 province_code
        if("0".equals(req.getBwInstitution())){
            if (StringUtil.isBlank(req.getProvinceCode()) && CheckMustFillUtil.checkMustFill("province_code", list)) {
                result.setErrMsg("电力公司为空");
                return result;
            }
        }else if("1".equals(req.getBwInstitution())){
            if (StringUtil.isBlank(req.getPowerPlantCode()) && CheckMustFillUtil.checkMustFill("power_plant_code", list)) {
                throw new BusinessException("电厂编码不能为空");
            }
            if (StringUtil.isBlank(req.getProvinceCodeHand()) && CheckMustFillUtil.checkMustFill("province_code_hand", list)) {
                throw new BusinessException("南网电力公司不能为空");
            }
        }


        // 保险类型 insurance_type
     /*   if (StringUtil.isBlank(req.getApplication().getInsurance().getInsuranceType())
                && CheckMustFillUtil.checkMustFill("insurance_type", list)) {
            result.setErrMsg("保险类型为空");
            return result;
        }
        // 保险公司 insurance_company
        if (StringUtil.isBlank(req.getApplication().getInsurance().getInsuranceCompany())
                && CheckMustFillUtil.checkMustFill("insurance_company", list)) {
            result.setErrMsg("保险公司为空");
            return result;
        }*/
        // 第一受益人 first_beneficiary
      /*  if (StringUtil.isBlank(req.getApplication().getInsurance().getFirstBeneficiary())
                && CheckMustFillUtil.checkMustFill("first_beneficiary", list)) {
            result.setErrMsg("第一受益人为空");
            return result;
        }*/
        // 保险编号 insurance_number
  /*      if (StringUtil.isBlank(req.getApplication().getInsurance().getInsuranceNumber())
                && CheckMustFillUtil.checkMustFill("insurance_number", list)) {
            result.setErrMsg("保险编号为空");
            return result;
        }*/
        // 投保金额 insurance_amount
    /*    if (req.getApplication().getInsurance().getInsuranceAmount() == null
                && CheckMustFillUtil.checkMustFill("insurance_amount", list)) {
            result.setErrMsg("投保金额为空");
            return result;
        }*/
        // 保险开始日期 insurance_date_from
      /*  if (StringUtil.isBlank(req.getApplication().getInsurance().getInsuranceDateFrom())
                && CheckMustFillUtil.checkMustFill("insurance_date_from", list)) {
            result.setErrMsg("保险开始日期为空");
            return result;
        }*/
        // 保险结束日期 insurance_date_to
   /*     if (StringUtil.isBlank(req.getApplication().getInsurance().getInsuranceDateTo())
                && CheckMustFillUtil.checkMustFill("insurance_date_to", list)) {
            result.setErrMsg("保险结束日期为空");
            return result;
        }*/
        // 近3天发电量 yx_img
        if (StringUtil.isBlank(req.getYxImg())
                && CheckMustFillUtil.checkMustFill("yx_img", list)) {
            result.setErrMsg("近3天发电量为空");
            return result;
        }
        if (StringUtil.isBlank(req.getPowerCapacityUrl())
                && CheckMustFillUtil.checkMustFill("power_capacity_url", list)) {
            result.setErrMsg("三天发电量截图为空");
            return result;
        }
        // 其他补充信息 geb_img
        if (StringUtil.isBlank(req.getGebImg())
                && CheckMustFillUtil.checkMustFill("geb_img", list)) {
            result.setErrMsg("其他补充信息为空");
            return result;
        }
        // 其他补充信息 geb_img2
    /*    if (StringUtil.isBlank(req.getGebImg2())
                && CheckMustFillUtil.checkMustFill("geb_img2", list)) {
            result.setErrMsg("其他补充信息2为空");
            return result;
        }*/
        // 购售电合同 contract
        if (StringUtil.isBlank(req.getContractFile())
                && CheckMustFillUtil.checkMustFill("contract", list)) {
            result.setErrMsg("购售电合同为空");
            return result;
        }
        // 并网调试报告 bwts_file
        if (StringUtil.isBlank(req.getApplication().getInsurance().getBwtsFile())
                && CheckMustFillUtil.checkMustFill("bwts_file", list)) {
            result.setErrMsg("并网调试报告为空");
            return result;
        }
        // 电表箱照片
        if (StringUtil.isBlank(req.getDbxImgs())
                && CheckMustFillUtil.checkMustFill("dbx_imgs", list)) {
            result.setErrMsg("电表箱照片为空");
            return result;
        }
        // 保险单 insurance_policy
    /*    if (StringUtil.isBlank(req.getApplication().getInsurance().getInsurancePolicy())
                && CheckMustFillUtil.checkMustFill("insurance_policy", list)) {
            result.setErrMsg("保险单为空");
            return result;
        }*/
        // 铜铝转换接头
        if (StringUtil.isBlank(req.getTlzhjkImgs())
                && CheckMustFillUtil.checkMustFill("tlzhjk_imgs", list)) {
            result.setErrMsg("铜铝转换接头照片为空");
            return result;
        }
        return Result.ok();
    }

    private CrmAcceptingReport saveReportZc(CustomerEntry customerEntry, AddReportZcReq req, Operator operator,
                                            Date time, int i) {
        CrmAcceptingReport report;
        if (StrKit.notBlank(customerEntry.getReceivingReportId())) {
            report = reportDao.get(customerEntry.getReceivingReportId());
        } else {
            report = new CrmAcceptingReport();
            report.setCreateBy(operator.getUserId());
            report.setCreator(operator.getUserName());
            report.setCreateTime(time);
            report.setStatus(CustomerEntryConstants.REPORT_STATUS_DYS);
        }
        report.setComponentSpec(customerEntry.getComponentSpec());
        report.setComponentNum(i);
        report.setCapacity(customerEntry.getActualCapacity());
        report.setOtherImgs1(req.getOtherImgs1());
        report.setOtherImgs2(req.getOtherImgs2());
        report.setOtherImgs3(req.getOtherImgs3());
        report.setOtherImgs4(req.getOtherImgs4());
        report.setDzjc1(req.getDzjc1());
        report.setDzjc2(req.getDzjc2());
        report.setZjImg1(req.getZjImg1());
        report.setZjImg2(req.getZjImg2());
        report.setZjImg3(req.getZjImg3());
        report.setZjImg4(req.getZjImg4());
        report.setZjImg5(req.getZjImg5());
        report.setComponentImg1(req.getComponentImg1());
        report.setComponentImg2(req.getComponentImg2());
        report.setSizeMeasureImgs(req.getSizeMeasureImgs());
        report.setFixOtherImg(req.getFixOtherImg());
        report.setTotalImgs(req.getTotalImgs());
        report.setBwInnerImg(req.getBwInnerImg());
        report.setDcImgs(req.getDcImgs());
        report.setNbqZbImg(req.getNbqZbImg());
        report.setNbqPlateImg(req.getNbqPlateImg());
        report.setDqsbAnImgOne(req.getDqsbAnImgOne());
        report.setNbqPlateImg(req.getNbqPlateImg());
        report.setZjPlateImg(req.getZjPlateImg());
        report.setOpenWayVoltageImgs(req.getOpenWayVoltageImgs());
        report.setJdImg1(req.getJdImg1());
        report.setJdImg2(req.getJdImg2());
        report.setJdImg3(req.getJdImg3());
        report.setJdImg4(req.getJdImg4());
        report.setJdImg5(req.getJdImg5());
        report.setOtherFiles(req.getOtherFiles());
        report.setJdImg6(req.getJdImg6());
        report.setZjReport(req.getZjReport());
        report.setFixAcceptBy(operator.getUserId());
        report.setFixAcceptName(operator.getUserName());
        report.setFixAcceptTime(time);
        report.setStatus(CustomerEntryConstants.REPORT_STATUS_DYS);
        report.setSupplementVideoUrl(req.getSupplementVideoUrl());
        report.setCompleteRemark(req.getCompleteRemark());
        //广发新增字段
        report.setSafetyDiscloseDocImg(req.getSafetyDiscloseDocImg());
        report.setComponentImg3(req.getComponentImg3());
        report.setTotalImgs(req.getTotalImgs());
        report.setSafetyWarningImg(req.getSafetyWarningImg());
        report.setSafetyWarningImg2(req.getSafetyWarningImg2());
        report.setSafetyWarningImg3(req.getSafetyWarningImg3());
        report.setNbqZlcImg(req.getNbqZlcImg());
        report.setBwJdImg(req.getBwJdImg());
        report.setZjImg8(req.getZjImg8());
        report.setZjImg9(req.getZjImg9());
        report.setZjImg10(req.getZjImg10());
        report.setZjImg11(req.getZjImg11());
        report.setZjImg12(req.getZjImg12());
        report.setZjImg13(req.getZjImg13());
        report.setZjImg14(req.getZjImg14());
        report.setZjImg15(req.getZjImg15());
        report.setBkImg1(req.getBkImg1());
        report.setBkImg2(req.getBkImg2());
        report.setBkImg3(req.getBkImg3());
        report.setYkImg1(req.getYkImg1());
        report.setJdImg8(req.getJdImg8());
        report.setJdImg9(req.getJdImg9());
        report.setJdImg10(req.getJdImg10());
        report.setJdImg11(req.getJdImg11());
        report.setJdImg12(req.getJdImg12());
        report.setFsImg1(req.getFsImg1());
        report.setFsImg2(req.getFsImg2());
        report.setFsImg3(req.getFsImg3());
        report.setComponentImg4(req.getComponentImg4());
        report.setContractUrl(req.getContractUrl());
        report.setWaterMudClampImgs(req.getWaterMudClampImgs());
        //华融新增字段
        report.setOtherImgs5(req.getOtherImgs5());
        report.setOtherImgs6(req.getOtherImgs6());
        report.setOtherImgs7(req.getOtherImgs7());
        report.setOtherImgs8(req.getOtherImgs8());
        report.setKgConditionFiles(req.getKgConditionFiles());
        reportDao.save(report);
        return report;
    }

    private CrmAcceptingReport saveReportZcHr(CustomerEntry customerEntry, AddReportZcReq req, Operator operator,
                                            Date time, int i) {

        CrmAcceptingReport acceptingReport;
        if (StrKit.notBlank(customerEntry.getReceivingReportId())) {
            reportDetailDao.deleteReportDetailByEntryId(customerEntry.getId());
            acceptingReport = reportDao.get(customerEntry.getReceivingReportId());
        } else {
            acceptingReport = new CrmAcceptingReport();
            acceptingReport.setCreateBy(operator.getUserId());
            acceptingReport.setCreator(operator.getUserName());
            acceptingReport.setCreateTime(time);
            acceptingReport.setStatus(CustomerEntryConstants.REPORT_STATUS_DYS);
        }
        acceptingReport.setComponentSpec(customerEntry.getComponentSpec());
        acceptingReport.setComponentNum(i);
        acceptingReport.setCapacity(customerEntry.getActualCapacity());
        List<CrmAcceptingReportDetail> completeList = req.getCompleteList();
        for(CrmAcceptingReportDetail reportDetail : completeList){
            CrmAcceptingReportDetail report = new CrmAcceptingReportDetail();
            String projectId = reportDetail.getProjectId();
            Record record = entryDao.countByEntryProjectId(customerEntry.getId(), projectId);
            if (record != null) {
                if (record.get("spec") != null) {
                    report.setComponentSpec(record.getStr("spec"));
                }
                if (record.get("num") != null) {
                    report.setComponentNum(record.getLong("num").intValue());
                }
                if (record.get("total") != null) {
                    report.setCapacity(BigDecimal.valueOf(record.getDouble("total")));
                }
            }
            report.setEntryId(req.getEntryId());
            report.setProjectId(projectId);
            report.setCreateBy(operator.getUserId());
            report.setCreator(operator.getUserName());
            report.setCreateTime(time);
            report.setStatus(CustomerEntryConstants.REPORT_STATUS_DYS);
            report.setOtherImgs1(reportDetail.getOtherImgs1());
            report.setOtherImgs2(reportDetail.getOtherImgs2());
            report.setOtherImgs3(reportDetail.getOtherImgs3());
            report.setOtherImgs4(reportDetail.getOtherImgs4());
            report.setDzjc1(reportDetail.getDzjc1());
            report.setDzjc2(reportDetail.getDzjc2());
            report.setZjImg1(reportDetail.getZjImg1());
            report.setZjImg2(reportDetail.getZjImg2());
            report.setZjImg3(reportDetail.getZjImg3());
            report.setZjImg4(reportDetail.getZjImg4());
            report.setZjImg5(reportDetail.getZjImg5());
            report.setComponentImg1(reportDetail.getComponentImg1());
            report.setComponentImg2(reportDetail.getComponentImg2());
            report.setSizeMeasureImgs(reportDetail.getSizeMeasureImgs());
            report.setFixOtherImg(reportDetail.getFixOtherImg());
            report.setTotalImgs(reportDetail.getTotalImgs());
            report.setBwInnerImg(reportDetail.getBwInnerImg());
            report.setDcImgs(reportDetail.getDcImgs());
            report.setNbqZbImg(reportDetail.getNbqZbImg());
            report.setNbqPlateImg(reportDetail.getNbqPlateImg());
            report.setDqsbAnImgOne(reportDetail.getDqsbAnImgOne());
            report.setNbqPlateImg(reportDetail.getNbqPlateImg());
            report.setZjPlateImg(reportDetail.getZjPlateImg());
            report.setOpenWayVoltageImgs(reportDetail.getOpenWayVoltageImgs());
            report.setJdImg1(reportDetail.getJdImg1());
            report.setJdImg2(reportDetail.getJdImg2());
            report.setJdImg3(reportDetail.getJdImg3());
            report.setJdImg4(reportDetail.getJdImg4());
            report.setJdImg5(reportDetail.getJdImg5());
            report.setOtherFiles(reportDetail.getOtherFiles());
            report.setJdImg6(reportDetail.getJdImg6());
            report.setZjReport(reportDetail.getZjReport());
            report.setFixAcceptBy(operator.getUserId());
            report.setFixAcceptName(operator.getUserName());
            report.setFixAcceptTime(time);
            report.setStatus(CustomerEntryConstants.REPORT_STATUS_DYS);
            report.setSupplementVideoUrl(reportDetail.getSupplementVideoUrl());
            report.setCompleteRemark(reportDetail.getCompleteRemark());
            //广发新增字段
            report.setSafetyDiscloseDocImg(reportDetail.getSafetyDiscloseDocImg());
            report.setComponentImg3(reportDetail.getComponentImg3());
            report.setTotalImgs(reportDetail.getTotalImgs());
            report.setSafetyWarningImg(reportDetail.getSafetyWarningImg());
            report.setSafetyWarningImg2(req.getSafetyWarningImg2());
            report.setSafetyWarningImg3(reportDetail.getSafetyWarningImg3());
            report.setNbqZlcImg(reportDetail.getNbqZlcImg());
            report.setBwJdImg(reportDetail.getBwJdImg());
            report.setZjImg8(reportDetail.getZjImg8());
            report.setZjImg9(reportDetail.getZjImg9());
            report.setZjImg10(reportDetail.getZjImg10());
            report.setZjImg11(reportDetail.getZjImg11());
            report.setZjImg12(reportDetail.getZjImg12());
            report.setZjImg13(reportDetail.getZjImg13());
            report.setZjImg14(reportDetail.getZjImg14());
            report.setZjImg15(reportDetail.getZjImg15());
            report.setBkImg1(reportDetail.getBkImg1());
            report.setBkImg2(reportDetail.getBkImg2());
            report.setBkImg3(reportDetail.getBkImg3());
            report.setYkImg1(reportDetail.getYkImg1());
            report.setJdImg8(reportDetail.getJdImg8());
            report.setJdImg9(reportDetail.getJdImg9());
            report.setJdImg10(reportDetail.getJdImg10());
            report.setJdImg11(reportDetail.getJdImg11());
            report.setJdImg12(reportDetail.getJdImg12());
            report.setFsImg1(reportDetail.getFsImg1());
            report.setFsImg2(reportDetail.getFsImg2());
            report.setFsImg3(reportDetail.getFsImg3());
            report.setComponentImg4(reportDetail.getComponentImg4());
            report.setContractUrl(reportDetail.getContractUrl());
            //华融新增字段
            report.setOtherImgs5(reportDetail.getOtherImgs5());
            report.setOtherImgs6(reportDetail.getOtherImgs6());
            report.setOtherImgs7(reportDetail.getOtherImgs7());
            report.setOtherImgs8(reportDetail.getOtherImgs8());
            report.setKgConditionFiles(req.getKgConditionFiles());
            reportDetailDao.save(report);
        }
        reportDao.save(acceptingReport);
        return acceptingReport;
    }

    public Record findSysHomeList(Map<String, String> map, Operator operator) {
        Record record = customerDao.findSysHomeList(map, operator);
        List<Long> listlong = new ArrayList<>();
        listlong.add(record.getLong("newCount"));
        listlong.add(record.getLong("tksjCount"));
        listlong.add(record.getLong("sjshCount"));
        listlong.add(record.getLong("dazCount"));
        listlong.add(record.getLong("azysCount"));
        // listlong.add(record.getLong("fpscCount"));
        listlong.add(record.getLong("dzbwCount"));
        listlong.add(record.getLong("bwysCount"));
        listlong.add(record.getLong("ywcCount"));
        // listlong.add(record.getLong("dzzgCount"));
        record.set("echarts", listlong);

        boolean allNull = true;
        if (record.getLong("yazCount") == 0) {
            record.set("yazCount", null);
        } else {
            allNull = false;
        }
        if (record.getLong("ybwCount") == 0) {
            record.set("ybwCount", null);
        } else {
            allNull = false;
        }
        if (record.getLong("ywcCount") == 0) {
            record.set("ywcCount", null);
        } else {
            allNull = false;
        }
        if (record.getLong("ysjCount") == 0) {
            record.set("ysjCount", null);
        } else {
            allNull = false;
        }
        if (record.getLong("yysCount") == 0) {
            record.set("yysCount", null);
        } else {
            allNull = false;
        }
        if (allNull) {
            record.set("yazCount", 0);
            record.set("ybwCount", 0);
            record.set("ywcCount", 0);
            record.set("ysjCount", 0);
            record.set("yysCount", 0);
        }

        return record;
    }

    public Record findSysPancakeList(Map<String, String> map, Operator operator) {
        return customerDao.findSysPancakeList(map, operator);
    }


    public String getWarehouseId(String entryId) {
        return Db.queryStr("select warehouse_id from crm_customer_entry where id = ?", entryId);
    }

    public Result doConfirm(String ids) {
        if (StringUtil.isBlank(ids)) {
            Result.fail("请选择操作的数据");
        }
        SqlBuilder builder = new SqlBuilder();
        builder.line("UPDATE crm_customer_entry_out_confirm a SET a.status = '2', a.confirm_time=now()");
        builder.line(",a.confirm_by=?", UserUtils.getUser().getId());
        builder.inst("WHERE a.status = '1' AND a.id IN ", ids.split(","));
        Db.update(builder.build(), builder.params());
        return Result.ok();
    }

    public List<Record> selectMaterialList(String confirmId) {
        return customerDao.selectMaterialList(confirmId);
    }

    /**
     * type:2.并网箱  4.支架
     */
    public List<Record> getMateriallist(String entryId, String type, String warehouseId) {
//        SqlBuilder builder = new SqlBuilder();
//        builder.line("SELECT e.model FROM crm_customer_entry_component c LEFT JOIN crm_electric_set e ON c.item_id = e.id");
//        builder.line("WHERE c.status = '0' AND c.entry_id = ?", entryId);
//        builder.line("AND c.item_type=?", type);
//        List<String> specsList = Db.query(builder.toString(), builder.params());
//        if (specsList == null || specsList.isEmpty()) {
//            return null;
//        }
        String materialType = "2".equals(type) ? "并网箱" : "支架";
        SqlBuilder builder2 = new SqlBuilder();
        builder2.line("SELECT a.id,a.code,a.material_specs,a.material_brand,a.material_name,c.warning");
        builder2.line("FROM crm_supply_material a");
        builder2.line("LEFT JOIN crm_supply_material_type b ON b.id = a.material_type_id");
        builder2.line("LEFT JOIN crm_supply_material_warehouse_stocks c ON c.material_id = a.id AND c.warehouse_id=?", warehouseId);
        builder2.line("WHERE b.name=?", materialType);
//        builder2.inst("AND a.material_specs IN",specsList);
        builder2.line("AND c.warning > 0");
        return Db.find(builder2.build(), builder2.params());
    }

    /**
     * 专用与逆变器
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Result saveMaterialSN(List<AddMaterialSnReq> req, Operator operator) {
        List<String> snList = Lists.newArrayList();
        List<String> nbqSnList = Lists.newArrayList();
        for (AddMaterialSnReq snReq : req) {
            CustomerEntry customerEntry = customerDao.get(snReq.getEntryId());
            String[] projectIds = customerEntry.getProjectId().split(",");
            if (StringUtil.isAnyBlank(snReq.getSn(), snReq.getNbqSn(), snReq.getBarcode(), snReq.getEntryId()
                    , snReq.getMaterialId())) {
                throw new BusinessException("缺少必要参数");
            }
            if (StringUtils.isEmpty(snReq.getYzCode())) {
                String querySql = "select count(1) from crm_supply_material as a where id=? and  a.material_brand in ('固德威','爱士惟')";
                Long result = Db.queryLong(querySql, snReq.getMaterialId());
                if (result > 0) {
                    throw new BusinessException("验证码不能为空");
                }
            }

            // 校验序列号唯一性
            boolean b = customerDao.checkSnUniqueness(snReq.getSn());
            if (b) {
                throw new BusinessException("序列号：" + snReq.getSn() + "已存在");
            }
            snList.add(snReq.getSn());
            nbqSnList.add(snReq.getNbqSn());

            if("04".equals(customerEntry.getPartnerId())){
                CrmPlanMaterialEntry crmPlanMaterialEntry = entryDao.findByEntryIdProjectMaterial(snReq.getEntryId(), snReq.getMaterialId()
                        , snReq.getBarcode(),projectIds);
                crmPlanMaterialEntry.setNbqSn(snReq.getNbqSn());
                crmPlanMaterialEntry.setSn(snReq.getSn());
                crmPlanMaterialEntry.setYzCode(snReq.getYzCode());
                entryDao.save(crmPlanMaterialEntry);
            }else{
                CrmPlanMaterialEntry crmPlanMaterialEntry = entryDao.findByEntryIdMaterial(snReq.getEntryId(), snReq.getMaterialId()
                        , snReq.getBarcode());
                crmPlanMaterialEntry.setNbqSn(snReq.getNbqSn());
                crmPlanMaterialEntry.setSn(snReq.getSn());
                crmPlanMaterialEntry.setYzCode(snReq.getYzCode());
                entryDao.save(crmPlanMaterialEntry);
            }



        }
        CustomerEntry entry = customerDao.get(req.get(0).getEntryId());
        entry.setInstallBy(operator.getUserId());
        entry.setInstallTime(new Date());
        entry.setSn(StringUtil.join(snList, ","));
        entry.setNbqSn(StringUtil.join(nbqSnList, ","));
        customerDao.save(entry);
        return Result.ok();
    }

    /**
     * 使用物料
     */
    public Result usedMaterial2(UsedMaterialReq req) {
        Date now = new Date();
        List<UsedMaterialDetailReq> materialList = req.getMaterialList();
        CustomerEntry entry = customerDao.get(req.getEntryId());
        for (UsedMaterialDetailReq materialReq : materialList) {
            // 查询物料id
            SupplyMaterial material = supplyMaterialDao.get(materialReq.getMaterialId());
            if (material == null) {
                return Result.fail("未查询到该物料");
            }
            // 查询物料类型
            CrmSupplyMaterialType materialType = materialTypeDao.get(material.getMaterialTypeId());
            if("04".equals(entry.getPartnerId())){
                    entryDao.createOne(material.getId(), materialType.getName(), material.getCode(), material.getMaterialName(),
                            material.getMaterialSpecs(), material.getUnitName(), null,
                            Integer.valueOf(materialReq.getNum()), now, req.getEntryId(),material.getMaterialModel(),req.getProjectId());
            }else {
                entryDao.createOne(material.getId(), materialType.getName(), material.getCode(), material.getMaterialName(),
                        material.getMaterialSpecs(), material.getUnitName(), null,
                        Integer.valueOf(materialReq.getNum()), now, req.getEntryId(),material.getMaterialModel(),entry.getProjectId());
            }


        }

        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> findPreauditStatus(String entryId) {
        CustomerEntry entry = customerDao.get(entryId);
        if (entry == null) {
            return null;
        }
        String idCode = "";
        // 如果是自然人承租人，则使用承租人证件号码查询
        // 如果是法人承租人，则使用登记注册号码查询
        if ("1".equals(entry.getTenantType())) {
            idCode = entry.getIdCode();
        } else {
            idCode = entry.getRegno();
        }
        if (StringUtil.isBlank(idCode)) {
            return null;
        }
        Map<String, String> resultMap = null;
        String partnerName = null;
        switch (entry.getPartnerId()) {
            case PartnerConstants.PARTNER_ID_YX:
                resultMap = operatingLeaseService.findPreauditStatus(idCode);
                partnerName = "资方-越秀";
                break;
            case PartnerConstants.PARTNER_ID_HR:
                resultMap = queryHuarongPreauditStatus(entry);
                partnerName = "资方-华融";
                break;
            case PartnerConstants.PARTNER_ID_GF:
                return queryGuangfaPreauditStatus(entry);
        }
        if (resultMap != null) {
            if (entry.getPartnerId().equals(PartnerConstants.PARTNER_ID_YX) || entry.getPartnerId().equals(PartnerConstants.PARTNER_ID_HR)) {
                dealYsQueryData(idCode, entry, partnerName, resultMap);
            }

        }
        return resultMap;
    }

    //查询广发电站的预审结果
    public Map<String, String> queryGuangfaPreauditStatus(CustomerEntry entry) {
        Map<String, String> resultMap = new HashMap<>();
        StatusFormVo vo = dealGfQueryData(entry);
        Integer businessSate= vo.getBusinesssSate();
        if (businessSate == 30) {
            // 预审通过
            resultMap.put("result", "APPROVED");
            return resultMap;
        } else if (40 == businessSate || 50 == businessSate) {
            // 预审不通过
            resultMap.put("result", "REJECT");
            resultMap.put("reason",  vo.getBusinesssMsg());
        } else {
            // 预审中
            resultMap.put("result", "APPROVING");
        }
        return resultMap;
    }


    /**
     * 广发处理预审
     */
    @Transactional(rollbackFor = Exception.class)
    public StatusFormVo dealGfQueryData(String entryId) {
        CustomerEntry entry = getById(entryId);
        return dealGfQueryData(entry);
    }

    /**
     * 广发处理预审
     */
    @Transactional(rollbackFor = Exception.class)
    public StatusFormVo dealGfQueryData(CustomerEntry entry) {
        CrmCustomerIncomingApplication incomingApplication = incomingApplicationDao.getByEntryId(entry.getId());
        try {
            StatusFormVo statusFormVo = guangfaOperatingService.guangFaPreStatus(incomingApplication.getPartnerId(), incomingApplication.getInputPieceId());
            guangFaManagemnetService.changePreStatus(statusFormVo, incomingApplication, entry);
            incomingApplicationDao.save(incomingApplication);
            customerDao.save(entry);
            return statusFormVo;
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }

    }
    @Transactional(rollbackFor = Exception.class)
    public void dealHRQueryData(String entryId,String type){
        CustomerEntry entry = customerDao.get(entryId);
        CrmCustomerIncomingApplication incomingApplication = incomingApplicationDao.getByEntryId(entry.getId());
        List<HuaRongStatusFormVo> result = huaRongApiService.queryRongStatus(PartnerConstants.PARTNER_ID_HR, incomingApplication.getPartnersContractNumber());
        HuaRongCustomer customer = result.get(0).getCustomerList().get(0);
        //更新 进件状态
        huaRongManagementService.updateIncomingApplicationStatus(incomingApplication,customer,entry,type);
    }
    @Transactional(rollbackFor = Exception.class)
    public  void terminateHuaRongProject(User user ,CustomerEntry entry,String reason){
        Date date = new Date();
        CrmCustomerIncomingApplication application = applicationDao.getByEntryId(entry.getId());
        if (application == null){
            throw new IllegalArgumentException("进件信息不存在");
        }
        application.setStatus("a");
        application.setCancelReason(reason);
        application.setUpdateTime(date);
        application.setUpdateBy(user.getId());
        applicationDao.save(application);
        entry.setApplyStatus("4");
        entry.setFirstApplyStatus("CL");
        entry.setNextApplyStatus("CL");
        entry.setSignStatus(CustomerEntryConstants.SIGN_STATUS_UNSTART);
        customerDao.save(entry);
        //删除对应进件的合同
        CrmCustomerContractManagement management=contractManagementDao.getContractByEntryId(entry.getId());
        if(management!=null){
            management.setStatus("0");
            management.setUpdateTime(date);
            contractManagementDao.save(management);
        }
        //取消进件
        huaRongApiService.cancelHRApply(entry,application.getPartnersContractNumber(),reason);
        msgService.saveCustomerEntryMsg(user,entry.getId(), CustomerEntryConstants.INCOMING_CANCEL,"取消进件,"+reason);
    }

    public void dealYsQueryData(String idCode, CustomerEntry entry, String partnerName,
                                Map<String, String> resultMap) {
        String requestParam = "idCode:" + idCode + ",partnerId:" + entry.getPartnerId();
        String str = new Gson().toJson(resultMap);
        CrmYxProcessDao.addProcess(entry.getId(), "5", "预审结果查询", requestParam, str, "0");
        //更新电站预审状态
        String itemStatus = null;
        String remarks = "";
        String auditStatus = "1";
        String newCredit = getMsgByType(resultMap.get("result"));
        if (newCredit.equals(entry.getCredit())) {
            return;
        }
        entry.setCredit(newCredit);

        StringBuilder sqlStr = new StringBuilder();
        sqlStr.append("update crm_customer_yx_condition ");
        sqlStr.append("set preaudit=:preaudit ");
        if (StringUtil.isNotBlank(resultMap.get("reason"))) {
            remarks = resultMap.get("reason");
            sqlStr.append(",preaudit_reason=:remarks ");
        }
        sqlStr.append("WHERE id_code=:idCode and partner_id =:partnerId");
        if ("4".equals(entry.getCredit())) {
            // 如果是预审通过 控制重复操作
            sqlStr.append(" and preaudit != '4' ");
        }
        SQLQuery sqlQuery = customerDao.getSession()
                .createSQLQuery(sqlStr.toString());
        sqlQuery.setParameter("partnerId", entry.getPartnerId());
        sqlQuery.setParameter("idCode", idCode);
        sqlQuery.setParameter("preaudit", entry.getCredit());
        if (StringUtil.isNotBlank(remarks)) {
            sqlQuery.setParameter("remarks", remarks);
        }
        int update = sqlQuery.executeUpdate();
        if (update < 1) {
            throw new IllegalArgumentException("已预审通过，筛选列表获取最新数据");
        }

        if (StringUtil.equalsAny(entry.getCredit(), "2", "3")) {
            entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSZ);
        } else if ("1".equals(entry.getCredit())) {
            entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_DYS);
        } else if ("4".equals(entry.getCredit())) {
            entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSCG);
            entry.setCreditDsc(null);
            itemStatus = "0";
            auditStatus = "2";
            if (!CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK.equals(entry.getDesignAuditFlag())) {
                entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
            }
            // 更改客户信息预审状态 为预审通过
            tenantDao.updateYxFlag(entry.getTenantId(), "1");
            Operator operator = Operator.of("1", partnerName, "资方");
            Operator operator2 = Operator.of("1", partnerName, "系统");
            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ENTRY_ZF_YSTG, "预审通过", "");
            if (PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
                //预审通过自动发起合同
                createHRContract(entry,operator2);
            }
            if (!"1".equals(entry.getSecCardStatus()) && "1".equals(entry.getFilingType()) &&
                    PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())) {
                // 需要生成一条待开卡-1的记录 因为华融的开卡线下生成 线上查询结果
                boolean secondCardFlag = checkDKKSecondCard(idCode, entry.getPartnerId());
                if (secondCardFlag) {
                    CrmTenantYxBankCard card = new CrmTenantYxBankCard();
                    card.setName(entry.getTenantName());
                    card.setIdCode(entry.getIdCode());
                    card.setMobile(entry.getMobile());
                    card.setManagementType(entry.getManagementType());
                    card.setPartnerId(entry.getPartnerId());
                    card.setStatus(YueXiuConstants.BANK_CODE_DKK);
                    tenantYxBankCardDao.save(card);
                }
            }
        } else if ("5".equals(entry.getCredit())) {
            entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_YSBH);
            entry.setCreditDsc(remarks);
            itemStatus = "1";
            auditStatus = "3";
            // 更改客户信息预审状态 为预审不通过
            tenantDao.updateYxFlag(entry.getTenantId(), "2");
            Operator operator = Operator.of("1", partnerName, "资方");
            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ENTRY_ZF_YSBTG, "预审不通过，" + remarks, "");
        }
        customerDao.save(entry);

        CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(), "1", itemStatus, "0", auditStatus, remarks);
    }

    //校验是否已生成二类卡记录
    public boolean checkDKKSecondCard(String idCode, String partnerId) {
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT c.id,c.name,c.id_code,c.management_type ");
        sb.append("FROM `crm_tenant_yx_bank_card` c ");
        sb.append("WHERE c.status in ('-1','4') and c.partner_id= ? ");
        sb.append(" and c.id_code = ? ");
        sb.append("ORDER BY c.status ASC ");
        //先校验是否已生成记录
        Record check = Db.findFirst(sb.toString(),partnerId, idCode);
        if (check != null) {
            return false;
        }
        return true;
    }

    //查询华融电站的预审结果
    public Map<String, String> queryHuarongPreauditStatus(CustomerEntry entry) {
        JSONObject jsonObject = huaRongApiService.queryPreAudit(entry);
        Map<String, String> resultMap = new HashMap<>();
        if (jsonObject != null) {
            String result = jsonObject.getString("result");
            if (StringUtil.isBlank(result)) {
                resultMap.put("result", "APPROVING");
                return resultMap;
            }
            //0:未通过校验 1:通过校验 2:未查询到该客户的大数据查询结果
            switch (result) {
                case "1":
                    resultMap.put("result", "APPROVED");
                    break;
                case "2":
                    resultMap.put("result", "APPROVING");
                    resultMap.put("reason", jsonObject.getString("dsc"));
                    break;
                default:
                    resultMap.put("result", "REJECT");
                    resultMap.put("reason", jsonObject.getString("dsc"));
                    break;
            }
        }
        return resultMap;
    }

    @Transactional(rollbackFor = Exception.class)
    public void createHRContract(CustomerEntry entry,Operator operator ){
        if(CustomerEntryConstants.TENANT_TYPE_PERSON.equals(entry.getTenantType())){  //个人
            CrmCustomerIncomingApplication incomingApplication = applicationDao.saveIncomingApplication(entry);
            String partnersContractNumber = incomingApplication.getPartnersContractNumber();
            //根据进件序号，如果该进件没有合同，那么需要邀请签约合同
            CrmCustomerContractManagement contractManagement=contractManagementDao.getContract(entry.getId());
            if(contractManagement==null){
                CrmPartner partner = partnerService.getById(entry.getPartnerId());
                //多产品生成待生成的合同
                if("1".equals(partner.getIfSignContract()) && entry.getProjectNum() == 1){  //是否开启在线签署模式：1.开启 2.关闭（该设置主要针对华融合同）
                    contractESignSignService.InviteSign(partnersContractNumber,entry,operator,"预审通过，发起合同",null,null);
                }else{ //合同上传的模式
                    StringBuffer sf = new StringBuffer();
                    sf.append(" INSERT INTO crm_customer_contract_management(id,entry_id,power_station_code,trader_id,STATUS,update_time,partners_contract_number," +
                            "invitation_time,project_company_id,project_company_name,tenant_mobile,tenant_name,id_code,tenant_address ) ");
                    sf.append(" VALUES(:p1,:p2,:p3,:p4,'f',NOW(),:p5,NOW(),:p6,:p7,:p8,:p9,:p10,:p11 )");
                    SQLQuery sqlQuery = customerDao.getSession().createSQLQuery(sf.toString());
                    sqlQuery.setParameter("p1",IdGen.uuid());
                    sqlQuery.setParameter("p2",entry.getId());
                    sqlQuery.setParameter("p3",entry.getPowerStationCode());
                    sqlQuery.setParameter("p4",entry.getDistributorId());
                    sqlQuery.setParameter("p5",partnersContractNumber);
                    sqlQuery.setParameter("p6",entry.getProjectCompanyId());
                    sqlQuery.setParameter("p7",entry.getProjectCompanyName());
                    sqlQuery.setParameter("p8",entry.getMobile());
                    sqlQuery.setParameter("p9",entry.getTenantName());
                    sqlQuery.setParameter("p10",entry.getIdCode());
                    sqlQuery.setParameter("p11",entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress());
                    int i = sqlQuery.executeUpdate();
                    logger.info("华融预审通过  add:{}", i);
                    entry.setSignStatus(ESignConstants.GF_CONTRACT_STATUS_DSC);
                }
            }
        }
    }

    public String getMsgByType(String status) {
        String content = "2";
        //预审结果:NEW-预审待审批 APPROVING-预审审批中 APPROVED-预审通过 REJECT-预审拒绝
        switch (status) {
            case "NEW":
                content = "2";
                break;
            case "APPROVING":
                content = "3";
                break;
            case "APPROVED":
                content = "4";
                break;
            case "REJECT":
                content = "5";
                break;
            default:
        }
        return content;
    }

    // 自然人 预审上传信息使用授权书
    public Result updateAuditFile(CustomerEntry entry) {
        if (!"1".equals(entry.getTenantType())) {
            return null;
        }
        String contractPath = commonStaticImgPath + getContractPath(entry);
        if (StringUtil.isBlank(contractPath)) {
            return null;
        }
        List<FinanceProjectFile> fileList = new ArrayList<>();
        FinanceProjectFile projectFile = new FinanceProjectFile();
        projectFile.setFileName("信息使用授权书.pdf");
        projectFile.setFileCode(FileCodeConstants.GR_FILE_A_01);
//        projectFile.setFileAddress("https://esignoss.esign.cn/1111563786/ff110a34-4283-4fbd-9c59-df9428f07404/%E4%BF%A1%E6%81%AF%E4%BD%BF%E7%94%A8%E6%8E%88%E6%9D%83%E5%8D%8F%E8%AE%AE.pdf?Expires=1698041304&OSSAccessKeyId=LTAI4G23YViiKnxTC28ygQzF&Signature=fggokZnK7YDRHQRNLDUFYRKW%2F7A%3D");
        projectFile.setFileAddress(contractPath);
        fileList.add(projectFile);
        return operatingLeaseService.updateFile2(entry, fileList, "02", entry.getIdCode(), "1");
    }

    //获取授权签署文件链接
    public String getContractPath(CustomerEntry entry) {
        return getContractPath(entry.getTenantType(), entry.getIdCode(), entry.getPartnerId());

    }

    //获取授权签署文件链接
    public String getContractPath(String tenantType, String idCode, String partnerId) {
        if (!"1".equals(tenantType)) {
            return null;
        }
        String contractPath = Db.queryStr("SELECT authorization_contract_path FROM crm_customer_yx_condition " +
                        "WHERE id_code=? and partner_id = ?",
                idCode, partnerId);
        if (StringUtil.isBlank(contractPath)) {
            return null;
        }
        return contractPath;

    }

    public String getContractPath(String tenantType, String idCode, String partnerId,String filingType) {
        if (!"1".equals(tenantType)) {
            return null;
        }
        String contractPath = Db.queryStr("SELECT authorization_contract_path FROM crm_customer_yx_condition " +
                        "WHERE id_code=? and partner_id = ? and filing_type = ?",
                idCode, partnerId,filingType);
        if (StringUtil.isBlank(contractPath)) {
            return null;
        }
        return contractPath;

    }


    /**
     * 提交进件申请---第一次进件
     //     * @param type 操作途径 1.开卡后自动推送  2.设计审核后推送
     */
    @Transactional(rollbackFor = Exception.class)
    public Result accessProjectApply(CustomerEntry entry,CrmTenantYxBankCard bankCard,Operator operator,String designId) {
        CrmPartner crmPartner = partnerService.getById(entry.getPartnerId());
        Result result = null;
        CrmCustomerIncomingApplication application = null;
        switch (entry.getPartnerId()) {
            case PartnerConstants.PARTNER_ID_YX:
                List<PrjProjectLeaseItem> prjProjectLeaseItemList = new ArrayList<>();
                if ("1".equals(entry.getFilingType())&&"1".equals(crmPartner.getIsOpenBankCard())) {
                    if (bankCard == null || StringUtil.isBlank(bankCard.getAccountCode())) {
                        throw new IllegalArgumentException("进件申请前，请先开通二类卡");
                    }
                }
                /**
                 * 关闭 预审通过之后自动进件逻辑
                 if("1".equals(type)){
                 Record pro = projectDao.getProject(entry.getProjectId());
                 PrjProjectLeaseItem leaseItem = new PrjProjectLeaseItem();
                 leaseItem.setPartnersLeaseItemId(entry.getId());
                 leaseItem.setFullName("光伏发电设备");
                 int spec=pro.getInt("assembly_specs")==null?660:pro.getInt("assembly_specs");//组件型号
                 leaseItem.setProductModel(String.valueOf(spec));

                 prjProjectLeaseItemList.add(leaseItem);
                 }else{
                 **/
                List<Record> componentList = new ArrayList<>();
                if (StringUtil.isBlank(designId)){
                    componentList = entryComponentDao.findByEntryId2(entry.getId());
                }else {
                    List<Record> records = customerEntryChangeDesignComponentDao.findByDesignId1(designId);
                    componentList = records.stream().filter(r-> "3".equals(r.getStr("item_type"))).collect(Collectors.toList());
                }
                for (Record r : componentList) {
                    PrjProjectLeaseItem leaseItem = new PrjProjectLeaseItem();
                    leaseItem.setPartnersLeaseItemId(entry.getId());
                    leaseItem.setFullName("光伏发电设备");
//            leaseItem.setProducer("逆变器生产商");
                    leaseItem.setProductModel(r.getStr("model"));//组件型号
                    Integer model = Integer.parseInt(r.getStr("model"));
                    Integer num = r.getInt("num");
                    leaseItem.setInstalledCapacity(model * num);//装机容量
                    leaseItem.setModuleQuantity(num);//组件数量
                    prjProjectLeaseItemList.add(leaseItem);
                }
//        }
                application = applicationDao.getIncomingApplication(entry);
                result = operatingLeaseService.accessProjectApply(entry,prjProjectLeaseItemList,bankCard,application);

                break;
            case PartnerConstants.PARTNER_ID_GF:

                application = applicationDao.getIncomingApplication(entry);
                result = guangfaOperatingService.accessProjectApply(entry, application);
                break;
            case PartnerConstants.PARTNER_ID_HR:
                if ("1".equals(entry.getFilingType())&&"1".equals(crmPartner.getIsOpenBankCard())) {
                    if (bankCard == null || StringUtil.isBlank(bankCard.getAccountCode())) {
                        throw new IllegalArgumentException("进件申请前，请先开通二类卡");
                    }
                }
                application = applicationDao.getIncomingApplication(entry);
                // howManyTimes 0：建档进件  1：第一次进件  3：建档审核资料上传完成
                result = huaRongApiService.accessProjectApply(entry, application, crmPartner,"0");
                if (!"200".equals(result.getCode())) {
                    return result;
                }
                //上传附件
                result = huaRongApiService.uploadFile(entry, application,"1", new HashSet<>());
                if ("200".equals(result.getCode())) {
                    //建档审核资料上传完成
                    result = huaRongApiService.accessProjectApply(entry, application, crmPartner,"3");
//                    if ("200".equals(result.getCode())) {
                        //一次进件
//                        result = huaRongApiService.accessProjectApply(entry, application, "1");
//                    }
                }
                break;
        }
        logger.info("第一次进件返回结果 code :{} msg:{}",result.getCode(),result.getMsg());
        if ("200".equals(result.getCode())) {
            entry.setFirstApplyStatus("NEW");
            application.setProjectStatus("NEW");
            if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
                entry.setFirstApplyStatus("FR");
                application.setProjectStatus("FR");
            }
            entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_JJSH);
            CustomerEntryOrgFiles files = null;
            if (!"1".equals(entry.getTenantType())) {
                files = orgFilesDao.findOneByEntryId(entry.getId());
            }
            application.setApplyTime(new Date());
            application.setStatus(entry.getApplyStatus());
            //上传进件资料
            if (PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())) {
                updateIncomingApplicationFile(entry, files, application.getPartnersContractNumber());
            }
            applicationDao.save(application);
            yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(), application.getPartnersContractNumber(), "2", "推送进件信息", operator);
            //判断是否有取消进件，但是状态还没有删除的，那么就要删除了
            //删除 status=a 已经取消进件，但是if_delete 还没变成删除 的进件
            applicationDao.updateIncomingIfDelete(entry.getId());
        } else {
            return result;
        }
        return Result.ok();
    }

    //华融 一次进件接口调用（正常流程调建档进件即可）
    public Result hrOneJJ(String entryId) {
        CustomerEntry entry = customerDao.get(entryId);
        CrmCustomerIncomingApplication application = applicationDao.getIncomingApplication(entry);
        CrmPartner partner = partnerService.getById(entry.getPartnerId());
        // howManyTimes 0：建档进件  1：第一次进件  3：建档审核资料上传完成
        Result result = huaRongApiService.accessProjectApply(entry, application, partner,"1");
        if (!"200".equals(result.getCode())) {
            return result;
        }
        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateFirstState(String entryId, String partnersContractNumber, String status, String firstMsg){
        Operator operator = Operator.of("1", "资方-广发", "资方");
        GFFirstStateKM innerState = Optional.ofNullable(GFFirstStateKM.externalOf(Integer.valueOf(status)))
                .orElse(null);
        if (Objects.isNull(innerState)) throw new RuntimeException(entryId+"无效状态:"+status);
        CustomerEntry entry = customerDao.get(entryId);

        CrmCustomerIncomingApplication incomingApplication = incomingApplicationDao.getByEntryId(entryId);
        incomingApplication.setStatus(innerState.getInternalCode().toString());
        incomingApplication.setProjectStatus(innerState.getCode());
        incomingApplication.setPartnersContractNumber(partnersContractNumber);
        incomingApplicationDao.save(incomingApplication);
        String applyStatus = null;
        String auditStatus = "0";
        if (innerState == GFFirstStateKM.Success){
            logger.info("进件审核通过 partnersContractNumber {}",partnersContractNumber);
            applyStatus = "6";
            auditStatus="2";
            Db.update(" insert into crm_customer_contract_management (id,status,entry_id,power_station_code,trader_id) values (?,?,?,?,?) ",IdGen.uuid(),ESignConstants.GF_CONTRACT_STATUS_WAITADD,entryId,entry.getPowerStationCode(),entry.getDistributorId());
            // 进件审核通过 进入待安装
            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.setSignStatus(ESignConstants.GF_CONTRACT_STATUS_WAITADD);
            }
            entry.setInComingTime(new Date());//进件时间：第一次进件审核通过时间
            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.ADVANCE_TYPE_INCOMING_TYPE_APPROVE);
        }else if(innerState == GFFirstStateKM.AuditFailed || innerState == GFFirstStateKM.Fail){
            applyStatus = "7";
            auditStatus="3";
            //第一次进件审核不通过，电站状态改为设计自审

            //判断是否需要设计自审
            if (!FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_SJZS)) {
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DSH);
                entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSTG);
                String stationName = CrmUtils.getStationName(entry);
                Date now = new Date();
                itemManageDao.addItem(FormUtils.ENTRY_STATUS_SJSH,entry.getId(),PlantformUtils.getOrderNumber(),"设计审核("+stationName+"-"+entry.getPowerStationCode()+")-"+DateUtils.formatDate(now,"yyyy-MM-dd HH:mm:ss"),now,operator.getUserName());
            } else {
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_KCZS);
                entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHBH);
            }
            entry.setApplyBackReason(firstMsg);


            msgService.saveCustomerEntryMsg(operator, entry.getId(),
                    CustomerEntryConstants.ADVANCE_TYPE_INCOMING_TYPE_FAIL,firstMsg,"");
        }
        if(!entry.getFirstApplyStatus().equals(innerState.getCode())){
            yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(),partnersContractNumber,"2","查询进件状态："+innerState.getName()+":"+firstMsg,operator);
        }
        if (StringUtil.isNotBlank(applyStatus)){
            entry.setApplyStatus(applyStatus);
        }
        entry.setFirstApplyStatus(innerState.getCode());
        customerDao.save(entry);
        CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"2",status,"0",auditStatus,firstMsg);
    }
    @Transactional(rollbackFor = Exception.class)
    public Result updateHRFiles(CustomerEntry entry, CrmCustomerIncomingApplication application,
                                Operator operator, String fileCode) {
        CrmPartner partner = partnerService.getById(entry.getPartnerId());
        Set<String> fileCodeS = new HashSet<>();
//        CrmYxIncomingProcess process =crmYxIncomingProcessDao.getProcess(entry.getId(),"2");
//        if (process == null || StringUtil.isBlank(process.getRemarks()) ) {
//            return Result.fail("未获取到待补充附件编码");
//        }
//        String remarks = process.getRemarks();
//        if (remarks.length() <= 8) {
//            return Result.fail("未获取到待补充附件编码");
//        }
//        remarks = remarks.substring(8);
//        for (String str : remarks.split(",")) {
//            if (StringUtil.isNotBlank(str)) {
//                fileCodeS.add(PartnerConstants.queryHrFileCode(str));
//            }
//        }
        fileCodeS.addAll(Arrays.asList(fileCode.split(",")));
        Result result = huaRongApiService.uploadFile(entry, application,"1", fileCodeS);
        if ("200".equals(result.getCode())) {
            //建档审核资料上传完成
            result = huaRongApiService.accessProjectApply(entry, application, partner, "3");
        }
        if ("200".equals(result.getCode())) {
            entry.setFirstApplyStatus("FR");
            entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_JJSH);
            application.setStatus("5");
            applicationDao.save(application);
            yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(), application.getPartnersContractNumber(), "2", "建档补充资料", operator);
            CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"2","FR","0","1","建档审核中");
            msgService.saveCustomerEntryMsg(operator,entry.getId(), CustomerEntryConstants.ENTRY_HR_JDBCZL);
            applicationDao.updateIncomingIfDelete(entry.getId());
            customerDao.save(entry);
        } else {
            return result;
        }
        return Result.ok();
    }
    @Transactional(rollbackFor = Exception.class)
    public Result updateHRBWFiles(CustomerEntry entry, CrmCustomerIncomingApplication application,
                                Operator operator, String fileCode) {
        CrmPartner partner = partnerService.getById(entry.getPartnerId());
        Set<String> fileCodeS = new HashSet<>();
        fileCodeS.addAll(Arrays.asList(fileCode.split(",")));
        Result result = huaRongApiService.uploadFile(entry, application,"3", fileCodeS);
        if ("200".equals(result.getCode())) {
            //并网资料上传完成
            result = huaRongApiService.accessProjectApply(entry, application, partner, "2");
        }
        if ("200".equals(result.getCode())) {
            entry.setNextApplyStatus("MR");
            entry.setGridPushTime(new Date());
            entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_BWSHZ);
            application.setStatus(CustomerEntryConstants.APPLY_STATUS_BWSHZ);
            applicationDao.save(application);
            yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(), application.getPartnersContractNumber(), "5", "补充并网资料", operator);
            CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"5","MR","0","1","人工审核中");
            msgService.saveCustomerEntryMsg(operator,entry.getId(), CustomerEntryConstants.ENTRY_HR_BWBCZL);
            customerDao.save(entry);
        } else {
            return result;
        }
        return Result.ok();
    }

    public Result uploadHRAllFile (CustomerEntry entry, CrmCustomerIncomingApplication application ){
        Result result = huaRongApiService.uploadFile(entry, application,"3", new HashSet<>());
        return result;
    }
    @Transactional(rollbackFor = Exception.class)
    public void updateFirstStateHuaRong(String entryId,HuaRongCustomer customer){
        Operator operator = Operator.of("1", "资方-华融", "-1");
        String projectStatus = customer.getProjectStatus();
        String reqContNumber  = customer.getReqContNumber();
        CustomerEntry entry = customerDao.get(entryId);
        HRFirstStateKM innerState = Optional.ofNullable(HRFirstStateKM.externalOf(projectStatus))
                .orElse(null);
        if (Objects.isNull(customer.getProjectStatus())) throw new RuntimeException(reqContNumber+"无效状态:"+projectStatus);
        CrmCustomerIncomingApplication incomingApplication = incomingApplicationDao.getByEntryId(entryId);
        incomingApplication.setProjectStatus(innerState.getCode());
        incomingApplication.setStatus(innerState.getInternalCode().toString());
        /**
         * applyStatus 4.待进件  5.进件审核中  6.进件审核成功 7.进件审核驳回 24.建档待补充资料
         * auditStatus 审核状态 0.待审核 1.审核中 2.审核通过 3.审核不通过
         */
        String auditStatus = "0";
        if (innerState == HRFirstStateKM.Success){//一次进件审核通过
            //如果有合同重签的情况，那么要删除之前的合同，重签合同的合同编码和之前是不一样的
           // contractManagementDao.changeHistoryContractStatus(reqContNumber);
            auditStatus="2";
            /*CrmCustomerContractManagement contractManagement = new CrmCustomerContractManagement();
            contractManagement.setStatus(ESignConstants.GF_CONTRACT_STATUS_DSC);
            contractManagement.setEntryId(entryId);
            contractManagement.setPowerStationCode(entry.getPowerStationCode());
            contractManagement.setTraderId(entry.getDistributorId());
            contractManagement.setPartnersContractNumber(reqContNumber);
            contractManagement.setProjectCompanyId(entry.getProjectCompanyId());
            contractManagement.setProjectCompanyName(entry.getProjectCompanyName());
            contractManagement.setTenantMobile(entry.getMobile());
            contractManagement.setInvitationId(operator.getUserId());
            contractManagement.setInvitationName(operator.getUserName());
            contractManagement.setInvitationTime(new Date());
            contractManagementDao.save(contractManagement);*/

            // 进件审核通过 进入待安装
            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);
            if(CustomerEntryConstants.TENANT_TYPE_PERSON.equals(entry.getTenantType())){  //个人
                //根据进件序号，如果该进件没有合同，那么需要邀请签约合同
                CrmCustomerContractManagement contractManagement=contractManagementDao.getContract(entry.getId());
                if(contractManagement==null){
                    CrmPartner partner = partnerService.getById(entry.getPartnerId());
                    if("1".equals(partner.getIfSignContract()) && entry.getProjectNum() == 1){  //是否开启在线签署模式：1.开启 2.关闭（该设置主要针对华融合同）
                        contractESignSignService.InviteSign(reqContNumber,entry,operator,"首次进件审核通过",null,null);
                    /*//目前首次进件后不主动发起合同，生成一条合同记录，等点击发起合同后，才创建合同
                    //生成待发起的合同
                    StringBuffer sf = new StringBuffer();
                    sf.append(" INSERT INTO crm_customer_contract_management(id,entry_id,power_station_code,trader_id,STATUS,update_time,partners_contract_number,invitation_time) ");
                    sf.append(" VALUES(?,?,?,?,'6',NOW(),?,NOW()) ");
                    int i = Db.update(sf.toString(), IdGen.uuid(), entry.getId(), entry.getPowerStationCode(), entry.getDistributorId(),reqContNumber);
                    logger.info("华融首次进件审核通过  add:{}", i);
                    entry.setSignStatus(CustomerEntryConstants.SIGN_STATUS_WAIT_CREATE);*/
                    }else{ //合同上传的模式
                        StringBuffer sf = new StringBuffer();
                        sf.append(" INSERT INTO crm_customer_contract_management(id,entry_id,power_station_code,trader_id,STATUS,update_time,partners_contract_number," +
                                "invitation_time,project_company_id,project_company_name,tenant_mobile,tenant_name,id_code,tenant_address ) ");
                        sf.append(" VALUES(?,?,?,?,'f',NOW(),?,NOW(),?,?,?,?,?,? )");
                        int i = Db.update(sf.toString(), IdGen.uuid(), entry.getId(), entry.getPowerStationCode(), entry.getDistributorId(),reqContNumber,
                                entry.getProjectCompanyId(),entry.getProjectCompanyName(),entry.getMobile(),entry.getTenantName(),entry.getIdCode(),entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress());
                        logger.info("华融首次进件审核通过  add:{}", i);
                        entry.setSignStatus(ESignConstants.GF_CONTRACT_STATUS_DSC);
                    }

                }else {
                    String address = entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress();
                    if (!entry.getTenantName().equals(contractManagement.getTenantName()) || !entry.getIdCode().equals(contractManagement.getIdCode())
                    || !entry.getMobile().equals(contractManagement.getTenantMobile()) || !address.equals(contractManagement.getTenantAddress())
                    ){
                        contractManagement.setStatus("0");
                        contractManagement.setReason("客户信息发生变化导致合同重签");
                        contractManagement.setUpdateTime(new Date());
                        contractManagementDao.save(contractManagement);
                        CrmPartner partner = partnerService.getById(entry.getPartnerId());
                        StringBuilder content = new StringBuilder();
                        content.append("首次进件审核通过，客户信息发生变化导致合同重签。");
                        if (!entry.getTenantName().equals(contractManagement.getTenantName())){
                            content.append("变更姓名：变更前：").append(contractManagement.getTenantName());
                            content.append("，变更后：").append(entry.getTenantName()).append("；");
                        }
                        if (!entry.getIdCode().equals(contractManagement.getIdCode())){
                            content.append("变更身份证号：变更前：").append(contractManagement.getIdCode());
                            content.append("，变更后：").append(entry.getIdCode()).append("；");
                        }
                        if (!entry.getMobile().equals(contractManagement.getTenantMobile()) ){
                            content.append("变更手机号：变更前：").append(contractManagement.getTenantMobile());
                            content.append("，变更后：").append(entry.getMobile()).append("；");
                        }
                        if (!address.equals(contractManagement.getTenantAddress() )){
                            content.append("变更地址：变更前：").append(contractManagement.getTenantAddress() );
                            content.append("，变更后：").append(address).append("；");
                        }
                        if("1".equals(partner.getIfSignContract()) && entry.getProjectNum() == 1){  //是否开启在线签署模式：1.开启 2.关闭（该设置主要针对华融合同）
                            contractESignSignService.InviteSign(incomingApplication.getPartnersContractNumber(),entry,operator,content.toString(),null,null);
                        }else{ //合同上传的模式
                            StringBuffer sf = new StringBuffer();
                            sf.append(" INSERT INTO crm_customer_contract_management(id,entry_id,power_station_code,trader_id,STATUS,update_time,partners_contract_number," +
                                    "invitation_time,project_company_id,project_company_name,tenant_mobile,tenant_name,id_code,tenant_address ) ");
                            sf.append(" VALUES(?,?,?,?,'f',NOW(),?,NOW(),?,?,?,?,?,? )");
                            int i = Db.update(sf.toString(), IdGen.uuid(), entry.getId(), entry.getPowerStationCode(), entry.getDistributorId(),reqContNumber,
                                    entry.getProjectCompanyId(),entry.getProjectCompanyName(),entry.getMobile(),entry.getTenantName(),entry.getIdCode(),entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress());
                            entry.setSignStatus(ESignConstants.GF_CONTRACT_STATUS_DSC);
                            msgService.saveEntryMsg(operator, entry.getId(), CustomerEntryConstants.SIGN_INVITE,content.toString());
                        }
                        logger.info(">>>>进件审核通过  客户信息发生变化引起了合同重签");
                    }
                }
            }

        } else if (innerState == HRFirstStateKM.AuditFailed2) {//建档待补充资料
            auditStatus="3";
            entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_KCZS);
            entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHBH);
            String hrContent = huaRongManagementService.getHRContent(customer);
            entry.setApplyBackReason(hrContent);
            msgService.saveCustomerEntryMsg(operator, entry.getId(),CustomerEntryConstants.ADVANCE_TYPE_INCOMING_TYPE_FAIL,hrContent,"");
        } else if (innerState == HRFirstStateKM.AuditFailed) {//拒绝
            auditStatus="3";
            //第一次进件审核不通过，电站状态改为设计自审
            //拒绝的需要重新生成进件序号
            Long maxVersion=incomingApplicationDao.getMaxVersion(entry.getPartnerId());
            String partnersContractNumber= CustomerEntryUtil.addZero(CustomerEntryUtil.getJJPrefix(entry.getPartnerId()),maxVersion+1);
            incomingApplication.setPartnersContractNumber(partnersContractNumber);
            incomingApplication.setVersion(maxVersion+1);
            //判断是否需要设计自审
            if (!FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_SJZS)) {
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DSH);
                entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSTG);
                String stationName = CrmUtils.getStationName(entry);
                Date now = new Date();
                itemManageDao.addItem(FormUtils.ENTRY_STATUS_SJSH,entry.getId(),PlantformUtils.getOrderNumber(),"设计审核("+stationName+"-"+entry.getPowerStationCode()+")-"+DateUtils.formatDate(now,"yyyy-MM-dd HH:mm:ss"),now,operator.getUserName());
            } else {
                entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_KCZS);
                entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHBH);
            }
            if (StringUtil.isNotBlank(customer.getReturnReason())) {
                entry.setApplyBackReason(customer.getReturnReason());
            }
            String remarks = customer.getReturnReason();
            msgService.saveCustomerEntryMsg(operator, entry.getId(),CustomerEntryConstants.ADVANCE_TYPE_INCOMING_TYPE_FAIL,remarks,"");
        }else if (innerState == HRFirstStateKM.Pending){//数据不存在

        }else if (innerState == HRFirstStateKM.Fail){//废止
            auditStatus="3";

        }else {//审核中
            auditStatus="1";
        }
        if (!innerState.getCode().equals(entry.getFirstApplyStatus())){
            yxIncomingLogDao.addCrmYxIncomingLog(entryId,reqContNumber,"2","查询进件状态,"+huaRongManagementService.getHRContent(customer),operator);
        }
        entry.setFirstApplyStatus(innerState.getCode());
        entry.setApplyStatus(innerState.getInternalCode().toString());
        if(innerState == HRFirstStateKM.Fail){
            entry.setApplyStatus("a");
        }
        customerDao.save(entry);
        incomingApplicationDao.save(incomingApplication);
        CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"2",projectStatus,"0",auditStatus,huaRongManagementService.getHRContent(customer));
    }

    /**
     * 提交进件申请---第二次进件
     */
    @Transactional(rollbackFor = Exception.class)
    public Result accessProjectApplySec(CustomerEntry entry, Operator operator) {
        CrmCustomerIncomingApplication application = applicationDao.getByEntryId(entry.getId());

        Result result = null;
        switch (entry.getPartnerId()) {
            case PartnerConstants.PARTNER_ID_YX:
                List<Map<String, Object>> prjProjectLeaseItemList = new ArrayList<>();
                List<Map<String, String>> moduleList = new ArrayList<>();

                String jjNumber = application.getPartnersContractNumber();
                String partnersLeaseItemId = entry.getId();
                if (jjNumber.contains("YX-NHKJ")) {
                    partnersLeaseItemId = jjNumber;
                }

                Map<String, Object> leaseItem = new HashMap<>();
                leaseItem.put("partnersLeaseItemId", partnersLeaseItemId);
                Map<String, String> moduleMap = PartnerBrandUtils.getBrandList("3", PartnerConstants.PARTNER_ID_YX);
                // 查询使用组件
                List<Record> modules = entryDao.findModuleByEntryId(entry.getId());
                for (Record r : modules) {
                    leaseItem.put("productModel", r.getStr("spec"));
                    Integer model = Integer.parseInt(r.getStr("spec"));
                    Integer num = r.getBigDecimal("amount").intValue();
                    leaseItem.put("installedCapacity", model * num);
                    leaseItem.put("moduleQuantity", num);
                    // 组件生产商
                    leaseItem.put("moduleProducer", moduleMap.get(r.getStr("brand")));
                }
                Map<String, String> inverterMap = PartnerBrandUtils.getBrandList("1", PartnerConstants.PARTNER_ID_YX);
                String inverterModel = "";
                String inverterNumber = "";
                // 查询使用组件
                List<Record> inverters = entryDao.findInverterByEntryId(entry.getId());
                for (Record r : inverters) {
                    String model = r.getStr("model");
                    if (StringUtil.isBlank(model)) {
                        model = r.getStr("material_model");
                    }
                    // 逆变器规格型号
                    if (StringUtil.isBlank(inverterModel)) {
                        inverterModel = model;
                    } else {
                        inverterModel = inverterModel + "," + model;
                    }
                    // 逆变器编码
                    if (StringUtil.isBlank(inverterNumber)) {
                        inverterNumber = r.getStr("barcode");
                    } else {
                        inverterNumber = inverterNumber + "," + r.getStr("barcode");
                    }
                    // 逆变器品牌
                    leaseItem.put("inverterBrand", inverterMap.get(r.getStr("brand")));
                }
                leaseItem.put("inverterModel", inverterModel);
                leaseItem.put("inverterNumber", inverterNumber);
                List<Record> list2 = entryDao.findNewMostSpecByEntryId3(entry.getId());
                for (Record r : list2) {
                    if ("组件".equals(r.getStr("type"))) {
                        Map<String, String> moduleCode = new HashMap<>();
                        moduleCode.put("moduleCode", r.getStr("barcode"));
                        moduleList.add(moduleCode);
                    }
                }

                leaseItem.put("moduleList", moduleList);
                prjProjectLeaseItemList.add(leaseItem);
                result = operatingLeaseService.accessProjectApplyTwo(entry, prjProjectLeaseItemList, application);
                break;
            case PartnerConstants.PARTNER_ID_GF:
                result = guangfaOperatingService.accessProjectApplyTwo(entry,application);
                break;
        }

        if ("200".equals(result.getCode())) {
            entry.setNextApplyStatus("NEW");
            if(entry.getPartnerId().equals(PartnerConstants.PARTNER_ID_GF)){
                entry.setNextApplyStatus("20");
            }
            entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_WGSH);
            application.setFarmerSignStatus(entry.getNextApplyStatus());
            application.setStatus(entry.getApplyStatus());
            applicationDao.save(application);
            if(entry.getPartnerId().equals(PartnerConstants.PARTNER_ID_YX)) {
                //上传进件资料
                updateSecoundFile(entry, application.getPartnersContractNumber());
            }
            yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(), application.getPartnersContractNumber(), "4", "推送完工资料信息", operator);
        } else {
            return result;
        }
        return Result.ok();
    }

    //第一次进件资料上传 已调整 wwj 2.3
    public Result updateIncomingApplicationFile(CustomerEntry entry, CustomerEntryOrgFiles files, String partnersContractNumber) {
        List<FinanceProjectFile> fileList = new ArrayList<>();
        // 自然人
        if ("1".equals(entry.getTenantType())) {
            FinanceProjectFile projectFile1 = new FinanceProjectFile();
            projectFile1.setFileName("身份证正面.jpg");
            projectFile1.setFileCode(FileCodeConstants.GR_FILE_B_01);
            projectFile1.setFileAddress(commonStaticImgPath + entry.getIdCardFront());
            fileList.add(projectFile1);

            FinanceProjectFile projectFile2 = new FinanceProjectFile();
            projectFile2.setFileName("身份证反面.jpg");
            projectFile2.setFileCode(FileCodeConstants.GR_FILE_B_02);
            projectFile2.setFileAddress(commonStaticImgPath + entry.getIdCardBack());
            fileList.add(projectFile2);

            if (StringUtil.isNotBlank(entry.getResidenceBooklet())) {
                String[] arr = entry.getResidenceBooklet().split(",");
                int i = 1;
                for (String img : arr) {
                    if (StringUtil.isBlank(img)) {
                        continue;
                    }
                    FinanceProjectFile file = createFinanceProjectFile(i, img, "户口本复印件", FileCodeConstants.GR_FILE_B_03);
                    fileList.add(file);
                    i++;
                }
            }

            String contractPath = Db.queryStr("SELECT authorization_contract_path FROM crm_customer_yx_condition " +
                    "WHERE id_code=? and partner_id =? limit 1", entry.getIdCode(), entry.getPartnerId());
            FinanceProjectFile projectFile4 = new FinanceProjectFile();
            projectFile4.setFileName("信息使用授权书.pdf");
            projectFile4.setFileCode(FileCodeConstants.GR_FILE_B_04);
            projectFile4.setFileAddress(commonStaticImgPath + contractPath);
            fileList.add(projectFile4);

            FinanceProjectFile projectFile5 = new FinanceProjectFile();
            int filenameLeng5 = entry.getBankCard().lastIndexOf(".");
            String extName5 = entry.getBankCard().substring(filenameLeng5).toLowerCase();
            projectFile5.setFileName("银行卡" + extName5);
            projectFile5.setFileCode(FileCodeConstants.GR_FILE_B_05);
            projectFile5.setFileAddress(commonStaticImgPath + entry.getBankCard());
            fileList.add(projectFile5);

            if (entry.getAge() >= 65) {
                FinanceProjectFile projectFile6 = new FinanceProjectFile();
                int filenameLeng6 = entry.getBpCardFront().lastIndexOf(".");
                String extName6 = entry.getBpCardFront().substring(filenameLeng6).toLowerCase();
                projectFile6.setFileName("共签人身份证正面" + extName6);
                projectFile6.setFileCode(FileCodeConstants.GR_FILE_B_06);
                projectFile6.setFileAddress(commonStaticImgPath + entry.getBpCardFront());
                fileList.add(projectFile6);

                FinanceProjectFile projectFile7 = new FinanceProjectFile();
                int filenameLeng7 = entry.getBpCardBack().lastIndexOf(".");
                String extName7 = entry.getBpCardBack().substring(filenameLeng7).toLowerCase();
                projectFile7.setFileName("共签人身份证反面" + extName7);
                projectFile7.setFileCode(FileCodeConstants.GR_FILE_B_07);
                projectFile7.setFileAddress(commonStaticImgPath + entry.getBpCardBack());
                fileList.add(projectFile7);

                if (StringUtil.isNotBlank(entry.getBpFile())) {
                    String[] arr = entry.getBpFile().split(",");
                    int i = 1;
                    for (String img : arr) {
                        if (StringUtil.isBlank(img)) {
                            continue;
                        }
                        FinanceProjectFile file = createFinanceProjectFile(i, img, "共签人子女证明材料", FileCodeConstants.GR_FILE_B_08);
                        fileList.add(file);
                        i++;
                    }
                }
            }
        } else {
            FinanceProjectFile projectFile1 = new FinanceProjectFile();
            projectFile1.setFileName("统一社会信用代码证书.jpg");
            projectFile1.setFileCode(FileCodeConstants.DW_FILE_B_01);
            projectFile1.setFileAddress(commonStaticImgPath + files.getRegnoUrl());
            fileList.add(projectFile1);

            FinanceProjectFile projectFile2 = new FinanceProjectFile();
            projectFile2.setFileName("法定代表人身份证正面.jpg");
            projectFile2.setFileCode(FileCodeConstants.DW_FILE_B_02);
            projectFile2.setFileAddress(commonStaticImgPath + entry.getIdCardFront());
            fileList.add(projectFile2);

            FinanceProjectFile projectFile3 = new FinanceProjectFile();
            projectFile3.setFileName("法定代表人身份证反面.jpg");
            projectFile3.setFileCode(FileCodeConstants.DW_FILE_B_03);
            projectFile3.setFileAddress(commonStaticImgPath + entry.getIdCardBack());
            fileList.add(projectFile3);

            FinanceProjectFile projectFile4 = new FinanceProjectFile();
            projectFile4.setFileName("村民代表大会决议书.jpg");
            projectFile4.setFileCode(FileCodeConstants.DW_FILE_B_04);
            projectFile4.setFileAddress(commonStaticImgPath + files.getResolutionPaperUrl());
            fileList.add(projectFile4);

            if (StringUtil.isNotBlank(files.getYszcUrl())) {
                FinanceProjectFile projectFile5 = new FinanceProjectFile();
                projectFile5.setFileName("村委议事章程.jpg");
                projectFile5.setFileCode(FileCodeConstants.DW_FILE_B_05);
                projectFile5.setFileAddress(commonStaticImgPath + files.getYszcUrl());
                fileList.add(projectFile5);
            }

            FinanceProjectFile projectFile6 = new FinanceProjectFile();
            projectFile6.setFileName("对公账户信息.jpg");
            projectFile6.setFileCode(FileCodeConstants.DW_FILE_B_06);
            projectFile6.setFileAddress(commonStaticImgPath + files.getAccountInfoUrl());
            fileList.add(projectFile6);

            FinanceProjectFile projectFile7 = new FinanceProjectFile();
            projectFile7.setFileName("产权证明-集体土地使用证.jpg");
            projectFile7.setFileCode(FileCodeConstants.DW_FILE_B_07);
            projectFile7.setFileAddress(commonStaticImgPath + files.getOwnershipCertificateUrl());
            fileList.add(projectFile7);

            FinanceProjectFile projectFile8 = new FinanceProjectFile();
            projectFile8.setFileName("产权证明-不动产证书.jpg");
            projectFile8.setFileCode(FileCodeConstants.DW_FILE_B_08);
            projectFile8.setFileAddress(commonStaticImgPath + files.getOtherOwnershipCertificateUrl());
            fileList.add(projectFile8);
        }
        return operatingLeaseService.updateFile2(entry, fileList, "01", partnersContractNumber, "2");
    }

    public FinanceProjectFile createFinanceProjectFile(int i, String sizeImg, String fileName, String fileCode) {
        FinanceProjectFile projectFile = new FinanceProjectFile();
        int filenameLeng = sizeImg.lastIndexOf(".");
        String extName = sizeImg.substring(filenameLeng).toLowerCase();
        projectFile.setFileName(fileName + i + extName);
        projectFile.setFileCode(fileCode);
        projectFile.setFileAddress(commonStaticImgPath + sizeImg);
        return projectFile;
    }

    //第二次进件资料上传-农户投放审查 已调整 wwj 2.6
    public Result updateSecoundFile(CustomerEntry entry, String partnersContractNumber) {
        CrmAcceptingReport report = getReportById(entry.getReceivingReportId());
        // 查询勘测记录
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entry.getId());
        List<FinanceProjectFile> fileList = new ArrayList<>();
        if ("1".equals(entry.getTenantType())) {
            if (StringUtil.isNotBlank(surveyRecord.getHouseOwnership())) {
                String[] arr = surveyRecord.getHouseOwnership().split(",");
                int i = 1;
                for (String houseCardImg : arr) {
                    if (StringUtil.isBlank(houseCardImg)) {
                        continue;
                    }
                    FinanceProjectFile file = createFinanceProjectFile(i, houseCardImg, "房产证明文件", FileCodeConstants.GR_FILE_C_01);
                    fileList.add(file);
                    i++;
                }
            }
        }
        else {
            if (StringUtil.isNotBlank(report.getOtherImgs1())) {
                // 银行印鉴留样  other_imgs1
                String[] arr = report.getOtherImgs1().split(",");
                int i = 1;
                for (String img : arr) {
                    if (StringUtil.isBlank(img)) {
                        continue;
                    }
                    FinanceProjectFile file = createFinanceProjectFile(i, img, "银行印鉴留样", FileCodeConstants.DW_FILE_C_04);
                    fileList.add(file);
                    i++;
                }
            }
            if (StringUtil.isNotBlank(report.getOtherImgs2())) {
                // 签约现场照片-法定代表人/负责人签字照  other_imgs2
                String[] arr = report.getOtherImgs2().split(",");
                int i = 1;
                for (String img : arr) {
                    if (StringUtil.isBlank(img)) {
                        continue;
                    }
                    FinanceProjectFile file = createFinanceProjectFile(i, img, "签约现场照片-负责人签字照", FileCodeConstants.DW_FILE_C_05);
                    fileList.add(file);
                    i++;
                }
            }
            if (StringUtil.isNotBlank(report.getOtherImgs3())) {
                // 签约现场照片-正脸、持笔/持印、合同签署页同框  other_imgs3
                String[] arr = report.getOtherImgs3().split(",");
                int i = 1;
                for (String img : arr) {
                    if (StringUtil.isBlank(img)) {
                        continue;
                    }
                    FinanceProjectFile file = createFinanceProjectFile(i, img, "签约现场照片-正脸合同签署页同框", FileCodeConstants.DW_FILE_C_06);
                    fileList.add(file);
                    i++;
                }
            }
            if (StringUtil.isNotBlank(report.getOtherImgs4())) {
                // 签署完成照片  other_imgs4
                String[] arr = report.getOtherImgs4().split(",");
                int i = 1;
                for (String img : arr) {
                    if (StringUtil.isBlank(img)) {
                        continue;
                    }
                    FinanceProjectFile file = createFinanceProjectFile(i, img, "签署完成照片", FileCodeConstants.DW_FILE_C_07);
                    fileList.add(file);
                    i++;
                }
            }
        }
        /**
         * 基础安装、基础防水照片-设备信息照片
         * 电站基础-主屋	基础安装-租赁物相关照片  dzjc1
         * 电站基础-副屋	基础安装-租赁物相关照片  dzjc2
         * 航拍图照片	基础安装-租赁物相关照片  zj_img5
         * 自检记录报告	基础安装-租赁物相关照片  zj_report
         * 三级安全教育登记卡 safety_warning_img2
         * 安全防护措施文件 kg_condition_files
         */
        String codeFile02 = ("1".equals(entry.getTenantType()) ? FileCodeConstants.GR_FILE_C_02 : FileCodeConstants.DW_FILE_C_08);
        if (StringUtil.isNotBlank(report.getDzjc1())) {
            String[] arr = report.getDzjc1().split(",");
            int i = 1;
            for (String sizeImg : arr) {
                if (StringUtil.isBlank(sizeImg)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, sizeImg, "电站基础-主屋", codeFile02);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getSafetyWarningImg2())) {
            String[] arr = report.getSafetyWarningImg2().split(",");
            int i = 1;
            for (String sizeImg : arr) {
                if (StringUtil.isBlank(sizeImg)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, sizeImg, "三级安全教育登记卡", codeFile02);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getKgConditionFiles())) {
            String[] arr = report.getKgConditionFiles().split(",");
            int i = 1;
            for (String sizeImg : arr) {
                if (StringUtil.isBlank(sizeImg)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, sizeImg, "安全防护措施文件", codeFile02);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getDzjc2())) {
            int i = 1;
            String[] arr = report.getDzjc2().split(",");
            for (String sizeImg : arr) {
                if (StringUtil.isBlank(sizeImg)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, sizeImg, "电站基础-副屋", codeFile02);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getZjImg5())) {
            int i = 1;
            String[] arr = report.getZjImg5().split(",");
            for (String sizeImg : arr) {
                if (StringUtil.isBlank(sizeImg)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, sizeImg, "航拍图照片", codeFile02);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getZjReport())) {
            int i = 1;
            String[] arr = report.getZjReport().split(",");
            for (String sizeImg : arr) {
                if (StringUtil.isBlank(sizeImg)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, sizeImg, "自检记录报告", codeFile02);
                fileList.add(file);
                i++;
            }
        }

        /**
         * 支架安装照片
         * 支架正面照片	支架安装-租赁物相关照片  zj_img1
         * 支架侧视图	支架安装-租赁物相关照片  zj_img2
         * 支架北侧图	支架安装-租赁物相关照片  zj_img3
         * 支架型号照片	支架安装-租赁物相关照片  zj_img4
         * 支架与接地扁铁连接照片	支架安装-租赁物相关照片  jd_img3
         * 支架接地电阻照片	支架安装-租赁物相关照片  jd_img5
         */
        String codeFile03 = ("1".equals(entry.getTenantType()) ? FileCodeConstants.GR_FILE_C_03 : FileCodeConstants.DW_FILE_C_09);
        if (StringUtil.isNotBlank(report.getZjImg1())) {
            int i = 1;
            String[] arr = report.getZjImg1().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "支架正面照片", codeFile03);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getZjImg2())) {
            int i = 1;
            String[] arr = report.getZjImg2().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "支架侧视图", codeFile03);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getZjImg3())) {
            int i = 1;
            String[] arr = report.getZjImg3().split(",");
            for (String sizeImg : arr) {
                if (StringUtil.isBlank(sizeImg)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, sizeImg, "支架北侧图", codeFile03);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getZjImg4())) {
            int i = 1;
            String[] arr = report.getZjImg4().split(",");
            for (String sizeImg : arr) {
                if (StringUtil.isBlank(sizeImg)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, sizeImg, "支架型号照片", codeFile03);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getJdImg3())) {
            int i = 1;
            String[] arr = report.getJdImg3().split(",");
            for (String sizeImg : arr) {
                if (StringUtil.isBlank(sizeImg)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, sizeImg, "支架与接地扁铁连接照片", codeFile03);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getJdImg5())) {
            int i = 1;
            String[] arr = report.getJdImg5().split(",");
            for (String sizeImg : arr) {
                if (StringUtil.isBlank(sizeImg)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, sizeImg, "支架接地电阻照片", codeFile03);
                fileList.add(file);
                i++;
            }
        }

        /**
         * 组件安装：组件安装、整体照片
         * 组件倾角照片	组件安装-租赁物相关照片  component_img1
         * 组件方位角照片	组件安装-租赁物相关照片  component_img2
         * 组件铭牌照片	组件安装-租赁物相关照片   zj_plate_img
         * 组件与组件之间接地照片	组件安装-租赁物相关照片  jd_img1
         * 组件与支架接地照片	组件安装-租赁物相关照片  jd_img2
         * 补充视频  组件安装-租赁物相关照片 supplement_video_url
         */
        String codeFile4 = ("1".equals(entry.getTenantType()) ? FileCodeConstants.GR_FILE_C_04 : FileCodeConstants.DW_FILE_C_10);
        if (StringUtil.isNotBlank(report.getComponentImg1())) {
            int i = 1;
            String[] arr = report.getComponentImg1().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "组件倾角照片", codeFile4);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getComponentImg2())) {
            int i = 1;
            String[] arr = report.getComponentImg2().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "组件方位角照片", codeFile4);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getZjPlateImg())) {
            int i = 1;
            String[] arr = report.getZjPlateImg().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "组件铭牌照片", codeFile4);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getJdImg1())) {
            int i = 1;
            String[] arr = report.getJdImg1().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "组件与组件之间接地照片", codeFile4);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getJdImg2())) {
            int i = 1;
            String[] arr = report.getJdImg2().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "组件与支架接地照片", codeFile4);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getSupplementVideoUrl())) {
            int i = 1;
            String[] arr = report.getSupplementVideoUrl().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "补充视频", codeFile4);
                fileList.add(file);
                i++;
            }
        }

        /**
         * 配电、逆变器安装：直流电缆、电压测试、配电箱、接地、逆变器等照片
         * 屋顶线缆安装照片	配电、逆变器安装-租赁物相关照片  size_measure_imgs
         * 线缆下墙照片	配电、逆变器安装-租赁物相关照片  fix_other_img
         * 逆变器组串接入照片	配电、逆变器安装-租赁物相关照片  total_imgs
         * 并网箱内部照片	配电、逆变器安装-租赁物相关照片  bw_inner_img
         * 逆变器安装照片	配电、逆变器安装-租赁物相关照片  dc_imgs
         * 并网箱逆变器整体照片	配电、逆变器安装-租赁物相关照片  nbq_zb_img
         * 逆变器注册截图照片	配电、逆变器安装-租赁物相关照片  dqsb_an_img_one
         * 逆变器铭牌照片	配电、逆变器安装-租赁物相关照片  nbq_plate_img
         * 开路电压图	配电、逆变器安装-租赁物相关照片  open_way_voltage_imgs
         * 接地扁铁下墙照片	配电、逆变器安装-租赁物相关照片   jd_img4
         * 电气接地电阻照片	配电、逆变器安装-租赁物相关照片  jd_img6
         */
        String codeFile5 = ("1".equals(entry.getTenantType()) ? FileCodeConstants.GR_FILE_C_05 : FileCodeConstants.DW_FILE_C_11);
        if (StringUtil.isNotBlank(report.getSizeMeasureImgs())) {
            int i = 1;
            String[] arr = report.getSizeMeasureImgs().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "屋顶线缆安装照片", codeFile5);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getFixOtherImg())) {
            int i = 1;
            String[] arr = report.getFixOtherImg().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "线缆下墙照片", codeFile5);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getTotalImgs())) {
            int i = 1;
            String[] arr = report.getTotalImgs().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "逆变器组串接入照片", codeFile5);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getBwInnerImg())) {
            int i = 1;
            String[] arr = report.getBwInnerImg().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "并网箱内部照片", codeFile5);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getDcImgs())) {
            int i = 1;
            String[] arr = report.getDcImgs().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "逆变器安装照片", codeFile5);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getNbqZbImg())) {
            int i = 1;
            String[] arr = report.getNbqZbImg().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "并网箱逆变器整体照片", codeFile5);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getDqsbAnImgOne())) {
            int i = 1;
            String[] arr = report.getDqsbAnImgOne().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "逆变器注册截图照片", codeFile5);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getNbqPlateImg())) {
            int i = 1;
            String[] arr = report.getNbqPlateImg().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "逆变器铭牌照片", codeFile5);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getOpenWayVoltageImgs())) {
            int i = 1;
            String[] arr = report.getOpenWayVoltageImgs().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "开路电压图", codeFile5);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getJdImg4())) {
            int i = 1;
            String[] arr = report.getJdImg4().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "接地扁铁下墙照片", codeFile5);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(report.getJdImg6())) {
            int i = 1;
            String[] arr = report.getJdImg6().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) {
                    continue;
                }
                FinanceProjectFile file = createFinanceProjectFile(i, img, "电气接地电阻照片", codeFile5);
                fileList.add(file);
                i++;
            }
        }

//        其他补充-租赁物相关照片 非必填项 不传
//        String codeFile6 = ("1".equals(entry.getTenantType()) ? FileCodeConstants.GR_FILE_C_06 : FileCodeConstants.DW_FILE_C_16);

        // 勘测资料
        /**
         * 无人机航拍图	房屋外部-踏勘设计资料  flyImgs
         * 安装区域整体照片(1-4张)	房屋外部-踏勘设计资料  roofPhotoOne
         * 安装区域东南角照片（1·4张）	房屋外部-踏勘设计资料  roofPhotoTwo
         * 安装区域西南角照片（1·4张）	房屋外部-踏勘设计资料  roofPhotoThree
         * 安装区域正南照片（1·4张）	房屋外部-踏勘设计资料  roofPhotoFour
         * 安装区域细节照片（1·4张）	房屋外部-踏勘设计资料  roofPhotoFive
         * 逆变器、配电箱预安装位置照片	房屋外部-踏勘设计资料  detailSupplementOne
         * 房屋其他障碍物照片	房屋外部-踏勘设计资料  houseSupplementOne
         */
        String codeFile9 = ("1".equals(entry.getTenantType()) ? FileCodeConstants.GR_FILE_C_09 : FileCodeConstants.DW_FILE_C_12);
        if (StringUtil.isNotBlank(surveyRecord.getFlyImgs())) {
            int i = 1;
            String[] arr = surveyRecord.getFlyImgs().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) continue;
                FinanceProjectFile file = createFinanceProjectFile(i, img, "房屋外部-无人机航拍图", codeFile9);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(surveyRecord.getRoofPhotoOne())) {
            int i = 1;
            String[] arr = surveyRecord.getRoofPhotoOne().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) continue;
                FinanceProjectFile file = createFinanceProjectFile(i, img, "房屋外部-安装区域整体照片", codeFile9);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(surveyRecord.getRoofPhotoTwo())) {
            int i = 1;
            String[] arr = surveyRecord.getRoofPhotoTwo().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) continue;
                FinanceProjectFile file = createFinanceProjectFile(i, img, "房屋外部-安装区域东南角照片", codeFile9);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(surveyRecord.getRoofPhotoThree())) {
            int i = 1;
            String[] arr = surveyRecord.getRoofPhotoThree().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) continue;
                FinanceProjectFile file = createFinanceProjectFile(i, img, "房屋外部-安装区域西南角照片", codeFile9);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(surveyRecord.getRoofPhotoFour())) {
            int i = 1;
            String[] arr = surveyRecord.getRoofPhotoFour().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) continue;
                FinanceProjectFile file = createFinanceProjectFile(i, img, "房屋外部-安装区域正南照片", codeFile9);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(surveyRecord.getRoofPhotoFive())) {
            int i = 1;
            String[] arr = surveyRecord.getRoofPhotoFive().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) continue;
                FinanceProjectFile file = createFinanceProjectFile(i, img, "房屋外部-安装区域细节照片", codeFile9);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(surveyRecord.getDetailSupplementOne())) {
            int i = 1;
            String[] arr = surveyRecord.getDetailSupplementOne().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) continue;
                FinanceProjectFile file = createFinanceProjectFile(i, img, "房屋外部-逆变器配电箱预安装位置照片", codeFile9);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(surveyRecord.getHouseSupplementOne())) {
            int i = 1;
            String[] arr = surveyRecord.getHouseSupplementOne().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) continue;
                FinanceProjectFile file = createFinanceProjectFile(i, img, "房屋外部-房屋其他障碍物照片", codeFile9);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(surveyRecord.getSurveyFiles())) {
            int i = 1;
            String[] arr = surveyRecord.getSurveyFiles().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) continue;
                FinanceProjectFile file = createFinanceProjectFile(i, img, "踏勘记录文件", codeFile9);
                fileList.add(file);
                i++;
            }
        }

        /**
         * 房屋内部环境照片	房屋内部-踏勘设计资料  roofPhotoInterior
         * 房屋内部结构照片	房屋内部-踏勘设计资料  roofPhotoFacade
         */
        String codeFile10 = ("1".equals(entry.getTenantType()) ? FileCodeConstants.GR_FILE_C_10 : FileCodeConstants.DW_FILE_C_13);
        if (StringUtil.isNotBlank(surveyRecord.getRoofPhotoInterior())) {
            int i = 1;
            String[] arr = surveyRecord.getRoofPhotoInterior().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) continue;
                FinanceProjectFile file = createFinanceProjectFile(i, img, "房屋内部环境照片", codeFile10);
                fileList.add(file);
                i++;
            }
        }
        if (StringUtil.isNotBlank(surveyRecord.getRoofPhotoFacade())) {
            int i = 1;
            String[] arr = surveyRecord.getRoofPhotoFacade().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) continue;
                FinanceProjectFile file = createFinanceProjectFile(i, img, "房屋内部结构照片", codeFile10);
                fileList.add(file);
                i++;
            }
        }

        String codeFile11 = ("1".equals(entry.getTenantType()) ? FileCodeConstants.GR_FILE_C_11 : FileCodeConstants.DW_FILE_C_14);
        if (StringUtil.isNotBlank(entry.getDesignDrawings())) {
            int i = 1;
            String[] arr = entry.getDesignDrawings().split(",");
            for (String img : arr) {
                if (StringUtil.isBlank(img)) continue;
                FinanceProjectFile file = createFinanceProjectFile(i, img, "设计图纸", codeFile11);
                fileList.add(file);
                i++;
            }
        }
//        FinanceProjectFile projectFile11_1 = new FinanceProjectFile();
//        int filenameLeng11_1 = entry.getDesignDrawings().lastIndexOf(".");
//        String extName11_1 = entry.getDesignDrawings().substring(filenameLeng11_1).toLowerCase();
//        projectFile11_1.setFileName("设计图纸1" + extName11_1);
//        projectFile11_1.setFileCode(codeFile11);
//        projectFile11_1.setFileAddress(commonStaticImgPath+entry.getDesignDrawings());
//        fileList.add(projectFile11_1);

//        if(StringUtil.isNotBlank(entry.getDzImgs())){
//            int i=1;
//            String[] arr= entry.getDzImgs().split(",");
//            for(String img:arr){
//                if(StringUtil.isBlank(img)) continue;
//                FinanceProjectFile file = createFinanceProjectFile(i, img, "设计图纸2-", codeFile11);
//                fileList.add(file);
//                i++;
//            }
//        }

//        if (StringUtil.isNotBlank(entry.getHouseOwnership())) {
//            FinanceProjectFile projectFile12 = new FinanceProjectFile();
//            int filenameLeng12 = entry.getHouseOwnership().lastIndexOf(".");
//            String extName12 = entry.getHouseOwnership().substring(filenameLeng12).toLowerCase();
//            projectFile12.setFileName("风险审查补充资料." + extName12);
//            projectFile12.setFileCode("HTY_C_12");
//            projectFile12.setFileAddress(commonStaticImgPath+entry.getHouseOwnership());
//            fileList.add(projectFile12);
//        }

        logger.info(">>>>>>>>>>>完工资料推送 {}", fileList.size());
        return operatingLeaseService.updateFile2(entry, fileList, "01", partnersContractNumber, "3");
    }

    /*public Result powerSellFilePush(CustomerEntry entry) {
        //租凭物信息
        List<Map<String,Object>> prjProjectLeaseItemList = new ArrayList<>();
        // 查询使用的物料
        List<Record> list = entryDao.findNewMostSpecByEntryId2(entry.getId());
        Map<String,Object> leaseItem = new HashMap<>();
        leaseItem.put("partnersLeaseItemId",entry.getId());
        leaseItem.put("addressConsistent","Y");
        for (Record r : list) {
            if ("逆变器".equals(r.getStr("type"))) {
                leaseItem.put("inverterNumber",r.getStr("barcode"));
            } else {
                leaseItem.put("productModel",r.getStr("spec"));
            }
        }
        prjProjectLeaseItemList.add(leaseItem);

        //文件信息
        List<FinanceProjectFile> fileList = new ArrayList<>();
        FinanceProjectFile projectFile = new FinanceProjectFile();
        int filenameLeng = entry.getContract().lastIndexOf(".");
        String extName = entry.getContract().substring(filenameLeng).toLowerCase();
        projectFile.setFileName("购售电合同."+extName);
        projectFile.setFileCode("NH_D_01");
        projectFile.setFileAddress(commonStaticImgPath+entry.getContract());
        fileList.add(projectFile);

        return operatingLeaseService.powerSellFilePush(entry,prjProjectLeaseItemList,fileList);
    }*/

    public String findYxBankConditionCode(String idCode, String mobile, String partner_id) {
        return customerDao.findYxBankConditionCode(idCode, mobile, partner_id);
    }

    // 设计自审退回
    @Transactional(rollbackFor = Exception.class)
    public void auditBack(AuditOperateReq req,User user) {
        String id = req.getId();
        CustomerEntry entry = customerDao.get(id);
        if (!CustomerEntryConstants.DESIGN_AUDIT_FLAG_DZS.equals(entry.getDesignAuditFlag())
         && !CustomerEntryConstants.DESIGN_AUDIT_FLAG_SJSHBH.equals(entry.getDesignAuditFlag()) ){
            throw new IllegalArgumentException("自审已操作，请先刷新列表");
        }
        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), id);
        if (StringUtil.isNotBlank(checkApplyResult)) {
            throw new IllegalArgumentException(checkApplyResult);
        }
        // 驳回节点：1.待勘测 2.待设计  默认到待勘测
        String type = (StringUtil.isBlank(req.getType()) ? "1" : req.getType());
        String designAuditFlag = ("1".equals(type) ? CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK : CustomerEntryConstants.DESIGN_AUDIT_FLAG_DSJ);
        customerDao.updateStatusById(id, CustomerEntryConstants.ENTRY_STATUS_ZC);
        customerDao.updateDesignAuditFlagById(id, StringUtil.isBlank(req.getAuditRemarks())?req.getZsAuditRemarks():req.getAuditRemarks(), designAuditFlag);
        String zsResult = ("1".equals(type) ? "2" : "3"); // 自审结果：0.无 1.通过 2.驳回至勘测 3.驳回至设计
        customerDao.updateZsResultById(id, zsResult);
        String content = "设计自审退回" + ("1".equals(type) ? "勘测" : "设计") + ",审核备注：" + ( StringUtil.isBlank(req.getAuditRemarks()) ? req.getZsAuditRemarks():req.getAuditRemarks() )+ ";";
        msgService.saveCustomerEntryMsg(user, id, CustomerEntryConstants.DESIGN_SELF_AUDIT_REFUSE, content);
    }

    // 设计自审通过
    @Transactional(rollbackFor = Exception.class)
    public void batchOneselfAudit(BatchOperateReq req) {
        User user = UserUtils.getUser();
        Operator operator = CrmUtils.getOperatorByTwo(user.getId());
        String auditRemarks = "";
        String content = "设计自审通过";
        if (StringUtil.isNotBlank(req.getAuditRemarks())) {
            auditRemarks = req.getAuditRemarks();
            content += ",审核备注：" + req.getAuditRemarks();
        }
        content += ";";
        Date date = new Date();
        for (String id : req.getIds()) {
            customerDao.updateStatusById(id, CustomerEntryConstants.ENTRY_STATUS_DSH);
            customerDao.updateDesignAuditFlagById(id, auditRemarks, CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSTG);
            msgService.saveCustomerEntryMsg(user, id, CustomerEntryConstants.DESIGN_SELF_AUDIT_PASS, content);

            //判断是否需要设计审核
            CustomerEntry entry = customerDao.get(id);
            if (!FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_SJSH)) {
                toExamine(entry.getId(), entry.getExamineRemarks(), operator, user);
            } else {
                String stationName = CrmUtils.getStationName(entry);
                itemManageDao.addItem(FormUtils.ENTRY_STATUS_SJSH, entry.getId(), PlantformUtils.getOrderNumber(), "设计审核(" + stationName + "-" + entry.getPowerStationCode() + ")-" + DateUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss"), date, operator.getUserName());
            }
        }
    }

    //安装自审通过
    @Transactional(rollbackFor = Exception.class)
    public void acceptZS(String id,User user) {
        //需要安装验收 ，那么生成安装验收的任务
        CustomerEntry customerEntry = customerDao.get(id);
        if (!StringUtil.equalsAny(customerEntry.getStatus(),
                CustomerEntryConstants.ENTRY_STATUS_AZYSTH,CustomerEntryConstants.ENTRY_STATUS_AZZS)) {
            throw new IllegalArgumentException("自审已操作，请先刷新列表");
        }
        String checkExistApply = CrmUtils.checkExistApply(customerEntry.getStatus(), customerEntry.getId());
        if (StringUtil.isNotBlank(checkExistApply)) {
            throw new IllegalArgumentException(checkExistApply);
        }
//        customerDao.updateStatusById(id,CustomerEntryConstants.ENTRY_STATUS_DAZYS);
        customerEntry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DAZYS);
//        customerDao.updateCheckAcceptFlagById(id, CustomerEntryConstants.CHECK_ACCEPT_FLAG_ZSTG);
        customerEntry.setCheckAcceptFlag(CustomerEntryConstants.CHECK_ACCEPT_FLAG_ZSTG);
        msgService.saveCustomerEntryMsg(user, id, CustomerEntryConstants.INSTALL_SELF_AUDIT_PASS, "安装自审通过；");
        Date now = new Date();
        //安装自审通过时间
        if (customerEntry.getInstallAuditFinishTime() == null) {
            customerEntry.setInstallAuditFinishTime(now);
        }
        customerDao.save(customerEntry);
        String stationName = CrmUtils.getStationName(customerEntry);
        ItemManage itemManage = itemManageDao.addItem(FormUtils.ENTRY_STATUS_AZYS,id, PlantformUtils.getOrderNumber(),"安装验收("+stationName+"-"+customerEntry.getPowerStationCode()+")-"+DateUtils.formatDate(now,"yyyy-MM-dd HH:mm:ss"),now,user.getUserName());
        //大代理商优先审核
        String groupName = "安装审核";
        crmPriorReviewSettingService.traderPriorityReview(customerEntry.getCreateTraderId(),itemManage.getId(),groupName);
        //清空安装验收审核备注
        CrmAcceptingReport report = getReportById(customerEntry.getReceivingReportId());
        report.setFixConclusion("");
        reportDao.save(report);
    }

    //安装自审退回
    @Transactional(rollbackFor = Exception.class)
    public void acceptZSRefuse(String id, String remarks,User user) {
        CustomerEntry customerEntry = customerDao.get(id);
        if (!StringUtil.equalsAny(customerEntry.getStatus(),
                CustomerEntryConstants.ENTRY_STATUS_AZYSTH,CustomerEntryConstants.ENTRY_STATUS_AZZS)) {
            throw new IllegalArgumentException("自审已操作，请先刷新列表");
        }
        String checkExistApply = CrmUtils.checkExistApply(customerEntry.getStatus(), customerEntry.getId());
        if (StringUtil.isNotBlank(checkExistApply)) {
            throw new IllegalArgumentException(checkExistApply);
        }
        customerDao.updateStatusById(id, CustomerEntryConstants.ENTRY_STATUS_DAZ);
        customerDao.updateInstallFlagById(id, CustomerEntryConstants.INSTALL_FLAG_ZSBH);
        customerDao.updateCheckAcceptFlagById(id, CustomerEntryConstants.FLAG_INIT);
        msgService.saveCustomerEntryMsg(user, id, CustomerEntryConstants.INSTALL_SELF_AUDIT_REFUSE, "安装自审退回；" + remarks);
    }

    //小程序里面客户管理、信息授权页面的统计
    public Record customerManagementStatic(Map<String, String> map, Operator operator) {
        return customerDao.customerManagementStatic(map, operator);
    }

    //查看授权合同
    public String lookAuthBook(String idCode, String partner_id) {
        String path = customerDao.lookAuthBook(idCode, partner_id);
        if (StringUtil.isBlank(path)) {
            throw new IllegalArgumentException("没有签署完成的合同，不能查看!");
        }
        return path;
    }

    /**
     * 获取电站使用的物料
     */
    public Map<String, Object> findUsedMaterial(String entryId) {
        List<Record> list = entryDao.findRecordByEntryId(entryId);
        // 组件
        List<Record> list1 = new ArrayList<>();
        // 逆变器
        List<Record> list2 = new ArrayList<>();
        // 其它
        List<Record> list3 = new ArrayList<>();
        for (Record r : list) {
            if (Objects.equals("组件", r.getStr("type"))) {
                list1.add(r);
            } else if (Objects.equals("逆变器", r.getStr("type"))) {
                list2.add(r);
            } else {
                list3.add(r);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("zj", list1);
        map.put("nbq", list2);
        map.put("other", list3);
        return map;
    }

    /**
     * 获取电站使用的物料
     */
    public Map<String, Object> findUsedMaterialByprojectId(String entryId, String projectId) {
        List<Record> list = entryDao.findRecordByEntryProjectId(entryId,projectId);
        // 组件
        List<Record> list1 = new ArrayList<>();
        // 逆变器
        List<Record> list2 = new ArrayList<>();
        // 其它
        List<Record> list3 = new ArrayList<>();
        for (Record r : list) {
            if (Objects.equals("组件", r.getStr("type"))) {
                list1.add(r);
            } else if (Objects.equals("逆变器", r.getStr("type"))) {
                list2.add(r);
            } else {
                list3.add(r);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("zj", list1);
        map.put("nbq", list2);
        map.put("other", list3);
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    public void joinCloud(JoinCloudReq req) {
        List<String> snList = new ArrayList<>();
        List<String> nbqSnList = new ArrayList<>();
        List<CrmPlanMaterialEntry> materialEntries = entryDao.findByEntryId(req.getEntryId());
        for (CrmPlanMaterialEntry materialEntry : materialEntries) {
            nbqSnList.add(materialEntry.getNbqSn());
            snList.add(materialEntry.getNbqSn());
        }
        String collectorSn = StringUtils.join(snList, ",");
        String nbqSn = StringUtils.join(nbqSnList, ",");
        if (StringUtils.isAnyBlank(collectorSn, nbqSn)) {
            throw new BusinessException("请检查逆变器和通讯棒 sn 是否完整");
        }
    }

    public List<Record> findEntryLists(String entryId, Operator operator, String ids) {
        return customerDao.findEntryLists(entryId, operator, ids);
    }

    public List<Record> getEntryListByEntryIds(String entryId, String ids) {
        return customerDao.getEntryListByEntryIds(entryId, ids);
    }

    public void designChangeHR(Record record, List<Record> postComponents) {
        List<Record> collect = postComponents.stream().filter(r ->"3".equals(r.getStr("item_type")) && r.getStr("project_id").equals(record.getStr("project_id"))).collect(Collectors.toList());
        String model ="";
        int capacity =0;
        for (Record r : collect) {
            model = r.getStr("model");
            capacity = Integer.parseInt(model)*r.getInt("num");
        }
        String entryId = record.getStr("entry_id");
        SqlBuilder sb = new SqlBuilder()
                .line("update crm_customer_entry_design ")
                .line("set scheme_type_id=:scheme_type_id," +
                        "scheme_type_name=:scheme_type_name," +
                        "scheme_id=:scheme_id," +
                        "scheme_name=:scheme_name," +
                        "design_capacity=:design_capacity," +
                        "component_spec=:component_spec," +
                        "design_drawings=:design_drawings "
                )
                .line("where entry_id=:entry_id  and project_id=:project_id");
        SQLQuery query = crmCustomerEntryDesignDao.getSession().createSQLQuery(sb.build());
        query.setString("scheme_type_id", record.getStr("scheme_type_id"));
        query.setString("scheme_type_name", record.getStr("scheme_type_name"));
        query.setString("scheme_id", record.getStr("scheme_id"));
        query.setString("scheme_name", record.getStr("scheme_name"));
        query.setParameter("design_capacity", capacity);
        query.setString("component_spec", model);
        query.setString("design_drawings", record.getStr("design_drawings"));
        query.setString("entry_id", entryId);
        query.setString("project_id", record.getStr("project_id"));
        query.executeUpdate();
    }
    public void  designChangeHR2(CustomerEntry entry,String model, List<Record> postComponents){
        //如果已生成验收报告记录 则同步更新组件规格
        if (StringUtil.isNotBlank(entry.getReceivingReportId())) {
            SqlBuilder updateReport = new SqlBuilder()
                    .line("update crm_accepting_report")
                    .line("set component_spec=:component_spec")
                    .line("where id=:id ");
            SQLQuery updateReportQuery = entryDao.getSession().createSQLQuery(updateReport.build());
            updateReportQuery.setString("component_spec", model);
            updateReportQuery.setString("id", entry.getReceivingReportId());
            updateReportQuery.executeUpdate();
        }
        // postComponents 修改后的物料清单
        customerEntryComponentService.designChange(entry.getId(), postComponents);

    }
    public void designChange(CrmCustomerEntryChangeDesign design, List<Record> postComponents, String componentSpec,
                             Integer designCapacity, String reportId) {
        String entryId = design.getEntryId();
        SqlBuilder sb = new SqlBuilder()
                .line("update crm_customer_entry")
                .line("set design_drawings=:design_drawings," +
                        "scheme_type=:scheme_type," +
                        "scheme_type_id=:scheme_type_id," +
                        "scheme_type_name=:scheme_type_name," +
                        "scheme_id=:scheme_id," +
                        "scheme_name=:scheme_name," +
                        "design_change='1'," +
                        "component_spec=:component_spec," +
                        "design_change_time=:design_change_time," +
                        "design_capacity=:design_capacity,"+
                        "zjpb_img=:zjpb_img,"+
                        "zjzx_img=:zjzx_img,"+
                        "zjcs_img=:zjcs_img,"+
                        "zjhs_img=:zjhs_img"
                )
                .line("where id=:id ");
        SQLQuery query = customerDao.getSession().createSQLQuery(sb.build());
        query.setString("design_drawings", design.getDesignDrawings());
        query.setString("scheme_type", design.getSchemeType());
        query.setString("scheme_type_id", design.getSchemeTypeId());
        query.setString("scheme_type_name", design.getSchemeTypeName());
        query.setString("scheme_id", design.getSchemeId());
        query.setString("scheme_name", design.getSchemeName());
        query.setString("zjpb_img", design.getZjpbImg());
        query.setString("zjzx_img", design.getZjzxImg());
        query.setString("zjcs_img", design.getZjcsImg());
        query.setString("zjhs_img", design.getZjhsImg());
        query.setParameter("design_capacity", designCapacity);
        query.setParameter("design_change_time", new Date());
        query.setString("component_spec", componentSpec);

        query.setString("id", entryId);
        int affected = query.executeUpdate();
        if (affected < 1) {
            throw new BusinessException("电站状态发生改变，请刷新后重试！");
        }

        //如果已生成验收报告记录 则同步更新组件规格
        if (StringUtil.isNotBlank(reportId)) {
            SqlBuilder updateReport = new SqlBuilder()
                    .line("update crm_accepting_report")
                    .line("set component_spec=:component_spec")
                    .line("where id=:id ");
            SQLQuery updateReportQuery = customerDao.getSession().createSQLQuery(updateReport.build());
            updateReportQuery.setString("component_spec", componentSpec);
            updateReportQuery.setString("id", reportId);
            updateReportQuery.executeUpdate();
        }

        // postComponents 修改后的物料清单
        customerEntryComponentService.designChange(entryId, postComponents);
    }

    private Integer calcDesignCapacity(List<Record> postComponents) {
        int ret = 0;
        for (Record postComponent : postComponents) {
            if (Objects.equals(postComponent.getStr("item_type"), "3")) {
                ret += postComponent.getInt("num") * Integer.parseInt(postComponent.getStr("model"));
            }
        }
        return ret;
    }


    public Object getProjectInfo(String projectId) {
        User user = UserUtils.getUser();
        CrmTrader trader = traderService.getById(user.getTraderId());

//        校验项目对应的项目公式与代理商区域进行匹配
//        获取产品（项目）授权区域  （暂时用不上）
        List<ProjectPcd> projects = projectPcdDao.findListByProjectId(projectId);
        CrmProjectSetting crmProjectSetting = projectDao.get(projectId);
        //获取代理商授权区域
        List<TraderPcd> traders = traderPcdDao.findListByTraderId(trader.getId());
        //获取项目公司的id
        String[] split = crmProjectSetting.getProjectCompanyId().split(",");
        List<Record> projectCompanyVo = new ArrayList<>();
        //授权区域集合
        List<String> idList = new ArrayList<>();
        for (String s : split) {
            //获取项目公司授权地址的id
            for (TraderPcd traderPcd : traders) {
                boolean b = projectCompanyDao.checkAuth2(s, traderPcd.getProvince(), traderPcd.getCity(), traderPcd.getArea());
                if (b) {
                    idList.add(s);
                    projectCompanyVo.add(projectCompanyDao.getProjectCompanyByIds(s));
                }
            }
        }
        Set<Record> projectSet = new HashSet<>(projectCompanyVo);
        return projectSet;
    }

    public String initBankImg() {
        String sql = "select  account_code from crm_tenant_yx_bank_card where status='4' and (front_img is null or front_img = '')";
        List<Record> list = Db.find(sql);

        String update = "update crm_tenant_yx_bank_card set front_img=? where account_code=?";
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                DownImg img = new DownImg();
                String url = img.downImg(list.get(i).getStr("account_code"));
                Db.update(update, url, list.get(i).getStr("account_code"));
            }
        }
        return "success";
    }

    public List<Record> findPartnerInfoByIds(Set<String> entryIds) {
        SqlBuilder sb = new SqlBuilder()
                .line("select partner_id,partner_name,id")
                .line("from crm_customer_entry")
                .inst("where id in", new ArrayList<>(entryIds));
        return Db.find(sb.build(), sb.params());
    }
//    @Transactional(rollbackFor = Exception.class)
    public void initCustomerData() {
        List<Record> list = Db.find(" select id, birthday_date,ic_validity_begin,ic_validity_end,id_card_front,id_card_back from crm_customer_entry_tenant where tenant_type = '1' and birthday_date is null");
        Gson gson = new Gson();
        list.forEach(x -> {
                    String id_card_front = x.getStr("id_card_front");
                    String id_card_back = x.getStr("id_card_back");
                    String id = x.getStr("id");

                    String birthDate = "";
                    String icValidityBegin = "";
                    String icValidityEnd = "";

                    if (StringUtils.isNotBlank(id_card_front)) {
                        String data = OcrUtils.uploadImgIdentify(commonStaticImgPath + id_card_front);

                        if (StringUtils.isNotBlank(data)) {
                            JsonObject dataObject = gson.fromJson(data, JsonObject.class).getAsJsonObject("data");
                            JsonObject face = dataObject.getAsJsonObject("face");
                            if (Objects.isNull(face)) {
                                logger.info(">>>>>>>>>>>身份证图片识别失败 {}", id_card_front);
                            } else {
                                JsonObject faceDataObject = face.getAsJsonObject("data");
                                // 获取birthDate的值
                                birthDate = faceDataObject.get("birthDate").getAsString();
                            }
                        }
                    }
                    if (StringUtils.isNotBlank(id_card_back)) {
                        String data = OcrUtils.uploadImgIdentify(commonStaticImgPath + id_card_back);
                        if (StringUtils.isNotBlank(data)) {
                            JsonObject dataObject = gson.fromJson(data, JsonObject.class).getAsJsonObject("data");
                            JsonObject back = dataObject.getAsJsonObject("back");
                            if (Objects.isNull(back)) {
                                logger.info(">>>>>>>>>>>身份证图片识别失败 {}", id_card_back);
                            } else {
                                JsonObject faceDataObject = back.getAsJsonObject("data");
                                String validPeriod = faceDataObject.get("validPeriod").getAsString();
                                if (StringUtils.isNotBlank(validPeriod)) {
                                    String[] valid = validPeriod.split("-");
                                    icValidityBegin = valid[0];
                                    icValidityEnd = valid[1];
                                    if ("长期".equals(icValidityEnd)) {
                                        icValidityEnd = "9999-12-31";
                                    }
                                }
                            }
                        }
                    }
                    Date date = null;
                    try {
                        date = DateUtils.parseDate(birthDate, "yyyy年MM月dd日");
                    } catch (ParseException e) {
                        logger.error(e.getMessage(), e);
                    }

                    if (date != null && StringUtils.isNotBlank(icValidityBegin) && StringUtils.isNotBlank(icValidityEnd)) {
                        Db.update("update crm_customer_entry_tenant set birthday_date=?,ic_validity_begin= ?,ic_validity_end=? where id =?"
                                , date, icValidityBegin, icValidityEnd, id);
                    }
                }
        );
//        Db.update("update crm_customer_entry ce,crm_customer_entry_tenant ct  set ce.birthday_date = ct.birthday_date,ce.ic_validity_begin = ct.ic_validity_begin,ce.ic_validity_end = ct.ic_validity_end where ce.id = ct.entry_id");
    }

    public void updateContractState(String status, String entryId, String contractNo,String contractNormState) {
        GFContractStateKM innerState = Optional.ofNullable(GFContractStateKM.externalOf(Integer.valueOf(status)))
                .orElse(null);
        if (Objects.isNull(innerState)) throw new RuntimeException(entryId+"无效状态:"+status);
        Long count = Db.queryLong(" select count(1) from  crm_customer_contract_management  where entry_id = ? and `status` != '0' ", entryId);
        if (count > 1) {
            Db.update("UPDATE `crm_customer_contract_management` SET status= '0' WHERE  status = 'h' and  entry_id=? ",entryId);
        }
        String signStatus = innerState.getInternalCode();
        if ("h".equals(signStatus)) {
            if ("-10".equals(contractNormState)) {
                signStatus = "l";
            }
        }
        Db.update("UPDATE `crm_customer_contract_management` SET status=?,contract_number = ? WHERE  status!= '0' and  entry_id=?;",signStatus, contractNo,entryId);
        Db.update("update crm_customer_entry set sign_status = ? where id = ? ",signStatus,entryId);
    }

    public void updateSecondStateHuaRong(CustomerEntry entry, HuaRongCustomer customer,CrmCustomerIncomingApplication incomingApplication) {
        String projectStatus = String.valueOf(customer.getProjectStatus());
        String hrContent = huaRongManagementService.getHRContent(customer);
        if (!projectStatus.equals(incomingApplication.getFarmerSignStatus())) {
            Operator operator = Operator.of("1", "资方-华融", "-1");
            yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(), incomingApplication.getPartnersContractNumber(), "0", "第三次进件状态查询：" + hrContent, null);
            if("DS".equals(projectStatus)){
                msgService.saveCustomerEntryMsg(operator, entry.getId(),CustomerEntryConstants.INCOMING_TWO_FAIL,"第二次进件审核不通过，原因："+hrContent,"");
            }else if(StringUtil.equalsAny(projectStatus,"CS","PR","LS")){
                msgService.saveCustomerEntryMsg(operator, entry.getId(),CustomerEntryConstants.INCOMING_TWO_PASS,"第二次进件审核通过","");
            }else if("RJ".equals(projectStatus)){
                msgService.saveCustomerEntryMsg(operator, entry.getId(),CustomerEntryConstants.INCOMING_TWO_FAIL,"并网进件拒绝，"+customer.getReturnReason(),"");
            }
        }
        //进件状态
        String applyStatus = entry.getApplyStatus();
        String auditStatus = "1";
        String errMsg = "";
        /**
         * DS-待进件  待补充资料
         * MR:人工审核中
         * ST:二次进件完成
         4.RJ:拒绝
         */
        if ("DS".equals(projectStatus)) {
            applyStatus = CustomerEntryConstants.APPLY_STATUS_BCBWZL;
            errMsg = hrContent;
        } else if (StringUtil.equalsAny(projectStatus,"MR","ST")) {
            applyStatus = CustomerEntryConstants.APPLY_STATUS_BWYTJ;
        } else if (StringUtil.equalsAny(projectStatus,"CS","PR","LS")) {
            auditStatus = "2";
            applyStatus = CustomerEntryConstants.APPLY_STATUS_BWSHTG;
            entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_YWC);
            entry.setMergeFlag(CustomerEntryConstants.MERGE_FLAG_ZFSHTG);
            if (entry.getPaymentTime() == null) {
                entry.setPaymentTime(new Date()); //华融的回款时间 存并网进件通过时间
            }
        }else if ("RJ".equals(projectStatus)) {
            auditStatus = "3";
            applyStatus = CustomerEntryConstants.APPLY_STATUS_BWSHBH;
            //拒绝的需要重新生成进件序号
            Long maxVersion=incomingApplicationDao.getMaxVersion(entry.getPartnerId());
            String partnersContractNumber= CustomerEntryUtil.addZero(CustomerEntryUtil.getJJPrefix(entry.getPartnerId()),maxVersion+1);
            incomingApplication.setPartnersContractNumber(partnersContractNumber);
            incomingApplication.setVersion(maxVersion+1);
            entry.setFirstApplyStatus("RJ");
            errMsg = hrContent;
        }else if ("CL".equals(projectStatus)){
            auditStatus = "3";
            applyStatus="a";
            entry.setFirstApplyStatus("CL");
            errMsg = customer.getReturnReason();
        }
        entry.setApplyStatus(applyStatus);
        entry.setNextApplyStatus(projectStatus);
        entry.setApplyBackReason(errMsg);
        incomingApplication.setFarmerSignStatus(projectStatus);
        incomingApplication.setStatus(applyStatus);
        customerDao.save(entry);
        incomingApplicationDao.save(incomingApplication);
        CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(), "5",projectStatus, "0", auditStatus, hrContent);
    }
    public void getHistoryEntryList(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        List<Record> list = customerDao.getHistoryEntryList(page, map, operator);
        page.setData(list);
        page.setCount(customerDao.countHistoryEntryList(map, operator));
    }

    public void getHistoryEntryJjsh(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
        List<Record> list = customerDao.getHistoryEntryJjsh(page, map, operator);
        page.setData(list);
        page.setCount(customerDao.getHistoryJjShCount(map, operator));
    }

    //广发终止进件
    @Transactional(rollbackFor = Exception.class)
    public Result cancelGFApply(String entryId, String returnType,String reason){
        logger.info("cancelGFApply  终止进件  entryId:{}",entryId);
        User user= UserUtils.getUser();
        Date date=new Date();
        Operator operator=Operator.of(user);
        CustomerEntry entry=customerDao.get(entryId);
        CrmCustomerIncomingApplication incomingApplication=applicationDao.getByEntryId(entryId);
        if(incomingApplication==null || StringUtil.isBlank(incomingApplication.getPartnerId())){
            throw new IllegalArgumentException("未找到进件信息！");
        }
        if (StringUtil.isNotBlank(incomingApplication.getStatus()) && StringUtil.equalsAny(incomingApplication.getStatus(),"5","14","19")){
            throw new IllegalArgumentException("资方进件审核中，不允许终止进件！");
        }
        if(StringUtil.isNotBlank(incomingApplication.getTerminateInputPieceState()) && StringUtil.equalsAny(incomingApplication.getTerminateInputPieceState(),"20","30","60")){
            throw new IllegalArgumentException("终止进件审核中，不允许再次终止！");
        }
        CrmCustomerContractManagement management = contractManagementDao.getContractByEntryId(entryId);
        //作废已完成的合同
        if (management != null){
            if (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);
            }
        }
        try{
            //广发的终止进件后 要审核，要查询终止进件的状态
            incomingApplication.setStatus("-10");
            incomingApplication.setTerminateInputPieceState("1");
            incomingApplication.setCancelReason(reason);
            incomingApplication.setUpdateTime(date);
            incomingApplication.setUpdateBy(operator.getUserId());
            entry.setApplyStatus("-10");
            saveByUpdate(entry);
            applicationDao.save(incomingApplication);
            //广发终止进件
            guangfaOperatingService.cancelGFApply(entry, incomingApplication.getInputPieceId(), returnType, reason);
            yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(),incomingApplication.getPartnersContractNumber(),"6","终止进件 ",operator);
            CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"1","CLOSED","0","","终止进件");
            CrmYxIncomingProcessDao.returnIncomingProcess(entry.getId(),"2,3,4,5");
            String str=StringUtil.isBlank(reason)?"":",原因："+reason;
            msgService.saveCustomerEntryMsg(user,entryId, CustomerEntryConstants.INCOMING_CANCEL,"终止进件"+str);
        }catch (Exception e){
            logger.error("cancelGFApply  e:{}",e);
            throw new IllegalArgumentException("终止进件失败，"+e.getMessage());
        }
        return Result.ok();
    }

    //广发 上传信息授权书
    @Transactional(rollbackFor = Exception.class)
    public Result uploadAuthorization(String entryId,String authorizationContractPath){
        CustomerEntry entry = customerDao.get(entryId);
        if (StringUtil.isNotBlank(entry.getBpIdCard()) && entry.getBpIdCard().equals(entry.getIdCode())) {
            throw new IllegalArgumentException("共签人证件号码不能与业主身份证号相同!");
        }
        Record pro = null;
        if (StringUtil.isNotBlank(entry.getProjectId())) {
            pro = projectDao.getProject(entry.getProjectId());
        }
        boolean checkAuth = traderPcdService.checkAuth(entry.getCreateTraderId(), entry.getProvince(), entry.getCity(), entry.getArea());
        if (!checkAuth) {
            throw new IllegalArgumentException("代理商区域暂未授权");
        }
        //编辑接口
        //TODO 校验产品区域权限  产品是否授权
        if (pro != null) {
            boolean b = projectDao.checkAuth(entry.getProjectId(), entry.getProvince(), entry.getCity(), entry.getArea());
            if (!b) {
                throw new IllegalArgumentException("产品区域暂未授权");
            }
        }
        //TODO 校验项目公司区域  产品是否授权
        boolean b1 = companyDao.checkAuth2(entry.getProjectCompanyId(), entry.getProvince(), entry.getCity(), entry.getArea());
        if (!b1) {
            throw new IllegalArgumentException("项目公司区域暂未授权");
        }

        CustomerEntryOrgFiles orgFiles = orgFilesDao.findOneByEntryId(entry.getId());
        String regnoUrl = "";
        if(StringUtil.isBlank(regnoUrl) &&
                orgFiles!=null && StringUtil.isNotBlank(orgFiles.getRegnoUrl())){
            regnoUrl = orgFiles.getRegnoUrl();
        }
        // 新建客户信息
        Result res = createTenant(entry, regnoUrl);
        if (res.isOk()) {
            entry.setTenantId(res.getMsg());
            customerDao.save(entry);
        } else {
            throw new IllegalArgumentException(res.getErrMsg());
        }
        //保存租金信息
        if (StringUtil.isNotBlank(entry.getProjectId())) {
            customerRentVariableService.saveEntryComponent(entry.getId(), entry.getProjectId());
        }
        String keyInfo = null;
        if ("1".equals(entry.getTenantType()) && StringUtil.isNotBlank(entry.getIdCode())) {
            keyInfo = entry.getIdCode();
        }else if ("2".equals(entry.getTenantType()) && StringUtil.isNotBlank(entry.getRegno())) {
            keyInfo = entry.getRegno();
        }
        CrmCustomerYxCondition condition = conditionDao.findCustomerYxCondition(keyInfo, entry.getPartnerId());
        if (condition!=null){
              Db.update(" UPDATE crm_customer_yx_condition  set authorization = '3' ,authorization_contract_path = ? where " +
                    " id_code = ? and partner_id = ?",authorizationContractPath,keyInfo,entry.getPartnerId());
        }else {
            Db.update("insert into  crm_customer_yx_condition (id,name,mobile,id_code,preaudit,authorization,authorization_contract_path,partner_id) " +
                    " values (?,?,?,?,?,?,?,?)", IdGen.uuid(),entry.getTenantName(), entry.getMobile(), keyInfo, "2","3",authorizationContractPath,entry.getPartnerId());
        }
        entry.setAuthorization(CustomerEntryConstants.AUTHORIZATION_SUCCESS);
        Result result = null;
        try {
            logger.info("上传信息授权书，提交预审，entryId:{}", entryId);
            result = submitAudit(entryId);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new IllegalArgumentException("操作失败，"+e.getMessage());
        }
        if (result != null && "200".equals(result.getCode())) {
            entry.setCredit("2");
        }
        customerDao.save(entry);
        return result;
    }
    //处理广发历史电站丢失客户记录问题
    public void selectEntryInfo(){
        List<Record> records = Db.find(" select e.id,e.power_station_code,e.tenant_type,e.tenant_name from crm_customer_entry e " +
                " LEFT JOIN crm_customer_entry_tenant t on e.id_code = t.id_code " +
                " where e.power_station_code like 'D%' and e.credit = '4' and e.tenant_id is null and t.id is null");
        for (Record record : records) {
            try {
                addEntryInfo(record.getStr("id"));
            }catch (Exception e){
                e.printStackTrace();
                logger.info("addEntryInfo error entryId:{} errMsg:{}",record.getStr("id"),e.getMessage());
            }
        }
    }
    public void addEntryInfo(String entryId){
        CustomerEntry entry = customerDao.get(entryId);
        CrmPartner partner = partnerService.getById(entry.getPartnerId());
        if (!"1".equals(partner.getTenantFlag()) && "1".equals(entry.getTenantType())) {
            Record bankCondition = customerDao.findYxBankCondition(entry.getIdCode(), entry.getMobile(),entry.getPartnerId());
            if (bankCondition != null && "4".equals(bankCondition.getStr("status"))) {
                entry.setSecCardStatus("1");
            }
        }
        String regnoUrl = "";
        CustomerEntryOrgFiles orgFiles = orgFilesDao.findOneByEntryId(entry.getId());
        if(StringUtil.isBlank(regnoUrl) &&
                orgFiles!=null && StringUtil.isNotBlank(orgFiles.getRegnoUrl())){
            regnoUrl = orgFiles.getRegnoUrl();
        }
        // 新建客户信息
        Result res = createTenant(entry, regnoUrl);
        if (res.isOk()) {
            entry.setTenantId(res.getMsg());
        } else {
            throw new IllegalArgumentException(res.getErrMsg());
        }
        customerDao.save(entry);
        //保存租金信息
        if (StringUtil.isNotBlank(entry.getProjectId())) {
            customerRentVariableService.saveEntryComponent(entry.getId(), entry.getProjectId());
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public Result returnToSurvey(Operator operator,String id){
        CustomerEntry entry = customerDao.get(id);
        if (!CustomerEntryConstants.DESIGN_AUDIT_FLAG_SJSHTG.equals(entry.getDesignAuditFlag())
                && !CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHBH.equals(entry.getDesignAuditFlag())){
            return Result.fail("当前电站状态不可退回勘测");
        }
        entry.setStatus("0");
        entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
        entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_DJJ);
        customerDao.save(entry);
        CrmCustomerIncomingApplication application = incomingApplicationDao.getByEntryId2(id);
        if(application!=null){
            if("a".equals(application.getStatus())){
                application.setIfDelete("1");
                incomingApplicationDao.save(application);
            }
        }
        msgService.saveCustomerEntryMsg(operator, entry.getId(),CustomerEntryConstants.RETURN_DKC,"退回勘测","");
        return Result.ok();
    }
    @Transactional(rollbackFor = Exception.class)
    public Result azReturnToSurvey(Operator operator,String id){
        CustomerEntry entry = customerDao.get(id);
        CrmCustomerIncomingApplication application = incomingApplicationDao.getByEntryId2(id);
        if (!"a".equals(application.getStatus())){
            return Result.fail("请先取消进件");
        }
        if (!CustomerEntryConstants.INSTALL_FLAG_DPG.equals(entry.getInstallFlag())
                && !CustomerEntryConstants.INSTALL_FLAG_DAZ.equals(entry.getInstallFlag())){
            return Result.fail("当前电站状态不可退回勘测");
        }

        List<Record> list = entryDao.findRecordByEntryId(id);
        if (!list.isEmpty()){
            return Result.fail("已使用物料不可退回勘测");
        }
        entry.setStatus("0");
        entry.setInstallFlag("0");
        entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_DTK);
        entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_DJJ);
        customerDao.save(entry);

        if(application!=null){
            if("a".equals(application.getStatus())){
                application.setIfDelete("1");
                incomingApplicationDao.save(application);
            }
        }
        msgService.saveCustomerEntryMsg(operator, entry.getId(),CustomerEntryConstants.RETURN_DKC,"安装退回勘测","");
        return Result.ok();
    }

    //设为历史电站
    @Transactional(rollbackFor = Exception.class)
    public void setHistoryEntry(String id, Operator operator) {
        CustomerEntry entry = customerDao.get(id);
        if (!"1".equals(entry.getCredit())){
            throw new IllegalArgumentException("待预审的电站才能设为历史电站");
        }
        CrmCustomerIncomingApplication application = applicationDao.getByEntryId2(id);
        if (application!=null){
            application.setIfDelete("1");
            applicationDao.save(application);
        }
        entry.setIsHistory("1");
        entry.setCredit("4");
        customerDao.save(entry);
        msgService.saveCustomerEntryMsg(operator, entry.getId(),CustomerEntryConstants.SET_HISTORY_ENTRY,"设为历史电站","");
    }
    @Transactional(rollbackFor = Exception.class)
    public void initBwSettle(String id){
        CustomerEntry entry = customerDao.get(id);
        entry.setBwSettleFlag("1");
        customerDao.save(entry);
        //生成结算记录
        customerEntryExtraService.bwSettle(entry);
        accountSettleDetailDao.changeRewardSettleStatus(entry.getId());
    }

    /**
     * 并网验收审核暂存
     */
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public void twoMergeAcceptTemp(String id, String finalConclusion, String fixConclusionSh, String materialMergeFlag, String materialFixFlag) {
        CustomerEntry entry = customerDao.get(id);
        CrmAcceptingReport report = getReportById(entry.getReceivingReportId());
        report.setMaterialMergeFlag(materialMergeFlag);
        report.setMaterialFixFlag(materialFixFlag);
        report.setMergeConclusion(finalConclusion);
        report.setFixConclusion(fixConclusionSh);
        entry.setMaterialMergeFlag(materialMergeFlag);
        entry.setMaterialFixFlag(materialFixFlag);
        customerDao.save(entry);
        reportDao.save(report);
    }

    /**
     * 设计审核 暂存
     */
    @Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
    public void tempCustomerEntry(String id, String remarks, Operator operator) {
        CustomerEntry entry = customerDao.get(id);
        entry.setExamine(operator.getUserId());
        entry.setExamineName(operator.getUserName());
        entry.setExamineRemarks(remarks);
        entry.setExamineTime(new Date());
        customerDao.save(entry);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeSign(String id, String removeSign) {
        CrmCustomerEntryInsurance insurance = entryInsuranceDao.get(id);
        CustomerEntry entry = customerDao.get(insurance.getEntryId());
        entry.setRemoveSign(removeSign);
        customerDao.save(entry);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeSign2(String id, String removeSign) {
        CustomerEntry entry = customerDao.get(id);
        entry.setRemoveSign(removeSign);
        customerDao.save(entry);
    }
}



