package com.sifang.modules.customer.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.config.SfCacheService;
import com.sifang.modules.customer.constant.CombinerBoxGroupConstants;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.customer.constant.YueXiuConstants;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.*;
import com.sifang.modules.customer.form.*;
import com.sifang.modules.customer.utils.TokenTestUtils;
import com.sifang.modules.insurance.dao.CrmCustomerNoSystemEntryInsuranceDao;
import com.sifang.modules.insurance.dao.CustomerEntryInsuranceDao;
import com.sifang.modules.insurance.entity.CrmCustomerEntryInsurance;
import com.sifang.modules.insurance.entity.CrmCustomerNoSystemEntryInsurance;
import com.sifang.modules.platform.utils.Base64Url;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectCompanyDao;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.util.GuardUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.HttpClientErrorException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OperatingLeaseService {

    @Autowired
    CustomerEntryDao customerDao;

    @Autowired
    ProjectCompanyDao projectCompanyDao;

    @Autowired
    SfCacheService cacheService;

    @Autowired
    private CrmCustomerIncomingApplicationDao applicationDao;

    @Autowired
    private CustomerEntrySurveyRecordDao surveyRecordDao;

    @Autowired
    private CrmYxIncomingLogDao yxIncomingLogDao;

    @Autowired
    private CrmEntryCombinerBoxGroupDao boxGroupDao;

    @Autowired
    private CrmEntryCombinerBoxGroupService boxGroupService;

    @Autowired
    private CrmCustomerIncomingApplicationDao crmCustomerIncomingApplicationDao;

    @Autowired
    CustomerEntryInsuranceDao entryInsuranceDao;

    @Autowired
    CrmCustomerNoSystemEntryInsuranceDao noSystemEntryInsuranceDao;

    private static boolean reFleshFlag = true; // 服务器重启之后，accessToken需要重新获取

    @Value("${yx.setting}")
    private String YX;

    private Logger logger = LoggerFactory.getLogger(OperatingLeaseService.class);

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

    /**
     * 获取token
     */
    public String findOauthToken() {

        String accessToken = null;
        try {
            String obj = TokenTestUtils.getLvsAccessToken();
            JSONObject key = JSONObject.parseObject(obj);
            System.out.println("access_token="+key.getString("access_token"));
            accessToken = key.getString("access_token");
            cacheService.setex("zyAccessToken", 1800, accessToken);
        }catch (Exception e){
            e.printStackTrace();
        }
        return accessToken;
    }


    public JSONObject clientPostZYMap(Map<String, Object> mapss, String url) {
        String faccount = cacheService.get("zyAccessToken");
        if (reFleshFlag) {
            logger.info("----->>>>>>>faccount  重新获取");
            faccount = null;
            reFleshFlag = false;
        }
//        String refresh_token = cacheService.get("refresh_token");
        logger.info("获取token值： {}",faccount);
        if (StringUtil.isBlank(faccount)) {
            faccount = findOauthToken();
        }
        JSONObject obj = null;
        try{
             obj = TokenTestUtils.clientPostYX(mapss, url, faccount);
        }catch (HttpClientErrorException c){
            logger.error(">>>>clientPostZYMap  c:{}",c);
            faccount=findOauthToken();
            obj = TokenTestUtils.clientPostYX(mapss, url, faccount);
        }
        return obj;
    }

    /**
     * 1.1	提交预审
     */
    public JSONObject admittanceEntry(CustomerEntry entry) {
        Map<String, Object> map = new HashMap<>();
        List<BpMasterBaseDto> bpMasterBaseDtoList = new ArrayList<>();
        BpMasterBaseDto bpMasterBaseDto = new BpMasterBaseDto();
        //承租人信息
        HlsBpMaster hlsBpMaster = new HlsBpMaster();
        hlsBpMaster.setBpClass("1".equals(entry.getTenantType()) ? "NP" : "ORG");
        hlsBpMaster.setBpCategory("TENANT");
        hlsBpMaster.setBpName(entry.getTenantName());
        switch (entry.getTenantType()) {
            case "1":
                hlsBpMaster.setIdType("ID_CARD");
                hlsBpMaster.setIdCardNo(entry.getIdCode());
                hlsBpMaster.setGender(entry.getGender());
                hlsBpMaster.setAge(entry.getAge().longValue());
                break;
            case "2":
                hlsBpMaster.setRegnotype("07"); // 默认 07.统一社会信用代码
                hlsBpMaster.setRegno(entry.getRegno());
                break;
        }
        hlsBpMaster.setNationality("46");
        hlsBpMaster.setCellPhone(entry.getMobile()); // 个人手机/企业联系手机
        bpMasterBaseDto.setHlsBpMaster(hlsBpMaster);

        List<HlsBpMasterAddress> hlsBpMasterAddressList = new ArrayList<>();
        //承租人地址信息
        HlsBpMasterAddress hlsBpMasterAddress = new HlsBpMasterAddress();
        hlsBpMasterAddress.setAddressType("LEASEITEM_ADDRESS");
        hlsBpMasterAddress.setCountryCode("46");
        Record province = customerDao.getProvinceCode(entry.getProvince());
        logger.info("entry.getProvince:{},province:{}", entry.getProvince(), new Gson().toJson(province));
        hlsBpMasterAddress.setProvinceCode(province.getLong("regionalism_code").toString());
        Record city = customerDao.getCityCode(entry.getCity(),province.getLong("ProvinceID"));
        hlsBpMasterAddress.setCityCode(city.getLong("regionalism_code").toString());
        hlsBpMasterAddress.setDistrictCode(customerDao.getDistrictCode(entry.getArea(),city.getLong("CityID")).toString());
        hlsBpMasterAddress.setAddress(entry.getAddress());
        switch (entry.getTenantType()) {
            case "1":
                hlsBpMasterAddress.setPhone(entry.getMobile());
                hlsBpMasterAddress.setCellPhone(entry.getMobile());
                break;
        }
        hlsBpMasterAddressList.add(hlsBpMasterAddress);
        bpMasterBaseDto.setHlsBpMasterAddressList(hlsBpMasterAddressList);

        if ("2".equals(entry.getTenantType())) {
            List<HlsBpMasterMainMembers> hlsBpMasterMainMembersList = new ArrayList<>();
            HlsBpMasterMainMembers members = new HlsBpMasterMainMembers();
            members.setMainMembersPosition("1"); // 1:法定代表人/非法人组织负责人
            members.setMainMembersName(entry.getCorp());
            members.setMainMembersCertType("ID_CARD"); // ID_CARD:身份证
            members.setMainMembersCertCode(entry.getIdCode());
            hlsBpMasterMainMembersList.add(members);
            bpMasterBaseDto.setHlsBpMasterMainMembersList(hlsBpMasterMainMembersList);
        }
        bpMasterBaseDtoList.add(bpMasterBaseDto);
        map.put("body",bpMasterBaseDtoList);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId", YueXiuConstants.CLIENT_ID);
        //以固定字符“YX”开头，拼接业务编码+环境;测试环境：SIT   用户验收环境：UAT   生产环境：PROD
        head.put("transactionCode","YX_FINANCE_PROJECT_TENANT"+ YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        String url = "/r/api/finance/sync/project/tenant";
        JSONObject jieMap = clientPostZYMap(map, url);
//      发送信息到越秀平台
        logger.info("提交预审 admittanceEntry -------返回结果：{}, PowerStationCode:{} ,maps:{}", jieMap, entry.getPowerStationCode(), map);



        JSONArray reqMap = jieMap.getJSONArray("body");
        if (reqMap != null) {
            JSONObject re = reqMap.getJSONObject(0);
            if ("S".equals(re.getString("type"))) {
                CrmYxProcessDao.addProcess(entry.getId(),"1","越秀承租人预审接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"0");
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"1","NEW","0","0","推送");
            } else {
                CrmYxProcessDao.addProcess(entry.getId(),"1","越秀承租人预审接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"1",null,"1",null,null);
            }
            yxIncomingLogDao.addCrmYxIncomingLog(entry.getId(),"","1","提交预审",null);
            return re;
        } else {
            CrmYxProcessDao.addProcess(entry.getId(),"1","越秀承租人预审接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
            CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"1",null,"1",null,null);

            JSONObject reqHeadMap = jieMap.getJSONObject("head");
            reqHeadMap.getString("errorMessage");
            return reqHeadMap;
        }
    }

    /**
     * 获取预审结果
     */
    public Map<String, String> findPreauditStatus(String idCode) {
        Map<String, String> resultMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> idCodeMap = new HashMap<>();
        idCodeMap.put("idCardNo",idCode);
        list.add(idCodeMap);
        map.put("body",list);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_FINANCE_PROJECT_TENANT_STATUS"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        String url = "/r/api/finance/project/tenant/status/query";
        JSONObject jieMap = clientPostZYMap(map, url);
//      发送信息到越秀平台
        logger.info("提交预审 admittanceEntry -------返回结果：{}, idCode:{} ,maps:{}", jieMap, idCode, map);

        JSONArray reqMap = jieMap.getJSONArray("body");
        if(reqMap==null){
            throw new IllegalArgumentException("查询越秀预审结果失败,请稍后在查询!");
        }
        JSONObject re = reqMap.getJSONObject(0);
        //type: S-请求成功 E-请求失败
        if ("S".equals(re.get("type"))) {
            //预审结果:NEW-预审待审批 APPROVING-预审审批中 APPROVED-预审通过 REJECT-预审拒绝
            resultMap.put("result",re.getString("result"));
            resultMap.put("reason",re.getString("reason"));
        } else if("E".equals(re.get("type"))){
            resultMap.put("result","REJECT");
            resultMap.put("reason",re.getString("message"));
        }else {
            throw new IllegalArgumentException("查询越秀预审结果失败,请稍后在查询!");
        }
        return resultMap;
    }


    public void investigation(CustomerEntry customerEntry) {
        String url = "/r/api/access/credit/investigation/query";
        Map<String, Object> map = new HashMap<>();
        map.put("name", customerEntry.getTenantName());
        map.put("idCardNo", customerEntry.getIdCode().toUpperCase());
        List<Map<String, String>> list = Lists.newArrayList();
        Map<String, String> mapus = Maps.newHashMap();
        mapus.put("name", "张**");
        mapus.put("idCardNo", "1");
        mapus.put("telephoneNum", "1");
        list.add(mapus);
        map.put("bpList", list);
        /*JSONObject jieMap = clientPostZYMap(map, url);
        if (SourceConstants.CODE_CG.equals(jieMap.get("code"))) {
            JSONArray reqMap = jieMap.getJSONArray("rows");
            JSONObject re = reqMap.getJSONObject(0);
            if ("通过校验".equals(re.get("result"))) {
                //征信通过
                customerEntry.setCredit(SourceConstants.CREADIT_ONE);
                customerEntry.setCreditDsc("");
            } else if ("未通过校验".equals(re.get("result"))) {
                //不通过原因
                customerEntry.setCredit(SourceConstants.CREADIT_TWO);
            }
            customerEntry.setCreditDsc(re.get("dsc") != null ? re.get("dsc").toString() : "");
        } else if (!jieMap.getBoolean("success")) {
            customerEntry.setCredit(SourceConstants.CREADIT_TWO);
            customerEntry.setCreditDsc(jieMap.getString("message"));
        }*/

        //征信通过
        customerEntry.setCredit(SourceConstants.CREADIT_ONE);
        customerEntry.setCreditDsc("");
        customerDao.save(customerEntry);


    }


    /**
     * 提交进件申请---第一次进件
     *
     * 设计审核通过后，后台自动出发进件申请，申请所涉及的字段内容处理如下：
     * 保险购买情况：默认“控制投放及续保”；
     * 预计投放日：当前日期+45天；
     * 设计安装容量：=预估安装容量；
     * 组件规格：默认“660”；（添加产品信息的时候维护，即产品信息设置中增加默认组件规格字段，手动输入规格，只能为数字）
     * 组件数量：(预估安装容量*1000)/660，结果向下取整；
     */
    public Result accessProjectApply(CustomerEntry entry,List<PrjProjectLeaseItem> prjProjectLeaseItemList,CrmTenantYxBankCard bankCard,CrmCustomerIncomingApplication incomingApplication) {
        String idCode = entry.getIdCode();
        if (Objects.equals("2", entry.getTenantType())) {
            idCode = entry.getRegno();
        }
        Record customerYxCondition = customerDao.findCustomerYxCondition(idCode,entry.getPartnerId());

        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> bodyMapList = new ArrayList<>();
        Map<String, Object> bodyMap = new HashMap<>();

        if(StringUtil.isNotBlank(incomingApplication.getProjectStatus()) && StringUtil.equalsAny(incomingApplication.getProjectStatus(),"APPROVING","APPROVED")){
            throw new IllegalArgumentException("进件状态不允许推送进件!");
        }

        //进件信息
        PrjProject prjProject = new PrjProject();
        /**
         * 厂商：上海能辉科技股份有限公司 91310000685457643J
         * 农户备案出卖人：第一出卖人：贵州能辉智慧能源科技有限公司 91520198MAAJWKQD32
         * 第二出卖人：上海能辉科技股份有限公司 91310000685457643J
         * 项目公司备案出卖人：上海能辉科技股份有限公司 91310000685457643J
         * 运维方：上海能辉科技股份有限公司 91310000685457643J
         */
        prjProject.setManufacturerRegno("91310000685457643J"); // 厂商
        prjProject.setFactoryRegno("91310000685457643J"); // 运维方
        if ("1".equals(entry.getFilingType())) { // 农户备案
            prjProject.setSellerRegno("91520198MAAJWKQD32"); // 第一出卖人
            prjProject.setSellerRegnoSecond("91310000685457643J"); // 第二出卖人
        }
        else { // 项目公司备案
            prjProject.setSellerRegno("91310000685457643J"); // 第一出卖人
        }
        prjProject.setPartnersContractNumber(incomingApplication.getPartnersContractNumber()); // 合作方进件序号
        prjProject.setLeaseChannel("50"); // 商业模式：40.经营租赁 50.合作共建
        prjProject.setDocumentType("JOINT_CONSTRUCTION"); // 单据类型：经营租赁：OPERATING_LEASE  合作共建：JOINT_CONSTRUCTION
        prjProject.setDivision("PHOTOVOLTAIC_DEVICES");
        prjProject.setPaymentBpType("VENDER");
        String leaseDate="";
        if(entry.getLeaseDate()!=null){
            leaseDate=DateUtils.formatDate(entry.getLeaseDate(),"yyyyMMdd");
        }else {
            leaseDate=DateUtils.dateChangeDays(new Date(),60,"yyyyMMdd");//预计投放日：当前日期+60天
            try {
                String dateStr=DateUtils.dateChangeDays(new Date(),60,"yyyy-MM-dd");
                entry.setLeaseDate(DateUtils.parseDate(dateStr,"yyyy-MM-dd"));
            } catch (ParseException e) {

            }
        }
        prjProject.setLeaseDate(leaseDate);
        prjProject.setInsuranceFlag(StringUtil.isBlank(entry.getInsuranceFlag())?"1":entry.getInsuranceFlag());

        Record projectSet = projectCompanyDao.getProjectCompanyDetail(entry.getProjectCompanyId());
        if (projectSet != null && StringUtil.isNotBlank(projectSet.getStr("company_code"))) {
            prjProject.setLessorCode(projectSet.getStr("company_code"));
        } else {
            prjProject.setLessorCode("3081");
        }

        String tenantSignType = "SIGN_ONLINE";
        //法人-承租人类型
        if ("2".equals(entry.getTenantType())) {
             tenantSignType = "SIGN_OFFLINE";
        }
        prjProject.setTenantSignType(tenantSignType);
        prjProject.setSellerSignType("SIGN_ONLINE");
        prjProject.setOperatorSignType("SIGN_ONLINE");


        //租赁物信息
//        List<PrjProjectLeaseItem> prjProjectLeaseItemList = new ArrayList<>();
//        PrjProjectLeaseItem projectLeaseItem = new PrjProjectLeaseItem();
//        projectLeaseItem.setPartnersLeaseItemId(leaseItem.getId());
//        projectLeaseItem.setFullName(leaseItem.getFullName());
//        projectLeaseItem.setProducer(leaseItem.getProducer());
//        projectLeaseItem.setProductModel(leaseItem.getProductModel());
//        projectLeaseItem.setInstalledCapacity(leaseItem.getInstalledCapacity().toString());
//        projectLeaseItem.setDescription(leaseItem.getDescription());
//        projectLeaseItem.setModuleProducer(leaseItem.getModuleProducer());
//        projectLeaseItem.setInverterNumber(leaseItem.getInverterNumber());
//        projectLeaseItem.setInverterBrand(leaseItem.getInverterBrand());
//        projectLeaseItem.setInverterModel(leaseItem.getInverterModel());
//        projectLeaseItem.setModuleQuantity(leaseItem.getModuleQuantity());
//        prjProjectLeaseItemList.add(projectLeaseItem);
        bodyMap.put("prjProjectLeaseItemList",prjProjectLeaseItemList);


        //产品信息
        PrjProjectProduct prjProjectProduct = new PrjProjectProduct();

        //if ("2".equals(entry.getFilingType())) {
            prjProjectProduct.setPlanCode(entry.getProjectCode());
  /*      } else {
            prjProjectProduct.setPlanCode("P005074");
        }*/
        List<ProductPara> productParaList = new ArrayList<>();
        List<Record> paraList = applicationDao.findProductParaList(entry.getFilingType(),entry.getProjectCode());
        for (Record r : paraList) {
            ProductPara productPara1 = new ProductPara();
            productPara1.setProductParaName(r.getStr("product_para_code"));//承租人收益（元/块光伏板/年）
            productPara1.setProductParaValue(StringToNumber(r.getStr("product_para_value")));
            productPara1.setLeaseTermFrom(r.getStr("lease_term_from"));
            productPara1.setLeaseTermTo(r.getStr("lease_term_to"));
            productParaList.add(productPara1);
        }
        prjProjectProduct.setProductParaList(productParaList);
        bodyMap.put("prjProjectProduct",prjProjectProduct);

        //承租人信息
        List<BpMasterBaseJJDto> bpMasterBaseDtoList = new ArrayList();
        BpMasterBaseJJDto bpMasterBaseDto = new BpMasterBaseJJDto();
        InComingHlsBpMaster master = new InComingHlsBpMaster();
        master.setTenantCode(customerYxCondition.getStr("tenant_code"));
        master.setBpName(entry.getTenantName());
        //法人-承租人类型
        if ("2".equals(entry.getTenantType())) {
            master.setRegno(entry.getRegno());
        }
        else {
            master.setIdCardNo(entry.getIdCode());
            master.setCellPhone(entry.getMobile());
        }
//        master.setMaritalStatus(perInfo.getMarriageInfo());
        //已婚则录入配偶信息
//        if ("MARRIED".equals(perInfo.getMarriageInfo())) {
//            master.setBpNameSp(perInfo.getPartnerNameSpan());
//            master.setIdTypeSp(perInfo.getSpouseIdCardType());
//            master.setIdCardNoSp(perInfo.getSpouseIdCardNo());
//            master.setGenderSp(perInfo.getSpouseSex());
//        }
//        master.setAcademicBackground(perInfo.getEduExperience());
//        master.setAcademicDegree(perInfo.getEduDegree());
//        master.setEmploymentStatus(perInfo.getEmploymentStatus());
//        master.setWorkingPlace(perInfo.getWorkCorp());
//        master.setJobNature(perInfo.getJobNature());
//        master.setIndustry("");
//        master.setProfession(perInfo.getOccupation());
//        master.setPosition(perInfo.getHeadShip());
//        master.setJobTitle(perInfo.getPosition());
//        master.setHouseProperty(perInfo.getFamilyStatus());
        bpMasterBaseDto.setHlsBpMaster(master);
        List<HlsBpMasterAddress> hlsBpMasterAddressList = new ArrayList<>();
        HlsBpMasterAddress masterAddress = new HlsBpMasterAddress();
        masterAddress.setAddressType("LEASEITEM_ADDRESS");
        masterAddress.setCountryCode("46");

        Record province = customerDao.getProvinceCode(entry.getProvince());
        masterAddress.setProvinceCode(province.getLong("regionalism_code").toString());
        Record city = customerDao.getCityCode(entry.getCity(),province.getLong("ProvinceID"));
        masterAddress.setCityCode(city.getLong("regionalism_code").toString());
        masterAddress.setDistrictCode(customerDao.getDistrictCode(entry.getArea(),city.getLong("CityID")).toString());
        masterAddress.setAddress(entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress());
        masterAddress.setPhone(entry.getMobile());
        masterAddress.setCellPhone(entry.getMobile());
        hlsBpMasterAddressList.add(masterAddress);
        bpMasterBaseDto.setHlsBpMasterAddressList(hlsBpMasterAddressList);
        List<HlsBpMasterBankAccount> hlsBpMasterBankAccountList = new ArrayList<>();
        HlsBpMasterBankAccount masterBankAccount = new HlsBpMasterBankAccount();
        masterBankAccount.setBankAccountName(entry.getBankName());
        masterBankAccount.setBankAccountNum(entry.getBankCode());
        masterBankAccount.setTssBankNum(entry.getTssBankNum());
        hlsBpMasterBankAccountList.add(masterBankAccount);
        bpMasterBaseDto.setHlsBpMasterBankAccountList(hlsBpMasterBankAccountList);
        bpMasterBaseDtoList.add(bpMasterBaseDto);
        bodyMap.put("bpMasterBaseDtoList",bpMasterBaseDtoList);

        //账户信息
        List<PrjProjectAccount> prjProjectAccountList = new ArrayList<>();
        //农户备案才会传
        if("1".equals(entry.getFilingType())){
            if (bankCard != null && StringUtil.isNotBlank(bankCard.getAccountCode())) {
                PrjProjectAccount account = new PrjProjectAccount();
                account.setAccountType("01");
                account.setAccountName(entry.getTenantName());//发电户号和工行二类卡的账户名称记得也要传承租人的名称
                account.setAccountNumber(bankCard.getAccountCode());
                account.setTssBankNumber("102581000353");// 二类卡的联行号都是 102581000353
//        account.setElecCode("");
                prjProjectAccountList.add(account);
            }
        }

        bodyMap.put("prjProjectAccountList",prjProjectAccountList);

        if (entry.getAge() != null && entry.getAge() >= 65) {
            //共签人信息
            List<Map<String,Object>> hlsBpMasterList = new ArrayList<>();
            Map<String,Object> hlsBpMaster = new HashMap<>();
            Map<String,String> hlsBpMasterMap = new HashMap<>();
            hlsBpMasterMap.put("bpName",entry.getBpName());
            hlsBpMasterMap.put("idCardNo",entry.getBpIdCard());
            hlsBpMasterMap.put("cellPhone",entry.getBpMobile());
            hlsBpMaster.put("hlsBpMaster",hlsBpMasterMap);
            hlsBpMasterList.add(hlsBpMaster);
            bodyMap.put("bpMasterCoSignerBaseDtoList",hlsBpMasterList);
        }

        //判断电站汇流组信息
        Record boxGroupRecord=boxGroupDao.getEntryBoxGroup(entry.getId());
        String sql="";
        if(boxGroupRecord!=null && !CombinerBoxGroupConstants.MERGE_TYPE_DHBW.equals(boxGroupRecord.getStr("type"))){ //非单户并网
            prjProject.setConfluenceGroupNumber(boxGroupRecord.getStr("group_number"));
            prjProject.setConfluenceTotalNumber(boxGroupRecord.getInt("total_count"));
            if(boxGroupRecord.getInt("serial_number")!=null){
                prjProject.setConfluenceSerialNumber(boxGroupRecord.getInt("serial_number"));
            }else{
                prjProject.setConfluenceSerialNumber(boxGroupRecord.getInt("already_incoming_count")+1);
                sql=" UPDATE crm_entry_combiner_box_group g,crm_entry_combiner_box_group_detail d SET g.already_incoming_count=g.already_incoming_count+1,d.serial_number=g.already_incoming_count+1,d.status='1' " +
                        "WHERE g.id=d.box_group_id AND d.entry_id='"+entry.getId()+"' and d.serial_number IS NULL ";
                logger.info("....推送首次进件，电站编码:{},推送的汇流组序列号:{}",entry.getPowerStationCode(),prjProject.getConfluenceSerialNumber());
            }
            logger.info("....推送首次进件，电站编码:{},推送的汇流组编号:{}",entry.getPowerStationCode(),prjProject.getConfluenceGroupNumber());
        }
        bodyMap.put("prjProject",prjProject);

        bodyMapList.add(bodyMap);
        map.put("body",bodyMapList);
        logger.info(">>>>>>>>>>>>>>>提交进件申请-越秀接口 json:{}",new Gson().toJson(map));
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_FINANCE_PROJECT_OL"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);

        String url = "/r/api/finance/sync/project/operating/lease";
        JSONObject jieMap = clientPostZYMap(map, url);

        logger.info("提交进件申请-越秀接口 电站编码PowerStationCode：{} -----返回报文：{}", entry.getPowerStationCode(), jieMap);

        JSONArray reqMap = jieMap.getJSONArray("body");
        if (reqMap != null) {
            JSONObject re = reqMap.getJSONObject(0);
            if ("S".equals(re.getString("type"))) {
                CrmYxProcessDao.addProcess(entry.getId(),"2","越秀进件同步接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"0");
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"2","NEW","0","0","推送");
                //修改汇流箱进件数量，保存汇流箱进件序号
                if(StringUtil.isNotBlank(sql)){
                    try{
                        int count= Db.update(sql);
                        logger.info(">>>>>>>>>>>>>>>提交进件申请-越秀接口 电站编码PowerStationCode：{},count:{},sql:{}",entry.getPowerStationCode(),count,sql);
                    }catch (Exception e){
                        e.printStackTrace();
                        logger.error("越秀进件，修改汇流箱进件数量，保存汇流箱进件序号 失败：e:{}",e);
                    }

                }
                return Result.ok();
            } else if ("E".equals(re.getString("type"))) {
                //re.getString("message");//失败原因
                CrmYxProcessDao.addProcess(entry.getId(),"2","越秀进件同步接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"2",null,"1",null,null);
                return Result.fail(re.getString("message"));
            } else {
                //重复提交
                CrmYxProcessDao.addProcess(entry.getId(),"2","越秀进件同步接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"2",null,"1",null,null);
                return Result.fail("重复提交");
            }
        } else {
            CrmYxProcessDao.addProcess(entry.getId(),"2","越秀进件同步接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
            CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"2",null,"1",null,null);
            JSONObject reqHeadMap = jieMap.getJSONObject("head");
            reqHeadMap.getString("errorMessage");
            return Result.fail(reqHeadMap.getString("errorMessage"));
        }
    }

    /**
     * 投放审查信息-第二次进件
     */
    public Result accessProjectApplyTwo(CustomerEntry entry, List<Map<String,Object>> prjProjectLeaseItemList,CrmCustomerIncomingApplication application) {

        if(StringUtil.isNotBlank(application.getFarmerSignStatus()) && StringUtil.equalsAny(application.getFarmerSignStatus(),"APPROVING","APPROVED")){
            throw new IllegalArgumentException("进件状态不允许推送完工资料!");
        }
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> bodyMapList = new ArrayList<>();
        Map<String, Object> bodyMap = new HashMap<>();
        //进件信息
        Map<String, String> prjProject = new HashMap<>();
        //进件序号
        prjProject.put("partnersContractNumber",application.getPartnersContractNumber());
        //10-完工信息
        //20-所有信息
        prjProject.put("informationType","10");
        //项目备案代码
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entry.getId());
        prjProject.put("recordCode", surveyRecord.getFilingDocumentCode());
        bodyMap.put("prjProject",prjProject);

        //租赁物信息
//        List<Map<String,Object>> prjProjectLeaseItemList = new ArrayList<>();
//        Map<String,Object> projectLeaseItem = new HashMap<>();
//        projectLeaseItem.put("partnersLeaseItemId",leaseItem.getId());
//        projectLeaseItem.put("moduleProducer",leaseItem.getModuleProducer());
//        projectLeaseItem.put("productModel",leaseItem.getProductModel());
//        projectLeaseItem.put("inverterNumber",leaseItem.getInverterNumber());
//        projectLeaseItem.put("installedCapacity",leaseItem.getInstalledCapacity());
//        projectLeaseItem.put("inverterBrand",leaseItem.getInverterBrand());
//        projectLeaseItem.put("inverterModel",leaseItem.getInverterModel());
//        projectLeaseItem.put("moduleQuantity",leaseItem.getModuleQuantity());

        //保险信息
//        List<Insurance> insuranceList = new ArrayList<>();
//        Insurance insurance = new Insurance();
//        insurance.setInsuranceType(applicationInsurance.getInsuranceType());
//        insurance.setInsuranceDateFrom(applicationInsurance.getInsuranceDateFrom());
//        insurance.setInsuranceDateTo(applicationInsurance.getInsuranceDateTo());
//        insurance.setInsuranceCompany(applicationInsurance.getInsuranceCompany());
//        insurance.setInsuranceNumber(applicationInsurance.getInsuranceNumber());
//        insurance.setInsuranceAmount(applicationInsurance.getInsuranceAmount());
//        insurance.setFirstBeneficiary(applicationInsurance.getFirstBeneficiary());
//        insuranceList.add(insurance);
//        projectLeaseItem.put("insuranceList",insuranceList);

        //组件编码
//        List<Map<String,String>> moduleList = new ArrayList<>();
//        Map<String,String> moduleCode = new HashMap<>();
//        moduleCode.put("moduleCode","");
//        moduleList.add(moduleCode);
//        projectLeaseItem.put("moduleList",moduleList);

//        prjProjectLeaseItemList.add(projectLeaseItem);
        bodyMap.put("prjProjectLeaseItemList",prjProjectLeaseItemList);

        //账户信息
        List<PrjProjectAccount> prjProjectAccountList = new ArrayList<>();
        PrjProjectAccount account = new PrjProjectAccount();
        prjProjectAccountList.add(account);
        bodyMap.put("prjProjectAccountList",prjProjectAccountList);

        //承租人模块
        Map<String,Object> firBpMasterBaseDto=new HashMap<>();
        //承租人地址信息
        List<HlsBpMasterAddress2> hlsBpMasterAddressList = new ArrayList<>();
        HlsBpMasterAddress2 address2 = new HlsBpMasterAddress2();
        address2.setAddress(entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress());
        hlsBpMasterAddressList.add(address2);
        firBpMasterBaseDto.put("hlsBpMasterAddressList",hlsBpMasterAddressList);
        //承租人银行信息
        List<HlsBpMasterBankAccount> hlsBpMasterBankAccountList = new ArrayList<>();
        HlsBpMasterBankAccount masterBankAccount = new HlsBpMasterBankAccount();
        masterBankAccount.setBankAccountName(entry.getBankName());
        masterBankAccount.setBankAccountNum(entry.getBankCode());
        masterBankAccount.setTssBankNum(entry.getTssBankNum());
        hlsBpMasterBankAccountList.add(masterBankAccount);
        firBpMasterBaseDto.put("hlsBpMasterBankAccountList",hlsBpMasterBankAccountList);
        bodyMap.put("firBpMasterBaseDto",firBpMasterBaseDto);

        bodyMapList.add(bodyMap);
        map.put("body",bodyMapList);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_FINANCE_PROJECT_OL_SIGN"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);

        String url = "/r/api/finance/sync/project/operating/lease/sign";
        JSONObject jieMap = clientPostZYMap(map, url);
        logger.info("农户投放审查-越秀接口 电站编码PowerStationCode：{} -----返回报文：{}", entry.getPowerStationCode(), jieMap);

        JSONArray reqMap = jieMap.getJSONArray("body");
        if (reqMap != null) {
            JSONObject re = reqMap.getJSONObject(0);
            if ("S".equals(re.getString("type"))) {
                CrmYxProcessDao.addProcess(entry.getId(),"3","越秀农户投放审查信息同步接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"0");
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"4","NEW","0","0","推送");
                return Result.ok();
            } else if ("E".equals(re.getString("type"))) {
                CrmYxProcessDao.addProcess(entry.getId(),"3","越秀农户投放审查信息同步接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"4",null,"1",null,null);
                //re.getString("message");//失败原因
                return Result.fail(re.getString("message"));
            } else {
                //重复提交
                CrmYxProcessDao.addProcess(entry.getId(),"3","越秀农户投放审查信息同步接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"4",null,"1",null,null);
                return Result.fail("重复提交");
            }
        } else {
            CrmYxProcessDao.addProcess(entry.getId(),"3","越秀农户投放审查信息同步接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
            CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"4",null,"1",null,null);
            JSONObject reqHeadMap = jieMap.getJSONObject("head");
            reqHeadMap.getString("errorMessage");
            return Result.fail(reqHeadMap.getString("errorMessage"));
        }
    }

    /**
     * 并网及商务信息更新-第三次进件
     */
    public Result accessProjectApplyThree(CustomerEntry entry, CrmCustomerIncomingApplicationInsurance applicationInsurance,CrmCustomerIncomingApplication incomingApplication) {
        logger.info(">>>>>>>>>>>>并网及商务信息更新-第三次进件  entryId:{}",entry.getId());
        if(StringUtil.isNotBlank(incomingApplication.getFarmerSignStatus()) && StringUtil.equalsAny(incomingApplication.getFarmerSignStatus(),"APPROVING","APPROVED")){
            throw new IllegalArgumentException("进件状态不允许推送并网资料!");
        }
        GuardUtils.notNull(entry.getFirstGenerationTime(),"尚未获取到首日发电日期，不满足越秀并网要求！");
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> bodyMapList = new ArrayList<>();
        Map<String, Object> bodyMap = new HashMap<>();
        //进件信息
        Map<String, String> prjProject = new HashMap<>();
        //进件序号
        prjProject.put("partnersContractNumber",incomingApplication.getPartnersContractNumber());
        //并网日期，格式为：yyyyMMdd
        prjProject.put("gridTiedDate",DateUtils.formatDate(entry.getFirstGenerationTime(),"yyyyMMdd"));
        bodyMap.put("prjProject",prjProject);

        //租赁物信息
        List<Map<String,Object>> prjProjectLeaseItemList = new ArrayList<>();
        Map<String,Object> projectLeaseItem = new HashMap<>();
        String jjNumber = incomingApplication.getPartnersContractNumber();
        String partnersLeaseItemId = entry.getId();
        if (jjNumber.contains("YX-NHKJ")) {
            partnersLeaseItemId = jjNumber;
        }
        projectLeaseItem.put("partnersLeaseItemId",partnersLeaseItemId);
        //购售电地址是否一致:"Y:是"、"N:否"
        if (CustomerEntryConstants.ADDESS_CONSISTENT_NO.equals(entry.getAddressConsistent())) {
            projectLeaseItem.put("addressConsistent",CustomerEntryConstants.ADDESS_CONSISTENT_NO);
            Record province = customerDao.getProvinceCode(entry.getElectricProvince());
            projectLeaseItem.put("electricProvinceCode",province.getLong("regionalism_code").toString());
            Record city = customerDao.getCityCode(entry.getElectricCity(),province.getLong("ProvinceID"));
            projectLeaseItem.put("electricCityCode",city.getLong("regionalism_code").toString());
            projectLeaseItem.put("electricAreaCode",customerDao.getDistrictCode(entry.getElectricArea(),city.getLong("CityID")).toString());
            projectLeaseItem.put("electricAddress",entry.getElectricAddress());
        } else {
            projectLeaseItem.put("addressConsistent",CustomerEntryConstants.ADDESS_CONSISTENT_YES);
        }

        //保险信息
        List<Insurance> insuranceList = new ArrayList<>();
        Insurance insurance = new Insurance();
        insurance.setInsuranceType(applicationInsurance.getInsuranceType());
        insurance.setInsuranceDateFrom(applicationInsurance.getInsuranceDateFrom());
        insurance.setInsuranceDateTo(applicationInsurance.getInsuranceDateTo());
        insurance.setInsuranceCompany(applicationInsurance.getInsuranceCompany());
        insurance.setInsuranceNumber(applicationInsurance.getInsuranceNumber());
        insurance.setInsuranceAmount(applicationInsurance.getInsuranceAmount());
        insurance.setFirstBeneficiary(applicationInsurance.getFirstBeneficiary());
        insuranceList.add(insurance);
        projectLeaseItem.put("insuranceList",insuranceList);
        prjProjectLeaseItemList.add(projectLeaseItem);
        bodyMap.put("prjProjectLeaseItemList",prjProjectLeaseItemList);

        List<Map<String,String>> hlsBpMasterAddressList = Lists.newArrayList();
        Map<String, String> addressList = new HashMap<>();
        addressList.put("itemAddress",entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress());
        hlsBpMasterAddressList.add(addressList);
        bodyMap.put("hlsBpMasterAddressList",hlsBpMasterAddressList);

        //账户信息
        List<PrjProjectAccount> prjProjectAccountList = new ArrayList<>();
        PrjProjectAccount account = new PrjProjectAccount();
        account.setAccountType("02");
        account.setAccountName(entry.getTenantName());//发电户号和工行二类卡的账户名称记得也要传承租人的名称
        account.setAccountNumber(entry.getGeneratorNo());
        //电站省码
        account.setElecCode(entry.getProvinceCode());

        prjProjectAccountList.add(account);
        bodyMap.put("prjProjectAccountList",prjProjectAccountList);

        List<HlsBpMasterBankAccount> hlsBpMasterBankAccountList = new ArrayList<>();
        HlsBpMasterBankAccount masterBankAccount = new HlsBpMasterBankAccount();
        masterBankAccount.setBankAccountName(entry.getBankName());
        masterBankAccount.setBankAccountNum(entry.getBankCode());
        masterBankAccount.setTssBankNum(entry.getTssBankNum());
        hlsBpMasterBankAccountList.add(masterBankAccount);
        bodyMap.put("hlsBpMasterBankAccountList",hlsBpMasterBankAccountList);

        bodyMapList.add(bodyMap);
        map.put("body",bodyMapList);

        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_FINANCE_PROJECT_OL_SIGN_UPDATE"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);

        String url = "/r/api/finance/ol/sync/sign/update";
        JSONObject jieMap = clientPostZYMap(map, url);
        logger.info("并网及商务信息更新-越秀接口 电站编码PowerStationCode：{} -----返回报文：{}", entry.getPowerStationCode(), jieMap);

        JSONObject reqMap = jieMap.getJSONObject("body");
        if (reqMap != null) {
            if ("S".equals(reqMap.getString("type"))) {
                CrmYxProcessDao.addProcess(entry.getId(),"4","越秀并网及商务信息更新接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"0");
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"5","NEW","0","0","推送");
                return Result.ok();
            } else if ("E".equals(reqMap.getString("type"))) {
                //re.getString("message");//失败原因
                CrmYxProcessDao.addProcess(entry.getId(),"4","越秀并网及商务信息更新接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"5",null,"1",null,null);
                return Result.fail(reqMap.getString("message"));
            } else {
                //重复提交
                CrmYxProcessDao.addProcess(entry.getId(),"4","越秀并网及商务信息更新接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
                CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"5",null,"1",null,null);
                return Result.fail("重复提交");
            }
        } else {
            CrmYxProcessDao.addProcess(entry.getId(),"4","越秀并网及商务信息更新接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
            CrmYxIncomingProcessDao.addIncomingProcess(entry.getId(),"5",null,"1",null,null);
            JSONObject reqHeadMap = jieMap.getJSONObject("head");
            reqHeadMap.getString("errorMessage");
            return Result.fail(reqHeadMap.getString("errorMessage"));
        }
    }

    /**
     * 购售电合同推送
     * @param entry
     * @param prjProjectLeaseItemList 租凭物信息
     * @param fileList 文件信息
     * @return
     */
    public Result powerSellFilePush(CustomerEntry entry, List<Map<String,Object>> prjProjectLeaseItemList, List<FinanceProjectFile> fileList) {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> bodyMapList = new ArrayList<>();
        Map<String, Object> bodyMap = new HashMap<>();
        //进件信息
        Map<String, Object> prjProject = new HashMap<>();
        prjProject.put("partnersContractNumber",entry.getPowerStationCode());
        bodyMap.put("prjProject",prjProject);

        bodyMap.put("prjProjectLeaseItemList",prjProjectLeaseItemList);

        Map<String, Object> financeProjectFileInfo = new HashMap<>();
        financeProjectFileInfo.put("keyType","01");
        financeProjectFileInfo.put("businessKey",entry.getPowerStationCode());
        financeProjectFileInfo.put("fileList",fileList);
        bodyMap.put("financeProjectFileInfoDto",financeProjectFileInfo);

        bodyMapList.add(bodyMap);
        map.put("body",bodyMapList);

        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_FINANCE_POWER_SELL_OL_FILE"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);

        String url = "/r/api/finance/ol/power/sell/file";
        JSONObject jieMap = clientPostZYMap(map, url);
        logger.info("租后购售电合同推送-越秀接口 电站编码PowerStationCode：{} -----返回报文：{}", entry.getPowerStationCode(), jieMap);

        JSONObject reqMap = jieMap.getJSONObject("body");
        if (reqMap != null) {
            if ("S".equals(reqMap.getString("type"))) {
                CrmYxProcessDao.addProcess(entry.getId(),"7","越秀并网及商务信息更新接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"0");
                return Result.ok();
            } else if ("E".equals(reqMap.getString("type"))) {
                //re.getString("message");//失败原因
                CrmYxProcessDao.addProcess(entry.getId(),"7","越秀并网及商务信息更新接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
                return Result.fail(reqMap.getString("message"));
            } else {
                //重复提交
                CrmYxProcessDao.addProcess(entry.getId(),"7","越秀并网及商务信息更新接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
                return Result.fail("重复提交");
            }
        } else {
            CrmYxProcessDao.addProcess(entry.getId(),"7","越秀并网及商务信息更新接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
            JSONObject reqHeadMap = jieMap.getJSONObject("head");
            reqHeadMap.getString("errorMessage");
            return Result.fail(reqHeadMap.getString("errorMessage"));
        }
    }

    /**
     * 资料与合同推送
     * @param entry
     * @param fileList 文件明细
     * @param keyType 附件类型:
     *                01.合同/进件下的附件;
     *                02.自然人承租人下的附件（预审阶段未关联合同的附件）;
     *                03.法人承租人下的附件（预审阶段未关联合同的附件）
     * @param businessKey 查询序号:
     *                    keyType为01时为方的合同编号（partnersContractNumber）;
     *                    keyType为02时为承租人证件号码（idCardNo）;
     *                    keyType为03时为法人的登记注册号码（regno）
     */
    @Async
    public void updateFile(CustomerEntry entry,List<FinanceProjectFile> fileList, String keyType, String businessKey) {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> bodyMapList = new ArrayList<>();
        //文件信息
        Map<String, Object> financeProjectFileInfo = new HashMap<>();
        financeProjectFileInfo.put("keyType",keyType);
        financeProjectFileInfo.put("businessKey",businessKey);
        //文件明细
        financeProjectFileInfo.put("fileList",fileList);
        bodyMapList.add(financeProjectFileInfo);
        map.put("body",bodyMapList);

        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_FINANCE_OL_FILE"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        String url = "/r/api/finance/ol/sync/file";
        JSONObject jieMap = clientPostZYMap(map, url);
        logger.info("经营租赁资料与合同推送-越秀接口 电站编码PowerStationCode：{} -----返回报文：{}", entry.getPowerStationCode(), jieMap);

        JSONArray reqMap = jieMap.getJSONArray("body");
        JSONObject re = reqMap.getJSONObject(0);
        if ("S".equals(re.getString("type"))) {

        } else if ("E".equals(re.getString("type"))) {
            //re.getString("message");//失败原因
        } else {
            //重复提交
        }
    }


    /**
     * 附件异步推送
     * @param entry
     * @param fileList 文件明细
     * @param keyType 附件类型:
     *                01.合同/进件下的附件;
     *                02.自然人承租人下的附件（预审阶段未关联合同的附件）;
     *                03.法人承租人下的附件（预审阶段未关联合同的附件）
     * @param businessKey 查询序号:
     *                    keyType为01时为方的合同编号（partnersContractNumber）;
     *                    keyType为02时为承租人证件号码（idCardNo）;
     *                    keyType为03时为法人的登记注册号码（regno）
     * @param source 来源 1预审 2进件 3完工资料提交 4并网资料提交
     */
    @Async
    public Result updateFile2(CustomerEntry entry,List<FinanceProjectFile> fileList, String keyType, String businessKey, String source) {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> bodyMapList = new ArrayList<>();
        //文件信息
        Map<String, Object> financeProjectFileInfo = new HashMap<>();
        financeProjectFileInfo.put("keyType",keyType);
        financeProjectFileInfo.put("businessKey",businessKey);
        //文件明细
        financeProjectFileInfo.put("fileList",fileList);
        bodyMapList.add(financeProjectFileInfo);
        map.put("body",bodyMapList);

        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_FINANCE_OL_ASYNC_FILE"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        String url = "/r/api/finance/ol/async/file";
        JSONObject jieMap = clientPostZYMap(map, url);
        logger.info("附件异步推送-越秀接口 电站编码PowerStationCode：{} -----返回报文：{}", entry.getPowerStationCode(), jieMap);

        JSONObject reqMap = jieMap.getJSONObject("body");
        if (!"E".equals(reqMap.getString("type"))) {
            CrmYxProcessDao.addProcess(entry.getId(),source,"越秀资料推送接口接口(异步)",JSONObject.toJSONString(map),jieMap.toJSONString(),"0");
            return Result.ok();
        } else {
            //重复提交
            CrmYxProcessDao.addProcess(entry.getId(),source,"越秀资料推送接口接口(异步)",JSONObject.toJSONString(map),jieMap.toJSONString(),"1");
            return Result.fail(reqMap.getString("message"));
        }
    }

    //附件异步推送结果查询
    @Async
    public Result findUpdateFile2(String quryId) {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, String>> bodyMapList = new ArrayList<>();
        Map<String, String> quryIdMap = new HashMap<>();
        quryIdMap.put("quryId",quryId);
        bodyMapList.add(quryIdMap);
        map.put("body",bodyMapList);

        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_FINANCE_OL_ASYNC_FILE_QUERY"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        String url = "/r/api/finance/ol/async/file/query";
        JSONObject jieMap = clientPostZYMap(map, url);
        logger.info("附件异步推送结果查询-越秀接口-----返回报文：{}", jieMap);

        JSONObject reqMap = jieMap.getJSONObject("body");
        if ("S".equals(reqMap.getString("type"))) {
            JSONArray fileList = jieMap.getJSONArray("fileList");
            return Result.success(fileList);
        } else if ("E".equals(reqMap.getString("type"))) {
            //re.getString("message");//失败原因
            return Result.fail("");
        } else {
            //重复提交
            return Result.fail("");
        }
    }


    public void uploadCheckProject(CrmCustomerIncomingApplication inco, String fileName, String fileUrl, String sileSize, byte[] buffer) {

        String url = "/r/api/access/project/atm/upload";
        Map<String, Object> map = new HashMap<>();
        map.put("fileName", fileName);
        map.put("fileSize", sileSize);
        try {
            if (buffer == null) {
                buffer = Base64Url.openFile(fileUrl);
            }
            map.put("fileBase64", Base64Url.encodeBase64Byte(buffer));
        } catch (Exception e) {
            logger.error("uploadProject 上传验收报告附件 Base64加密错误 Exception ：{}", e);
        }
        JSONObject jieMap = clientPostZYMap(map, url);
        if (jieMap.getBoolean("success")) {
            //附件上传成功
            logger.info("上传验收报告附件成功 jieMap:{}", jieMap);
            cacheService.hdel("entryIdFileSize", inco.getEntryId());
            cacheService.hdel("entryIdFileName", inco.getEntryId());
            inco.setImgUpload("3");
            Db.update("UPDATE `crm_customer_incoming_application` SET img_upload='3' WHERE entry_id=? and if_delete = '0'", inco.getEntryId());
        } else {
            JSONObject jsonerror = jieMap.getJSONObject("error");
            if (jsonerror.getString("message").indexOf("附件名称存在") > 0) {
                Db.update("UPDATE `crm_customer_incoming_application` SET img_upload='3' WHERE entry_id=? and if_delete = '0'", inco.getEntryId());
            } else if (jsonerror.getString("message").indexOf("进件已经结束") > 0) {
                Db.update("UPDATE `crm_customer_incoming_application` SET img_upload='3' WHERE entry_id=? and if_delete = '0'", inco.getEntryId());
            } else {
                returnCode(jieMap);
                inco.setImgUpload("1");
                //
            }
        }
        System.out.println(jieMap);
    }

    public void returnCode(JSONObject jieMap) {
        boolean success = jieMap.getBoolean("success");
        if (!success) {
            throw new BusinessException(jieMap.getString("message"));
        }
    }

    /**
     * 获取二类卡开卡状态
     * @param certNo 证件号码
     * @param corpCommSerno 合作方交易单号
     * @return
     * certNo:证件号码
     * type:接口响应状态,S-请求成功 E-请求失败
     * businessKey;合作方交易单号
     * account:电子二类账号
     * acctName:电子账户户名
     * protocolStatus:协议开通状态,0.未开通 1.已开通
     * result:二类卡账户状态,1.申请已受理、2.预开户成功、3.预开户失败、4.正式开户成功、5.正式开户失败、6.销户成功、7.销户失败、8.销户中、9.工行受理中、10.过期
     * retMsg:提示信息,失败必传
     *
     */
    public JSONObject findICBCStatus(String certNo, String corpCommSerno) {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("certNo",certNo);
        bodyMap.put("corpCommSerno",corpCommSerno);
        list.add(bodyMap);
        map.put("body",list);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_FINANCE_TENANT_ICBC_BUSINESS"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        String url = "/r/api/tenant/account/info/query";
        JSONObject jieMap = clientPostZYMap(map, url);
//      发送信息到越秀平台
        logger.info("提交预审 admittanceEntry -------返回结果：{}, maps:{}", jieMap, map);

        JSONArray reqMap = jieMap.getJSONArray("body");
        return reqMap.getJSONObject(0);
    }

    /**
     *  取消进件
     * @param partnersContractNumber    合作方进件序号
     * @param cancelReason  退回原因 当退回类型为cancel-取消进件、return-退回进件时必填； 退回类型为returnToCompletion-退回完工时非必填；
     * @param signReturnType  退回类型    cancel-取消进件  return-退回进件   returnToCompletion-退回完工
     *
     * 取消进件：
     * 1）需注意取消的进件无法再次推送，如要继续进行业务，需使用新的合作方进件序号进行新的进行；
     * 2）支持取消的进件状态为：待审批、审批拒绝、退回、撤回、审批通过；
     * 3）支持取消的农户投放审查状态为：待审批、审批拒绝、撤回；
     * 退回进件：
     * 1）需注意操作退回进件后会触发合同文本重签；
     * 2）支持退回进件的进件状态为：审批通过；
     * 3）支持退回进件的农户投放审查状态为：待审批、审批拒绝、撤回；
     * 退回完工：
     * 1）需注意操作退回完工后需重新提交农户投放审批流程；
     * 2）支持退回完工的进件状态为：审批通过；
     * 3）支持退回完工的农户投放审查状态为：审批中且处于“厂商补充并网及商务信息及附件”审批节点；
     */
    public void cancelProjectApply(String partnersContractNumber,String cancelReason,String signReturnType){
        logger.info(">>>>>>>>>>>>>>>>>>>>cancelProjectApply   partnersContractNumber:{},cancelReason:{},signReturnType:{}",partnersContractNumber,cancelReason,signReturnType);
        Map<String, Object> map = new HashMap<>();
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("partnersContractNumber",partnersContractNumber);
        bodyMap.put("prjCancelReason",cancelReason);
        bodyMap.put("signReturnType",signReturnType);
        list.add(bodyMap);
        map.put("body",list);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_FINANCE_PROJECT_CANCEL"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        String url = "/r/api/finance/project/operating/lease/cancel";
        JSONObject jieMap = clientPostZYMap(map, url);
//      发送信息到越秀平台
        logger.info("取消或退回进件 cancelProjectApply -------返回结果：{}, maps:{}", jieMap, map);
        JSONArray reqMap = jieMap.getJSONArray("body");
        JSONObject object=reqMap.getJSONObject(0);
        logger.info(">>>>>>>>>>>cancelProjectApply  object:{}",object);
        String type=object.getString("type");
        CrmYxProcessDao.addProcess(partnersContractNumber,"6","进件取消或退回"+signReturnType,JSONObject.toJSONString(map),jieMap.toJSONString(),"0");
        if("S".equals(type)){
             //成功
        }else if("风险审查状态已为【取消】,不能取消".equals(object.getString("message"))){  //已经取消了，再次取消
            logger.info("已取消进件了");
        }else {
            throw new IllegalArgumentException("进件操作失败，"+object.getString("message"));
        }
    }

    //农户收益查询
    public List<CrmEntryCashFlow> financeGet(String dueDateFrom,String dueDateTo,String partnersContractNumber){
        logger.info(">>>>>>>>>>>>>>>>>>>>financeGet 农户收益查询   dueDateFrom:{},dueDateTo:{},partnersContractNumber:{},now:{}",dueDateFrom,dueDateTo,partnersContractNumber,new Date());
        Map<String, Object> map = new HashMap<>();
        List<Object> list = new ArrayList<>();
        Map<String,Object> obj=new HashMap<>();
        Map<String, String> bodyMap = new HashMap<>();
        if(StringUtil.isBlank(partnersContractNumber)){
            bodyMap.put("synchronizationType","FULL");
            bodyMap.put("dueDateFrom",dueDateFrom);
            bodyMap.put("dueDateTo",dueDateTo);
        }else if(StringUtil.isNotBlank(partnersContractNumber)){
            bodyMap.put("synchronizationType","INC");
            bodyMap.put("partnersContractNumber",partnersContractNumber);
        }
        obj.put("olDocumentFarmGainsDto",bodyMap);
        list.add(obj);
        map.put("body",list);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_FINANCE_PROJECT_OL_GAINS"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        String url = "/r/api/finance/project/operating/lease/farm/gains";
        JSONObject jieMap = clientPostZYMap(map, url);
//      发送信息到越秀平台
        logger.info("农户收益查询 financeGet -------返回结果：{}, maps:{}", jieMap, map);
        JSONArray reqMap = jieMap.getJSONArray("body");
        JSONObject object=reqMap.getJSONObject(0);
        logger.info(">>>>>>>>>>>financeGet  object:{}",object);
        String type=object.getString("type");
        if("S".equals(type)){
            //成功
            String cashflowList = object.getString("cashflowList");
            logger.info(">>>>>>>>>>>financeGet  cashflowList:{}",cashflowList);
            Gson gson=new Gson();
            List<CrmEntryCashFlow> cashList=gson.fromJson(cashflowList,new TypeToken<ArrayList<CrmEntryCashFlow>>(){}.getType());
            return cashList;
        }else {
            throw new IllegalArgumentException("农户收益查询失败，"+object.getString("message"));
        }
    }


    /**
     * 续保推送至越秀
     * @param insurance
     * @param entry
     * @return
     */
    public String renewalInsurance(CrmCustomerEntryInsurance insurance, CustomerEntry entry){
        logger.info(">>>>>>>>>>>>>>>>>>>> renewalInsurance   insurance:{}",insurance);
        String renewalNumber = "";
        CrmCustomerIncomingApplication application = crmCustomerIncomingApplicationDao.getByEntryId(entry.getId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startTime = sdf.format(insurance.getStartTime());
        String endTime = sdf.format(insurance.getEndTime());

        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> bodyMap = new HashMap<>();

        Map<String, String> leaseItemRenewalMap = new HashMap<>();
        leaseItemRenewalMap.put("division","PHOTOVOLTAIC_DEVICES");//业务模式
        leaseItemRenewalMap.put("insuranceNumber",insurance.getNumber());//新保险编号

        List<Map<String, String>> insuranceList = new ArrayList<>();
        Map<String, String> insuranceMap = new HashMap<>();
        insuranceMap.put("partnersContractNumber",application.getPartnersContractNumber());//合同方进件唯一编号
        insuranceMap.put("businessKey",entry.getId());//租赁物ID/车架号
        insuranceMap.put("insuranceType","1");//保险类型 1:财产险
        insuranceMap.put("insuranceDateFrom",startTime);//保险开始日期
        insuranceMap.put("insuranceDateTo",endTime);//保险结束日期
        insuranceMap.put("insuranceCompany",insurance.getInsuranceCompanyName());//保险公司
        insuranceMap.put("insuranceAmount", String.valueOf(insurance.getInsuranceMoney()));//投保金额
        insuranceMap.put("firstBeneficiary",insurance.getInsurant());//第一受益人
        insuranceMap.put("renewalType","1");//续保类型
        insuranceList.add(insuranceMap);

        Map<String, Object> inanceProjectFileInfoMap = new HashMap<>();
        List<Map<String, String>> fileList = new ArrayList<>();
        Map<String, String> fileInfoMap = new HashMap<>();
        fileInfoMap.put("fileName","保险单.jpg");//文件名称
        fileInfoMap.put("fileAddress",filePrePath+insurance.getDownUrl());//文件的下载路径
        fileList.add(fileInfoMap);
        inanceProjectFileInfoMap.put("keyType","01");
        inanceProjectFileInfoMap.put("fileList",fileList);

        bodyMap.put("leaseItemRenewal",leaseItemRenewalMap);
        bodyMap.put("insuranceList",insuranceList);
        bodyMap.put("financeProjectFileInfo",inanceProjectFileInfoMap);
        list.add(bodyMap);
        map.put("body",list);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_LEASE_ITEM_RENEWAL"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        logger.info(String.valueOf(map));
        String url = "/r/api/lease/item/renewal";
        JSONObject jieMap = clientPostZYMap(map, url);
        //发送信息到越秀平台
        logger.info("续保 renewalInsurance -------返回结果：{}, maps:{}", jieMap, map);
        JSONArray reqMap = jieMap.getJSONArray("body");
        JSONObject object=reqMap.getJSONObject(0);
        logger.info(">>>>>>>>>>>renewalInsurance  object:{}",object);
        String type = object.getString("type");
        CrmYxProcessDao.addProcess(entry.getId(),"8","推送续保接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"0");
        if("S".equals(type)){
            //成功
            renewalNumber = object.getString("renewalNumber");
            insurance.setRenewalNumber(renewalNumber);
            insurance.setRenewalStatus("审批中");
            entryInsuranceDao.save(insurance);
            return "200";
        }else {
            return object.getString("message");
        }

    }

    /**
     * 查询越秀续保状态
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void getYueXiuRenewalInsuranceStatus(String id){
        CrmCustomerEntryInsurance insurance = entryInsuranceDao.get(id);
        String renewalStatus = "";
        logger.info(">>>>>>>>>>>>>>>>>>>> getYueXiuRenewalInsuranceStatus   id:{}",id);
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> bodyMap = new HashMap<>();
        Map<String, Object> leaseItemRenewalMap = new HashMap<>();
        leaseItemRenewalMap.put("renewalNumber",insurance.getRenewalNumber());
        bodyMap.put("leaseItemRenewal",leaseItemRenewalMap);
        list.add(bodyMap);
        map.put("body",list);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_LEASE_ITEM_RENEWAL"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        logger.info(String.valueOf(map));
        String url = "/r/api/lease/item/renewal";
        JSONObject jieMap = clientPostZYMap(map, url);
        //发送信息到越秀平台
        logger.info("续保查询 getYueXiuRenewalInsuranceStatus -------返回结果：{}, maps:{}", jieMap, map);
        JSONArray reqMap = jieMap.getJSONArray("body");
        JSONObject object=reqMap.getJSONObject(0);
        logger.info(">>>>>>>>>>>renewalInsurance  object:{}",object);
        String type = object.getString("type");
        CrmYxProcessDao.addProcess(insurance.getEntryId(),"8","续保查询接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"0");
        if("S".equals(type)){
            //成功
            renewalStatus = object.getString("renewalStatus");
            insurance.setRenewalStatus(renewalStatus);
            if("审批拒绝".equals(renewalStatus)){
                insurance.setReason(object.getString("reason"));
            }
            entryInsuranceDao.save(insurance);
        }else {
            throw new IllegalArgumentException("续保操作失败，"+object.getString("message"));
        }
    }

    /**
     * 非系统电站续保推送至越秀
     * @param insurance
     * @return
     */
    public String renewalNoSysInsurance(CrmCustomerNoSystemEntryInsurance insurance){
        logger.info(">>>>>>>>>>>>>>>>>>>> renewalInsurance   insurance:{}",insurance);
        String renewalNumber = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startTime = sdf.format(insurance.getStartTime());
        String endTime = sdf.format(insurance.getEndTime());

        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> bodyMap = new HashMap<>();

        Map<String, String> leaseItemRenewalMap = new HashMap<>();
        leaseItemRenewalMap.put("division","PHOTOVOLTAIC_DEVICES");//业务模式
        leaseItemRenewalMap.put("insuranceNumber",insurance.getNumber());//新保险编号

        List<Map<String, String>> insuranceList = new ArrayList<>();
        Map<String, String> insuranceMap = new HashMap<>();
        insuranceMap.put("partnersContractNumber",insurance.getInputPieceId());//合同方进件唯一编号
        insuranceMap.put("businessKey",insurance.getRequestNo());//租赁物ID/车架号
        insuranceMap.put("insuranceType","1");//保险类型 1:财产险
        insuranceMap.put("insuranceDateFrom",startTime);//保险开始日期
        insuranceMap.put("insuranceDateTo",endTime);//保险结束日期
        insuranceMap.put("insuranceCompany",insurance.getInsuranceCompanyName());//保险公司
        insuranceMap.put("insuranceAmount", String.valueOf(insurance.getInsuranceMoney()));//投保金额
        insuranceMap.put("firstBeneficiary",insurance.getInsurant());//第一受益人
        insuranceMap.put("renewalType","1");//续保类型
        insuranceList.add(insuranceMap);

        Map<String, Object> inanceProjectFileInfoMap = new HashMap<>();
        List<Map<String, String>> fileList = new ArrayList<>();
        Map<String, String> fileInfoMap = new HashMap<>();
        fileInfoMap.put("fileName","保险单.jpg");//文件名称
        fileInfoMap.put("fileAddress",filePrePath+insurance.getDownUrl());//文件的下载路径
        fileList.add(fileInfoMap);
        inanceProjectFileInfoMap.put("keyType","01");
        inanceProjectFileInfoMap.put("fileList",fileList);

        bodyMap.put("leaseItemRenewal",leaseItemRenewalMap);
        bodyMap.put("insuranceList",insuranceList);
        bodyMap.put("financeProjectFileInfo",inanceProjectFileInfoMap);
        list.add(bodyMap);
        map.put("body",list);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_LEASE_ITEM_RENEWAL"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        logger.info(String.valueOf(map));
        String url = "/r/api/lease/item/renewal";
        JSONObject jieMap = clientPostZYMap(map, url);
        //发送信息到越秀平台
        logger.info("续保 renewalInsurance -------返回结果：{}, maps:{}", jieMap, map);
        JSONArray reqMap = jieMap.getJSONArray("body");
        JSONObject object=reqMap.getJSONObject(0);
        logger.info(">>>>>>>>>>>renewalInsurance  object:{}",object);
        String type = object.getString("type");
        CrmYxProcessDao.addProcess(insurance.getRequestNo(),"8","推送续保接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"0");
        if("S".equals(type)){
            //成功
            renewalNumber = object.getString("renewalNumber");
            insurance.setRenewalNumber(renewalNumber);
            insurance.setRenewalStatus("审批中");
            noSystemEntryInsuranceDao.save(insurance);
            return "200";
        }else {
            return object.getString("message");
        }
    }

    /**
     * 查询越秀续保状态
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void getYueXiuNoSysRenewalInsuranceStatus(String id){
        CrmCustomerNoSystemEntryInsurance insurance = noSystemEntryInsuranceDao.get(id);
        String renewalStatus = "";
        logger.info(">>>>>>>>>>>>>>>>>>>> getYueXiuRenewalInsuranceStatus   id:{}",id);
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> bodyMap = new HashMap<>();
        Map<String, Object> leaseItemRenewalMap = new HashMap<>();
        leaseItemRenewalMap.put("renewalNumber",insurance.getRenewalNumber());
        bodyMap.put("leaseItemRenewal",leaseItemRenewalMap);
        list.add(bodyMap);
        map.put("body",list);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber",UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode","YX_LEASE_ITEM_RENEWAL"+YX);
        head.put("transactionTime",DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        logger.info(String.valueOf(map));
        String url = "/r/api/lease/item/renewal";
        JSONObject jieMap = clientPostZYMap(map, url);
        //发送信息到越秀平台
        logger.info("续保查询 getYueXiuRenewalInsuranceStatus -------返回结果：{}, maps:{}", jieMap, map);
        JSONArray reqMap = jieMap.getJSONArray("body");
        JSONObject object=reqMap.getJSONObject(0);
        logger.info(">>>>>>>>>>>renewalInsurance  object:{}",object);
        String type = object.getString("type");
        CrmYxProcessDao.addProcess(insurance.getRequestNo(),"8","续保查询接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"0");
        if("S".equals(type)){
            //成功
            renewalStatus = object.getString("renewalStatus");
            insurance.setRenewalStatus(renewalStatus);
            if("审批拒绝".equals(renewalStatus)){
                insurance.setReason(object.getString("reason"));
            }
            noSystemEntryInsuranceDao.save(insurance);
        }else {
            throw new IllegalArgumentException("续保操作失败，"+object.getString("message"));
        }
    }

    public Number StringToNumber(String str) {
        if (StringUtil.isBlank(str)) {
            return null;
        }
        if (str.contains(".")) {
            return Double.valueOf(str);
        } else {
            return Integer.valueOf(str);
        }
    }
}
