package com.sifang.modules.partner.service;
import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.*;
import com.sifang.modules.partner.dao.CrmHrUploadFileDetailDao;
import com.sifang.modules.partner.dto.HuaRongEquipList;
import com.sifang.modules.partner.dto.HuaRongInputPiece;
import com.sifang.modules.partner.dto.MixtureRoofInfo;
import com.sifang.modules.partner.entity.CrmHrUploadFileDetail;
import com.sifang.modules.partner.utils.HuaRongStatusFormVo;
import com.sifang.modules.partner.utils.PartnerApiUtils;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.setting.dao.CrmHrEpcPriceSetDao;
import com.sifang.modules.sunshine.SystemSetting.dao.PlanMaterialEntryDao;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectSettingDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectSetting;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.partnerManagement.dao.PartnerBrandUtils;
import com.sifang.modules.sunshine.partnerManagement.entity.CrmPartner;
import com.sifang.modules.sunshine.partnerManagement.service.PartnerService;
import com.sifang.modules.supply.stock.dao.SupplyMaterialDao;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.Arith;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.dao.SysCapitalDictDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

@Service
public class HuaRongApiService extends BaseService {

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

    public static final String clientId = "C2024071000004779074";

    @Value("${dh.url}")
    private String DH;

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


    @Autowired
    private CustomerEntrySurveyRecordDao surveyRecordDao;

    @Autowired
    private CrmCustomerIncomingApplicationRetailPayInfoDao retailPayInfoDao;

    @Autowired
    private CustomerEntryComponentDao entryComponentDao;

    @Autowired
    private CustomerRentVariableDao rentVariableDao;

    @Autowired
    private SysCapitalDictDao sysCapitalDictDao;

    @Autowired
    private SupplyMaterialDao supplyMaterialDao;
    @Autowired
    @Lazy
    private CustomerEntryService customerEntryService;
    @Autowired
    private ContractManagementDao contractManagementDao;
    @Autowired
    PlanMaterialEntryDao entryDao;
    @Autowired
    private CustomerEntryOrgFilesDao orgFilesDao;
    @Autowired
    private CrmHrEpcPriceSetDao epcPriceSetDao;
    @Autowired
    private TenantYxBankCardDao tenantYxBankCardDao;
    @Autowired
    private PartnerService partnerService;
    @Autowired
    private CrmCustomerEntryProjectDao crmCustomerEntryProjectDao;
    @Autowired
    private ProjectSettingDao projectSettingDao;
    @Autowired
    private CrmCustomerEntrySurveyRecordDetailDao crmCustomerEntrySurveyRecordDetailDao;
    @Autowired
    private CrmHrUploadFileDetailDao hrUploadFileDetailDao;
    @Autowired
    CrmAcceptingReportDetailDao reportDetailDao;
    @Autowired
    CrmCustomerEntryDesignDao crmCustomerEntryDesignDao;
    /**
     * 提交预审 - 提交白名单准入申请
     */
    public JSONObject capitalPreAudit(CustomerEntry entry, String authorizationContractPath) {
        CrmPartner partner = partnerService.getById(entry.getPartnerId());
        Map<String,Object> map=new HashMap<>();
        map.put("capital",entry.getPartnerId()); //√
        map.put("clientId",clientId); // √
        // 待完善
        map.put("tenant_type",entry.getTenantType());//客户类型，1.个人 2.单位 √
        map.put("tenant_name",entry.getTenantName()); //客户名称√
        map.put("filing_type",entry.getFilingType()); //备案类型:1.农户备案 2.项目公司备案 √
        if ("1".equals(entry.getTenantType())) {
            map.put("id_code",entry.getIdCode());////客户类型为个人时，传客户身份证；为单位时，传负责人身份证 √
            if ("1".equals(partner.getOverageFlag()) && entry.getAge() > partner.getNeedSignerAge()) {
                map.put("isCosigner","1");
            }else {
                map.put("isCosigner","0");
            }
        }
        else {
            map.put("id_code",entry.getRegno());//营业执照，客户类型为单位时有效(信用代码) √
        }
        map.put("certificate_type", "A01"); //项目公司证件类型 √
        map.put("management_type", entry.getManagementType()); //项目公司编码对应 management_type
        map.put("mobile", entry.getMobile());  //客户类型为个人时，传客户手机号码；为单位时，传负责人手机号码 √
        map.put("corp", entry.getCorp()); //负责人姓名，客户类型为单位时有效 √
        map.put("businessType", "1022"); //经营性租赁 //√
        if (StringUtil.isNotBlank(authorizationContractPath)){
            map.put("authorization_contract_path", commonStaticImgPath + authorizationContractPath);
        }else {
            //测试环境
            //map.put("authorization_contract_path", commonStaticImgPath+"energy_img/pdf/20241016/0b3397d443754644b9e783da64eb7783/ss_7a4dd.pdf");
            //真实环境
            map.put("authorization_contract_path", commonStaticImgPath+"energy_img/pdf/20241015/da9ac76d3fc14e649900856774668450/ss_5d405.pdf");
        }
        Record province = AddressUtils.getProvinceCode(entry.getProvince());//省
        // map.put("provinceCode",province.getLong("regionalism_code").toString());//√
        Record city = AddressUtils.getCityCode(entry.getCity(),province.getLong("ProvinceID"));
        // map.put("cityCode",city.getLong("regionalism_code").toString());//市 √
        // map.put("areaCode",AddressUtils.getDistrictCode(entry.getArea(),city.getLong("CityID")).toString());//区 √
        if (entry.getProvince().equals(entry.getCity())) {
            map.put("address", province.getLong("regionalism_code").toString()+ "," +
                    AddressUtils.getDistrictCode(entry.getArea(),city.getLong("CityID")).toString());     //地址√
        }
        else {
            if ("东莞市".equals(entry.getCity()) || "中山市".equals(entry.getCity()) || "嘉峪关市".equals(entry.getCity()) || "三沙市".equals(entry.getCity())) {
                map.put("address", province.getLong("regionalism_code").toString() + "," +
                        city.getLong("regionalism_code").toString());     //地址√
            }else {
                map.put("address", province.getLong("regionalism_code").toString() + "," +
                        city.getLong("regionalism_code").toString() + "," +
                        AddressUtils.getDistrictCode(entry.getArea(), city.getLong("CityID")).toString());     //地址√
            }
        }
        map.put("bank_name",entry.getBankName());   //账户名称√
        map.put("bank_code",entry.getBankCode());   //银行账号√
        map.put("tss_bank_num_name",entry.getTssBankNum());   //开户行编码√
        if ("1".equals(entry.getTenantType())){
            if ("1".equals(entry.getFilingType())){
                JSONObject jsonObject = new JSONObject();
                JSONObject result = PartnerApiUtils.getresultDoPost(map, DH + "/open/link/capitalPreAudit");
                if (result!=null){
                    jsonObject.put("code",200);
                }
                return jsonObject;
            } else {
                return PartnerApiUtils.getresultDoPost2(map, DH + "/open/link/capitalPreAudit");
            }
        }else {
            return PartnerApiUtils.getresultDoPost(map, DH + "/open/link/capitalPreAudit");
        }

    }

    /**
     * 查询预审结果
     */
    public JSONObject queryPreAudit(CustomerEntry entry) {
        Map<String,Object> map=new HashMap<>();
        map.put("capital",entry.getPartnerId());
        map.put("clientId", clientId);
        if ("1".equals(entry.getTenantType())) {
            map.put("id_code",entry.getIdCode());////客户类型为个人时，传客户身份证；为单位时，传负责人身份证 √
        }
        else {
            map.put("id_code",entry.getRegno());//营业执照，客户类型为单位时有效(信用代码) √
        }
        map.put("name", entry.getTenantName());
        // isProjectCompanyModel 进件模式 1：项目公司模式 2：合作共建模式
        if ("1".equals(entry.getFilingType())){
            map.put("isProjectCompanyModel","2");
        }else {
            map.put("isProjectCompanyModel","1");
        }
        map.put("certificateType","A01");//项目公司证件类型
        map.put("certificateNumber",entry.getManagementType());//项目公司编码

        return PartnerApiUtils.getresultDoPost(map, DH + "/open/link/queryPreAuditState");
    }

    /**
     * 查询二类卡开卡结果
     */
    public JSONObject querySecondCard(String partnerId, String idCode, String managementType) {
        Map<String,Object> map=new HashMap<>();
        map.put("capital",partnerId);//资方id
        map.put("clientId", clientId);//合作伙伴 ID
        map.put("id_code", idCode); //身份证号
        map.put("bizSerialNo", managementType);//项目公司编码
        return PartnerApiUtils.getresultDoPost(map, DH + "/open/link/querySecondCardState");
    }

    //状态查询
    public List<HuaRongStatusFormVo> queryRongStatus(String partnerId, String reqContNumber) {
        Map<String,Object> map=new HashMap<>();
        map.put("capital",partnerId); //资方id，03:广发  04:华融
        map.put("reqContNumber",clientId+reqContNumber);
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("HuaRongProjectStatus  状态查询：reqContNumber:{},json:{}",reqContNumber,jsonStr);
        JSONArray jsonObject = PartnerApiUtils.doPostForPartnerApi(map, DH + "/open/link/queryProjectState");
        if(jsonObject!=null){
            List<HuaRongStatusFormVo> statusFormVoList = new Gson().fromJson(jsonObject.toJSONString(), new TypeToken<List<HuaRongStatusFormVo>>() {}.getType());
            return statusFormVoList;

        }else{
            throw new IllegalArgumentException("请求失败！");
        }
    }

    //上传附件
    public Result uploadFile(CustomerEntry entry, CrmCustomerIncomingApplication incomingApplication ,
                             String type, Set<String> fileCodeS){
        String partnersContractNumber = incomingApplication.getPartnersContractNumber();
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entry.getId());
        CrmCustomerContractManagement contract = contractManagementDao.getContractByEntryId(entry.getId());
        CustomerEntryOrgFiles orgFiles = orgFilesDao.findOneByEntryId(entry.getId());
        if (orgFiles == null) {
            throw new IllegalArgumentException("档案信息有误");
        }
        CrmAcceptingReport report = new CrmAcceptingReport();
        if (StringUtil.isNotBlank(entry.getReceivingReportId())){
            CrmAcceptingReport crmAcceptingReport = customerEntryService.getReportById(entry.getReceivingReportId());
            if (crmAcceptingReport != null){
                report = crmAcceptingReport;
            }
        }
        List<CrmAcceptingReportDetail> reportDetailList = reportDetailDao.findByEntryId(entry.getId());

        List<CrmCustomerEntrySurveyRecordDetail> entrySurveys = crmCustomerEntrySurveyRecordDetailDao.findByEntryId(entry.getId());
        try {
            if(StringUtil.equalsAny(type,"1","3")){ //勘测、并网
                boolean checkUploadFlag = true;
                boolean flagA1 = false;
                boolean flagA6 = false;
                boolean flagA4 = false;
                boolean flagA2 = false;
                boolean flagB2 = false;
                boolean flagB3 = false;
                //一次进件
                if ("1".equals(type)){
                    checkUploadFlag = false;
                    flagA1 = true;
                    flagA6 = true;
                    flagA4 = true;
                    flagA2 = true;
                    flagB2 = true;
                    flagB3 = true;
                }
                if (surveyRecord != null) {
                    int i = 1;
                    int j = 1;
                    for (CrmCustomerEntrySurveyRecordDetail entrySurvey : entrySurveys) {
                        String projectId = entrySurvey.getProjectId();
                        String roofType = crmCustomerEntryProjectDao.getRoofTypeByProjectId(entry.getId(), projectId);

                        CrmHrUploadFileDetail hrUploadFileDetail = hrUploadFileDetailDao.getDetailByEntryId(entry.getId(),projectId);
                        if(hrUploadFileDetail == null){
                            hrUploadFileDetail = new CrmHrUploadFileDetail();
                        }
                        if ("1".equals(type)){
                            hrUploadFileDetail.setEntryId(entry.getId());
                            hrUploadFileDetail.setProjectId(projectId);
                            hrUploadFileDetail.setIdCardFront(entry.getIdCardFront());
                            hrUploadFileDetail.setIdCardBack(entry.getIdCardBack());
                            hrUploadFileDetail.setRegnoUrl(orgFiles.getRegnoUrl());
                            hrUploadFileDetail.setBpIdCardFront(entry.getBpCardFront());
                            hrUploadFileDetail.setBpIdCardBack(entry.getBpCardBack());
                            hrUploadFileDetail.setBpFile(entry.getBpFile());
                            hrUploadFileDetail.setBankCard(entry.getBankCard());
                            hrUploadFileDetail.setHouseOwnership(surveyRecord.getHouseOwnership());
                            hrUploadFileDetail.setResidenceBooklet(entry.getResidenceBooklet());
                            hrUploadFileDetail.setFlyImg(entrySurvey.getFlyImgs());
                            hrUploadFileDetail.setRoofPhotoTwo(entrySurvey.getRoofPhotoTwo());
                            hrUploadFileDetail.setRoofPhotoThree(entrySurvey.getRoofPhotoThree());
                            hrUploadFileDetail.setRoofPhotoFour(entrySurvey.getRoofPhotoFour());
                            hrUploadFileDetail.setVrRoofFour(entrySurvey.getVrRoofFour());
                            hrUploadFileDetail.setHouseOutlinePhoto(entrySurvey.getHouseOutlinePhoto());
                            hrUploadFileDetail.setRoofPhotoFacade(entrySurvey.getRoofPhotoFacade());
                            hrUploadFileDetail.setRoofPhotoInterior(entrySurvey.getRoofPhotoInterior());
                            hrUploadFileDetail.setSurveyFile(entrySurvey.getSurveyFiles());
                            hrUploadFileDetailDao.save(hrUploadFileDetail);
                        }

                        if (checkUploadFlag){
                            if ( (StringUtil.isNotBlank(entry.getIdCardFront()) &&!entry.getIdCardFront().equals(hrUploadFileDetail.getIdCardFront()))
                                    || (StringUtil.isNotBlank(entry.getIdCardBack()) && !entry.getIdCardBack().equals(hrUploadFileDetail.getIdCardBack()))
                                    || (StringUtil.isNotBlank(orgFiles.getRegnoUrl()) && !orgFiles.getRegnoUrl().equals(hrUploadFileDetail.getRegnoUrl()))){
                                flagA1 = true;
                            }
                            if ((StringUtil.isNotBlank(entry.getBpCardFront()) && !entry.getBpCardFront().equals(hrUploadFileDetail.getBpIdCardFront()))
                                    ||  (StringUtil.isNotBlank(entry.getBpCardBack()) && !entry.getBpCardBack().equals(hrUploadFileDetail.getBpIdCardBack()))
                                    ||  (StringUtil.isNotBlank(entry.getBpFile()) && !entry.getBpFile().equals(hrUploadFileDetail.getBpFile()))){
                                flagA6 =true;
                            }

                            if (StringUtil.isNotBlank(entry.getBankCard()) && !entry.getBankCard().equals(hrUploadFileDetail.getBankCard())){
                                flagA4 = true;
                            }
                            if ((StringUtil.isNotBlank(surveyRecord.getHouseOwnership())&& !surveyRecord.getHouseOwnership().equals(hrUploadFileDetail.getHouseOwnership()))
                                    || (StringUtil.isNotBlank(entry.getResidenceBooklet())&&  !entry.getResidenceBooklet().equals(hrUploadFileDetail.getResidenceBooklet()))){
                                flagA2 = true;
                            }
                            if ( (StringUtil.isNotBlank(entrySurvey.getFlyImgs()) && !entrySurvey.getFlyImgs().equals(hrUploadFileDetail.getFlyImg()))
                                    || (StringUtil.isNotBlank(entrySurvey.getRoofPhotoTwo()) &&  !entrySurvey.getRoofPhotoTwo().equals(hrUploadFileDetail.getRoofPhotoTwo()))
                                    || (StringUtil.isNotBlank(entrySurvey.getRoofPhotoThree()) &&  !entrySurvey.getRoofPhotoThree().equals(hrUploadFileDetail.getRoofPhotoThree()))
                                    || (StringUtil.isNotBlank(entrySurvey.getRoofPhotoFour()) &&  !entrySurvey.getRoofPhotoFour().equals(hrUploadFileDetail.getRoofPhotoFour()))){
                                flagB2 = true;
                            }
                            if ( (StringUtil.isNotBlank(entrySurvey.getVrRoofFour()) &&  !entrySurvey.getVrRoofFour().equals(hrUploadFileDetail.getVrRoofFour()))
                                    ||  (StringUtil.isNotBlank(entrySurvey.getHouseOutlinePhoto()) &&  !entrySurvey.getHouseOutlinePhoto().equals(hrUploadFileDetail.getHouseOutlinePhoto()))
                                    ||  (StringUtil.isNotBlank(entrySurvey.getRoofPhotoFacade()) &&  !entrySurvey.getRoofPhotoFacade().equals(hrUploadFileDetail.getRoofPhotoFacade()))
                                    ||  (StringUtil.isNotBlank(entrySurvey.getRoofPhotoInterior()) &&  !entrySurvey.getRoofPhotoInterior().equals(hrUploadFileDetail.getRoofPhotoInterior()))
                                    ||  (StringUtil.isNotBlank(entrySurvey.getSurveyFiles()) &&  !entrySurvey.getSurveyFiles().equals(hrUploadFileDetail.getSurveyFile()))
                            ){
                                flagB3 = true;
                            }
                        }
                        if ((fileCodeS.isEmpty() || fileCodeS.contains("B2")) && flagB2)  {
                            //屋顶高空俯视照片
                            if (StringUtil.isNotBlank(entrySurvey.getFlyImgs())) {
                                String[] flyList = entrySurvey.getFlyImgs().split(",");
                                i = 1;
                                for (String fly : flyList) {
                                    uploadFileApply(partnersContractNumber, fly, roofType+"-屋顶高空俯视照片-" + i, "B2");
                                    i++;
                                }
                            }
                            //屋顶东南照片
                            if (StringUtil.isNotBlank(entrySurvey.getRoofPhotoTwo())) {
                                String[] roofPhotoTwoList = entrySurvey.getRoofPhotoTwo().split(",");
                                i = 1;
                                for (String roofPhotoTwo : roofPhotoTwoList) {
                                    uploadFileApply(partnersContractNumber, roofPhotoTwo, roofType+"-屋顶东南照片-" + i, "B2");
                                    i++;
                                }
                            }
                            //屋顶正南照片
                            if (StringUtil.isNotBlank(entrySurvey.getRoofPhotoFour())) {
                                String[] roofPhotoFourList = entrySurvey.getRoofPhotoFour().split(",");
                                i = 1;
                                for (String roofPhotoFour : roofPhotoFourList) {
                                    uploadFileApply(partnersContractNumber, roofPhotoFour, roofType+"-屋顶正南照片-" + i, "B2");
                                    i++;
                                }
                            }
                            //屋顶西南照片
                            if (StringUtil.isNotBlank(entrySurvey.getRoofPhotoThree())) {
                                String[] roofPhotoThreeList = entrySurvey.getRoofPhotoThree().split(",");
                                i = 1;
                                for (String roofPhotoThree : roofPhotoThreeList) {
                                    uploadFileApply(partnersContractNumber, roofPhotoThree, roofType+"-屋顶西南照片-" + i, "B2");
                                    i++;
                                }
                            }
                        }
                        if ((fileCodeS.isEmpty() || fileCodeS.contains("B3")) && flagB3) {
                            CrmCustomerEntryDesign entryDesign = crmCustomerEntryDesignDao.findByEntryIdAndProjectId2(entry.getId(), projectId);
                            if (entryDesign != null) {
                                //设计图纸
                                if (StringUtil.isNotBlank(entryDesign.getDesignDrawings())) {
                                    String[] designDrawings = entryDesign.getDesignDrawings().split(",");
                                    i = 1;
                                    for (String designDrawing : designDrawings) {
                                        uploadFileApply(partnersContractNumber, designDrawing, roofType+"-设计图纸-" + i, "B3");
                                        i++;
                                    }
                                }
                            }

                            //入户全景照片
                            if (StringUtil.isNotBlank(entrySurvey.getVrRoofFour())) {
                                String[] vrRoofFourList = entrySurvey.getVrRoofFour().split(",");
                                i = 1;
                                for (String vrRoofFour : vrRoofFourList) {
                                    uploadFileApply(partnersContractNumber, vrRoofFour, roofType+"-入户全景照片-" + i, "B3");
                                    i++;
                                }
                            }
                            //房屋轮廓照片
                            if (StringUtil.isNotBlank(entrySurvey.getHouseOutlinePhoto())) {
                                String[] houseOutlinePhotoList = entrySurvey.getHouseOutlinePhoto().split(",");
                                i = 1;
                                for (String houseOutlinePhoto : houseOutlinePhotoList) {
                                    uploadFileApply(partnersContractNumber, houseOutlinePhoto, roofType+"-房屋轮廓照片-" + i, "B3");
                                    i++;
                                }
                            }

                            // 房屋内部结构照片
                            if (StringUtil.isNotBlank(entrySurvey.getRoofPhotoFacade())) {
                                String[] roofPhotoFacadeList = entrySurvey.getRoofPhotoFacade().split(",");
                                i = 1;
                                for (String roofPhotoFacade : roofPhotoFacadeList) {
                                    uploadFileApply(partnersContractNumber, roofPhotoFacade, roofType+"-房屋内部结构照片-" + i, "B3");
                                    i++;
                                }
                            }

                            // 房屋内部环境照片
                            if (StringUtil.isNotBlank(entrySurvey.getRoofPhotoInterior())) {
                                String[] roofPhotoInteriorList = entrySurvey.getRoofPhotoInterior().split(",");
                                i = 1;
                                for (String roofPhotoInterior : roofPhotoInteriorList) {
                                    uploadFileApply(partnersContractNumber, roofPhotoInterior, roofType+"-房屋内部环境照片-" + i, "B3");
                                    i++;
                                }
                            }
                            //现场勘测表
                            if (StringUtil.isNotBlank(entrySurvey.getSurveyFiles())) {
                                String[] surveyFileList = entrySurvey.getSurveyFiles().split(",");
                                i = 1;
                                for (String surveyFile : surveyFileList) {
                                    uploadFileApply(partnersContractNumber, surveyFile, roofType+"-现场勘测表-" + i, "B3");
                                    i++;
                                }
                            }
                        }
                    }
                    //房产证
                    if ((fileCodeS.isEmpty() || fileCodeS.contains("A2")) && flagA2) {
                        if (StringUtil.isNotBlank(surveyRecord.getHouseOwnership())) {
                            String[] houseOwnershipList = surveyRecord.getHouseOwnership().split(",");
                            for (String houseOwnership : houseOwnershipList) {
                                uploadFileApply(partnersContractNumber, houseOwnership, "房产证-" + i, "A2");
                                i++;
                            }
                        }
                        if (StringUtil.isNotBlank(entry.getResidenceBooklet())){
                            String[] residenceBookletList = entry.getResidenceBooklet().split(",");
                            for (String residenceBooklet : residenceBookletList) {
                                uploadFileApply(partnersContractNumber, residenceBooklet, "户口本复印件-" + j, "A2");
                                j++;
                            }
                        }

                    }
                }else {
                    return Result.fail("勘测记录为空！");
                }
                //身份证正面
                if ( (fileCodeS.isEmpty() || fileCodeS.contains("A1")) && flagA1) {
                    // 个人
                    if ("1".equals(entry.getTenantType())) {
                        // 身份证正面
                        String idCardFront = entry.getIdCardFront();
                        uploadFileApply(partnersContractNumber, idCardFront, "身份证正面", "A1");
                        // 身份证反面
                        String idCardBack = entry.getIdCardBack();
                        uploadFileApply(partnersContractNumber, idCardBack, "身份证反面", "A1");
                    }
                    else {
                        // 营业执照
                        String regnoUrl = orgFiles.getRegnoUrl();
                        uploadFileApply(partnersContractNumber, regnoUrl, "营业执照", "A1");
                        //法人身份证正面
                        String idCardFront = entry.getIdCardFront();
                        uploadFileApply(partnersContractNumber, idCardFront, "法人身份证正面", "A1");
                        //法人身份证反面
                        String idCardBack = entry.getIdCardBack();
                        uploadFileApply(partnersContractNumber, idCardBack, "法人身份证反面", "A1");
                    }
                }
                if ((fileCodeS.isEmpty() || fileCodeS.contains("A6")) && "1".equals(entry.getTenantType()) && flagA6) {
                    // 共签人身份证正面
                    if (StringUtil.isNotBlank(entry.getBpCardFront())) {
                        String bpIdCardFront = entry.getBpCardFront();
                        uploadFileApply(partnersContractNumber, bpIdCardFront, "共签人身份证正面", "A6");
                    }
                    // 共签人身份证反面
                    if (StringUtil.isNotBlank(entry.getBpCardBack())) {
                        String bpCardBack = entry.getBpCardBack();
                        uploadFileApply(partnersContractNumber, bpCardBack, "共签人身份证反面", "A6");
                    }
                    // 共签人子女证明材料
                    if (StringUtil.isNotBlank(entry.getBpFile())) {
                        String bpFile = entry.getBpFile();
                        String[] imgs = bpFile.split(",");
                        int i = 1;
                        for (String img : imgs) {
                            if (StringUtil.isNotBlank(img)) {
                                uploadFileApply(partnersContractNumber, img, "共签人子女证明材料-" + i, "A6");
                                i++;
                            }
                        }
                    }
                }
                //银行卡照片
                if ((fileCodeS.isEmpty() || fileCodeS.contains("A4")) && flagA4) {
                    String bankCard = entry.getBankCard();
                    uploadFileApply(partnersContractNumber, bankCard, "银行卡照片", "A4");
                }
            }
            if(StringUtil.equalsAny(type,"2","3")){ //完工、并网
                int i = 1;
                for (CrmAcceptingReportDetail reportDetail : reportDetailList) {
                    String projectId = reportDetail.getProjectId();
                    String roofType = crmCustomerEntryProjectDao.getRoofTypeByProjectId(entry.getId(), projectId);
                    if (fileCodeS.isEmpty() || fileCodeS.contains("B4")) {
                        if (StringUtil.isNotBlank(reportDetail.getDzjc2())) {
                            i=1;
                            String[] dzjcs = reportDetail.getDzjc2().split(",");
                            for (String dzjc : dzjcs) {
                                uploadFileApply(partnersContractNumber, dzjc, roofType+"-电站基础照片-" + i, "B4");
                                i++;
                            }
                        }
                        if (StringUtil.isNotBlank(reportDetail.getZjImg5())) {
                            // 航拍图照片
                            i = 1;
                            String[] componentImg3s = reportDetail.getZjImg5().split(",");
                            for (String componentImg3 : componentImg3s) {
                                uploadFileApply(partnersContractNumber, componentImg3, roofType+"-组件安装-整体照片-" + i, "B4");
                                i++;
                            }
                        }
                        if (StringUtil.isNotBlank(reportDetail.getSizeMeasureImgs())) {
                            // 屋顶线缆安装照片
                            i = 1;
                            String[] imgs = reportDetail.getSizeMeasureImgs().split(",");
                            for (String img : imgs) {
                                uploadFileApply(partnersContractNumber, img, roofType+"-屋顶线缆安装照片-" + i, "B4");
                                i++;
                            }
                        }
                        if (StringUtil.isNotBlank(reportDetail.getComponentImg1())) {
                            i = 1;
                            String[] componentImg1s = reportDetail.getComponentImg1().split(",");
                            for (String componentImg1 : componentImg1s) {
                                uploadFileApply(partnersContractNumber, componentImg1, roofType+"-组件安装-倾角照片-" + i, "B4");
                                i++;
                            }
                        }
                        if (StringUtil.isNotBlank(reportDetail.getComponentImg2())) {
                            i = 1;
                            String[] componentImg2s = reportDetail.getComponentImg2().split(",");
                            for (String componentImg2 : componentImg2s) {
                                uploadFileApply(partnersContractNumber, componentImg2, roofType+"-组件安装-方位角照片-" + i, "B4");
                                i++;
                            }
                        }
                        if (StringUtil.isNotBlank(reportDetail.getNbqZbImg())) {
                            i = 1;
                            String[] nbqZbImgs = reportDetail.getNbqZbImg().split(",");
                            for (String nbqZbImg : nbqZbImgs) {
                                uploadFileApply(partnersContractNumber, nbqZbImg, roofType+"-并网箱逆变器整体照片-" + i, "B4");
                                i++;
                            }
                        }
                        if (StringUtil.isNotBlank(reportDetail.getTotalImgs())) {
                            i = 1;
                            String[] totalImgs = reportDetail.getTotalImgs().split(",");
                            for (String totalImg : totalImgs) {
                                uploadFileApply(partnersContractNumber, totalImg, roofType+"-组串接入部位照片-" + i, "B4");
                                i++;
                            }
                        }
                        if (StringUtil.isNotBlank(reportDetail.getBwInnerImg())) {
                            i = 1;
                            String[] bwInnerImgs = reportDetail.getBwInnerImg().split(",");
                            for (String bwInnerImg : bwInnerImgs) {
                                uploadFileApply(partnersContractNumber, bwInnerImg, roofType+"-并网箱-内部照片-" + i, "B4");
                                i++;
                            }
                        }
                        if (StringUtil.isNotBlank(reportDetail.getJdImg1())) {
                            i = 1;
                            String[] jdImg1s = reportDetail.getJdImg1().split(",");
                            for (String jdImg1 : jdImg1s) {
                                uploadFileApply(partnersContractNumber, jdImg1, roofType+"-接地系统照片(组件与组件)-" + i, "B4");
                                i++;
                            }
                        }
                        if (StringUtil.isNotBlank(reportDetail.getJdImg2())) {
                            i = 1;
                            String[] jdImg2s = reportDetail.getJdImg2().split(",");
                            for (String jdImg2 : jdImg2s) {
                                uploadFileApply(partnersContractNumber, jdImg2, roofType+"-接地系统照片(组件与支架)-" + i, "B4");
                                i++;
                            }
                        }
                        if (StringUtil.isNotBlank(reportDetail.getJdImg3())) {
                            i = 1;
                            String[] jdImg3s = reportDetail.getJdImg3().split(",");
                            for (String jdImg3 : jdImg3s) {
                                uploadFileApply(partnersContractNumber, jdImg3, roofType+"-接地系统照片(支架与接地扁铁)-" + i, "B4");
                                i++;
                            }
                        }
                        if (StringUtil.isNotBlank(reportDetail.getJdImg5())) {
                            i = 1;
                            String[] jdImg5s = reportDetail.getJdImg5().split(",");
                            for (String jdImg5 : jdImg5s) {
                                uploadFileApply(partnersContractNumber, jdImg5, roofType+"-接地阻值照片-" + i, "B4");
                                i++;
                            }
                        }
                    }
                    if (fileCodeS.isEmpty() || fileCodeS.contains("B5")) {
                        if (StringUtil.isNotBlank(reportDetail.getZjPlateImg())) {
                            i = 1;
                            String[] zjPlateImgs = reportDetail.getZjPlateImg().split(",");
                            for (String zjPlateImg : zjPlateImgs) {
                                uploadFileApply(partnersContractNumber, zjPlateImg, roofType+"-组件铭牌照片-" + i, "B5");
                                i++;
                            }
                        }
                    }
                    if (fileCodeS.isEmpty() || fileCodeS.contains("B6")) {
                        if (StringUtil.isNotBlank(reportDetail.getNbqPlateImg())) {
                            i = 1;
                            String[] nbqPlateImgs = reportDetail.getNbqPlateImg().split(",");
                            for (String nbqPlateImg : nbqPlateImgs) {
                                uploadFileApply(partnersContractNumber, nbqPlateImg, roofType+"-逆变器铭牌照片-" + i, "B6");
                                i++;
                            }
                        }
                    }

                    if (fileCodeS.isEmpty() || fileCodeS.contains("B7")) {
                        if (StringUtil.isNotBlank(reportDetail.getOtherImgs5())) {
                            i = 1;
                            String[] otherImgs5s = reportDetail.getOtherImgs5().split(",");
                            for (String otherImgs5 : otherImgs5s) {
                                uploadFileApply(partnersContractNumber, otherImgs5, roofType+"-水槽细节照片-" + i, "B7");
                                i++;
                            }
                        }
                    }
                    if (fileCodeS.isEmpty() || fileCodeS.contains("B8")) {
                        if (StringUtil.isNotBlank(reportDetail.getOtherImgs6())) {
                            i = 1;
                            String[] otherImgs6s = reportDetail.getOtherImgs6().split(",");
                            for (String otherImgs6 : otherImgs6s) {
                                uploadFileApply(partnersContractNumber, otherImgs6, roofType+"-落水管照片-" + i, "B8");
                                i++;
                            }
                        }
                    }
                    if (fileCodeS.isEmpty() || fileCodeS.contains("B10")) {
                        if (StringUtil.isNotBlank(reportDetail.getOtherImgs7())) {
                            i = 1;
                            String[] otherImgs7s = reportDetail.getOtherImgs7().split(",");
                            for (String otherImgs7 : otherImgs7s) {
                                uploadFileApply(partnersContractNumber, otherImgs7, roofType+"-假梁-斜梁方向-" + i, "B10");
                                i++;
                            }
                        }
                    }
                    if (fileCodeS.isEmpty() || fileCodeS.contains("B9")) {
                        if (StringUtil.isNotBlank(reportDetail.getZjReport())) {
                            i = 1;
                            String[] zjReports = reportDetail.getZjReport().split(",");
                            for (String zjReport : zjReports) {
                                uploadFileApply(partnersContractNumber, zjReport, roofType+"-项目施工验收单（自检单）-" + i, "B9");
                                i++;
                            }
                        }
                    }
                }
            }
            if(StringUtil.equalsAny(type,"3")){ //并网
                int i = 1;
                if (fileCodeS.isEmpty() || fileCodeS.contains("D2")) {
                    if (StringUtil.isNotBlank(entry.getContract())) {
                        String[] contractList = entry.getContract().split(",");
                        for (String contractUrl : contractList) {
                            uploadFileApply(partnersContractNumber, contractUrl, "购售电合同-" + i, "D2");
                            i++;
                        }
                    }
                }
                if (fileCodeS.isEmpty() || fileCodeS.contains("D1")) {
                    if (StringUtil.isNotBlank(report.getYxImg())) {
                        i = 1;
                        String[] yxImgs = report.getYxImg().split(",");
                        for (String yxImg : yxImgs) {
                            uploadFileApply(partnersContractNumber, yxImg, "发电截图-" + i, "D1");
                            i++;
                        }
                    }
                }
                if (fileCodeS.isEmpty() || fileCodeS.contains("D8")) {
                    if (StringUtil.isNotBlank(contract.getContractUrl())) {
                        i = 1;
                        String[] contractUrls = contract.getContractUrl().split(",");
                        for (String contractUrl : contractUrls) {
                            uploadFileApply(partnersContractNumber, contractUrl, "屋顶租赁合同-" + i, "D8");
                            i++;
                        }
                    }
                }
                if (fileCodeS.isEmpty() || fileCodeS.contains("D14")) {
                    if ("2".equals(entry.getFilingType())) {
                        if (StringUtil.isNotBlank(surveyRecord.getFilingDocumentPhoto())) {
                            i = 1;
                            String[] filingDocumentPhotoList = surveyRecord.getFilingDocumentPhoto().split(",");
                            for (String filingDocumentPhoto : filingDocumentPhotoList) {
                                uploadFileApply(partnersContractNumber, filingDocumentPhoto, "备案证-" + i, "D14");
                                i++;
                            }
                        }
                    }
                }
            }
        }catch (IllegalArgumentException e){
            return Result.fail(e.getMessage());
        }
        return Result.ok();
    }

    public JSONObject uploadFileApply(String reqContNumber, String fileUrl, String fileName ,String fileCode){
        fileUrl = commonStaticImgPath+fileUrl;
        fileName = fileName+fileUrl.substring(fileUrl.lastIndexOf("."));
        Map<String,Object> map = new HashMap<>();
        map.put("capital","04");
        map.put("reqContNumber",clientId+reqContNumber);
        map.put("fileUrl",fileUrl);
        map.put("fileName",fileName);
        map.put("fileCode",fileCode);
        logger.info(" uploadFileApply 华融附件上传参数：{}",new Gson().toJson(map));
        JSONObject jsonObject = PartnerApiUtils.doPostForHRUploadFile(map, DH + "/open/link/uploadFile");
        if (!jsonObject.getBoolean("success")){
            throw new IllegalArgumentException(fileName+"附件上传失败！失败原因："+jsonObject.getString("msg"));
        }
        return jsonObject;
    }

    /**
     * 首次进件/合规进件/二次进件
     */
    public Result accessProjectApply(CustomerEntry entry, CrmCustomerIncomingApplication incomingApplication,
                                     CrmPartner partner, String howManyTimes) {
        HuaRongInputPiece huaRongInputPiece = new HuaRongInputPiece();
        huaRongInputPiece.setHowManyTimes(howManyTimes);
        huaRongInputPiece.setPartner("nenghui");
        String roofType = "";
        boolean mixRoofFlag = false;//是否是多产品
        if (entry.getProjectNum()>1){
            mixRoofFlag = true;
            roofType = "10";//混合屋顶
        }else {
            if ("2".equals(howManyTimes)){
                roofType =  sysCapitalDictDao.getDictKey2(entry.getPartnerId(), "roof_type", entry.getRoofType());
            }else {
                roofType = sysCapitalDictDao.getDictKey(entry.getPartnerId(), "roof_type", entry.getRoofType());
            }
        }
        huaRongInputPiece.setRoofType(roofType);//屋顶类型
        huaRongInputPiece.setCapital(entry.getPartnerId());
        huaRongInputPiece.setTenantType(entry.getTenantType());
        huaRongInputPiece.setCertificateNumber(entry.getManagementType()); //项目公司编码

        huaRongInputPiece.setCertificateType("A01"); //项目公司证件类型 √
//        huaRongInputPiece.setDistributor(entry.getTraderName());

        huaRongInputPiece.setElectronicSignFlag("1");  //是否电子签约 1 ：是 0：否 默认 ：是
        huaRongInputPiece.setLeaseItemCategory("household_light");  //租赁物类型
        huaRongInputPiece.setManufacturer("上海能辉科技股份有限公司"); //厂商
        CrmCustomerContractManagement contract = contractManagementDao.getContractByEntryId(entry.getId());
        if(contract != null){
            huaRongInputPiece.setPeasantContCode(entry.getPowerStationCode());//农户合同
        }

        huaRongInputPiece.setPropertyType("0"); //0：动产
        huaRongInputPiece.setSeller("上海能辉科技股份有限公司"); //出卖人
        huaRongInputPiece.setBusinessType("1022_0"); //租赁类型

        //perInfo (业主信息)
        /**
         *         leaseType  租赁类型   1022_0
         *         legalRepresen tative	法人代表姓名
         *         accountName	二类卡户名
         *         bankName	二类卡开户行
         *         accountNo	二类卡银行账号
         * */
        huaRongInputPiece.setTenantName(entry.getTenantName());
        huaRongInputPiece.setSex(entry.getGender());
        if (entry.getBirthdayDate() != null) {
            huaRongInputPiece.setBirthdayDate(DateUtils.formatDate(entry.getBirthdayDate(), "yyyy-MM-dd"));
        }
        if(entry.getTenantType().equals("1")){
            huaRongInputPiece.setidCardType("B01");
        }else {
            huaRongInputPiece.setidCardType("A01");
        }
        huaRongInputPiece.setidCode(entry.getIdCode());
        if (entry.getIcValidityBegin() != null) {
            huaRongInputPiece.seticValidityBegin(DateUtils.formatDate(entry.getIcValidityBegin(), "yyyy-MM-dd"));
        }
        if (entry.getIcValidityEnd() != null) {
            huaRongInputPiece.seticValidityEnd(DateUtils.formatDate(entry.getIcValidityEnd(), "yyyy-MM-dd"));
        }
        if ("1".equals(entry.getTenantType())){
            if ("1".equals(entry.getFilingType())){
                CrmTenantYxBankCard card=tenantYxBankCardDao.getByIdCard(entry.getIdCode(),
                        entry.getManagementType(), entry.getPartnerId());
                huaRongInputPiece.setSecondAccountCode(card.getAccountCode());//二类卡银行账号
                huaRongInputPiece.setSecondAccountName(card.getAccountName());//二类卡账户户名
                huaRongInputPiece.setSecondBankName(card.getOpenBankName());//二类卡的开户行名称
            }
            // 共签人开启 且客户年龄大于 设置值：大于等于age需要共签人
            if ("1".equals(partner.getOverageFlag()) && entry.getAge() > partner.getNeedSignerAge()) {
                huaRongInputPiece.setIsCosigner("1");
                huaRongInputPiece.setCosigneridCardNo(entry.getBpIdCard());
                huaRongInputPiece.setCosignerName(entry.getBpName());
                huaRongInputPiece.setCosignerIdCardType("B01");
                huaRongInputPiece.setCosignerTelephoneNum(entry.getBpMobile());
            }
            else {
                huaRongInputPiece.setIsCosigner("0");
            }
            huaRongInputPiece.setAge(entry.getAge().toString());
        }
        huaRongInputPiece.setMobile(entry.getMobile());
        huaRongInputPiece.setBankName(entry.getBankName());
        huaRongInputPiece.setTssBankNumName(entry.getTssBankNumName());
        huaRongInputPiece.setBankCode(entry.getBankCode());
        huaRongInputPiece.setAccountBankBranch(entry.getTssBankNumName());


//        //租赁方案信息
        huaRongInputPiece.setLeaseScheme(entry.getProjectCode());
//        String payCycle = dealHRPayCycle(entry.getPayCycle());
        // 华融的租金支付周期 实际是指华融对项目公司的考核频率， 1按月支付 2按季支付 3按半年支付 4按年支付
        huaRongInputPiece.setRepayFrequency("4"); //华融对项目公司的考核频率 按年考核
        huaRongInputPiece.setNominalPrice("0"); // 剩余留购款
        Integer maxYear = rentVariableDao.getMaxYear(entry.getId());
//        huaRongInputPiece.setLeaseTimes(String.valueOf(dealLeaseTerm(payCycle, maxYear))); // 期数
        huaRongInputPiece.setLeaseTimes("25"); // 期数固定25次


        //进件模块
        ///进件序号
        huaRongInputPiece.setCapitalNumber(clientId+incomingApplication.getPartnersContractNumber());
        ///备案方式
        huaRongInputPiece.setFilingType(entry.getFilingType());//备案类型:1.农户备案 2.项目公司备案
        // 组件品牌
        Map<String, String> componentMap = PartnerBrandUtils.getBrandList("3", PartnerConstants.PARTNER_ID_HR);
        // 逆变器品牌
        Map<String, String> inverterMap = PartnerBrandUtils.getBrandList("1", PartnerConstants.PARTNER_ID_HR);
        AtomicBoolean checkCompBrand = new AtomicBoolean(true); // 校验组件品牌是否为空
        AtomicBoolean checkInvertBrand = new AtomicBoolean(true); // 校验逆变器品牌是否为空
        if("2".equals(howManyTimes)){
            String mergeTime = DateUtils.formatDate(entry.getMergeTime(), "yyyy-MM-dd");
            huaRongInputPiece.setConnectedDate(mergeTime); //第二次进件时必须 传输；yyyy-MM-dd
            huaRongInputPiece.setPowerGenerationNo(entry.getGeneratorNo());  //发电户号 第二次进件时必须传输
            List<Record> modules = new ArrayList<>();
            if (mixRoofFlag){
                modules = entryDao.findModuleByEntryId2(entry.getId());
            }else {
                modules = entryDao.findModuleByEntryId(entry.getId());
            }
            List<Record> inverters = entryDao.findInverterByEntryId(entry.getId());
            String inverterModel = "";
            String inverterNumber = "";
            String inverterBrand = "";
            for (Record inverter : inverters) {
                // 逆变器规格型号
                if (StringUtil.isBlank(inverterModel)) {
                    inverterModel = inverter.getStr("spec");
                } else {
                    inverterModel = inverterModel + "," + inverter.getStr("spec");
                }
                // 逆变器编码
                if (StringUtil.isBlank(inverterNumber)) {
                    inverterNumber = inverter.getStr("barcode");
                } else {
                    inverterNumber = inverterNumber + "," + inverter.getStr("barcode");
                }
                // 逆变器品牌
                inverterBrand = inverterMap.get(inverter.getStr("brand"));
            }
            if (StringUtil.isBlank(inverterBrand)) {
                checkInvertBrand.set(false);
            }
            String finalInverterBrand = inverterBrand;
            String finalInverterModel = inverterModel;
            String finalInverterNumber = inverterNumber;
            HuaRongEquipList equip = new HuaRongEquipList();
            int quantity = 0;//装机容量
            int blockNumber = 0;//组件块数
            String materialBrands = "";//组件品牌
            BigDecimal price = BigDecimal.ZERO;//epc单价 混合屋顶要 除以 所有房型的总装机容量
            List<MixtureRoofInfo> mixtureRoofInfoList = new ArrayList<>();
            for (Record r : modules) {
                String spec = r.getStr("spec");
                if (spec.contains("KW")) {
                    spec = spec.substring(0, spec.indexOf("KW"));
                }
                int capatial = Integer.parseInt(spec) * r.getBigDecimal("amount").intValue();
                quantity =  quantity + capatial;
                blockNumber = blockNumber + r.getBigDecimal("amount").intValue();//组件块数
                if (!mixRoofFlag){
                    equip.setModulePower(spec);//组件功率
                    equip.setModel(r.getStr("model"));//组件型号
                    equip.setPackageSpecification("N01");//组件规格   N01：N 型  P01：P 型
                    equip.setBoardType("01");// 组件板面类型  01：双玻 02：单玻
                }
                //组件品牌
                String materialBrand = "";
                if (componentMap.containsKey(r.getStr("brand"))) {
                    materialBrand = componentMap.get(r.getStr("brand"));
                    if (StringUtil.isBlank(materialBrands)){
                        materialBrands = materialBrand;
                    }else {
                        // 获取华融的品牌名称
                        materialBrands = materialBrands + "," + materialBrand;
                    }
                }
                if (StringUtil.isBlank(materialBrands)) {
                    checkCompBrand.set(false);
                }
                //获取产品
                CrmProjectSetting project = projectSettingDao.get(r.getStr("project_id"));
                //当前产品对应的屋顶类型
                String roofType1 = crmCustomerEntryProjectDao.getRoofTypeByProjectId(entry.getId(), r.getStr("project_id"));
                //转换屋顶类型
                String roofType2 = sysCapitalDictDao.getDictKey2(entry.getPartnerId(), "roof_type", roofType1);

                if (!"阳光房".equals(roofType1)) {
                    roofType1 = "其他";
                }
                BigDecimal epcPriceSet = epcPriceSetDao.getEpcPriceSet(materialBrand, spec, roofType1);
                BigDecimal projectPrice;
                if(!mixRoofFlag){
                    //单产品
                    price = entry.getEpcPrice();
                    projectPrice = entry.getEpcPrice();
                    if (epcPriceSet != null) {
                        price = price.add(epcPriceSet);
                    }
                }else {
                    //多产品
                    projectPrice = project.getEpcPrice();
                    if (epcPriceSet != null) {
                        projectPrice = projectPrice.add(epcPriceSet);
                    }
                    BigDecimal price1 = new BigDecimal(capatial).multiply(projectPrice);
                    price = price.add(price1);
                }
                equip.setInverterBrand(finalInverterBrand);//逆变器品牌
                equip.setInverterTypeNumber(finalInverterModel);//逆变器型号
                equip.setEquipNum(finalInverterNumber);//逆变器序列号
                //混合屋顶信息
                MixtureRoofInfo mixtureRoof = new MixtureRoofInfo();
                mixtureRoof.setRoofType(roofType2);//屋顶类型
                mixtureRoof.setBoardType("01");// 组件板面类型  01：双玻 02：单玻
                mixtureRoof.setBlockNumber(String.valueOf(r.getBigDecimal("amount").intValue()));//组件块数
                mixtureRoof.setModulePower(spec);//组件功率
                mixtureRoof.setQuantity(String.valueOf(capatial));//装机容量
                mixtureRoof.setEquipValue(projectPrice.stripTrailingZeros().toPlainString());//单价
                mixtureRoof.setPackageSpecification("N01");//组件规格   N01：N 型  P01：P 型
                mixtureRoofInfoList.add(mixtureRoof);
            }


            //省市区转换为编码
            Record province = AddressUtils.getProvinceCode(entry.getProvince());
            Record city = AddressUtils.getCityCode(entry.getCity(), province.getLong("ProvinceID"));
            equip.setEquipUsePlace(province.getLong("regionalism_code").toString() + "," +
                    city.getLong("regionalism_code").toString() + "," +
                    AddressUtils.getDistrictCode(entry.getArea(), city.getLong("CityID")).toString());//存放地点
            equip.setEquipUsePlaceDetails(entry.getProvince() + entry.getCity() + entry.getArea() + entry.getAddress());//存放地点详细地址
            equip.setEquipName(entry.getTenantName() + Arith.div2P(new BigDecimal(quantity), new BigDecimal(1000)) + "KW"
                    + entry.getPowerStationCode() + "的电站");
            equip.setQuantity(String.valueOf(quantity));//装机容量
            equip.setBlockNumber(String.valueOf(blockNumber));//组件块数
            equip.setEquipmentDeliveryDate(mergeTime);
            equip.setPurchasedate(mergeTime);
            equip.setConfirmNetValueDate(mergeTime);
            equip.setEntryDate(mergeTime);
            equip.setComponentNameplate(materialBrands);//组件品牌
            equip.setManufacturer(materialBrands);//组件生产单位


            BigDecimal originalAssetValue = BigDecimal.ZERO;
            if(!mixRoofFlag){
                //单产品
                equip.setEquipValue(price.stripTrailingZeros().toPlainString());//epc单价
                //租赁物原值
                originalAssetValue = price.multiply(new BigDecimal(quantity));
            }else {
                //多产品
                equip.setEquipValue(price.divide(new BigDecimal(quantity),2,RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());//epc单价
                //租赁物原值
                originalAssetValue = price;
            }
            equip.setOriginalAssetValue(originalAssetValue.stripTrailingZeros().toPlainString());//租赁物原值/评估
            // 不含税原价 = 租赁物原值 - 租赁物原值*0.13/（1+0.13），保留两位小数 四舍五入
            BigDecimal netOriginalAssetValue = originalAssetValue.subtract(originalAssetValue.multiply(new BigDecimal("0.13")).divide(new BigDecimal("1.13"), 2, RoundingMode.HALF_UP));
            equip.setNetOriginalAssetValue(netOriginalAssetValue.stripTrailingZeros().toPlainString());
            //确定的租赁物价值 (元)
            equip.setConfirmValue(originalAssetValue.stripTrailingZeros().toPlainString());
            //确认折旧(元)
            equip.setAccumulatedDepreciation("0");
            //始确认物净值
            equip.setNetAssetValue(originalAssetValue.stripTrailingZeros().toPlainString());
            if (mixRoofFlag){
                //混合房型
                equip.setRoofList(mixtureRoofInfoList);
            }
            List<HuaRongEquipList> equips = new ArrayList<>();
            equips.add(equip);
            huaRongInputPiece.setEquipList(equips);
        }else {
            List<Record> componentLst = entryComponentDao.findByEntryId3(entry.getId());

            List<Record> equipsList = componentLst.stream().filter(r -> r.getStr("item_type").equals("3")).collect(Collectors.toList());
            List<Record> nbqList = componentLst.stream().filter(r -> r.getStr("item_type").equals("1")).collect(Collectors.toList());
            List<Record> nbqBrands = new ArrayList<>();
            for (Record record : nbqList) {
                String model = record.getStr("model");
                nbqBrands = supplyMaterialDao.findBrandBySpec(model, "1");
                break;
            }
            String nbqBrandName = "";
            String nbqMaterialModel = "";
            for (Record nbqBrand : nbqBrands) {
//                nbqBrandName = nbqBrand.getStr("material_brand");
                if (inverterMap.containsKey(nbqBrand.getStr("material_brand"))) {
                    // 获取华融的品牌名称
                    nbqBrandName =  inverterMap.get(nbqBrand.getStr("material_brand"));
                    break;
                }
            }
            if (StringUtil.isBlank(nbqBrandName)) {
                checkInvertBrand.set(false);
            }
            StringBuilder materialModelSb = new StringBuilder();
            nbqBrands.forEach(r -> {
                materialModelSb.append(","+r.getStr("material_model"));
            });
            if(materialModelSb.length()>0)
                nbqMaterialModel = materialModelSb.substring(1);
            String finalNbqBrandName = nbqBrandName;
            String finalNbqMaterialModel = nbqMaterialModel;
            HuaRongEquipList equip = new HuaRongEquipList();
            int quantity = 0;//装机容量
            int blockNumber = 0;//组件块数
            BigDecimal price = BigDecimal.ZERO;//epc单价 混合屋顶要 除以 所有房型的总装机容量
            List<MixtureRoofInfo> mixtureRoofInfoList = new ArrayList<>();
            for (Record r : equipsList) {
                String model = r.getStr("model");
                if(model.contains("KW")){
                    model = model.substring(0,model.indexOf("KW"));
                }
                //装机容量
                int capatial = Integer.parseInt(model) * r.getInt("num");
                quantity =  quantity + capatial;
                blockNumber = blockNumber + r.getInt("num");

                if (!mixRoofFlag){
                    //单产品
                    equip.setModulePower(model);//组件功率
                    equip.setBoardType("01");// 组件板面类型  01：双玻 02：单玻
                    equip.setPackageSpecification("N01");//组件规格   N01：N 型  P01：P 型
                }
                //组件品牌
                List<Record> brands = supplyMaterialDao.findBrandBySpec(r.getStr("model"), "3");
                String materialBrand = "";
                for (Record brand : brands) {
                    if (componentMap.containsKey(brand.getStr("material_brand"))) {
                        // 获取华融的品牌名称
                        materialBrand = componentMap.get(brand.getStr("material_brand"));
                        break;
                    }
                }
                if (StringUtil.isBlank(materialBrand)) {
                    checkCompBrand.set(false);
                }
                equip.setComponentNameplate(materialBrand);//组件品牌
                //获取产品
                CrmProjectSetting project = projectSettingDao.get(r.getStr("project_id"));
                //当前产品对应的屋顶类型
                String roofType1 = crmCustomerEntryProjectDao.getRoofTypeByProjectId(entry.getId(), r.getStr("project_id"));
                //转换屋顶类型
                String roofType2 = sysCapitalDictDao.getDictKey2(entry.getPartnerId(), "roof_type", roofType1);
                if(!"阳光房".equals(roofType1)){
                    roofType1 = "其他";
                }
                BigDecimal epcPriceSet = epcPriceSetDao.getEpcPriceSet(materialBrand, model, roofType1);
                BigDecimal projectPrice;
                if(!mixRoofFlag){
                    //单产品
                    price = entry.getEpcPrice();
                    projectPrice = entry.getEpcPrice();
                    if (epcPriceSet != null) {
                        price = price.add(epcPriceSet);
                    }
                }else {
                    //多产品
                    projectPrice = project.getEpcPrice();
                    if (epcPriceSet != null) {
                        projectPrice = projectPrice.add(epcPriceSet);
                    }
                    BigDecimal price1 = new BigDecimal(capatial).multiply(projectPrice);
                    price = price.add(price1);
                }
                equip.setManufacturer(materialBrand);//组件生产单位
                equip.setInverterBrand(finalNbqBrandName);//逆变器品牌
                equip.setInverterTypeNumber(finalNbqMaterialModel);//逆变器型号
                //混合屋顶信息
                MixtureRoofInfo mixtureRoof = new MixtureRoofInfo();
                mixtureRoof.setRoofType(roofType2);//屋顶类型
                mixtureRoof.setBoardType("01");// 组件板面类型  01：双玻 02：单玻
                mixtureRoof.setBlockNumber(String.valueOf(r.getInt("num")));//组件块数
                mixtureRoof.setModulePower(model);//组件功率
                mixtureRoof.setQuantity(String.valueOf(capatial));//装机容量
                mixtureRoof.setEquipValue(projectPrice.stripTrailingZeros().toPlainString());//单价
                mixtureRoof.setPackageSpecification("N01");//组件规格   N01：N 型  P01：P 型
                mixtureRoofInfoList.add(mixtureRoof);
            }
            //省市区转换为编码
            Record province = AddressUtils.getProvinceCode(entry.getProvince());
            Record city = AddressUtils.getCityCode(entry.getCity(),province.getLong("ProvinceID"));
            if (entry.getProvince().equals(entry.getCity())) {
                equip.setEquipUsePlace( province.getLong("regionalism_code").toString()+ "," +
                        AddressUtils.getDistrictCode(entry.getArea(),city.getLong("CityID")).toString());     //地址√
            }
            else {
                if ("东莞市".equals(entry.getCity()) || "中山市".equals(entry.getCity()) || "嘉峪关市".equals(entry.getCity()) || "三沙市".equals(entry.getCity())) {
                    equip.setEquipUsePlace(province.getLong("regionalism_code").toString() + "," +
                            city.getLong("regionalism_code").toString());     //地址√
                }else {
                    equip.setEquipUsePlace( province.getLong("regionalism_code").toString() + "," +
                            city.getLong("regionalism_code").toString() + "," +
                            AddressUtils.getDistrictCode(entry.getArea(), city.getLong("CityID")).toString());     //地址√
                }
            }
            equip.setEquipUsePlaceDetails(entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress());//存放地点详细地址

            equip.setEquipName(entry.getTenantName() + Arith.div2P(new BigDecimal(quantity),new BigDecimal(1000))+"KW"
                    + entry.getPowerStationCode()+"的电站");
            equip.setQuantity(String.valueOf(quantity));//装机容量
            equip.setBlockNumber(String.valueOf(blockNumber));//组件块数

            BigDecimal originalAssetValue = BigDecimal.ZERO;
            if(!mixRoofFlag){
                //单产品
                equip.setEquipValue(price.stripTrailingZeros().toPlainString());//epc单价
                //租赁物原值
                originalAssetValue = price.multiply(new BigDecimal(quantity));
            }else {
                //多产品
                equip.setEquipValue(price.divide(new BigDecimal(quantity),2,RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());//epc单价
                //租赁物原值
                originalAssetValue = price;
            }
            equip.setOriginalAssetValue(originalAssetValue.stripTrailingZeros().toPlainString());//租赁物原值/评估
            // 不含税原价 = 租赁物原值 - 租赁物原值*0.13/（1+0.13），保留两位小数 四舍五入
            BigDecimal netOriginalAssetValue  = originalAssetValue.subtract(originalAssetValue.multiply(new BigDecimal("0.13")).divide(new BigDecimal("1.13"),2, RoundingMode.HALF_UP));
            equip.setNetOriginalAssetValue(netOriginalAssetValue.stripTrailingZeros().toPlainString());
            //确定的租赁物价值 (元)
            equip.setConfirmValue(originalAssetValue.stripTrailingZeros().toPlainString());
            //确认折旧(元)
            equip.setAccumulatedDepreciation("0");
            //始确认物净值
            equip.setNetAssetValue(originalAssetValue.stripTrailingZeros().toPlainString());
            if (mixRoofFlag){
                //混合房型
                equip.setRoofList(mixtureRoofInfoList);
            }


            List<HuaRongEquipList> equips = new ArrayList<>();
            equips.add(equip);
            huaRongInputPiece.setEquipList(equips);
        }
        if (!checkCompBrand.get()) {
            throw new IllegalArgumentException("组件规格对应品牌没有匹配上华融已授权的品牌，需要打回重新设计");
        }
        if (!checkInvertBrand.get()) {
            throw new IllegalArgumentException("逆变器规格对应品牌没有匹配上华融已授权的品牌，需要打回重新设计");
        }
        String paramJson = new Gson().toJson(huaRongInputPiece);
        JSONObject resultMap = null;
        if ("2".equals(howManyTimes)){
             resultMap = PartnerApiUtils.clientPostToApi(paramJson, DH + "/open/link/completeInputPiece");
        }else {
             resultMap = PartnerApiUtils.clientPostToApi(paramJson, DH + "/open/link/firstInputPiece");
        }
        if (Objects.isNull(resultMap)) throw new IllegalArgumentException("请求失败！");
        String type = "2";
        String urlName = "";
        String itemStatus = "FR";
        if ("0".equals(howManyTimes)){
            urlName = "华融建档进件接口";
        } else if ("1".equals(howManyTimes)) {
            urlName = "华融进件同步接口";
        }else if ("3".equals(howManyTimes)) {
            urlName = "建档审核资料上传完成接口";
        }else if("2".equals(howManyTimes)){
            type = "5";
            urlName = "华融二次进件同步接口";
            itemStatus = "MR";
        }
        if (resultMap.getBoolean("success")){
            CrmYxProcessDao.addProcess(entry.getId(),type,urlName, paramJson, resultMap.toJSONString(),"0");
            CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),type,itemStatus,"0","0","推送");
            return Result.ok();
        }
        CrmYxProcessDao.addProcess(entry.getId(),type,urlName, paramJson, resultMap.toJSONString(),"1");
        CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),type,null,"1",null,null);
        return Result.fail(resultMap.getString("msg"));
    }

    // 租金支付周期值转换
    public String dealHRPayCycle(String payCycle) {
        // 系统的租金支付周期 1按月支付 2按季支付 3按年支付
        // 华融的租金支付周期 1按月支付 2按季支付 3按半年支付 4按年支付
        if ("3".equals(payCycle)) {
            return "4";
        }
        return payCycle;
    }

    // 计算租金期限
    // 华融的租金支付周期 1按月支付 2按季支付 3按半年支付 4按年支付
    public int dealLeaseTerm(String payCycle, Integer year) {
        int num = 0;
        switch (payCycle) {
            case "1":
                num = 12;
                break;
            case "2":
                num = 4;
                break;
            case "3":
                num = 2;
                break;
            case "4":
                num = 1;
                break;
        }
        if (year == null) {
            year = 25;
        }
        return  year*num;
    }

    //取消进件
    public Result cancelHRApply(CustomerEntry entry,String inputPieceId ,String reason){
        Map<String, Object> map = new HashMap<>();
        map.put("partner","nenghui");
        map.put("capital",entry.getPartnerId());
        map.put("inputPieceId",clientId+inputPieceId);
        map.put("cancelReason",reason);
        if ("1".equals(entry.getTenantType())) {
            map.put("idCardType","B01");
            map.put("id_code",entry.getIdCode());
        }
        else {
            map.put("idCardType","A01");
            map.put("id_code",entry.getRegno());//营业执照，客户类型为单位时有效(信用代码) √
        }
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("cancelHRApply  取消进件 请求参数：inputPieceId:{},json:{}",inputPieceId,jsonStr);
        JSONObject resultMap = PartnerApiUtils.clientPostToApi(jsonStr, DH + "/open/link/terminateProject");
        logger.info("华融取消进件接口返回结果：{}", resultMap);
        if (resultMap!=null){
            if (resultMap.getBoolean("success")){
                CrmYxProcessDao.addProcess(entry.getId(),"2","华融取消进件接口", jsonStr, resultMap.toJSONString(),"0");
            }else {
                throw new IllegalArgumentException(resultMap.getString("msg"));
            }
        }else{
            throw new IllegalArgumentException("请求资方接口失败！");
        }
        return Result.ok();
    }

    //投放单查询
    public JSONArray queryReleOrderInfo(String partnerId, int pageNum) {
        Map<String,Object> map=new HashMap<>();
        map.put("capital",partnerId); //资方id，03:广发  04:华融
        map.put("releOrderStatus","1"); //0：业务员审核中 1：业务员已提交付款申请 2：财务出纳审核中 3：已投放
        map.put("pageNum",pageNum);
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("queryReleOrderInfo  状态查询：json:{}",jsonStr);
        JSONArray jsonObject = PartnerApiUtils.doPostForHRreleOrder(map, DH + "/open/link/releOrderInfo");
        return jsonObject;
    }

    //投放单的发票
    public JSONArray releOrderInfoUpload(Map<String,Object> map) {
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("releOrderInfoUpload  投放单的发票：json:{}",jsonStr);
        JSONArray jsonObject = PartnerApiUtils.doPostForHRreleOrderUpload(map, DH + "/open/link/releOrderInfoUpload");
        if(jsonObject!=null){
            return jsonObject;
        }else{
            throw new IllegalArgumentException("请求失败！");
        }
    }

}
