package com.sifang.modules.partner.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.dao.CrmCustomerEntryTenantChangeRecordDao;
import com.sifang.modules.changes.dao.CrmCustomerEntryTenantChangeRecordDetailDao;
import com.sifang.modules.changes.dao.CustomerEntryChangeDesignComponentDao;
import com.sifang.modules.changes.entity.CrmCustomerEntryChangeDesign;
import com.sifang.modules.changes.entity.CustomerEntryCompletionChangeRecord;
import com.sifang.modules.changes.entity.CrmCustomerEntryTenantChangeRecord;
import com.sifang.modules.changes.entity.CustomerEntrySurveyChangeRecord;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.dao.CrmYxIncomingProcessDao;
import com.sifang.modules.customer.dao.CrmYxProcessDao;
import com.sifang.modules.customer.dao.CustomerEntryComponentDao;
import com.sifang.modules.customer.dao.CustomerEntrySurveyRecordDao;
import com.sifang.modules.customer.entity.*;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.CrmAcceptingReport;
import com.sifang.modules.customer.entity.CrmCustomerIncomingApplication;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.entity.CustomerEntrySurveyRecord;
import com.sifang.modules.factory.BrandFactInfo;
import com.sifang.modules.partner.dto.GuangfaInputPiece;
import com.sifang.modules.partner.dto.InputPieceComponent;
import com.sifang.modules.partner.utils.GuangfaQryContractVO;
import com.sifang.modules.partner.utils.PartnerApiUtils;
import com.sifang.modules.partner.utils.StatusFormVo;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.PlanMaterialEntryDao;
import com.sifang.modules.sunshine.SystemSetting.service.PlanService;
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.supply.stock.dao.SupplyMaterialDao;
import com.sifang.modules.supply.stock.entity.SupplyMaterial;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.dao.SysCapitalDictDao;
import org.apache.commons.lang3.StringUtils;
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.text.ParseException;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

@Service
public class GuangfaOperatingService extends BaseService {

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

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

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

    @Autowired
    private CustomerEntrySurveyRecordDao surveyRecordDao;

    @Autowired
    private CustomerEntryComponentDao entryComponentDao;

    @Autowired
    private SysCapitalDictDao sysCapitalDictDao;

    @Autowired
    private PlanService planService;

    @Autowired
    private CrmCustomerEntryTenantChangeRecordDetailDao tenantChangeRecordDetailDao;

    @Autowired
    CrmAcceptingReportDao reportDao;

    @Autowired
    private SupplyMaterialDao supplyMaterialDao;

    private static Map<String,String> electricSetMap;

    @Autowired
    PlanMaterialEntryDao entryDao;
    @Autowired
    @Lazy
    CustomerEntryChangeDesignComponentDao customerEntryChangeDesignComponentDao;

    static {
        electricSetMap=new HashMap<>();
        electricSetMap.put("1","逆变器");
        electricSetMap.put("2","并网箱");
        electricSetMap.put("3","组件");
    }

    //商机注册
    public JSONObject capitalPreAudit(CustomerEntry entry,Map<String,Object> params, CrmCustomerIncomingApplication  incomingApplication) throws Exception {
        Map<String,Object> map=new HashMap<>();
        map.put("capital",entry.getPartnerId()); //资方id，03:广发 04:华融 05:顶好

        map.put("capital_number",incomingApplication.getPartnersContractNumber());  //进件序号,合同方进件唯一编号
        map.put("tenant_type",entry.getTenantType());  //客户类型，1.个人 2.单位
        map.put("tenant_name",entry.getTenantName()); //客户名称

        map.put("mobile",entry.getMobile());   //客户类型为个人时，传客户手机号码；为单位时，传负责人手机号码
        map.put("regno",entry.getRegno());     //营业执照，客户类型为单位时有效(信用代码)
        map.put("corp",entry.getCorp());     //负责人姓名，客户类型为单位时有效
        //map.put("exigence_name",entry.getExigenceName());   //紧急联系人
        //map.put("exigence_phone",entry.getExigencePhone());   //紧急联系人手机号码
//        map.put("exigence_rel",entry.getExigenceRel());   //紧急联系人关系
        Record province = AddressUtils.getProvinceCode(entry.getProvince());
        map.put("provinceCode",province.getLong("regionalism_code").toString().concat("000000"));
        Record city = AddressUtils.getCityCode(entry.getCity(),province.getLong("ProvinceID"));
        map.put("cityCode",city.getLong("regionalism_code").toString().concat("000000"));
        map.put("areaCode",AddressUtils.getDistrictCode(entry.getArea(),city.getLong("CityID")).toString().concat("000000"));
        map.put("d",entry.getAddress());
        map.put("address",entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress());//业主常住地址
        map.put("bank_name",entry.getBankName());   //账户名称
        map.put("bank_code",entry.getBankCode());   //银行账号
        map.put("tss_bank_num_name",entry.getTssBankNumName());   //开户行
        map.put("bp_name",entry.getBpName());  //共签人姓名
        map.put("bp_id_card",entry.getBpIdCard()); //共签人身份证
        map.put("bp_mobile",entry.getBpMobile()); //共签人手机号
//        map.put("bp_card_address",entry.getBpCardAddress());  //共签人联系地址（共签人身份证识别的）
        String relation = "";//共签人关系
        if("父子".equals(entry.getBpRelation())){
            relation = "father_son_relationship";
        }else if("父女".equals(entry.getBpRelation())){
            relation = "father_daughter_relationship";
        }else if("夫妻".equals(entry.getBpRelation())){
            relation = "spouse";
        }else if("母子".equals(entry.getBpRelation())){
            relation = "mother_and_son";
        }else if("母女".equals(entry.getBpRelation())){
            relation = "mother_and_daughter";
        }else if("孙子".equals(entry.getBpRelation())){
            relation = "grandson";
        }else if("孙女".equals(entry.getBpRelation())){
            relation = "granddaughter";
        }
        map.put("bp_relation",relation);
        map.put("stationType","1");   //合作方的电站类型，固定为1
        map.put("businessType","20");    //商业模式：固定为20
        map.put("filing_type",entry.getFilingType()); //备案类型:1.农户备案 2.项目公司备案
        //map.put("repayment_method","");  //划转方式：1.二类卡 2.光E宝 0 其它
        map.put("project_code",entry.getProjectCode()); // 产品编码
        map.put("management_type",entry.getManagementType());  //项目公司编码 ORG202405230002
        if(CustomerEntryConstants.TENANT_TYPE_PERSON.equals(entry.getTenantType())){  //个人
            map.put("id_code",entry.getIdCode());  //客户类型为个人时，传客户身份证；为单位时，传负责人身份证
            map.put("authorization_contract_path",commonStaticImgPath+params.get("contractPath"));
            map.put("legal_id_card_type","");
            if(StringUtil.isNotBlank(entry.getIdCardFront())){
                map.put("id_card_front",commonStaticImgPath+entry.getIdCardFront());
            }
            if(StringUtil.isNotBlank(entry.getIdCardBack())){
                map.put("id_card_back",commonStaticImgPath+entry.getIdCardBack());
            }
            if(StringUtil.isNotBlank(entry.getBankCard())){
                map.put("bank_card",commonStaticImgPath+entry.getBankCard());  //银行卡正面照片
            }
//            if(StringUtil.isNotBlank(entry.getBankCardBack())){
//                map.put("bank_card_back",commonStaticImgPath+entry.getBankCardBack());  //银行卡照片反面
//            }
            map.put("residence_booklet",commonStaticImgPath+entry.getResidenceBooklet()); //户口本复印件图片
        }else if(CustomerEntryConstants.TENANT_TYPE_COMPANY.equals(entry.getTenantType())){
            if(StringUtil.isNotBlank(entry.getIdCardFront())){
                map.put("legal_id_card_front",commonStaticImgPath+entry.getIdCardFront());
            }
            if(StringUtil.isNotBlank(entry.getIdCardBack())){
                map.put("legal_id_card_back",commonStaticImgPath+entry.getIdCardBack());
            }
            if(StringUtil.isNotBlank(entry.getBankCard())){
                map.put("bank_card_dw",commonStaticImgPath+entry.getBankCard());  //银行卡正面照片
            }
            map.put("regno_url",commonStaticImgPath+params.get("regno_url")); //营业执照图片

            map.put("legal_name",entry.getCorp());
            map.put("legal_card",entry.getIdCode());
            map.put("legal_phone",entry.getMobile());
            if(params.get("house_ownership") != null) {
                map.put("house_ownership", dealImgUrls((String) params.get("house_ownership")));
            }
            map.put("legal_id_card_type","ID_CARD");

        }

        if(StringUtil.isNotBlank(entry.getBpCardFront())){
            map.put("bp_card_front",commonStaticImgPath+entry.getBpCardFront());
        }
        if(StringUtil.isNotBlank(entry.getBpCardBack())){
            map.put("bp_card_back",commonStaticImgPath+entry.getBpCardBack());
        }
        if(StringUtil.isNotBlank(entry.getBpFile())){
            map.put("bp_file",dealImgUrls(entry.getBpFile()));
        }

        logger.info("商机注册： number:{}, json:{}", incomingApplication.getPartnersContractNumber(), map);
        JSONObject result = PartnerApiUtils.getGfresultDoPost(map, DH + "/open/link/capitalPreAudit");
        CrmYxProcessDao.addProcess(entry.getId(), "1", "广发商机注册", new Gson().toJson(map),
                result.toJSONString(), "0");
        CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"1","NEW","0","0","");
        return result;
    }

    //状态查询
    public StatusFormVo guangFaPreStatus(String partnerId, String inputPieceIds) throws Exception {
        Map<String,Object> map=new HashMap<>();
        map.put("capital",partnerId); //资方id，03:广发  05 顶好
        map.put("inputPieceIds",inputPieceIds); //资方id，03:广发  05 顶好
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("guangFaPreStatus  状态查询：inputPieceIds:{},json:{}",inputPieceIds,jsonStr);
        JSONObject jsonObject = PartnerApiUtils.getresultDoPost(map, DH + "/open/link/queryPreAuditState");
        if(jsonObject!=null){
            CrmYxProcessDao.addProcess(inputPieceIds,"5","广发单据状态查询",jsonStr,jsonObject.toJSONString(),"0");
            StatusFormVo statusFormVo = new Gson().fromJson(jsonObject.toJSONString(), new TypeToken<StatusFormVo>() {}.getType());
            return statusFormVo;

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

    //状态查询
    public List<StatusFormVo> guangFaStatus(String partnerId, String inputPieceIds) {
        Map<String,Object> map=new HashMap<>();
        map.put("capital",partnerId); //资方id，03:广发  05 顶好
        map.put("inputPieceIds",inputPieceIds); //资方id，03:广发  05 顶好
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("guangFaPreStatus  状态查询：inputPieceIds:{},json:{}",inputPieceIds,jsonStr);
        JSONArray jsonObject = PartnerApiUtils.doPostForPartnerApi(map, DH + "/open/link/queryPreAuditState");
        if(jsonObject!=null){
//            CrmYxProcessDao.addProcess(inputPieceIds,"5","广发单据状态查询",jsonStr,jsonObject.toJSONString(),"0");
            List<StatusFormVo> statusFormVoList = new Gson().fromJson(jsonObject.toJSONString(), new TypeToken<List<StatusFormVo>>() {}.getType());
            return statusFormVoList;

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

    public Result accessProjectApply(CustomerEntry entry,CrmCustomerIncomingApplication incomingApplication){
        if(StringUtil.isNotBlank(incomingApplication.getProjectStatus()) && StringUtil.equalsAny(incomingApplication.getProjectStatus(),"APPROVING","APPROVED")){
            throw new IllegalArgumentException("进件状态不允许推送进件!");
        }
        GuangfaInputPiece inputPiece = new GuangfaInputPiece();
        inputPiece.setPartner("nenghui");
        inputPiece.setCapital(entry.getPartnerId());
        inputPiece.setRoofType(entry.getRoofType());

        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entry.getId());
        inputPiece.setCompletionYear(surveyRecord.getCompletionYear());
        //房屋朝向转换为文字
        String angleAzimuth = sysCapitalDictDao.getDictValue("03", "angle_azimuth", surveyRecord.getAzimuth());
        inputPiece.setAzimuth(angleAzimuth);
        inputPiece.setAngle(surveyRecord.getDipAngle().stripTrailingZeros().toPlainString());//广发的倾角就是组件倾角，没有房屋倾角
        inputPiece.setEwLength(surveyRecord.getEwLength().stripTrailingZeros().toPlainString());
        inputPiece.setnsWide(surveyRecord.getNsWide().stripTrailingZeros().toPlainString());
        inputPiece.setBuildingHeight(surveyRecord.getBuildingHeight().stripTrailingZeros().toPlainString());
        inputPiece.setRoofArea(surveyRecord.getRoofArea().stripTrailingZeros().toPlainString());
        inputPiece.setComponentSpec(entry.getComponentSpec());
        inputPiece.setLongitude(entry.getLongitude().stripTrailingZeros().toPlainString());
        inputPiece.setLatitude(entry.getLatitude().stripTrailingZeros().toPlainString());
        if("平屋顶".equals(surveyRecord.getRoofType())){
              inputPiece.setRoofFaceThickness(surveyRecord.getRoofFaceThickness());
              inputPiece.setFlatStructureType(surveyRecord.getStructureType());
        }else if("斜屋顶".equals(surveyRecord.getRoofType())){
            inputPiece.setWdAngel(surveyRecord.getDipAngle()+"");
        }else if("庭院".equals(surveyRecord.getRoofType())){
              inputPiece.setCourtyardSiteSlope(surveyRecord.getSiteSlope());
              inputPiece.setCourtyardGroundType(surveyRecord.getGroundType());
              inputPiece.setCourtyardGeologicalCondition(surveyRecord.getGeologicalCondition());
              inputPiece.setCourtyardfenceHeight(surveyRecord.getFenceHeight());
        }else if("道路".equals(surveyRecord.getRoofType())){
               inputPiece.setRoadSiteSlope(surveyRecord.getSiteSlope());
               inputPiece.setRoadGroundType(surveyRecord.getGroundType());
               inputPiece.setRoadGeologicalCondition(surveyRecord.getGeologicalCondition());
        }else if("广场".equals(surveyRecord.getRoofType())){
               inputPiece.setSquareSiteSlope(surveyRecord.getSiteSlope());
               inputPiece.setSquareGroundType(surveyRecord.getGroundType());
               inputPiece.setSquareGeologicalCondition(surveyRecord.getGeologicalCondition());
        }else if("长廊".equals(surveyRecord.getRoofType())){
               inputPiece.setLcCourtSiteSlope(surveyRecord.getSiteSlope());
               inputPiece.setLcCourtGroundType(surveyRecord.getGroundType());
               inputPiece.setLcCourtGeologicalCondition(surveyRecord.getGeologicalCondition());
        }else if("篮球场".equals(surveyRecord.getRoofType())){
               inputPiece.setBbCourtSiteSlope(surveyRecord.getSiteSlope());
               inputPiece.setBbCourtGroundType(surveyRecord.getGroundType());
               inputPiece.setBbCourtGeologicalCondition(surveyRecord.getGeologicalCondition());
        }
        //进件模块
        ///进件序号
        inputPiece.setCapitalNumber(incomingApplication.getInputPieceId());
        ///商业模式
        inputPiece.setBusinessType("20");    //商业模式：固定为20;
        ///电费归集方式
        String repaymentMethod = surveyRecord.getRepaymentMethod();
        if ("0".equals(repaymentMethod)) {
            inputPiece.setRepaymentMethod("3");
        }else {
            inputPiece.setRepaymentMethod(repaymentMethod);  //划转方式：1.二类卡 2.光E宝 0 其它
        }
        ///备案方式
        inputPiece.setFilingType(entry.getFilingType());//备案类型:1.农户备案 2.项目公司备案
        //产品模块
        ///产品编号
        inputPiece.setProjectCode(entry.getProjectCode());// 产品编码
        //设计模块
        ///设计方案
        inputPiece.setPlanType(entry.getSchemeTypeName());
        ///组件容量
        inputPiece.setDesignCapacity(entry.getDesignCapacity().toString());

        //附件模块
        inputPiece.setvrRoofOne(dealImgUrls(surveyRecord.getVrRoofOne()));
        inputPiece.setvrRoofTwo(dealImgUrls(surveyRecord.getVrRoofTwo()));
        inputPiece.setvrRoofThree(dealImgUrls(surveyRecord.getVrRoofThree()));
        inputPiece.setvrRoofFour(dealImgUrls(surveyRecord.getVrRoofFour()));
        inputPiece.setFwImg1(dealImgUrls(surveyRecord.getFwImg1()));
        inputPiece.setFwImg2(dealImgUrls(surveyRecord.getFwImg2()));
        inputPiece.setFwImg3(dealImgUrls(surveyRecord.getFwImg3()));
        inputPiece.setFwImg4(dealImgUrls(surveyRecord.getFwImg4()));
        inputPiece.setFwImg5(dealImgUrls(surveyRecord.getFwImg5()));
        inputPiece.setRoofPhotoOne(dealImgUrls(surveyRecord.getRoofPhotoOne()));
        inputPiece.setRoofPhotoTwo(dealImgUrls(surveyRecord.getRoofPhotoTwo()));
        inputPiece.setRoofPhotoThree(dealImgUrls(surveyRecord.getRoofPhotoThree()));
        inputPiece.setRoofPhotoFour(dealImgUrls(surveyRecord.getRoofPhotoFour()));

        inputPiece.setSurveyFiles(dealImgUrls(surveyRecord.getSurveyFiles()));
        if(CustomerEntryConstants.TENANT_TYPE_PERSON.equals(entry.getTenantType())){  //个人
            inputPiece.setHouseOwnership(dealImgUrls(surveyRecord.getHouseOwnership()));
        }else if(CustomerEntryConstants.TENANT_TYPE_COMPANY.equals(entry.getTenantType())){
            inputPiece.setHouseOwnershipDw(dealImgUrls(surveyRecord.getHouseOwnership()));
        }
        inputPiece.setDesignDrawings(dealImgUrls(entry.getDesignDrawings()));
        inputPiece.setZjhsImg(dealImgUrls(entry.getZjhsImg()));
        inputPiece.setZjpbImg(dealImgUrls(entry.getZjpbImg()));
        inputPiece.setZjcsImg(dealImgUrls(entry.getZjcsImg()));
        inputPiece.setZjzxImg(dealImgUrls(entry.getZjzxImg()));

        List<Record> records = entryComponentDao.findByEntryId3(entry.getId());
        List<InputPieceComponent> componentList = new ArrayList<>();

        for (Record r : records) {
            InputPieceComponent component = new InputPieceComponent();
            component.setItemType(r.getStr("item_type"));
            component.setName(electricSetMap.get(r.getStr("item_type")));  //名称
            component.setNum(String.valueOf(r.getInt("num"))); //数量
            component.setSpecs(r.getStr("material_model"));  //物料型号
            String model = r.getStr("model");
            if(model.contains("KW")){
                model = model.substring(0,model.indexOf("KW"));
                model = model + "000";
            }
            component.setMaterialModel(model);  ////物料规格/组件功率
            component.setComponentShape("2");  // 组件玻型:1.单玻 2.双玻 (固定双玻)
            component.setBatteryParam("1"); // 电池参数: 1.N型 2.P型
            componentList.add(component);
        }
        ///组件数量
        inputPiece.setDesignNum(componentList.stream().filter(c -> "3".equals(c.getItemType())).map(InputPieceComponent::getNum).findFirst().get());
        inputPiece.setComponentList(componentList);
        String paramJson = new Gson().toJson(inputPiece);
        JSONObject resultMap = PartnerApiUtils.clientPostToApi(paramJson, DH + "/open/link/firstInputPiece");
        logger.info("广发第一次进件接口返回结果：{}", resultMap);
        if (Objects.isNull(resultMap)) throw new IllegalArgumentException("请求失败！");
        if (resultMap.getBoolean("success")){
            CrmYxProcessDao.addProcess(entry.getId(),"2","广发进件同步接口", paramJson, resultMap.toJSONString(),"0");
            CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"2","NEW","0","0","推送");
            return Result.ok();
        }
        CrmYxProcessDao.addProcess(entry.getId(),"2","广发进件同步接口",paramJson,resultMap.toJSONString(),"1");
        CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"2",null,"1",null,null);
        return Result.fail(resultMap.getString("msg"));
    }


    public void gridIncomingApplication(CustomerEntry entry, CustomerEntrySurveyRecord surveyRecord, CrmCustomerIncomingApplication  incomingApplication,
                                        CrmAcceptingReport report, List<Record> compRecordList, List<CrmCustomerIncomingApplicationInsurance> insurancesList
    ) throws ParseException {
        logger.info("gridIncomingApplication  广发开始第三次进件 entry:{}",entry.getPowerStationCode());
        Map<String,Object> map=new HashMap<>();
        map.put("partner","nenghui"); //合作方，固定为atesi
        map.put("capital",entry.getPartnerId()); //资方id，03:广发  05 顶好
        map.put("capital_number",incomingApplication.getInputPieceId());  //进件序号

        //并网信息
        map.put("stationName","nenghui"+entry.getTenantName()+entry.getDesignCapacity());  //平台方进件名称
        map.put("voltageLevel",surveyRecord.getVoltageClasses());  //电压等级
        map.put("mergeType","20");  //并网类型
        map.put("fdhh",entry.getGeneratorNo());  //发电户号
        if(entry.getFirstGenerationTime()!=null){
            map.put("effectiveFirstDate", entry.getFirstGenerationTime().getTime());  //首日发电日期
        }
        if(entry.getCheckAcceptTime()!=null){
            map.put("checkTime",entry.getCheckAcceptTime().getTime());  //合作方自审日期
        }
        map.put("countryCode","46");  //国家
        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().concat("000000"));
        map.put("areaCode",AddressUtils.getDistrictCode(entry.getArea(),city.getLong("CityID")).toString().concat("000000"));
        if ("0".equals(entry.getAddressFlag())){
            map.put("detailAddress",entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress());
        }else {
            map.put("detailAddress",entry.getAddress());
        }
        map.put("townCode","0");  //镇
        map.put("longitude",entry.getLongitude());  //经度
        map.put("latitude",entry.getLatitude());  //纬度
        map.put("feecollectType","0".equals(surveyRecord.getRepaymentMethod())?"3":surveyRecord.getRepaymentMethod());

        if("1".equals(entry.getFilingType())){
            //电费收益信息
            map.put("openBank",entry.getTssBankNumName());  //开户行
            map.put("accountName",entry.getBankName());  //账户名称
            map.put("accountNum",entry.getBankCode());  //账号
            map.put("accountType","1");  //账号类型
        }else if("3".equals(entry.getFilingType())){
            map.put("accountType","2");  //账号类型
        }
        //设计方案信息
        Record plan = planService.getPlanById(entry.getSchemeId());
//        List<Map<String,Object>> componentList=new ArrayList<>();
        for(Record r:compRecordList){
//            Map<String,Object> componentMap = new HashMap<>();
            if(plan!=null){
                map.put("plan_type",plan.getStr("plan_type"));////设计方案
            }else{
                map.put("plan_type",entry.getSchemeTypeName());//设计方案
            }
            Integer num = r.getInt("zjNum");
            Integer model = Integer.parseInt(r.getStr("zjModel"));
            map.put("moduleCount",num);
//            map.put("mergeVolume",model);
            map.put("mergeCapacity",String.valueOf(model * num));
            map.put("mergeVolume",String.valueOf(model * num));
        }
        //保险信息
        String ysbgImg = "";
//        StringBuilder ccxImg = new StringBuilder();
//        StringBuilder gzzrxImg = new StringBuilder();
//        StringBuilder gcxImg = new StringBuilder();
        // 2024-09-03
        // 1、工程安装一切险GZFZCP_200020_170，名称调整为：工程安装一切险、财产险和公众险
        // 2、财产险GZFZMG_200020_313、公众责任险GZFZMG_200020_314，停用
        StringBuilder bdImg = new StringBuilder();
        List<Map<String,Object>> insuranceList = new ArrayList<>();
        for(CrmCustomerIncomingApplicationInsurance insurance: insurancesList){

                Map<String,Object> insuranceMap = new HashMap<>();
                insuranceMap.put("insuranceNumber",insurance.getInsuranceNumber());//保险单号
                insuranceMap.put("insuranceCompany",insurance.getInsuranceCompany());//保险公司名称
                if("1".equals(insurance.getInsuranceType())){
                    insuranceMap.put("insuranceType","1");//险种类型
                    insuranceList.add(new HashMap<>(insuranceMap));
                    insuranceMap.put("insuranceType","3");//险种类型
                    insuranceList.add(new HashMap<>(insuranceMap));
                }else {
                    insuranceMap.put("insuranceType","2");//险种类型
                    insuranceList.add(insuranceMap);
                }
            ysbgImg= insurance.getBwtsFile();
            if(StringUtil.isNotBlank(insurance.getInsurancePolicy())){
                for(String img:insurance.getInsurancePolicy().split(",")){
                    if(StringUtil.isNotBlank(img)){
                        /*switch (insurance.getInsuranceType()){
                            case "1":
                                ccxImg.append(","+commonStaticImgPath+img); // 财产险保单
                                gzzrxImg.append(","+commonStaticImgPath+img);  //责任险保单
                                break;
                            case "5":
                                gcxImg.append(","+commonStaticImgPath+img); //工程险保单
                                break;
                        }*/
                        bdImg.append(","+commonStaticImgPath+img); // 保单
                    }
                }
            }
        }
        map.put("insuranceList",insuranceList);
        //附件信息
        StringBuilder sb = new StringBuilder();
        if(StringUtil.isNotBlank(surveyRecord.getFilingDocumentPhoto())){
            sb.setLength(0);
            for(String img:surveyRecord.getFilingDocumentPhoto().split(",")){
                sb.append(","+commonStaticImgPath+img);
            }
            map.put("xmgsbaz_img",sb.substring(1)); //备案证
        }
        if(StringUtil.isNotBlank(report.getPowerCapacityUrl())){
            sb.setLength(0);
            for(String img:report.getPowerCapacityUrl().split(",")){
                sb.append(","+commonStaticImgPath+img);
            }
            map.put("stfdjt_img",sb.substring(1)); //三天连续发电量监控系统截图
        }
        if(StringUtil.isNotBlank(ysbgImg)){
            sb.setLength(0);
            for(String img:ysbgImg.split(",")){
                sb.append(","+commonStaticImgPath+img);
            }
            map.put("ysbg_img",sb.substring(1)); //验收报告
        }
        if(StringUtil.isNotBlank(entry.getContract())){
            sb.setLength(0);
            for(String img:entry.getContract().split(",")){
                sb.append(","+commonStaticImgPath+img);
            }
            map.put("gxdht_img",sb.substring(1)); //购销电合同
        }
        if(StringUtil.isNotBlank(report.getDbxImgs())){
            sb.setLength(0);
            for(String img:report.getDbxImgs().split(",")){
                sb.append(","+commonStaticImgPath+img);
            }
            map.put("dxb_img",sb.substring(1)); //电表箱
        }
        if(StringUtil.isNotBlank(report.getDbImgs())){
            sb.setLength(0);
            for(String img:report.getDbImgs().split(",")){
                sb.append(","+commonStaticImgPath+img);
            }
            map.put("db_img",sb.substring(1)); //电表照片
        }
//        if(StringUtils.isNotBlank(ccxImg))
//            map.put("ccx_img", ccxImg.substring(1));  //财产险附件
//        if(StringUtils.isNotBlank(gzzrxImg))
//            map.put("gzzrx_img",gzzrxImg.substring(1));  //责任险附件
        if(StringUtils.isNotBlank(bdImg))
            map.put("gcazyqx_img",bdImg.substring(1));  //工程险附件

        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("gridIncomingApplication  广发第三次进件：PartnersContractNumber:{},json:{}",incomingApplication.getPartnersContractNumber(),jsonStr);
        JSONObject jsonObject = PartnerApiUtils.clientPostToApi(jsonStr, DH + "/open/link/mergeGridInputPiece");
        if(jsonObject!=null){
            CrmYxProcessDao.addProcess(entry.getId(),"5","广发第三次进件",jsonStr,jsonObject.toJSONString(),"0");
            Integer code=jsonObject.getInteger("code");
            if(code==200){
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"5","20","0","0","推送");
            }else{
                throw new IllegalArgumentException(jsonObject.getString("msg"));
            }
        }else{
            throw new IllegalArgumentException("请求资方接口失败！");
        }

    }

    public String dealImgUrls(String urls) {
        if (StringUtil.isBlank(urls)) {
            return null;
        }
        String[] urlList = urls.split(",");
        String urlStr = "";
        for (String str : urlList) {
            if (StringUtil.isNotBlank(str)) {
                if (StringUtil.isBlank(urlStr)) {
                    urlStr = commonStaticImgPath+str;
                }
                else {
                    urlStr = urlStr + "," + commonStaticImgPath+str;
                }
            }
        }
        return urlStr;
    }

    //第二次进件
    public Result accessProjectApplyTwo(CustomerEntry entry,CrmCustomerIncomingApplication incomingApplication){


        CrmAcceptingReport acceptingReport = reportDao.get(entry.getReceivingReportId());

        Map<String, Object> reqMap = new HashMap<>();
        List<Map<String, Object>> inverterList = new ArrayList<>();
        List<Map<String, Object>> moduleList = new ArrayList<>();
        List<Map<String, Object>> cageInfoList = new ArrayList<>();

        reqMap.put("partner", "nenghui");

        reqMap.put("capital", entry.getPartnerId());
        //进件模块
        ///进件序号
        reqMap.put("capital_number", incomingApplication.getInputPieceId());
        //安装时间
        reqMap.put("install_time", DateUtils.formatDate(entry.getInstallTime(), "yyyyMMdd"));
        //组件容量
        reqMap.put("design_capacity", entry.getDesignCapacity().toString());

        // 组件品牌
        Map<String, String> componentMap = PartnerBrandUtils.getBrandList("3", PartnerConstants.PARTNER_ID_GF);
        // 逆变器品牌
        Map<String, String> inverMap = PartnerBrandUtils.getBrandList("1", PartnerConstants.PARTNER_ID_GF);
        AtomicBoolean checkCompBrand = new AtomicBoolean(true); // 校验组件品牌是否为空
        AtomicBoolean checkInvertBrand = new AtomicBoolean(true); // 校验逆变器品牌是否为空

        List<Record> list2 = entryDao.findCageByEntryId(entry.getId(),electricSetMap.get("3"));
        for (Record r : list2) {
                HashMap<String, Object> moduleMap = new HashMap<>();
                moduleMap.put("materialCode",r.getStr("barcode"));
                moduleMap.put("materialName",r.getStr("type"));
                moduleMap.put("moduleModel",r.getStr("model"));
                moduleMap.put("modulePower",r.get("spec"));
                String brand = "";
                if (componentMap.containsKey(r.getStr("brand"))) {
                    // 获取广发的品牌名称
                    brand = componentMap.get(r.getStr("brand"));
                }
                if (StringUtil.isBlank(brand)) {
                    checkCompBrand.set(false);
                }
                moduleMap.put("moduleBrand",brand);
                //电池参数: 1.N型 2.P型
                moduleMap.put("batteryParam","1");
                //组件玻型:1.单玻 2.双玻
                moduleMap.put("moduleGlassType","2");

                int snLength = 0;
                String sns = r.getStr("sns");
                if(StringUtil.isNotBlank(sns)){
                    String[] sn = sns.split(",");
                    moduleMap.put("sns",Lists.newArrayList(sn));
                    snLength = sn.length;
                }
            int completeVolume =   Integer.parseInt(r.getStr("spec")) * snLength;
            //完工容量（W）
            moduleMap.put("completeVolume",String.valueOf(completeVolume));
            moduleList.add(moduleMap);


        }

        // 查询使用逆变器
        List<Record> inverters = entryDao.findInverterByEntryId(entry.getId());
        for (Record r : inverters) {
            HashMap<String, Object> inverterMap = new HashMap<>();
            inverterMap.put("materialCode", r.getStr("barcode"));
            inverterMap.put("materialName", r.getStr("type"));
            inverterMap.put("inverterSpec", r.getStr("spec"));
            String model = r.getStr("spec");
            if (model.contains("KW")) {
                model = model.substring(0, model.indexOf("KW"));
                model = model + "000";
            }
            inverterMap.put("inverterPower", model);
            String brand = "";
            if (inverMap.containsKey(r.getStr("brand"))) {
                // 获取广发的品牌名称
                brand = inverMap.get(r.getStr("brand"));
            }
            if (StringUtil.isBlank(brand)) {
                checkInvertBrand.set(false);
            }
            inverterMap.put("inverterBrand", brand);
            inverterMap.put("nbq_sn",r.getStr("nbq_sn"));
            inverterMap.put("cjq_sn",r.getStr("sn"));
//            inverterMap.put("yz_code",r.getStr(""));
            inverterList.add(inverterMap);
        }
        if (!checkCompBrand.get()) {
            throw new IllegalArgumentException("组件规格对应品牌没有匹配上广发已授权的品牌，需要打回重新设计");
        }
        if (!checkInvertBrand.get()) {
            throw new IllegalArgumentException("逆变器规格对应品牌没有匹配上广发已授权的品牌，需要打回重新设计");
        }
        List<Record> cages = entryDao.findCageByEntryId(entry.getId(),electricSetMap.get("2"));
        for (Record r : cages) {
            HashMap<String, Object> cageInfoMap = new HashMap<>();
            cageInfoMap.put("materialCode",r.getStr("barcode"));
            cageInfoMap.put("materialName",r.getStr("type"));
            //并网箱品牌
            cageInfoMap.put("cageBrand",r.getStr("brand"));
            //并网箱型号
            cageInfoMap.put("parallelCageSpec",r.getStr("spec"));
            String model = r.getStr("spec");
            if (model.contains("KW")) {
                model = model.substring(0, model.indexOf("KW"));
            }
            //并网箱功率
            cageInfoMap.put("parallelCagePower",model);
            //并网箱数量
            cageInfoMap.put("parallelCageCount",r.getInt("amount"));
            //并网箱功能
//            cageInfoMap.put("parallelCageFeature",r.getStr(""));
            String sns = r.getStr("sns");
            if(StringUtil.isNotBlank(sns)){
                String[] sn = sns.split(",");
                cageInfoMap.put("sns",Lists.newArrayList(sn));
            }

            cageInfoList.add(cageInfoMap);
        }
        reqMap.put("inverterList",inverterList);
        reqMap.put("moduleList",moduleList);
        reqMap.put("cageInfoList",cageInfoList);
        //图片
        reqMap.put("safety_warning_img", dealImgUrls(acceptingReport.getSafetyWarningImg()));
        reqMap.put("safety_warning_img2", dealImgUrls(acceptingReport.getSafetyWarningImg2()));
        reqMap.put("safety_warning_img3", dealImgUrls(acceptingReport.getSafetyWarningImg3()));
        reqMap.put("safety_disclose_doc_img", dealImgUrls(acceptingReport.getSafetyDiscloseDocImg()));
        reqMap.put("zj_img5", dealImgUrls(acceptingReport.getZjImg5()));

        reqMap.put("zj_plate_img", dealImgUrls(acceptingReport.getZjPlateImg()));
        reqMap.put("component_img3", dealImgUrls(acceptingReport.getComponentImg3()));
        reqMap.put("component_img4", dealImgUrls(acceptingReport.getComponentImg4()));
        reqMap.put("dc_imgs", dealImgUrls(acceptingReport.getDcImgs()));
        reqMap.put("nbq_plate_img", dealImgUrls(acceptingReport.getNbqPlateImg()));
        reqMap.put("total_imgs", dealImgUrls(acceptingReport.getTotalImgs()));
        reqMap.put("nbq_zlc_img", dealImgUrls(acceptingReport.getNbqZlcImg()));
        reqMap.put("open_way_voltage_imgs",dealImgUrls(acceptingReport.getOpenWayVoltageImgs()));
        reqMap.put("nbq_zb_img", dealImgUrls(acceptingReport.getNbqZbImg()));
        reqMap.put("bw_inner_img", dealImgUrls(acceptingReport.getBwInnerImg()));
        reqMap.put("bw_jd_img", dealImgUrls(acceptingReport.getBwJdImg()));

        reqMap.put("zj_img8", dealImgUrls(acceptingReport.getZjImg8()));
        reqMap.put("zj_img9", dealImgUrls(acceptingReport.getZjImg9()));
        reqMap.put("zj_img4", dealImgUrls(acceptingReport.getZjImg4()));
        reqMap.put("zj_img10", dealImgUrls(acceptingReport.getZjImg10()));
        reqMap.put("zj_img11", dealImgUrls(acceptingReport.getZjImg11()));
        reqMap.put("zj_img12", dealImgUrls(acceptingReport.getZjImg12()));
        reqMap.put("zj_img13", dealImgUrls(acceptingReport.getZjImg13()));
        reqMap.put("zj_img14", dealImgUrls(acceptingReport.getZjImg14()));
        reqMap.put("zj_img15", dealImgUrls(acceptingReport.getZjImg15()));

        reqMap.put("jd_img4", dealImgUrls(acceptingReport.getJdImg4()));
        reqMap.put("bk_img1", dealImgUrls(acceptingReport.getBkImg1()));
        reqMap.put("component_img1", dealImgUrls(acceptingReport.getComponentImg1()));
        reqMap.put("bk_img2", dealImgUrls(acceptingReport.getBkImg2()));
        reqMap.put("yk_img1", dealImgUrls(acceptingReport.getYkImg1()));
        reqMap.put("size_measure_imgs", dealImgUrls(acceptingReport.getSizeMeasureImgs()));

        reqMap.put("jd_img7", "");
        reqMap.put("jd_img8", dealImgUrls(acceptingReport.getJdImg8()));
        reqMap.put("jd_img5", dealImgUrls(acceptingReport.getJdImg5()));
        reqMap.put("jd_img9", dealImgUrls(acceptingReport.getJdImg9()));
        reqMap.put("jd_img10", dealImgUrls(acceptingReport.getJdImg10()));
        reqMap.put("jd_img11", dealImgUrls(acceptingReport.getJdImg11()));
        reqMap.put("jd_img12", dealImgUrls(acceptingReport.getJdImg12()));
        reqMap.put("fs_img1", dealImgUrls(acceptingReport.getFsImg1()));
        reqMap.put("wcazqjt_img", "");
        reqMap.put("fix_other_img", dealImgUrls(acceptingReport.getFixOtherImg()));
        reqMap.put("fs_img2", dealImgUrls(acceptingReport.getFsImg2()));
        reqMap.put("water_mud_clamp_imgs", dealImgUrls(acceptingReport.getWaterMudClampImgs()));

        String paramJson = new Gson().toJson(reqMap);
        logger.info("广发第二次进件接口请求参数：{}", paramJson);
        JSONObject resultMap = PartnerApiUtils.clientPostToApi(paramJson, DH + "/open/link/completeInputPiece");
        logger.info("广发第二次进件接口返回结果：{}", resultMap);
        if (Objects.isNull(resultMap)) throw new IllegalArgumentException("请求失败！");
        if (resultMap.getBoolean("success")){
            CrmYxProcessDao.addProcess(entry.getId(),"2","广发二次进件同步接口", paramJson, resultMap.toJSONString(),"0");
            CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"2","NEW","0","0","推送");
            return Result.ok();
        }
        CrmYxProcessDao.addProcess(entry.getId(),"2","广发二次进件同步接口",paramJson,resultMap.toJSONString(),"1");
        CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"2",null,"1",null,null);
        return Result.fail(resultMap.getString("msg"));
    }

    //电站信息变更（地址）
    public String stationInfoUpdate(CustomerEntry entry,String reason,String address,String inputPieceId){
        Map<String, Object> map = new HashMap<>();
        map.put("partner", "nenghui");
        map.put("capital", entry.getPartnerId());
        map.put("inputPieceId", inputPieceId);
        map.put("detailAddress", address);
        map.put("changeReason", reason);
        String jsonStr = new Gson().toJson(map);
        logger.info("stationInfoUpdate  广发电站信息变更进件：inputPieceId:{},json:{}",inputPieceId,jsonStr);
        JSONObject jsonObject = PartnerApiUtils.clientPostToApi(jsonStr, DH + "/open/link/stationInfoUpdate");
        if(jsonObject!=null){
            CrmYxProcessDao.addProcess(entry.getId(),"1","广发电站信息变更进件",jsonStr,jsonObject.toJSONString(),"0");
            Integer code=jsonObject.getInteger("code");
            if(code!=200){
                throw new IllegalArgumentException(jsonObject.getString("msg"));
            }
            return jsonObject.getString("data");
        }else{
            throw new IllegalArgumentException("请求资方接口失败！");
        }
    }
    //客户信息变更
    public String customerInfoUpdate(CustomerEntry entry, CrmCustomerEntryTenantChangeRecord changeRecord, String inputPieceId) {
        List<Record> details = tenantChangeRecordDetailDao.getDetails(changeRecord.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("partner", "nenghui");
        map.put("capital", entry.getPartnerId());
        map.put("capital_number", inputPieceId);
        map.put("changeReason", changeRecord.getChangeReason());//变更原因
        map.put("tenant_type", entry.getTenantType());//业主类型
        map.put("tenant_name", entry.getTenantName());//业主名称
        map.put("bank_name",entry.getBankName());//账户名称
        if(CustomerEntryConstants.TENANT_TYPE_PERSON.equals(entry.getTenantType())){
            map.put("id_code",entry.getIdCode());//身份证号
        }else {
            map.put("regno",entry.getRegno());     //营业执照，客户类型为单位时有效(信用代码)
            map.put("legal_name",entry.getCorp());
            map.put("legal_card",entry.getIdCode());
            map.put("legal_id_card_type","ID_CARD");
        }
        details.stream().forEach(r -> {
            String item=r.getStr("item_code");
            String ifChange=r.getStr("if_change");
            String afterChange=r.getStr("after_change");
            String beforeChange = r.getStr("before_change");
            if ("mobile".equals(item)){//联系方式
                if ("1".equals(entry.getTenantType())){
                    if ("1".equals(ifChange)){
                        map.put("mobile", afterChange);
                    }else {
                        map.put("mobile",beforeChange);
                    }
                }else {
                    if ("1".equals(ifChange)){
                        map.put("legal_phone", afterChange);
                    }else {
                        map.put("legal_phone",beforeChange);
                    }
                }
            }else if ("tssBankNumName".equals(item)){//开户行
                if ("1".equals(ifChange)){
                    map.put("tss_bank_num_name", afterChange);
                }else {
                    map.put("tss_bank_num_name",beforeChange);
                }
            }else if ("bankCode".equals(item)){//银行账号
                if ("1".equals(ifChange)){
                    map.put("bank_code", afterChange);
                }else {
                    map.put("bank_code",beforeChange);
                }
            }else if ("idCardFront".equals(item)){//身份证正面
                if ("1".equals(entry.getTenantType())){
                    if ("1".equals(ifChange)){
                        map.put("id_card_front", dealImgUrls(afterChange));
                    }else {
                        map.put("id_card_front",dealImgUrls(beforeChange));
                    }
                }else {
                    if ("1".equals(ifChange)){
                        map.put("legal_id_card_front", dealImgUrls(afterChange));
                    }else {
                        map.put("legal_id_card_front",dealImgUrls(beforeChange));
                    }
                }
            }else if ("idCardBack".equals(item)){//身份证反面
                if ("1".equals(entry.getTenantType())){
                    if ("1".equals(ifChange)){
                        map.put("id_card_back", dealImgUrls(afterChange));
                    }else {
                        map.put("id_card_back",dealImgUrls(beforeChange));
                    }
                }else {
                    if ("1".equals(ifChange)){
                        map.put("legal_id_card_back", dealImgUrls(afterChange));
                    }else {
                        map.put("legal_id_card_back",dealImgUrls(beforeChange));
                    }
                }
            }else if ("HouseOwnership".equals(item)){//房产证
                if ("1".equals(ifChange)){
                    map.put("house_ownership", dealImgUrls(afterChange));
                }else {
                    map.put("house_ownership",dealImgUrls(beforeChange));
                }
            }else if ("bankCard".equals(item)){//银行卡照片
                if ("1".equals(entry.getTenantType())){
                    if ("1".equals(ifChange)){
                        map.put("bank_card", dealImgUrls(afterChange));
                    }else {
                        map.put("bank_card",dealImgUrls(beforeChange));
                    }
                }else {
                    if ("1".equals(ifChange)){
                        map.put("bank_card_dw", dealImgUrls(afterChange));
                    }else {
                        map.put("bank_card_dw",dealImgUrls(beforeChange));
                    }
                }
            }else if ("address".equals(item)){//地址
                if ("1".equals(ifChange)){
                    map.put("address",entry.getProvince()+entry.getCity()+entry.getArea()+afterChange);
                }else {
                    map.put("address",entry.getProvince()+entry.getCity()+entry.getArea()+beforeChange);
                }
            }
            if ("2".equals(entry.getTenantType())){
                if("regnoUrl".equals(item)){//营业执照
                    if ("1".equals(ifChange)){
                        map.put("regno_url", dealImgUrls(afterChange));
                    }else {
                        map.put("regno_url",dealImgUrls(beforeChange));
                    }
                }
            }
            if ("1".equals(entry.getTenantType()) && entry.getAge()>65){
                if ("bpCardFront".equals(item)){//共签人身份证正面
                    if ("1".equals(ifChange)){
                        map.put("bp_card_front", dealImgUrls(afterChange));
                    }else {
                        map.put("bp_card_front",dealImgUrls(beforeChange));
                    }
                }else if ("bpCardBack".equals(item)){//共签人身份证反面
                    if ("1".equals(ifChange)){
                        map.put("bp_card_back", dealImgUrls(afterChange));
                    }else {
                        map.put("bp_card_back",dealImgUrls(beforeChange));
                    }
                }else if ("bpFile".equals(item)){//共签人证明材料
                    if ("1".equals(ifChange)){
                        map.put("bp_file", dealImgUrls(afterChange));
                    }else {
                        map.put("bp_file",dealImgUrls(beforeChange));
                    }
                }
            }
        });
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("customerInfoUpdate  广发客户信息变更进件：inputPieceId:{},json:{}",inputPieceId,jsonStr);
        JSONObject jsonObject = PartnerApiUtils.clientPostToApi(jsonStr, DH + "/open/link/customerInfoUpdate");
        logger.info("customerInfoUpdate  广发客户信息变更进件返回结果：inputPieceId:{},result:{}",inputPieceId,jsonObject);
        if(jsonObject!=null){
            CrmYxProcessDao.addProcess(entry.getId(),"1","广发客户信息变更进件",jsonStr,jsonObject.toJSONString(),"0");
            Integer code=jsonObject.getInteger("code");
            if(code!=200){
                throw new IllegalArgumentException(jsonObject.getString("msg"));
            }
            return jsonObject.getString("data");
        }else{
            throw new IllegalArgumentException("请求资方接口失败！");
        }
    }
    // 勘测信息变更
    public String prospectInfoUpdate(CustomerEntry entry , CustomerEntrySurveyChangeRecord changeRecord, String partnersContractNumber) {
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entry.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("partner", "nenghui");
        map.put("capital", entry.getPartnerId());
        map.put("inputPieceId", partnersContractNumber);
        map.put("changeReason", changeRecord.getReason());
        map.put("roof_type", entry.getRoofType());
        map.put("completion_year", surveyRecord.getCompletionYear());
        //房屋朝向转换为文字
        String angleAzimuth = sysCapitalDictDao.getDictValue("03", "angle_azimuth", surveyRecord.getAzimuth());
        map.put("azimuth", angleAzimuth);
        map.put("angle", surveyRecord.getDipAngle().stripTrailingZeros().toPlainString());
        map.put("ew_length", surveyRecord.getEwLength().stripTrailingZeros().toPlainString());
        map.put("ns_wide", surveyRecord.getNsWide().stripTrailingZeros().toPlainString());
        map.put("building_height", surveyRecord.getBuildingHeight().stripTrailingZeros().toPlainString());
        map.put("roof_area", surveyRecord.getRoofArea().stripTrailingZeros().toPlainString());
        map.put("longitude", entry.getLongitude().stripTrailingZeros().toPlainString());
        map.put("latitude", entry.getLatitude().stripTrailingZeros().toPlainString());
        map.put("roof_photo_one", dealImgUrls(changeRecord.getRoofPhotoOne()));
        map.put("roof_photo_two", dealImgUrls(changeRecord.getRoofPhotoTwo()));
        map.put("roof_photo_three", dealImgUrls(changeRecord.getRoofPhotoThree()));
        map.put("roof_photo_four",dealImgUrls(changeRecord.getRoofPhotoFour()) );
        map.put("survey_files", dealImgUrls(changeRecord.getSurveyFiles()));
        map.put("vr_roof_one", dealImgUrls(changeRecord.getVrRoofOne()));
        map.put("vr_roof_two", dealImgUrls(changeRecord.getVrRoofTwo()));
        map.put("vr_roof_three", dealImgUrls(changeRecord.getVrRoofThree()));
        map.put("vr_roof_four", dealImgUrls(changeRecord.getVrRoofFour()));
        map.put("fw_img1", dealImgUrls(changeRecord.getFwImg1()));
        map.put("fw_img2", dealImgUrls(changeRecord.getFwImg2()));
        map.put("fw_img3", dealImgUrls(changeRecord.getFwImg3()));
        map.put("fw_img4", dealImgUrls(changeRecord.getFwImg4()));
        map.put("fw_img5", dealImgUrls(changeRecord.getFwImg5()));
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
//        GuangfaInputPiece inputPiece = new GuangfaInputPiece();
//        getGuangfaInputPiece(inputPiece, entry, partnersContractNumber,null,changeRecord);
//        String jsonStr = new Gson().toJson(inputPiece);
        logger.info("gridIncomingApplication  广发勘测信息变更进件：PartnersContractNumber:{},json:{}",partnersContractNumber,jsonStr);
        JSONObject jsonObject = PartnerApiUtils.clientPostToApi(jsonStr, DH + "/open/link/prospectInfoUpdate");
        if(jsonObject!=null){
            CrmYxProcessDao.addProcess(entry.getId(),"3","广发勘测信息变更进件",jsonStr,jsonObject.toJSONString(),"0");
            Integer code=jsonObject.getInteger("code");
            if(code!=200){
                throw new IllegalArgumentException(jsonObject.getString("msg"));
            }
            return jsonObject.getString("data");
        }else{
            throw new IllegalArgumentException("请求资方接口失败！");
        }
    }
    //设计信息变更
    public String designInfoUpdate(CustomerEntry entry, CrmCustomerEntryChangeDesign design, String inputPieceId) {
        Map<String, Object> map = new HashMap<>();
        // todo
        map.put("partner", "nenghui");

        map.put("capital", entry.getPartnerId());
        //进件模块
        ///进件序号
        map.put("inputPieceId", inputPieceId);
        map.put("changeReason", design.getReason());
        map.put("zjhs_img",dealImgUrls(design.getZjhsImg()));
        map.put("zjpb_img",dealImgUrls(design.getZjpbImg()));
        map.put("zjcs_img",dealImgUrls(design.getZjcsImg()));
        map.put("zjzx_img",dealImgUrls(design.getZjzxImg()));

        List<Record> components = customerEntryChangeDesignComponentDao.findByDesignId1(design.getId());
        List<Record> postComponents = components.stream().filter(e -> Objects.equals(e.getStr("flag"), "1")).collect(Collectors.toList());
        //变化后的设计容量
        int ret = 0;
        for (Record postComponent : postComponents) {
            if (Objects.equals(postComponent.getStr("item_type"), "3")) {
                ret += postComponent.getInt("num") * Integer.parseInt(postComponent.getStr("model"));
            }
        }
        map.put("plan_type", entry.getSchemeTypeName());
        map.put("design_capacity", ret);
        List<InputPieceComponent> componentList = new ArrayList<>();
        for (Record r : components) {
            InputPieceComponent component = new InputPieceComponent();
            component.setItemType(r.getStr("item_type"));
            component.setName(electricSetMap.get(r.getStr("item_type")));  //名称
            component.setNum(String.valueOf(r.getInt("num"))); //数量
            component.setSpecs(r.getStr("material_model"));  //物料型号
            String model = r.getStr("model");
            if(model.contains("KW")){
                model = model.substring(0,model.indexOf("KW"));
                model = model + "000";
            }
            component.setMaterialModel(model);  ////物料规格/组件功率
            component.setComponentShape("2");  // 组件玻型:1.单玻 2.双玻 (固定双玻)
            component.setBatteryParam("1"); // 电池参数: 1.N型 2.P型
            componentList.add(component);
        }
        ///组件数量
        map.put("design_num",componentList.stream().filter(c -> "3".equals(c.getItemType())).map(InputPieceComponent::getNum).findFirst().get());
        map.put("componentList",componentList);
//        GuangfaInputPiece inputPiece = new GuangfaInputPiece();
//        getGuangfaInputPiece(inputPiece, entry, inputPieceId,design,null);
//        String jsonStr = new Gson().toJson(inputPiece);
        String jsonStr = new Gson().toJson(map);
        logger.info("gridIncomingApplication  广发设计信息变更进件：PartnersContractNumber:{},json:{}",inputPieceId,jsonStr);
        JSONObject jsonObject = PartnerApiUtils.clientPostToApi(jsonStr, DH + "/open/link/designInfoUpdate");
        if(jsonObject!=null){
            CrmYxProcessDao.addProcess(entry.getId(),"3","广发设计信息变更进件",jsonStr,jsonObject.toJSONString(),"0");
            Integer code=jsonObject.getInteger("code");
            if(code!=200){
                throw new IllegalArgumentException(jsonObject.getString("msg"));
            }
            return jsonObject.getString("data");
        }else{
            throw new IllegalArgumentException("请求资方接口失败！");
        }
    }

    public String completionInfoUpdate(CustomerEntry entry, CustomerEntryCompletionChangeRecord reportChange, String inputPieceId) {
        Map<String, Object> map = new HashMap<>();
        // todo
        map.put("partner", "nenghui");

        map.put("capital", entry.getPartnerId());
        //进件模块
        ///进件序号
        map.put("inputPieceId", inputPieceId);
        map.put("changeReason", reportChange.getReason());
        map.put("design_capacity",entry.getActualCapacity().stripTrailingZeros().toPlainString()); //装机容量
        map.put("safety_warning_img2", dealImgUrls(reportChange.getSafetyWarningImg2()));
        map.put("safety_warning_img3", dealImgUrls(reportChange.getSafetyWarningImg3()));
        map.put("safety_warning_img", dealImgUrls(reportChange.getSafetyWarningImg()));
        map.put("safety_disclose_doc_img", dealImgUrls(reportChange.getSafetyDiscloseDocImg()));
        map.put("zj_plate_img", dealImgUrls(reportChange.getZjPlateImg()));
        map.put("component_img1", dealImgUrls(reportChange.getComponentImg1()));
        map.put("component_img3", dealImgUrls(reportChange.getComponentImg3()));
        map.put("component_img4", dealImgUrls(reportChange.getComponentImg4()));
        map.put("dc_imgs", dealImgUrls(reportChange.getDcImgs()));
        map.put("nbq_plate_img", dealImgUrls(reportChange.getNbqPlateImg()));
        map.put("total_imgs", dealImgUrls(reportChange.getTotalImgs()));
        map.put("nbq_zlc_img", dealImgUrls(reportChange.getNbqZlcImg()));
        map.put("open_way_voltage_imgs", dealImgUrls(reportChange.getOpenWayVoltageImgs()));
        map.put("nbq_zb_img", dealImgUrls(reportChange.getNbqZbImg()));
        map.put("bw_inner_img", dealImgUrls(reportChange.getBwInnerImg()));
        map.put("bw_jd_img", dealImgUrls(reportChange.getBwJdImg()));
        map.put("zj_img8", dealImgUrls(reportChange.getZjImg8()));
        map.put("zj_img9", dealImgUrls(reportChange.getZjImg9()));
        map.put("zj_img4", dealImgUrls(reportChange.getZjImg4()));
        map.put("zj_img10", dealImgUrls(reportChange.getZjImg10()));
        map.put("zj_img11", dealImgUrls(reportChange.getZjImg11()));
        map.put("zj_img12", dealImgUrls(reportChange.getZjImg12()));
        map.put("zj_img13", dealImgUrls(reportChange.getZjImg13()));
        map.put("zj_img14", dealImgUrls(reportChange.getZjImg14()));
        map.put("jd_img4", dealImgUrls(reportChange.getJdImg4()));
        map.put("bk_img1", dealImgUrls(reportChange.getBkImg1()));
        map.put("bk_img2", dealImgUrls(reportChange.getBkImg2()));
        map.put("bk_img3", dealImgUrls(reportChange.getBkImg3()));
        map.put("yk_img1", dealImgUrls(reportChange.getYkImg1()));
        map.put("fix_other_img", dealImgUrls(reportChange.getFixOtherImg()));
        map.put("size_measure_imgs", dealImgUrls(reportChange.getSizeMeasureImgs()));
//        map.put("jd_img7", reportChange.getReason());
        map.put("jd_img8", dealImgUrls(reportChange.getJdImg8()));
        map.put("jd_img5", dealImgUrls(reportChange.getJdImg5()));
        map.put("jd_img9", dealImgUrls(reportChange.getJdImg9()));
        map.put("jd_img10", dealImgUrls(reportChange.getJdImg10()));
        map.put("jd_img11", dealImgUrls(reportChange.getJdImg11()));
//        map.put("jd_img12", reportChange.getReason());
        map.put("fs_img1", dealImgUrls(reportChange.getFsImg1()));
        map.put("fs_img2", dealImgUrls(reportChange.getFsImg2()));
        map.put("fs_img3", dealImgUrls(reportChange.getFsImg3()));
//        map.put("wcazqjt_img", reportChange.getReason());
        map.put("zj_img5", dealImgUrls(reportChange.getZjImg5()));
        map.put("water_mud_clamp_imgs", dealImgUrls(reportChange.getWaterMudClampImgs()));


        String jsonStr = new Gson().toJson(map);
        logger.info("gridIncomingApplication  广发完工信息变更进件：PartnersContractNumber:{},json:{}",inputPieceId,jsonStr);
        JSONObject jsonObject = PartnerApiUtils.clientPostToApi(jsonStr, DH + "/open/link/completeInfoUpdate");
        if(jsonObject!=null){
            CrmYxProcessDao.addProcess(entry.getId(),"3","广发完工信息变更进件",jsonStr,jsonObject.toJSONString(),"0");
            Integer code=jsonObject.getInteger("code");
            if(code!=200){
                throw new IllegalArgumentException(jsonObject.getString("msg"));
            }
            return jsonObject.getString("data");
        }else{
            throw new IllegalArgumentException("请求资方接口失败！");
        }
    }

    //物料信息变更
    public String materialInfoUpdate(CustomerEntry entry,List<Record> records,String inputPieceId,String changeReason){
        Map<String,Object> map=new HashMap<>();
        List<Map<String, Object>> inverterList = new ArrayList<>();
        List<Map<String, Object>> moduleList = new ArrayList<>();
        List<Record> zjList = records.stream().filter(record -> "1".equals(record.getStr("type"))).collect(Collectors.toList());
        List<Record> nbqList = records.stream().filter(record -> "2".equals(record.getStr("type"))).collect(Collectors.toList());
        // 组件品牌
        Map<String, String> componentMap = PartnerBrandUtils.getBrandList("3", PartnerConstants.PARTNER_ID_GF);
        // 逆变器品牌
        Map<String, String> inverMap = PartnerBrandUtils.getBrandList("1", PartnerConstants.PARTNER_ID_GF);

        map.put("partner", "nenghui");
        map.put("capital", entry.getPartnerId());
        map.put("inputPieceId", inputPieceId);
        map.put("changeReason", changeReason);
        List<String> snList = new ArrayList<>();
        HashMap<String, Object> moduleMap = new HashMap<>();
        String materialCode = "";
        String materialName = "";
        String materialSpec = "";
        String materialBrand = "";
        String materialId = "";
        for (Record record : zjList) {
            String barcode = record.getStr("barcode");
            String newBarcode = record.getStr("new_barcode");
            if(StringUtils.isNotBlank(newBarcode)){
                snList.add(newBarcode);
            }else {
                snList.add(barcode);
            }
            if (StringUtil.isBlank(materialCode)){
                materialCode = record.getStr("material_code");
            }
            if (StringUtil.isBlank(materialName)){
                materialName = record.getStr("material_name");
            }
            if (StringUtil.isBlank(materialSpec)){
                materialSpec = record.getStr("material_spec");
            }
            if (StringUtil.isBlank(materialBrand)){
                materialBrand = record.getStr("material_brand");
            }
            if (StringUtil.isBlank(materialId)){
                materialId = record.getStr("material_id");
            }
        }
        moduleMap.put("materialCode",materialCode);
        moduleMap.put("materialName",materialName);
        SupplyMaterial supplyMaterial = supplyMaterialDao.get(materialId);
        moduleMap.put("moduleModel",supplyMaterial.getMaterialModel());//组件型号
        moduleMap.put("modulePower",materialSpec);//组件功率
        String brand = "";
        if (componentMap.containsKey(materialBrand)) {
            // 获取广发的品牌名称
            brand = componentMap.get(materialBrand);
        }
        //组件品牌
        moduleMap.put("moduleBrand",brand);
        //电池参数: 1.N型 2.P型
        moduleMap.put("batteryParam","1");
        //组件玻型:1.单玻 2.双玻
        moduleMap.put("moduleGlassType","2");
        //完工容量（W）
        moduleMap.put("completeVolume",entry.getActualCapacity().stripTrailingZeros().toPlainString());
        //组件序列号集合
        moduleMap.put("sns",snList);
        moduleList.add(moduleMap);
        map.put("moduleList",moduleList);
        for (Record r : nbqList) {
            HashMap<String, Object> inverterMap = new HashMap<>();
            inverterMap.put("materialCode",r.getStr("material_code"));
            inverterMap.put("materialName",r.getStr("material_name"));
            String inverterBrand = "";
            if (inverMap.containsKey(r.getStr("material_brand"))) {
                // 获取广发的品牌名称
                inverterBrand = inverMap.get(r.getStr("material_brand"));
            }
            inverterMap.put("inverterBrand", inverterBrand); //逆变器品牌

            SupplyMaterial material = supplyMaterialDao.get(r.getStr("material_id"));
            inverterMap.put("inverterSpec", material.getMaterialModel());//逆变器型号

            String model = r.getStr("material_spec");
            if (model.contains("KW")) {
                model = model.substring(0, model.indexOf("KW"));
                model = model + "000";
            }
            inverterMap.put("inverterPower", model); //逆变器功率

            String nbqSn = r.getStr("nbq_sn");
            String newNbqSn = r.getStr("new_nbq_sn");
            if (StringUtils.isNotBlank(newNbqSn)) {
                inverterMap.put("nbq_sn",newNbqSn);
            }else {
                inverterMap.put("nbq_sn",nbqSn);
            }
            String sn = r.getStr("sn");
            String newSn = r.getStr("new_sn");
            if (StringUtils.isNotBlank(newSn)) {
                inverterMap.put("cjq_sn",newSn);
            }else {
                inverterMap.put("cjq_sn",sn);
            }
            String yzCode = r.getStr("yz_code");
            String newYzCode = r.getStr("new_yz_code");
            BrandFactInfo info = BrandFactInfo.externalOf(r.getStr("material_brand"));
            if (info != null && info.isYzCodeFlag()){
                if (StringUtil.isNotBlank(newYzCode)) {
                    inverterMap.put("yz_code", newYzCode);
                }else {
                    inverterMap.put("yz_code", yzCode);
                }
            }
            inverterList.add(inverterMap);
        }
        map.put("inverterList",inverterList);
        String jsonStr = new Gson().toJson(map);
        logger.info("materialInfoUpdate  广发物料信息变更进件：inputPieceId:{},json:{}",inputPieceId,jsonStr);
        JSONObject jsonObject = PartnerApiUtils.clientPostToApi(jsonStr, DH + "/open/link/deviceInfoUpdate");
        logger.info("materialInfoUpdate  广发物料信息变更进件返回结果：inputPieceId:{},result:{}",inputPieceId,jsonObject);
        if(jsonObject!=null){
            CrmYxProcessDao.addProcess(entry.getId(),"3","广发物料信息变更进件",jsonStr,jsonObject.toJSONString(),"0");
            Integer code=jsonObject.getInteger("code");
            if(code!=200){
                throw new IllegalArgumentException(jsonObject.getString("msg"));
            }
            return jsonObject.getString("data");
        }else{
            throw new IllegalArgumentException("请求资方接口失败！");
        }
    }

    public JSONArray getChangeStatus(String changeNumbers) {
        Map<String, Object> map = new HashMap<>();
        map.put("changeNoList",changeNumbers);
        map.put("partner", "nenghui");
        map.put("capital", PartnerConstants.PARTNER_ID_GF);
        String jsonStr = new Gson().toJson(map);
        logger.info("gridIncomingApplication  变更状态查询：changeNumbers:{},json:{}",changeNumbers,jsonStr);
        JSONObject jsonObject = PartnerApiUtils.clientPostToApi(jsonStr, DH + "/open/link/updateInputPieceResult");
        if(jsonObject!=null){
            Integer code=jsonObject.getInteger("code");
            if(code!=200){
                throw new IllegalArgumentException(jsonObject.getString("msg"));
            }
            return jsonObject.getJSONArray("data");
        }else{
            throw new IllegalArgumentException("请求资方接口失败！");
        }
    }
    //获取合同签约
    public String guangFaSignContract(String partnerId, String inputPieceId) {
        Map<String,Object> map=new HashMap<>();
//        map.put("bizNo",bizNo);
        map.put("inputPieceId",inputPieceId);
        map.put("capital",partnerId);
        map.put("partner","nenghui");
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("guangFaSignContract  获取合同签约：inputPieceIds:{},json:{}",inputPieceId,jsonStr);
        String res = PartnerApiUtils.doPostForGfApiResulToString(map, DH + "/open/link/signContract");
        if(res!=null){
            return res;
        }else{
            throw new IllegalArgumentException("请求失败！");
        }
    }


    //查询合同-广发
    public List<GuangfaQryContractVO> queryContract(String partnerId, List<String> inputPieceIdList) {
        Map<String,Object> map=new HashMap<>();
        map.put("inputPieceIdList",inputPieceIdList);
        map.put("capital",partnerId);
        map.put("partner","nenghui");
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("queryContract  查询合同：inputPieceIdList:{},json:{}",inputPieceIdList,jsonStr);
        JSONArray jsonObject = PartnerApiUtils.doPostForPartnerApi(map, DH + "/open/link/queryContract");
        if(jsonObject!=null){
            List<GuangfaQryContractVO> qryContractVOS = new Gson().fromJson(jsonObject.toJSONString(), new TypeToken<List<GuangfaQryContractVO>>() {}.getType());
            return qryContractVOS;
        }else{
            throw new IllegalArgumentException("请求失败！");
        }
    }


    //预览合同-广发
    public String guangFaPreviewInpContract(String partnerId, String contractNo) {
        Map<String,Object> map=new HashMap<>();
        map.put("contractNo",contractNo);
        map.put("capital",partnerId);
        map.put("partner","nenghui");
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("guangFaPreviewInpContract  预览合同：contractNo:{},json:{}",contractNo,jsonStr);
        String res = PartnerApiUtils.doPostForGfApiResulToString(map, DH + "/open/link/previewInpContract");
        if(res!=null){
            return res;
        }else{
            throw new IllegalArgumentException("请求失败！");
        }
    }

    //终止合同-广发/顶好
    public String guangFaTerminateContract(String partnerId, String inputPieceId, String prjCancelReason) {
        Map<String,Object> map=new HashMap<>();
        map.put("inputPieceId",inputPieceId);
        map.put("prjCancelReason",prjCancelReason);
        map.put("capital",partnerId);
        map.put("partner","nenghui");
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("guangFaTerminateContract  终止合同：inputPieceId:{},json:{}",inputPieceId,jsonStr);
        String res = PartnerApiUtils.doPostForGfApiResulToString(map, DH + "/open/link/terminateContract");
        if(res!=null){
            return res;
        }else{
            throw new IllegalArgumentException("请求失败！");
        }
    }

    //项目公司合同落章
    public String guangFaDoSealContract(String partnerId, String inputPieceId) {
        Map<String,Object> map=new HashMap<>();
        map.put("inputPieceId",inputPieceId);
        map.put("capital",partnerId);
        map.put("partner","nenghui");
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("guangFaDoSealContract  终止合同：inputPieceId:{},json:{}",inputPieceId,jsonStr);
        String res = PartnerApiUtils.doPostForGfApiResulToString(map, DH + "/open/link/doSealContract");
        if(res!=null){
            return res;
        }else{
            throw new IllegalArgumentException("请求失败！");
        }
    }

    //终止进件
    public void cancelGFApply(CustomerEntry entry, String inputPieceId,String returnType, String cancelReason){
        Map<String,Object> map=new HashMap<>();
        map.put("inputPieceId",inputPieceId);
        map.put("capital",entry.getPartnerId());
        map.put("partner","nenghui");
        map.put("returnType",returnType);//退回类型
        map.put("cancelReason",cancelReason);//退回原因
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("cancelGFApply  终止进件 请求参数：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("请求资方接口失败！");
        }
    }

    //竣工进件
    public String doPostForGfAcceptInputPiece(Map<String,Object> map) {
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("acceptInputPiece  竣工进件：map:{},json:{}",map,jsonStr);
        String res = PartnerApiUtils.doPostForGfAcceptReformed(map, DH + "/open/link/acceptInputPiece");
        if(res!=null){
            return res;
        }else{
            throw new IllegalArgumentException("请求失败！");
        }
    }

    //竣工查询
    public JSONArray acceptResultQry(Map<String,Object> map) {
        map.put("partner","nenghui"); //合作方，固定为nenghui
        map.put("capital","03"); //资方广发，03
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("acceptResultQry  竣工查询：map:{},json:{}",map,jsonStr);
        JSONArray result = PartnerApiUtils.doPostForPartnerApi(map, DH + "/open/link/acceptResultQry");
        if(result!=null){
            return result;
        }else{
            throw new IllegalArgumentException("请求失败！");
        }
    }

    //整改提交
    public String submitReformedInfo(Map<String,Object> map) {
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("submitReformedInfo  整改提交：map:{},json:{}",map,jsonStr);
        String res = PartnerApiUtils.doPostForGfReformed(map, DH + "/open/link/submitReformedInfo");
        if(res!=null){
            return res;
        }else{
            throw new IllegalArgumentException("请求失败！");
        }
    }

    //整改查询
    public JSONArray queryReformedList(Map<String,Object> map) {
        map.put("partner","nenghui"); //合作方，固定为nenghui
        map.put("capital","03"); //资方广发，03
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("queryReformedList  整改查询：map:{},json:{}",map,jsonStr);
        JSONArray result = PartnerApiUtils.doPostForPartnerApi(map, DH + "/open/link/queryReformedList");
        if(result!=null){
            return result;
        }else{
            throw new IllegalArgumentException("请求失败！");
        }
    }
    //查询二维码-广发
    public JSONArray queryQrCodeUrl(String partnerId, String inputPieceId) {
        Map<String,Object> map=new HashMap<>();
        map.put("inputPieceIds",inputPieceId);
        map.put("capital",partnerId);
        map.put("partner","nenghui");
        Gson gson=new Gson();
        String jsonStr=gson.toJson(map);
        logger.info("guangFadownloadQrCodeUrl  查询二维码：inputPieceId:{},json:{}",inputPieceId,jsonStr);
        JSONObject jsonObject = PartnerApiUtils.clientPostToApi(jsonStr, DH + "/open/link/queryStationQrUrlList");
        if(jsonObject!=null){
            Integer code=jsonObject.getInteger("code");
            if(code!=200){
                throw new IllegalArgumentException(jsonObject.getString("msg"));
            }
            return jsonObject.getJSONArray("data");
        }else{
            throw new IllegalArgumentException("请求资方接口失败！");
        }
    }

    public static void main(String arr[]) throws Exception {

        Map<String,Object> map=new HashMap<>();
//        map.put("inputPieceId","ORG202405230001202408020001");
//        map.put("contractNo","202407230009");
//        map.put("bizNo",);
        map.put("capital","03");
        map.put("partner","nenghui");


//        Gson gson=new Gson();
//        String jsonStr=gson.toJson(map);
//
//        List<String> inputPieceIdList = new ArrayList<>() ;
//        inputPieceIdList.add("ORG202405230001202408020001");
//        map.put("inputPieceIdList",inputPieceIdList);
//        JSONArray jsonObject= PartnerApiUtils.doPostForPartnerApi(map,"http://uat.91hyx.com/api/open/link/queryContract");

        //签名http://assetstest.gdgnec.com.cn/h5Page/#/pages/H5OnlineSigning/index?cipherText=
        map.put("inputPieceId","ORG202405230001202407230009_null");
//        map.put("bizNo","12321");
        String jsonObject = PartnerApiUtils.doPostForGfApiResulToString(map,  "http://uat.91hyx.com/api/open/link/signContract");

        //预览
//        map.put("contractNo","");
//        String jsonObject = PartnerApiUtils.doPostForGfApiResulToString(map,  "http://uat.91hyx.com/api/open/link/previewInpContract");

        System.out.println(jsonObject);
//        Map<String,Object> map=new HashMap<>();
//        map.put("capital","03"); //资方id，03:广发  05 顶好
//        map.put("inputPieceIds","ORG202405230001202407180003"); //资方id，03:广发  05 顶好
//        JSONObject jsonObject= PartnerApiUtils.getresultDoPost(map,"http://uat.91hyx.com/api/open/link/queryPreAuditState");
//        System.out.println(new Gson().toJson(jsonObject));
//        List<StatusFormVo> list=new Gson().fromJson(jsonObject.getString("data"), new TypeToken< List<StatusFormVo>>() {
//        }.getType());
//        StatusFormVo statusFormVo=list.get(0);
//
//        System.out.println(statusFormVo.getBusinesssMsg());
    }
}
