package com.sifang.modules.esign.service;


import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.contract.dao.TraderContractTemplateDao;
import com.sifang.modules.contract.entity.TraderContractTemplate;
import com.sifang.modules.customer.Service.CustomerEntryMsgService;
import com.sifang.modules.customer.Service.CustomerRentVariableService;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.CrmCustomerContractManagement;
import com.sifang.modules.customer.entity.CrmCustomerIncomingApplication;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.esign.cn.tsign.hz.exception.EsignDemoException;
import com.sifang.modules.esign.constants.ESignConstants;
import com.sifang.modules.esign.utils.ConvertUpMoney;
import com.sifang.modules.esign.vo.ComponentVo;
import com.sifang.modules.esign.vo.FileVo;
import com.sifang.modules.esign.vo.RentVariableVo;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectCompanyDao;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectSettingDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectSetting;
import com.sifang.modules.sunshine.SystemSetting.entity.ProjectCompanySettings;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.SqlBuilder;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class PartnerContractESignSignService extends BaseService {

    @Autowired
    private CustomerEntryDao customerDao;

    @Autowired
    ProjectSettingDao projectDao;

    @Autowired
    private ProjectCompanyDao projectCompanySettingsDao;

    @Autowired
    private TraderContractTemplateDao templateDao;

    @Autowired
    private ContractManagementDao contractManagementDao;

    @Autowired
    CustomerEntryMsgService msgService;

    @Autowired
    private CustomerEntryComponentDao entryComponentDao;

    @Autowired
    private CustomerRentVariableService rentVariableService;

    @Autowired
    CrmCustomerIncomingApplicationDao incomingApplicationDao;

    @Autowired
    private CrmCustomerEntryProjectDao crmCustomerEntryProjectDao;

    /**
     *  资方邀请农户发起合同（目前只有华融）
     * @param entry  电站
     * @param partnersContractNumber 进件序号
     * @param operator 操作人
     *       componentList  这个参数针对设计信息变更   设置的
     *      contractManagement 加这个参数 当时是客户 要首次进件后不主动发起合同，生成一条合同记录，等点击发起合同后，才创建合同，后面客户又改主意了，首次进件直接通过，所以，这个参数  没什么用
     */
    @Transactional(rollbackFor = Exception.class)
    public void InviteSign(String partnersContractNumber,CustomerEntry entry, Operator operator,String content, List<Record> componentList, CrmCustomerContractManagement contractManagement){
        logger.info(">>>>资方邀请农户发起合同  InviteSign  id:{}",entry.getId());
        Date now = new Date();
       /* if(StringUtil.equalsAny(entry.getSignStatus(), CustomerEntryConstants.SIGN_STATUS_TENANT_ING,
                CustomerEntryConstants.SIGN_STATUS_COMPANY_ING,CustomerEntryConstants.SIGN_STATUS_COMPLETED)){
            throw new BusinessException("该电站已邀请了签约合同，请勿重复签约!");
        }*/
        if(StringUtil.isBlank(entry.getTenantName()) || StringUtil.isBlank(entry.getMobile())){
            throw new BusinessException("农户姓名和联系方式不能为空!");
        }

        // 查询项目信息
        CrmProjectSetting projectSetting = projectDao.get(entry.getProjectId());
        // 查询项目公司信息
        ProjectCompanySettings companySettings = projectCompanySettingsDao.get(entry.getProjectCompanyId());
        if(companySettings==null){
            throw new BusinessException("项目信息未关联项目公司!");
        }
        entry.setSignStatus(CustomerEntryConstants.SIGN_STATUS_TENANT_ING);
        if(contractManagement==null){
            // 创建合同信息
            contractManagement = new CrmCustomerContractManagement();
            contractManagement.setEntryId(entry.getId());
            contractManagement.setPowerStationCode(entry.getPowerStationCode());
            contractManagement.setTraderId(entry.getDistributorId());
            contractManagement.setPartnersContractNumber(partnersContractNumber);
        }
        contractManagement.setContractNumber(PlantformUtils.getContractNumber(companySettings.getContractPrefix(), companySettings.getContractIndex()));
        contractManagement.setProjectCompanyId(companySettings.getId());
        contractManagement.setProjectCompanyName(companySettings.getName());
        contractManagement.setTenantMobile(entry.getMobile());
        contractManagement.setStatus(ESignConstants.STATUS_SIGNED_BY_TENANT);
        contractManagement.setInvitationId(operator.getUserId());
        contractManagement.setInvitationName(operator.getUserName());
        contractManagement.setInvitationTime(now);
        contractManagement.setPsnId(companySettings.getPsnId());
        contractManagement.setOrgId(companySettings.getSignerCode());
        contractManagement.setTenantName(entry.getTenantName());
        contractManagement.setIdCode(entry.getIdCode());
        contractManagement.setTenantAddress(entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress());

        //获取模板
        TraderContractTemplate template = templateDao.getTemplateByPartnerId(entry.getPartnerId(),entry.getFilingType());
        if (template == null) {
            throw new BusinessException("请先维护合同模板");
        }
        try {
            List<ComponentVo> componentS = Lists.newArrayList();

            //获取项目公司信息
            SqlBuilder sql = new SqlBuilder();

            sql.line("select s.code,s.name,s.`epc_price` as epcPrice,p.`enterprise_qualification_number` as enterpriseQualificationNumber,");
            sql.line("p.`charge_person` as chargePerson,p.`charge_person_id_card` as chargePersonIdCard,p.`telephone`,p.name as companyName ");
            sql.line(",concat(p.province, p.city, p.area, p.address) as companyAddress");
            sql.line("from `crm_project_setting` s");
            sql.line("left join `crm_project_company_settings` p on p.`id`=s.`epc_company_id`");
            sql.line("where  s.`id`=?",entry.getProjectId());
            Record setting = Db.findFirst(sql.build(),sql.params());

            ComponentVo vo0 = new ComponentVo();
            vo0.setComponentKey("powerStationCode");
            vo0.setComponentValue(entry.getPowerStationCode());
            componentS.add(vo0);
            //甲方
            ComponentVo vo1 = new ComponentVo();
            vo1.setComponentKey("tenantName");
            vo1.setComponentValue(entry.getTenantName());
            componentS.add(vo1);

            ComponentVo vo2 = new ComponentVo();
            vo2.setComponentKey("idCode");
            vo2.setComponentValue(entry.getIdCode());
            componentS.add(vo2);

            ComponentVo vo3 = new ComponentVo();
            vo3.setComponentKey("mobile");
            vo3.setComponentValue(entry.getMobile());
            componentS.add(vo3);

            String tenantAddress=entry.getProvince()+entry.getCity()+entry.getArea()+entry.getAddress();
            if (entry.getProvince().equals(entry.getCity())){
                tenantAddress=entry.getProvince()+entry.getArea()+entry.getAddress();
            }
            ComponentVo vo4 = new ComponentVo();
            vo4.setComponentKey("tenantAddress");
            vo4.setComponentValue(tenantAddress);
            componentS.add(vo4);

            ComponentVo vo5 = new ComponentVo();
            vo5.setComponentKey("tenantAddress1");
            vo5.setComponentValue(tenantAddress);
            componentS.add(vo5);

            //乙方
            ComponentVo vo1_1 = new ComponentVo();
            vo1_1.setComponentKey("companyName");
            vo1_1.setComponentValue(companySettings.getName());
            componentS.add(vo1_1);

            ComponentVo vo1_2 = new ComponentVo();
            vo1_2.setComponentKey("enterpriseQualificationNumber");
            vo1_2.setComponentValue(companySettings.getEnterpriseQualificationNumber());
            componentS.add(vo1_2);

            ComponentVo vo1_3 = new ComponentVo();
            vo1_3.setComponentKey("companyMobile");
            vo1_3.setComponentValue(companySettings.getTelephone());
            componentS.add(vo1_3);

            String companyAddress=companySettings.getProvince()+companySettings.getCity()+companySettings.getArea()+companySettings.getAddress();
            ComponentVo vo1_4 = new ComponentVo();
            vo1_4.setComponentKey("companyAddress");
            vo1_4.setComponentValue(companyAddress);
            componentS.add(vo1_4);

            //组件信息
//            if(componentList==null){
//                componentList = entryComponentDao.findByEntryId2(entry.getId());
//            }

//            Integer componentNum=0;  //组件块数
//            String  componentSpec="";  //组件规格
//
//            BigDecimal itemPrice=new BigDecimal("4"); //单价  固定
//            BigDecimal totalAmount=BigDecimal.ZERO;  //总价
//            for(Record record:componentList){
//                componentNum=record.getInt("num")+componentNum;
//                componentSpec+=record.getStr("model");
//                totalAmount=(new BigDecimal(componentNum).multiply(itemPrice).multiply(new BigDecimal(componentSpec))).add(totalAmount);
//            }

            ComponentVo voZJ_1 = new ComponentVo();
            voZJ_1.setComponentKey("componentNum");
//            voZJ_1.setComponentValue(componentNum);
            voZJ_1.setComponentValue(250);
            componentS.add(voZJ_1);

            ComponentVo voZJ_2 = new ComponentVo();
            voZJ_2.setComponentKey("componentSpec");
//            voZJ_2.setComponentValue(componentSpec);
            voZJ_2.setComponentValue(710);
            componentS.add(voZJ_2);

           /* ComponentVo voZJ_3 = new ComponentVo();
            voZJ_3.setComponentKey("itemPrice");
            voZJ_3.setComponentValue(itemPrice);
            componentS.add(voZJ_3);*/

            ComponentVo voZJ_4 = new ComponentVo();
            voZJ_4.setComponentKey("totalAmount");
//            voZJ_4.setComponentValue(totalAmount);
            voZJ_4.setComponentValue(710000);
            componentS.add(voZJ_4);
            //人民币大写
//            String bigWrite = ConvertUpMoney.toChinese(totalAmount.toString());
            String bigWrite = ConvertUpMoney.toChinese("710000");
            ComponentVo voZJ_5 = new ComponentVo();
            voZJ_5.setComponentKey("bigWrite");
            voZJ_5.setComponentValue(bigWrite);//大写
            componentS.add(voZJ_5);

            //收益信息
            int i=1;
           /*
             List<Record> rentVariableList= rentVariableService.getRentVariableList(projectSetting.getId());
            for(Record record:rentVariableList){
                ComponentVo voSy_5 = new ComponentVo();
                voSy_5.setComponentKey("rentYear"+i);
                String rentYear="第"+record.get("start_year")+"年---第"+record.get("end_year")+"年";
                voSy_5.setComponentValue(rentYear);//大写
                componentS.add(voSy_5);

                ComponentVo voSy_6 = new ComponentVo();
                voSy_6.setComponentKey("unitPrice"+i);
                voSy_6.setComponentValue(record.get("unit_price"));
                componentS.add(voSy_6);

                ComponentVo voSy_7 = new ComponentVo();
                voSy_7.setComponentKey("yearPrice"+i);
                voSy_7.setComponentValue(record.get("unit_price"));
                componentS.add(voSy_7);
                i++;
            }*/
            Map<Integer,RentVariableVo> rentMap=getRentGroup(entry);
            while(i<4){
               RentVariableVo rentVariableVo=rentMap.get(i);
               if(rentVariableVo==null){
                   i++;
                   continue;
               }
                ComponentVo voSy_5 = new ComponentVo();
                voSy_5.setComponentKey("rentYear"+i);
                String rentYear="第"+rentVariableVo.getMin()+"年---第"+rentVariableVo.getMax()+"年";
                voSy_5.setComponentValue(rentYear);//大写
                componentS.add(voSy_5);

                ComponentVo voSy_6 = new ComponentVo();
                voSy_6.setComponentKey("unitPrice"+i);
                voSy_6.setComponentValue(rentVariableVo.getMonthRent());
                componentS.add(voSy_6);

                ComponentVo voSy_7 = new ComponentVo();
                voSy_7.setComponentKey("yearPrice"+i);
                voSy_7.setComponentValue(rentVariableVo.getRent());
                componentS.add(voSy_7);
                i++;
            }


            ComponentVo voF_1 = new ComponentVo();
            voF_1.setComponentKey("powerStationCode1");
            voF_1.setComponentValue(entry.getPowerStationCode());
            componentS.add(voF_1);

            ComponentVo voF_2 = new ComponentVo();
            voF_2.setComponentKey("idCode1");
            voF_2.setComponentValue(entry.getIdCode());
            componentS.add(voF_2);

            ComponentVo voF_3 = new ComponentVo();
            voF_3.setComponentKey("companyName1");
            voF_3.setComponentValue(companySettings.getName());
            componentS.add(voF_3);


            ComponentVo voQ_1 = new ComponentVo();
            voQ_1.setComponentKey("tenantAddressQ");
            voQ_1.setComponentValue(tenantAddress);
            componentS.add(voQ_1);

            ComponentVo voQ_2 = new ComponentVo();
            voQ_2.setComponentKey("mobileQ");
            voQ_2.setComponentValue(entry.getMobile());
            componentS.add(voQ_2);

            ComponentVo voQ_3 = new ComponentVo();
            voQ_3.setComponentKey("companyAddressQ");
            voQ_3.setComponentValue(companyAddress);
            componentS.add(voQ_3);

            ComponentVo voQ_4 = new ComponentVo();
            voQ_4.setComponentKey("companyMobileQ");
            voQ_4.setComponentValue(companySettings.getTelephone());
            componentS.add(voQ_4);

            ComponentVo voQ_5 = new ComponentVo();
            voQ_5.setComponentKey("tenantNameQ");
            voQ_5.setComponentValue(entry.getTenantName());
            componentS.add(voQ_5);

            if(CustomerEntryConstants.FILING_TYPE_COMPANY.equals(entry.getFilingType())){
                ComponentVo voC_1 = new ComponentVo();
                voC_1.setComponentKey("bankAccountName");
                voC_1.setComponentValue(entry.getTenantName());
                componentS.add(voC_1);

                ComponentVo voC_2 = new ComponentVo();
                voC_2.setComponentKey("tenantAccount");
                voC_2.setComponentValue(entry.getBankCode());
                componentS.add(voC_2);

                ComponentVo voC_3 = new ComponentVo();
                voC_3.setComponentKey("bankName");
                voC_3.setComponentValue(entry.getTssBankNumName());
                componentS.add(voC_3);
            }
            if(StringUtil.isNotBlank(entry.getBpIdCard())){
                ComponentVo voG_1 = new ComponentVo();
                voG_1.setComponentKey("bpName");
                voG_1.setComponentValue(entry.getBpName());
                componentS.add(voG_1);

                ComponentVo voG_2 = new ComponentVo();
                voG_2.setComponentKey("bpIdCode");
                voG_2.setComponentValue(entry.getBpIdCard());
                componentS.add(voG_2);
            }else{
                ComponentVo voG_1 = new ComponentVo();
                voG_1.setComponentKey("bpName");
                voG_1.setComponentValue("/");
                componentS.add(voG_1);

                ComponentVo voG_2 = new ComponentVo();
                voG_2.setComponentKey("bpIdCode");
                voG_2.setComponentValue("/");
                componentS.add(voG_2);
            }

            //未邀请，流程ID为空
            FileVo fileVo = ESignFileService.createByDocTemplate(template.getDocTemplateId(), template.getContractName(), componentS);
            contractManagement.setFileId(fileVo.getFileId());
            String signFlowTitle = String.format("能辉光伏%s年户用电站运营合同(%s)-%s",
                    DateUtils.formatDate(new Date(), "yy"), entry.getTraderName(), entry.getTenantName());
            //基于文件发起签署---获取到流程ID
            String signFlow = ESignSignService.createTentConcatByFile(fileVo.getFileId(), template.getContractName(),
                    contractManagement, signFlowTitle, companySettings,entry.getBpMobile(), template);
            contractManagement.setSignFlowId(signFlow);

            contractManagementDao.save(contractManagement);

            companySettings.setContractIndex(companySettings.getContractIndex() + 1);


            projectCompanySettingsDao.save(companySettings);
            msgService.saveEntryMsg(operator, entry.getId(), CustomerEntryConstants.SIGN_INVITE,content);
            //发邀请签约短信 到农户手机号上
          //  Map<String,String> map=ESignSignService.signUrl(signFlow, contractManagement.getTenantMobile(), "");
        /*    String shortUrl=map.get("shortUrl");
            StringBuilder contextString = new StringBuilder("尊敬的" + entry.getTenantName()
                    + "，您好！能辉光伏邀请您签署合同。点击进入:"+shortUrl);
            Map<String, Object> result = SfSmsNUtils.sendBatchMsg(contractManagement.getTenantMobile(), contextString.toString(), "能辉光伏", "", SfSmsNUtils.SMS_TYPE_A);
           */
          //  logger.info("SfSmsUtils.sendMsg result:{}", map);
        } catch (EsignDemoException e) {
            e.printStackTrace();
            logger.error("邀请签约获取链接出错=================  {}", e);
            throw new BusinessException(e.getMessage());
        }

    }

    //获取签约链接、共签链接
    public String getSignUrl(String id) throws EsignDemoException {
        // 获取合同
        CrmCustomerContractManagement contractManagement = contractManagementDao.get(id);
        if(!ESignConstants.STATUS_SIGNED_BY_TENANT.equals(contractManagement.getStatus()) && !ESignConstants.STATUS_SIGNED_BY_BP.equals(contractManagement.getStatus())){  //待农户签约,待共签人签约
            throw new BusinessException("合同状态 不允许获取签约链接");
        }
        CustomerEntry entry= customerDao.get(contractManagement.getEntryId());
        String mobile="";
         if(ESignConstants.STATUS_SIGNED_BY_TENANT.equals(contractManagement.getStatus())){  //待农户签约
              mobile=entry.getMobile();
         }else if("2".equals(contractManagement.getStatus())){  //待共签人签约
             mobile=entry.getBpMobile();
         }
        // 根据流程ID获取签署链接
        Map<String,String> remap = ESignSignService.signUrl(contractManagement.getSignFlowId(), mobile,"");
        String url=remap.get("url");
        logger.info("签署农户合同的合同链接 getSignUrl url:{}",url);
        return url;
    }

    //预览合同（获取预览链接）
    public String getFilePreviewUrl(String id) throws EsignDemoException {
        // 获取合同
        CrmCustomerContractManagement contractManagement = contractManagementDao.get(id);
        String url=ESignSignService.filePreviewUrl(contractManagement.getSignFlowId(),contractManagement.getFileId());
        return url;
    }

    //合同撤销
    @Transactional(rollbackFor = Exception.class)
    public void revokeContract(String id,String reason,Operator operator){
        logger.info(".....revokeContract  id:{}",id);
        CrmCustomerContractManagement contractManagement = contractManagementDao.get(id);
        if(!CustomerEntryConstants.SIGN_STATUS_FINISH.equals(contractManagement.getStatus())){
            String signFlowId=contractManagement.getSignFlowId();
            try {
                ESignSignService.revoke(signFlowId);
            } catch (EsignDemoException e) {
                e.printStackTrace();
                logger.error("作废合同失败 e:{}",e);
                throw new BusinessException("合同作废失败！"+e.getMessage());
            }
            logger.info("...revokeContract 合同已撤销  signFlowId:{}",signFlowId);
        }
        contractManagement.setStatus(ESignConstants.STATUS_ZF);
        contractManagement.setUpdateTime(new Date());
        contractManagementDao.save(contractManagement);

        SQLQuery sqlQuery = customerDao.getSession().createSQLQuery("UPDATE crm_customer_entry SET sign_status = '6'  WHERE id = :id ");
        sqlQuery.setParameter("id", contractManagement.getEntryId());
        int i=sqlQuery.executeUpdate();
        if(i==0){
            throw new BusinessException("作废合同，更新状态失败！");
        }
        msgService.saveEntryMsg(operator, contractManagement.getEntryId(), CustomerEntryConstants.SIGN_REVOKE,"合同作废，原因"+reason);
    }

    //重新发起合同
    @Transactional(rollbackFor = Exception.class)
    public void createContractAgain(String id,Operator operator){
        logger.info(">>>>>createContractAgain  id:{}",id);
        CrmCustomerContractManagement contractManagement = contractManagementDao.get(id);
        contractManagement.setStatus(ESignConstants.STATUS_DEL);
        contractManagement.setUpdateTime(new Date());
        contractManagementDao.save(contractManagement);
        CustomerEntry entry= customerDao.get(contractManagement.getEntryId());
        CrmCustomerIncomingApplication incomingApplication = incomingApplicationDao.getByEntryId(contractManagement.getEntryId());
        if(incomingApplication==null){
            throw new BusinessException("未找到进件信息！");
        }
        InviteSign(incomingApplication.getPartnersContractNumber(),entry,operator,"重新发起合同",null,null);
        customerDao.save(entry);
    }

    //发起合同
    @Transactional(rollbackFor = Exception.class)
    public void createHuaRongContract(String id,Operator operator){
        logger.info(">>>>>createHuaRongContract  id:{}",id);
        CrmCustomerContractManagement contractManagement = contractManagementDao.get(id);
        if(!StringUtil.equalsAny(contractManagement.getStatus(),ESignConstants.STATUS_WAIT_CREATE)){
            throw new BusinessException("合同状态不允许发起合同");
        }
        CustomerEntry entry= customerDao.get(contractManagement.getEntryId());
        CrmCustomerIncomingApplication incomingApplication = incomingApplicationDao.getByEntryId(contractManagement.getEntryId());
        if(incomingApplication==null){
            throw new BusinessException("未找到进件信息！");
        }
        InviteSign(incomingApplication.getPartnersContractNumber(),entry,operator,"发起合同",null,contractManagement);
        customerDao.save(entry);
    }

    //合同转换 线上签约模式《===》上传 模式
    @Transactional(rollbackFor = Exception.class)
    public void changeContractPattern(String id,Operator operator){
        logger.info(">>>>>changeContractPattern  id:{}",id);
        CrmCustomerContractManagement contractManagement = contractManagementDao.get(id);
        if(!StringUtil.equalsAny(contractManagement.getStatus(),ESignConstants.STATUS_SIGNED_BY_TENANT,ESignConstants.STATUS_WAIT_UPLOAD,ESignConstants.STATUS_ZF,ESignConstants.STATUS_WAIT_CREATE)){
            throw new BusinessException("合同状态不允许转换合同");
        }
        CustomerEntry customerEntry = customerDao.get(contractManagement.getEntryId());
        String content="";
        //转换为 上传 模式
        if(StringUtil.equalsAny(contractManagement.getStatus(),ESignConstants.STATUS_SIGNED_BY_TENANT,ESignConstants.STATUS_ZF,ESignConstants.STATUS_WAIT_CREATE)){
            if(ESignConstants.STATUS_SIGNED_BY_TENANT.equals(contractManagement.getStatus())){
                //撤销之前的线上合同
                String signFlowId=contractManagement.getSignFlowId();
                try {
                    ESignSignService.revoke(signFlowId);
                } catch (EsignDemoException e) {
                    e.printStackTrace();
                    logger.error("转换合同的时候，撤销合同失败 e:{}",e);
                }
                logger.info("...changeContractPattern 转换合同的时候，合同已撤销  signFlowId:{}",signFlowId);
            }
            contractManagement.setStatus(ESignConstants.STATUS_WAIT_UPLOAD);
            customerEntry.setSignStatus(ESignConstants.STATUS_WAIT_UPLOAD);
            content="合同转换为上传模式";
        }else if(contractManagement.getStatus().equals(ESignConstants.STATUS_WAIT_UPLOAD)){  //转为在线签署,那么合同状态改为待发起合同
            contractManagement.setStatus(ESignConstants.STATUS_WAIT_CREATE);
            customerEntry.setSignStatus(ESignConstants.STATUS_WAIT_CREATE);
            content="合同转换为在线签署模式";
        }
        msgService.saveEntryMsg(operator, customerEntry.getId(), CustomerEntryConstants.SIGN_INVITE,content);
        contractManagement.setContractUrl("");
        contractManagementDao.save(contractManagement);
        customerDao.save(customerEntry);
    }

    public Map<Integer,RentVariableVo> getRentGroup(CustomerEntry entry){
          String entryId=entry.getId();
          List<String> projectIds=crmCustomerEntryProjectDao.getEntryProjectIds(entryId);
          if(projectIds==null || projectIds.size()==0){
              projectIds= Arrays.asList(entry.getProjectId().split(","));
          }
          List<Record> rents=rentVariableService.getRentVariableListByProjectIds(projectIds);
          if(rents.size()==0){
              throw new BusinessException("请设置产品租金方案！");
          }
          int i=1;
          int min=1;
          int max=1;
          Map<Integer,RentVariableVo> map=new HashMap<>();
          while(i<4){
              logger.info("getRentGroup  i:{},min:{},max:{}",i,min,max);
              for(Record record:rents){
                  int endYear=record.getInt("end_year");
                  if(max==1){
                      max=endYear;
                  }else if(min==(max+1)){
                      if(endYear>min){
                          max=endYear;
                      }
                  }else if(endYear>min && max>endYear){
                      max=endYear;
                  }
              }
              logger.info("getRentGroup2  i:{},min:{},max:{}",i,min,max);

              RentVariableVo rentVariableVo=new RentVariableVo();
              rentVariableVo.setMin(min);
              rentVariableVo.setMax(max);
              String rentStr="";
              String monthRentStr="";
              if(min>max){
                  i++;
                  continue;
              }
              for(Record re:rents){
                  int starY=re.getInt("start_year");
                  int endY=re.getInt("end_year");
                  if(starY<=min && endY>=max){
                      Integer unitPrice=re.getBigDecimal("unit_price").intValue();
                      if(!rentStr.contains(unitPrice.toString())){
                          rentStr+="+"+unitPrice+"*N";
                          monthRentStr+="/"+unitPrice;

                      }
                  }
              }
              logger.info("getRentGroup   rentStr:{},monthRentStr:{}",rentStr,monthRentStr);
              rentVariableVo.setRent(rentStr.substring(1));
              rentVariableVo.setMonthRent(monthRentStr.substring(1));
              map.put(i,rentVariableVo);
              i++;
              min=max+1;
          }
        return map;
    }

}
