package com.sifang.modules.sunshine.SystemSetting.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.config.SfCacheService;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.customer.dao.CrmCustomerIncomingProductParaDao;
import com.sifang.modules.customer.entity.CrmCustomerIncomingProductPara;
import com.sifang.modules.order.utils.excelExt.ExcelReader;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.sunshine.SystemSetting.dao.*;
import com.sifang.modules.sunshine.SystemSetting.entity.*;
import com.sifang.modules.sunshine.SystemSetting.form.AddAreaVo;
import com.sifang.modules.sunshine.SystemSetting.form.AddProjectInfo;
import com.sifang.modules.sunshine.SystemSetting.form.AddProjectInfoParameter;
import com.sifang.modules.sunshine.SystemSetting.form.AddProjectVo;
import com.sifang.modules.sunshine.SystemSetting.handler.ExcelImportProjectInfoNumberHandler;
import com.sifang.modules.sunshine.SystemSetting.handler.ExcelImportProjectInfoParameterNumberHandler;
import com.sifang.modules.sunshine.SystemSetting.utils.*;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author hongzq
 */
@Service
public class ProjectInfoSettingService extends BaseService {

    @Autowired
    ProjectSettingDao projectSettingDao;

    @Autowired
    ProjectRentVariableDao variableDao;

    @Autowired
    SfCacheService cacheService;

    @Autowired
    private CrmCustomerIncomingProductParaDao paraDao;

    @Autowired
    private ProjectPcdDao projectPcdDao;

    @Autowired
    CrmProjectPcdDao pcdDao;
    @Resource
    AddressService addressService;

    @Autowired
    ProjectCompanyDao projectCompanyDao;



    public CrmProjectSetting getById(String id){
        return projectSettingDao.get(id);
    }

    public void listProjectSettings(LayuiPage<Record> page, Map<String, String> map) {
        List<Record> list = projectSettingDao.selectProjectSettings(page,map);
        Long count = projectSettingDao.countProjectSettings(map);
        page.setData(list);
        page.setCount(count);
    }

    public List<Record> findProjectSettingsList(Map<String, String> map){
        return projectSettingDao.selectProjectSettings(null,map);
    }

    public Record getProjectSettingDetail(String projectId){
        return projectSettingDao.getProjectSettingDetail(projectId);
    }

    public List<ProjectRentVariable> getProjectVariable(String projectId){
        List<ProjectRentVariable> list=variableDao.getProjectVariable(projectId);
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(AddProjectVo projectVo) {
        // 如果资方是越秀，那么必须购买保险
        if (Objects.equals("01", projectVo.getManagement())) {
            if (!Objects.equals("1", projectVo.getBuyInsuranceFlag())) {
                throw new IllegalArgumentException("需设置购买保险");
            }
        }
        List<CrmCustomerIncomingProductPara> productParas = projectVo.getProductPara();
        Result result = checkPara(productParas);
        if (!result.isOk()) {
            throw new IllegalArgumentException(result.getErrMsg());
        }
//        for (ProjectCompanySettings projectCompanySettings : projectVo.getCompanyList()) {
//            int  i = 0;
//            for (AddAreaVo addAreaVo : projectVo.getAreaList()) {
//                if (projectCompanyDao.checkAuth2(projectCompanySettings.getId(),addAreaVo.getProvince(),addAreaVo.getCity(),addAreaVo.getArea())) {
//                    i++;
//                }
//            }
//            if (i == 0){
//                throw new IllegalArgumentException("所选项目授权区域与产品授权区域不一致,请重新选择！");
//            }
//        }
        CrmProjectSetting projectSetting=new CrmProjectSetting();
        checkNameExists(projectVo.getName(), "");
        checkCodeExists(projectVo.getCode(), "");
        Date date=new Date();
        User user=UserUtils.getUser();
        projectSetting.setId(IdGen.uuid());
        projectSetting.setCode(projectVo.getCode());
        projectSetting.setName(projectVo.getName());
        projectSetting.setProductLineId(projectVo.getProductLineId());
        projectSetting.setEpcCompanyId(projectVo.getEpcCompanyId());
        projectSetting.setEpcPrice(projectVo.getEpcPrice());
        projectSetting.setPayCycle(projectVo.getPayCycle());
        projectSetting.setStatus(SourceConstants.ZERO);
        projectSetting.setCreateBy(user.getId());
        projectSetting.setCreator(user.getUserName());
        projectSetting.setCreateTime(date);
        projectSetting.setManagementType(projectVo.getManagementType());
        projectSetting.setFilingType(projectVo.getFilingType());
        projectSetting.setAssemblySpecs(projectVo.getAssemblySpecs());
        projectSetting.setConnectManageFlag(projectVo.getConnectManageFlag());
        projectSetting.setStateAuthorizedFlag(projectVo.getStateAuthorizedFlag());
        if ("1".equals(projectVo.getConnectManageFlag())) {
            projectSetting.setManagement(projectVo.getManagement());
        }
        projectSetting.setBuyInsuranceFlag(projectVo.getBuyInsuranceFlag());
        if ("1".equals(projectVo.getBuyInsuranceFlag())) {
            projectSetting.setInsuranceId(projectVo.getInsuranceId());
        }
        projectSetting.setManagement(projectVo.getManagement());

        CrmCustomerIncomingProductPara parae = new CrmCustomerIncomingProductPara();
        parae.setProductParaCode("EQUIPMENT_PRICE");
        parae.setProductParaName("设备单价(元/瓦)");
        parae.setProductParaValue(projectVo.getEpcPrice().toString());
        parae.setLeaseTermFrom("1");
        parae.setLeaseTermTo("25");
        productParas.add(parae);

        List<ProjectRentVariable> variables=projectVo.getVariables();
        List<ProjectRentVariable> varilist= Lists.newArrayList();
        if(variables!=null && variables.size()>0){
             for(ProjectRentVariable variable:variables){
                 if(variable.getEndYear()== null && variable.getEndYear()==null && variable.getUnitPrice()==null){
                     continue;
                 }
                 variable.setProjectId(projectSetting.getId());
                 variable.setCreateTime(date);
                 variable.setCreateBy(user.getId());
                 variable.setCreateName(user.getUserName());
                 variable.setStatus(SourceConstants.ZERO);
                 varilist.add(variable);
                 CrmCustomerIncomingProductPara para = new CrmCustomerIncomingProductPara();
                 para.setProductParaCode("TENANT_INCOME_PRICE");
                 para.setProductParaName("承租人收益(元/块光伏板/年)");
                 para.setProductParaValue(variable.getUnitPrice().toString());
                 para.setLeaseTermFrom(variable.getStartYear().toString());
                 para.setLeaseTermTo(variable.getEndYear().toString());
                 productParas.add(para);
             }
            variableDao.save(varilist);
        }

        // 保存区域设置
        List<AddAreaVo> areaList = projectVo.getAreaList();
        List<ProjectPcd> pcdList = Lists.newArrayList();
        int i = 1;
        if(areaList != null && areaList.size() > 0){
            for (AddAreaVo areaVo : areaList) {
                ProjectPcd pcd = new ProjectPcd();
                pcd.setProjectId(projectSetting.getId());
                pcd.setProvince(areaVo.getProvince());
                if (StringUtil.isNotBlank(areaVo.getCity())) {
                    pcd.setCity(areaVo.getCity());
                }
                if (StringUtil.isNotBlank(areaVo.getArea())) {
                    pcd.setArea(areaVo.getArea());
                }
                pcd.setSort(i);
                pcd.setCreateTime(date);
                pcd.setStatus("0");
                pcdList.add(pcd);
                i++;
            }
        }
        projectPcdDao.save(pcdList);
//        String cmIds = "";
//        for (ProjectCompanySettings settings : projectVo.getCompanyList()) {
//            cmIds += settings.getId()+',';
//        }
//        projectSetting.setProjectCompanyId(cmIds);
        for(CrmCustomerIncomingProductPara para:productParas){
            para.setType(projectVo.getFilingType());
            para.setProjectCode(projectVo.getCode());
        }
        paraDao.save(productParas);
        projectSettingDao.save(projectSetting);
        cacheService.del("projectList");
    }



    public List<CrmCustomerIncomingProductPara> getProductPara(String projectCode){
        return paraDao.getProductPara(projectCode);
    }

    // 获取授权区域列表
    public List<ProjectPcd> getProjectArea(String projectId){
        return projectPcdDao.findListByProjectId(projectId);
    }

    /**
     * 启用禁用
     * @param id
     * @param status
     */
    @Transactional(rollbackFor = Exception.class)
    public void changeProjectSettingStatus(String id,String status){
        logger.info(">>>>>>>>>>>>>>>>>changeProjectSettingStatus id:{}",id);
        User user = UserUtils.getUser();
        CrmProjectSetting crmProjectSetting = projectSettingDao.get(id);
        crmProjectSetting.setStatus(status);
        crmProjectSetting.setUpdateBy(user.getId());
        crmProjectSetting.setUpdateTime(new Date());
        projectSettingDao.save(crmProjectSetting);
    }

    @Transactional(rollbackFor = Exception.class)
    public void edit(AddProjectVo projectVo) {
        logger.info(">>>>>>>>>>>>>>>>>edit  id:{}",projectVo.getId());
    /*    checkNameExists(projectVo.getName(), projectVo.getId());
        checkCodeExists(projectVo.getCode(), projectVo.getId());*/
        CrmProjectSetting projectSetting = projectSettingDao.get(projectVo.getId());
        /*projectSetting.setCode(projectVo.getCode());*/
        // 如果资方是越秀，那么必须购买保险
        if (Objects.equals("01", projectVo.getManagement())) {
            if (!Objects.equals("1", projectVo.getBuyInsuranceFlag())) {
                throw new IllegalArgumentException("需设置购买保险");
            }
        }
        List<CrmCustomerIncomingProductPara> productParas = projectVo.getProductPara();
        Result result = checkPara(productParas);
        if (!result.isOk()) {
            throw new IllegalArgumentException(result.getErrMsg());
        }
//        for (ProjectCompanySettings projectCompanySettings : projectVo.getCompanyList()) {
//            int  i = 0;
//            for (AddAreaVo addAreaVo : projectVo.getAreaList()) {
//                if (projectCompanyDao.checkAuth2(projectCompanySettings.getId(),addAreaVo.getProvince(),addAreaVo.getCity(),addAreaVo.getArea())) {
//                    i++;
//                }
//            }
//            if (i == 0){
//                throw new IllegalArgumentException("所选项目授权区域与产品授权区域不一致,请重新选择！");
//            }
//        }
        Date date=new Date();
        User user=UserUtils.getUser();
        projectSetting.setName(projectVo.getName());
        projectSetting.setProductLineId(projectVo.getProductLineId());
        projectSetting.setEpcCompanyId(projectVo.getEpcCompanyId());
     //   projectSetting.setProjectCompanyId(projectVo.getProjectCompanyId());
        projectSetting.setEpcPrice(projectVo.getEpcPrice());
        projectSetting.setPayCycle(projectVo.getPayCycle());
        projectSetting.setUpdateBy(user.getId());
        projectSetting.setUpdator(user.getUserName());
        projectSetting.setUpdateTime(date);
        projectSetting.setManagementType(projectVo.getManagementType());
        projectSetting.setFilingType(projectVo.getFilingType());
        projectSetting.setAssemblySpecs(projectVo.getAssemblySpecs());
        projectSetting.setManagement(projectVo.getManagement());
        projectSetting.setConnectManageFlag(projectVo.getConnectManageFlag());
        projectSetting.setBuyInsuranceFlag(projectVo.getBuyInsuranceFlag());
        projectSetting.setInsuranceId(projectVo.getInsuranceId());
        projectSetting.setStateAuthorizedFlag(projectVo.getStateAuthorizedFlag());
        List<ProjectRentVariable> variables=projectVo.getVariables();
        CrmCustomerIncomingProductPara parae = new CrmCustomerIncomingProductPara();
        parae.setProductParaCode("EQUIPMENT_PRICE");
        parae.setProductParaName("设备单价(元/瓦)");
        parae.setProductParaValue(projectVo.getEpcPrice().toString());
        parae.setLeaseTermFrom("1");
        parae.setLeaseTermTo("25");
        productParas.add(parae);
        List<ProjectRentVariable> varilist= Lists.newArrayList();
        if(variables!=null && variables.size()>0){
            for(ProjectRentVariable variable:variables){
                if(variable.getEndYear()== null && variable.getEndYear()==null && variable.getUnitPrice()==null){
                    continue;
                }
                variable.setProjectId(projectSetting.getId());
                variable.setCreateTime(date);
                variable.setCreateBy(user.getId());
                variable.setCreateName(user.getUserName());
                variable.setStatus(SourceConstants.ZERO);
                varilist.add(variable);
                CrmCustomerIncomingProductPara para = new CrmCustomerIncomingProductPara();
                para.setProductParaCode("TENANT_INCOME_PRICE");
                para.setProductParaName("承租人收益(元/块光伏板/年)");
                para.setProductParaValue(variable.getUnitPrice().toString());
                para.setLeaseTermFrom(variable.getStartYear().toString());
                para.setLeaseTermTo(variable.getEndYear().toString());
                productParas.add(para);
            }
            //删除原来保存的
            variableDao.deleteVariable(projectSetting.getId());
            variableDao.save(varilist);
        }

        // 保存区域设置
        List<AddAreaVo> areaList = projectVo.getAreaList();
        List<ProjectPcd> pcdList = Lists.newArrayList();
        int i = 1;
        if(areaList != null && areaList.size() > 0){
            for (AddAreaVo areaVo : areaList) {
                ProjectPcd pcd = new ProjectPcd();
                pcd.setProjectId(projectSetting.getId());
                pcd.setProvince(areaVo.getProvince());
                if (StringUtil.isNotBlank(areaVo.getCity())) {
                    pcd.setCity(areaVo.getCity());
                }
                if (StringUtil.isNotBlank(areaVo.getArea())) {
                    pcd.setArea(areaVo.getArea());
                }
                pcd.setSort(i);
                pcd.setCreateTime(date);
                pcd.setStatus("0");
                pcdList.add(pcd);
                i++;
            }
        }
        //删除原来保存的
        projectPcdDao.deleteProductArea(projectSetting.getId());
        projectPcdDao.save(pcdList);

        for(CrmCustomerIncomingProductPara para:productParas){
            para.setType(projectVo.getFilingType());
            para.setProjectCode(projectVo.getCode());
        }

//        String cmIds = "";
//        for (ProjectCompanySettings settings : projectVo.getCompanyList()) {
//           cmIds += settings.getId()+',';
//        }
//        projectSetting.setProjectCompanyId(cmIds);
        paraDao.deleteProductPara(projectSetting.getCode());
        paraDao.save(productParas);
        projectSettingDao.save(projectSetting);
        cacheService.del("projectList");
        cacheService.del(projectSetting.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(String ids) {
        List<CrmProjectSetting> settings = new ArrayList<>();
        long count  = Db.queryLong(" SELECT COUNT(*) FROM `crm_trader_project` WHERE project_id IN("+ StringUtil.joinInSql(ids.split(","))+")");
        if(count>0){
            throw new BusinessException("选择的项目中有代理商关联的项目，不可删除！");
        }
        for(String id: ids.split(",")){
            CrmProjectSetting setting = projectSettingDao.get(id);
            setting.setStatus(SourceConstants.ONE);
            setting.setUpdateBy(UserUtils.getUser().getId());
            setting.setUpdator(CrmUtils.getUserXM(UserUtils.getUser()));
            setting.setUpdateTime(new Date());
            settings.add(setting);
            cacheService.del(setting.getId());

            variableDao.changeVariableStatus(id);
            projectPcdDao.changeAreaStatus(id);
        }

        projectSettingDao.save(settings);
        cacheService.del("projectList");

    }

    public void checkNameExists(String name, String excludeId) {
        if (projectSettingDao.countExistsName(name, excludeId) > 0) {
            throw new BusinessException("产品名称已存在");
        }
    }

    public void checkCodeExists(String code, String excludeId) {
        if (projectSettingDao.countExistsCode(code, excludeId) > 0) {
            throw new BusinessException("产品编号已存在");
        }
    }

    public List<Record> getProductLineList(){
        return projectSettingDao.getProductLineList();
    }

    public String getManageType(String type){
        String managementType = "";
        if(StringUtil.isBlank(type)){
            return managementType;
        }
        switch (type){
            case CustomerEntryConstants
                    .TYPE_YX:
                managementType="越秀";
                break;
            case CustomerEntryConstants
                    .TYPE_ZJYL:
                managementType="浙江浙银金融租赁股份有限公司";
                break;
            case CustomerEntryConstants
                    .TYPE_ZX:
                managementType="中信";
                break;
        }
        return managementType;
    }

    /**
     * 录单获取产品信息
     */
    public Record getProjectForTranscription(String projectId){
        Record record = projectSettingDao.findProjectForTranscription(projectId);
        if (Objects.equals("1", record.getStr("pay_cycle"))) {
            record.set("payCycleName", "按月支付");
        } else if (Objects.equals("2", record.getStr("pay_cycle"))) {
            record.set("payCycleName", "按季支付");
        } else if (Objects.equals("3", record.getStr("pay_cycle"))) {
            record.set("payCycleName", "按年支付");
        }
        if (Objects.equals("1", record.getStr("filing_type"))) {
            record.set("filingTypeName", "农户备案");
        } else {
            record.set("filingTypeName", "项目公司备案");
        }
        return record;
    }

   public List<Record> getProjectInfo(String projectId){
       Record record = projectSettingDao.finProjectSettingById(projectId);
       List<Record> recordList = new ArrayList<>();
       String pcIds = record.getStr("project_company_id");
       for (String psId : pcIds.split(",")) {
           Record project = projectCompanyDao.getProjectByPCId(psId);
           recordList.add(project);
       }
       return recordList;
   }


    public List<Record> getProjectByArea( Map<String, String> map){
        SqlBuilder builder = new SqlBuilder();
        builder.line(" select * FROM crm_project_setting")
                .line(" where `status` = 0 ")
                .line(" and management = ?",map.get("partner"));
                if (map.get("type") != null && map.get("type").equals("2")){
                    builder.line(" and  filing_type = ?",map.get("type"));
                }
                //华融
                if(StringUtils.isNotBlank(map.get("filingType") )){
                    builder.line(" and  filing_type = ?",map.get("filingType"));
                }
                builder.line(" and  id in ( SELECT project_id FROM crm_project_pcd")
                .line(" where project_id in ( SELECT project_id FROM crm_trader_project")
                .line("where trader_id = ? )",map.get("traderId"));
                 builder.line(" and ( (province = ? and city is null )" ,map.get("province"));
                 builder.line("or (province = ? and city = ? and area is null)",map.get("province") ,map.get("city"));
                 builder.line(" or (province = ? and city = ? and area = ? ) ))" ,map.get("province") ,map.get("city"),map.get("area"));
         List<Record> project = new ArrayList<>();
         project =  Db.find(builder.build(), builder.params());
        return project;
    }


    public Result getProjectById(String ids) {
        List<Object> list = new ArrayList<>();
        String[] arr = ids.split(",");
        for (String id : arr) {
            Record project = projectSettingDao.findProjectById(id);
            if (project == null) {
                return Result.fail("未查询到产品信息");
            }
            if (Objects.equals(project.getStr("filingType"), "1")) {
                project.set("filingType", "农户备案");
            } else {
                project.set("filingType", "项目公司备案");
            }
            if (Objects.equals(project.getStr("status"), "0")) {
                project.set("status", "启用");
            } else if (Objects.equals(project.getStr("status"), "2")) {
                project.set("status", "禁用");
            } else {
                project.set("status", "删除");
            }
            list.add(project);
        }
        return Result.success(list);
    }

    public List<Record> getProjectList(){
        return projectSettingDao.getProjectList();
    }

    public List<CrmProjectSetting> getProjectSettingList(){
        return projectSettingDao.getProjectSettingList();
    }

    public Result checkPara(List<CrmCustomerIncomingProductPara> paraList) {
        Result result;
        // 电价(元/kwh)
        List<CrmCustomerIncomingProductPara> elePriceList = paraList.stream().filter(v -> "ELE_PRICE".equals(v.getProductParaCode()))
                .sorted(Comparator.comparing(CrmCustomerIncomingProductPara::getLeaseTermFrom)).collect(Collectors.toList());
        result = checkParaDetalil(elePriceList, "电价(元/kwh)");
        if (!result.isOk()) {
            return result;
        }
        // 基准发电小时数(小时)
        List<CrmCustomerIncomingProductPara> basicEleTimeList = paraList.stream().filter(v -> "BASIC_ELE_TIME".equals(v.getProductParaCode()))
                .sorted(Comparator.comparing(CrmCustomerIncomingProductPara::getLeaseTermFrom)).collect(Collectors.toList());
        result = checkParaDetalil(basicEleTimeList, "基准发电小时数(小时)");
        if (!result.isOk()) {
            return result;
        }
        // 收益分成比例(厂商)
        List<CrmCustomerIncomingProductPara> manufacturerInconeRatioList = paraList.stream().filter(v -> "MANUFACTURER_INCONE_RATIO".equals(v.getProductParaCode()))
                .sorted(Comparator.comparing(CrmCustomerIncomingProductPara::getLeaseTermFrom)).collect(Collectors.toList());
        result = checkParaDetalil(manufacturerInconeRatioList, "收益分成比例(厂商)");
        if (!result.isOk()) {
            return result;
        }
        // 光伏板衰减率(年)
        List<CrmCustomerIncomingProductPara> decayRateList = paraList.stream().filter(v -> "DECAY_RATE".equals(v.getProductParaCode()))
                .sorted(Comparator.comparing(CrmCustomerIncomingProductPara::getLeaseTermFrom)).collect(Collectors.toList());
        result = checkParaDetalil(decayRateList, "光伏板衰减率(年)");
        if (!result.isOk()) {
            return result;
        }
        // 运维费用(元/瓦/年)
        List<CrmCustomerIncomingProductPara> maintenancePriceList = paraList.stream().filter(v -> "MAINTENANCE_PRICE".equals(v.getProductParaCode()))
                .sorted(Comparator.comparing(CrmCustomerIncomingProductPara::getLeaseTermFrom)).collect(Collectors.toList());
        result = checkParaDetalil(maintenancePriceList, "运维费用(元/瓦/年)");
        if (!result.isOk()) {
            return result;
        }
        // 保证金比例
        List<CrmCustomerIncomingProductPara> depositRatioList = paraList.stream().filter(v -> "DEPOSIT_RATIO".equals(v.getProductParaCode()))
                .sorted(Comparator.comparing(CrmCustomerIncomingProductPara::getLeaseTermFrom)).collect(Collectors.toList());
        result = checkParaDetalil(depositRatioList, "保证金比例");
        if (!result.isOk()) {
            return result;
        }
        // 残值率
        List<CrmCustomerIncomingProductPara> residualsRateList = paraList.stream().filter(v -> "RESIDUALS_RATE".equals(v.getProductParaCode()))
                .sorted(Comparator.comparing(CrmCustomerIncomingProductPara::getLeaseTermFrom)).collect(Collectors.toList());
        result = checkParaDetalil(residualsRateList, "残值率");
        if (!result.isOk()) {
            return result;
        }
        // 投资资产到期处置价
        List<CrmCustomerIncomingProductPara> disposalPriceList = paraList.stream().filter(v -> "DISPOSAL_PRICE".equals(v.getProductParaCode()))
                .sorted(Comparator.comparing(CrmCustomerIncomingProductPara::getLeaseTermFrom)).collect(Collectors.toList());
        result = checkParaDetalil(disposalPriceList, "投资资产到期处置价");
        if (!result.isOk()) {
            return result;
        }
        return result;
    }

    public Result checkParaDetalil(List<CrmCustomerIncomingProductPara> list, String paraName) {
        if (list.size() > 0) {
            list = list.stream()
                    .sorted(Comparator.comparing(p -> Integer.parseInt(p.getLeaseTermFrom())))
                    .collect(Collectors.toList());
            for (int i = 0; i < list.size(); i++) {
                if (StringUtil.isBlank(list.get(i).getLeaseTermFrom()) || StringUtil.isBlank(list.get(i).getLeaseTermTo())){
                    return Result.fail(paraName + "，产品参数设置填写不完整");
                }
                int leaseTermFrom = Integer.parseInt(list.get(i).getLeaseTermFrom());
                int leaseTermTo = Integer.parseInt(list.get(i).getLeaseTermTo());
                if (leaseTermTo < leaseTermFrom) {
                    return Result.fail(paraName + "，设置规则不匹配");
                }
                if (i == 0) {
                    if (leaseTermFrom != 1) {
                        return Result.fail(paraName + "，设置规则不匹配");
                    }
                }
                if (i == list.size() - 1) {
                    if (leaseTermTo != 25) {
                        return Result.fail(paraName + "，设置规则不匹配");
                    }
                }
                if (i > 0) {
                    int lastLeaseTermTo = Integer.parseInt(list.get(i-1).getLeaseTermTo());
                    if (leaseTermFrom - lastLeaseTermTo != 1) {
                        return Result.fail(paraName + "，设置规则不匹配");
                    }
                }
            }
        }
        return Result.ok();
    }
    /**
     * 检验产品信息导入表格
     * @param params
     * @param in
     * @return
     */


    public Map<String, Object> checkImportProjectInfo(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "check");
        ExcelImportProjectInfoNumberHandler handler=new ExcelImportProjectInfoNumberHandler();
        handler.setStartSheet(1);
        handler.setStartRow(2);
        try {
            new ExcelReader().check(in, params.get("extName"), handler);
            Map<String, Object> map = (Map<String, Object>) handler.getHandlerResult();
            String templateError = (String) map.get("TemplateError");
            if(!handler.isCheckFlag()){
                handler.appendErrorDetail("<p>未填充数据</p>");
            }

            List<String> projectName = ProjectInfoUtil.findProjectName();

            //检索所属产品线
            List<String> productLine =  ProjectInfoUtil.findProductLine();
            //备案方式 农户备案 项目公司备案
            List<String> record = new ArrayList<>();
            record.add("农户备案");
            record.add("项目公司备案");
            //检索epc公司
            List<String> epcCompany =  ProjectInfoUtil.findEpcCompany();
            //检索所属项目公司名称
            List<String> company =  ProjectInfoUtil.findCompanyList();
            //租金支付周期  按月支付 按季支付 按年支付
            List<String> paymentCycle = new ArrayList<>();
            paymentCycle.add("按月支付");
            paymentCycle.add("按季支付");
            paymentCycle.add("按年支付");
            //组件规格
            List<String> assemblySpecsList = ProjectInfoUtil.findAssemblySpecsList();
            //资方名称
            List<String> partnerList =  ProjectInfoUtil.findPartnerList();

            //省
            List<String> provinceList = new ArrayList<>();
            List<Record> provinces = addressService.getProvinces();
            for (Record province : provinces) {
                String provinceName = province.getStr("ProvinceName");
                provinceList.add(provinceName);
            }

            //市
            List<String> cityList = new ArrayList<>();
            List<Record> citys = addressService.getCityList();
            for (Record city : citys) {
                String cityName = city.getStr("CityName");
                cityList.add(cityName);
            }
            List<AddProjectInfo> retList = handler.getAddProjectList();


            int i = 2;
            List<String> itName = new ArrayList<>();
            List<String> cfjc = new ArrayList<>();
            for (AddProjectInfo info : retList) {
                List<String> itArea = new ArrayList<>();
                if (Objects.equals("广州越秀融资租赁有限公司", info.getManagementType())) {
                    if (!Objects.equals("是", info.getBuyInsuranceFlag())) {
                        handler.appendErrorDetail("资方为广州越秀融资租赁有限公司时必须购买保险");
                    }
                }


                //检索保险名称
                List<String> projectInstalls = ProjectInfoUtil.findInsuranceNameList(info.getEpcCompanyId());
                //检索表中是否存在
                String str = info.getName()+""+info.getCode()+""+info.getProjectCompanyId();

                if (cfjc.contains(str)){
                    handler.appendErrorDetail("第" + (i + 1) + "行同一产品编号，产品名称所属项目公司在表单内不能重复");
                }
                if (!epcCompany.contains(info.getEpcCompanyId())){
                    handler.appendErrorDetail("第" + (i + 1) + "行epc公司不存在");
                }
                cfjc.add(str);
//                if (itName.contains(info.getName())){
//                    handler.appendErrorDetail("第" + (i + 1) + "行产品名称已在表中存在");
//                }
//                if (projectName.contains(info.getName())){
//                    handler.appendErrorDetail("第" + (i + 1) + "行产品名称已存在");
//                }

                if (!productLine.contains(info.getProductLineId())){
                    handler.appendErrorDetail("第" + (i + 1) + "行所属产品线不存在");
                }
                if (!record.contains(info.getFilingType())){
                    handler.appendErrorDetail("第" + (i + 1) + "行备案方式不存在");
                }
                if (info.getProjectCompanyId() != null && info.getProjectCompanyId() != ""){
                    String projectCompanyName = info.getProjectCompanyId();
                    String[] split = projectCompanyName.split(",");
                    for (String s : split) {
                        //检索同一产品编号 名称 和项目公司是否重复
                        String companyId = ProjectInfoUtil.getCompanyByCode(s);
                        List<String> project = ProjectInfoUtil.findProjectByCodeName(info.getCode(),info.getName(),companyId);
                        if (!project.isEmpty()){
                            handler.appendErrorDetail("第" + (i + 1) + "行同一产品编号，产品名称所属项目公司已存在");
                        }
                        if (!company.contains(s)){
                            handler.appendErrorDetail("第" + (i + 1) + "行所属项目公司不存在");
                        }
                    }
                }
                if (!paymentCycle.contains(info.getPayCycle())){
                    handler.appendErrorDetail("第" + (i + 1) + "行租金支付周期不存在");
                }
                if (!assemblySpecsList.contains(info.getAssemblySpecs())){
                    handler.appendErrorDetail("第" + (i + 1) + "行组件规格不存在");
                }
                if (!partnerList.contains(info.getManagementType())){
                    handler.appendErrorDetail("第" + (i + 1) + "行资方名称不存在");
                }
                if (!projectInstalls.contains(info.getInsuranceName())){
                    handler.appendErrorDetail("第" + (i + 1) + "行保险名称与epc公司不匹配");
                }
                if (!provinceList.contains(info.getProvince())){
                    handler.appendErrorDetail("第" + (i + 1) + "行省不存在");
                }
                List<String> cityInfo = Arrays.asList(info.getCity().split(","));
                if (!cityList.containsAll(cityInfo)){
                    handler.appendErrorDetail("第" + (i + 1) + "行市不存在");
                }
                itName.add(info.getName());
                for (String s : cityInfo) {
                    if (itArea.contains(info.getProvince()+""+s)){
                        handler.appendErrorDetail("第" + (i + 1) + "行市已在表中存在");
                    }
                    itArea.add(info.getProvince()+""+s);
                }
                i++;
            }
            String hanl = handler.getErrorDetail();
            if (StrKit.notBlank(templateError)){
                retMap.put("errorDetail", templateError);
                retMap.put("errorMessage", "y");
            }else if (StringUtils.isNotBlank(hanl)) {
                retMap.put("errorDetail", hanl);
                retMap.put("errorMessage", "y");
            } else if ("overLimit".equalsIgnoreCase((String) map.get("overLimit"))) {
                retMap.put("overLimit", "y");
            } else {
                retMap.put("pass", "y");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return retMap;
    }

    /**
     * 导入表格
     * @param params
     * @param in
     * @return
     */


    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importProjectInfo(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "import");
        ExcelImportProjectInfoNumberHandler handler=new ExcelImportProjectInfoNumberHandler();
        handler.setStartSheet(1);
        handler.setStartRow(3);
        User user = UserUtils.getUser();
        try {
            new ExcelReader().readExcel(in, params.get("fileName"), handler);
            List<AddProjectInfo> projectList = handler.getAddProjectList();
            for (AddProjectInfo add : projectList) {
                CrmProjectSetting crmProjectSetting = new CrmProjectSetting();
                crmProjectSetting.setCode(add.getCode());
                crmProjectSetting.setName(add.getName());
                String lineIdByName = ProjectInfoUtil.getProductLineIdByName(add.getProductLineId());
                crmProjectSetting.setProductLineId(lineIdByName);
                String epcCompanyId = ProjectInfoUtil.getEpcCompanyIdByName(add.getEpcCompanyId());
                crmProjectSetting.setEpcCompanyId(epcCompanyId);
                if (add.getEpcPrice() != null && add.getEpcPrice() != ""){
                    BigDecimal epcPrice = new BigDecimal(add.getEpcPrice());
                    crmProjectSetting.setEpcPrice(epcPrice);
                }else {
                    crmProjectSetting.setEpcPrice(BigDecimal.valueOf(0));
                }
                if (add.getPayCycle().equals("按月支付")){
                    crmProjectSetting.setPayCycle("1");
                }else if (add.getPayCycle().equals("按季支付")){
                    crmProjectSetting.setPayCycle("2");
                }else if (add.getPayCycle().equals("按年支付")){
                    crmProjectSetting.setPayCycle("3");
                }
                crmProjectSetting.setStatus("0");
                crmProjectSetting.setCreateBy(user.getId());
                crmProjectSetting.setCreator(user.getUserName());
                crmProjectSetting.setCreateTime(new Date());
                //String companyCode = ProjectInfoUtil.getCompanyByName(add.getProjectCompanyId());
                if (add.getFilingType().equals("农户备案")){
                    crmProjectSetting.setFilingType("1");
                }else {
                    crmProjectSetting.setFilingType("2");
                }
                crmProjectSetting.setAssemblySpecs(Integer.parseInt(add.getAssemblySpecs()));
                if (add.getManagementType().equals("广州越秀融资租赁有限公司")){
                    crmProjectSetting.setManagement("01");
                }
                if (add.getBuyInsuranceFlag().equals("是")){
                    crmProjectSetting.setConnectManageFlag("1");
                    crmProjectSetting.setBuyInsuranceFlag("1");
                }else {
                    crmProjectSetting.setBuyInsuranceFlag("0");
                }
                String insuranceId = ProjectInfoUtil.getInsuranceIdByName(add.getInsuranceName());
                crmProjectSetting.setInsuranceId(insuranceId);

                if (add.getStateAuthorizedFlag().equals("是")){
                    crmProjectSetting.setStateAuthorizedFlag("1");
                }else {
                    crmProjectSetting.setStateAuthorizedFlag("0");
                }



                List<String> city = Arrays.asList(add.getCity().split(","));

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                // 获取当前日期
                Date currentDate = new Date();
                List<CrmProjectPcd> pcdList = new ArrayList<>();
                // 格式化日期

                List<CrmProjectSetting> psList = new ArrayList<>();
                //项目公司不为空时
                String comIds = "";
                if ( add.getProjectCompanyId()!= null &&  add.getProjectCompanyId() != "" ){
                    String[] split = add.getProjectCompanyId().split(",");
                    for (String s : split) {

                        String psId = IdGen.uuid();
                        crmProjectSetting.setId(psId);
                        //添加产品授权区域信息
                        int i = 1;
                        for (String cy : city) {
                            CrmProjectPcd crmProjectPcd = new CrmProjectPcd();
                            crmProjectPcd.setProjectId(psId);
                            crmProjectPcd.setProvince(add.getProvince());
                            String formattedDate = sdf.format(currentDate);
                            crmProjectPcd.setCity(cy);
                            crmProjectPcd.setSort(String.valueOf(i));
                            crmProjectPcd.setCreateTime(formattedDate);
                            crmProjectPcd.setStatus("0");
                            pcdList.add(crmProjectPcd);
                            i++;
                            pcdDao.save(crmProjectPcd);
                        }
                        //添加项目信息
                        String companyId = ProjectInfoUtil.getCompanyByName(s);
                        comIds += companyId +",";

                        String managementType = ProjectInfoUtil.getManagementTypeByName(s);
                        crmProjectSetting.setManagementType(managementType);
                    }
                    crmProjectSetting.setProjectCompanyId(comIds);
                    psList.add(crmProjectSetting);
                }else {

                    String psId = IdGen.uuid();
                    crmProjectSetting.setId(psId);
                    int i = 1;
                    for (String cy : city) {
                        CrmProjectPcd crmProjectPcd = new CrmProjectPcd();
                        crmProjectPcd.setProjectId(psId);
                        crmProjectPcd.setProvince(add.getProvince());
                        String formattedDate = sdf.format(currentDate);
                        crmProjectPcd.setCity(cy);
                        crmProjectPcd.setSort(String.valueOf(i));
                        crmProjectPcd.setCreateTime(formattedDate);
                        crmProjectPcd.setStatus("0");
                        pcdList.add(crmProjectPcd);
                        i++;
                        pcdDao.save(crmProjectPcd);
                    }
                    psList.add(crmProjectSetting);
                }
                projectSettingDao.save(psList);
            }

            retMap.put("pass", "y");
            retMap.put("materialList", handler.getAddProjectList());

        }catch (Exception e){
            e.printStackTrace();
            logger.error(" 导入产品信息异常,e:{}",e);
            throw new BusinessException(e.getMessage());
        }finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return retMap;
    }

    /**
     * 检验产品信息
     * @param params
     * @param in
     * @return
     */

    public Map<String, Object> checkImportProjectParameterInfo(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "check");
        ExcelImportProjectInfoParameterNumberHandler handler=new ExcelImportProjectInfoParameterNumberHandler();
        handler.setStartSheet(1);
        handler.setStartRow(2);
        try {
            new ExcelReader().check(in, params.get("extName"), handler);
            Map<String, Object> map = (Map<String, Object>) handler.getHandlerResult();
            String templateError = (String) map.get("TemplateError");
            if(!handler.isCheckFlag()){
                handler.appendErrorDetail("<p>未填充数据</p>");
            }
            //获取产品编号
            List<String> codeList = ProjectInfoUtil.findProjectCode();


            //获取全部参数名
            //List<String> strings = ProjectInfoParameterUtil.finProductParaNameList();
            List<String> strings = new ArrayList<>();
            strings.add("基准发电小时数(小时)");
            strings.add("收益分成比例(厂商)");
            strings.add("电价(元/kwh)");
            strings.add("光伏板衰减率(年)");
            strings.add("运维费用(元/瓦/年)");
            strings.add("保证金比例");
            strings.add("残值率");
            strings.add("电价补贴");
            strings.add("投资资产到期处置价");
            strings.add("设备单价(元/瓦)");
            strings.add("承租人收益(元/块光伏板/年)");

            strings.add("基准发电小时数(h)");
            strings.add("光伏板衰减率");
            strings.add("投资资产到期处置价");
            strings.add("电价(元/kwh)");
            strings.add("设备单价(元/瓦)");
            strings.add("电价补贴");
            strings.add("运维费用(元/瓦/年)");
            strings.add("厂商收益分成比例");
            strings.add("承租人收益(元/块光伏板/年)");
            List<AddProjectInfoParameter> parameterList = handler.getParameterList();
            int i = 2;
            for (AddProjectInfoParameter infoParameter : parameterList) {
                List<String> list = ProjectInfoParameterUtil.finProductList(infoParameter.getParameterName(), infoParameter.getCode());
                if(!infoParameter.getParameterName().equals("设备单价(元/瓦)") && !infoParameter.getParameterName().equals("承租人收益(元/块光伏板/年)")){
                    if (!list.isEmpty()){
                        handler.appendErrorDetail("第" + (i + 1) + "行产品参数信息已存在");
                    }
                }
                if (infoParameter.getLeaseTermFrom() != null && infoParameter.getLeaseTermFrom() != "" && infoParameter.getLeaseTermTo() != null &&infoParameter.getLeaseTermTo() != ""){
                    if (Integer.parseInt(infoParameter.getLeaseTermFrom()) > Integer.parseInt(infoParameter.getLeaseTermTo())){
                        handler.appendErrorDetail("第" + (i + 1) + "行租赁年限从(含)晚于租赁年限到(含)");
                    }
                }
                if (infoParameter.getCode() != null && !codeList.contains(infoParameter.getCode())){
                    handler.appendErrorDetail("第" + (i + 1) + "行产品编号不存在");
                }
                if ( infoParameter.getParameterName() != null && !strings.contains(infoParameter.getParameterName())  ){
                    handler.appendErrorDetail("第" + (i + 1) + "行参数名不存在");
                }
                i++;
            }
//            Map<String, List<AddProjectInfoParameter>> groupedByParaName = parameterList.stream()
//                    .sorted(Comparator.comparing(AddProjectInfoParameter::getCode)
//                            .thenComparing(AddProjectInfoParameter::getParameterName))
//                    .collect(Collectors.groupingBy(AddProjectInfoParameter::getParameterName));
//            for (Map.Entry<String, List<AddProjectInfoParameter>> entry : groupedByParaName.entrySet()) {
//                String paraName = entry.getKey();
//                List<AddProjectInfoParameter> parameters = entry.getValue();
//                Result result = checkImportProject(parameters, paraName);
//                // 在这里处理返回的结果result
//                if (!result.isOk()) {
//                    System.out.println(result);
//                    if (result.getCode().equals("500")) {
//                        handler.appendErrorDetail(entry.getValue() + "" + result.getErrMsg());
//                    }
//                }
//            }


            Map<String, List<AddProjectInfoParameter>> groupedByCode = parameterList.stream()
                    .collect(Collectors.groupingBy(AddProjectInfoParameter::getCode));
            for (Map.Entry<String, List<AddProjectInfoParameter>> entry : groupedByCode.entrySet()) {
                List<AddProjectInfoParameter> value = entry.getValue();
                Map<String ,List<AddProjectInfoParameter>> parameterName = value.stream()
                        .collect(Collectors.groupingBy(AddProjectInfoParameter::getParameterName));
                for (Map.Entry<String, List<AddProjectInfoParameter>> listEntry : parameterName.entrySet()) {
                    String paraName = listEntry.getKey();
                    List<AddProjectInfoParameter> parameters = listEntry.getValue();
                    Result result = checkImportProject(parameters, paraName);
                    if (!result.isOk()) {
                        System.out.println(result);
                        if (result.getCode().equals("500")) {
                            handler.appendErrorDetail("产品编号"+entry.getKey() + "的信息," + result.getErrMsg());
                        }
                    }
                }
            }



            String hanl = handler.getErrorDetail();
            if (StrKit.notBlank(templateError)){
                retMap.put("errorDetail", templateError);
                retMap.put("errorMessage", "y");
            }else if (StringUtils.isNotBlank(hanl)) {
                retMap.put("errorDetail", hanl);
                retMap.put("errorMessage", "y");
            } else if ("overLimit".equalsIgnoreCase((String) map.get("overLimit"))) {
                retMap.put("overLimit", "y");
            } else {
                retMap.put("pass", "y");
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return retMap;
    }


    /**
     * 导入产品信息
     * @param params
     * @param in
     * @return
     */

    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importProjectParameterInfo(Map<String, String> params, InputStream in) {
        //产品参数code
        Map<String,String> ppc = new HashMap<>();
        ppc.put("基准发电小时数(小时)","BASIC_ELE_TIME");
        ppc.put("电价(元/kwh)","ELE_PRICE");
        ppc.put("收益分成比例(厂商)","MANUFACTURER_INCONE_RATIO");
        ppc.put("光伏板衰减率(年)","DECAY_RATE");
        ppc.put("运维费用(元/瓦/年)","MAINTENANCE_PRICE");
        ppc.put("保证金比例","DEPOSIT_RATIO");
        ppc.put("残值率","RESIDUALS_RATE");
        ppc.put("电价补贴","PRICE_SUBSIDY");
        ppc.put("投资资产到期处置价","DISPOSAL_PRICE");
        ppc.put("基准发电小时数(h)","BASIC_ELE_TIME");
        ppc.put("厂商收益分成比例","MANUFACTURER_INCONE_RATIO");
        ppc.put("光伏板衰减率","DECAY_RATE");
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "import");
        ExcelImportProjectInfoParameterNumberHandler handler=new ExcelImportProjectInfoParameterNumberHandler();
        handler.setStartSheet(1);
        handler.setStartRow(3);
        User user = UserUtils.getUser();
        try {
            new ExcelReader().readExcel(in, params.get("fileName"), handler);
            List<AddProjectInfoParameter> parameterList = handler.getParameterList();
            Collections.sort(parameterList, Comparator.comparing(AddProjectInfoParameter::getParameterName)
                    .thenComparing(AddProjectInfoParameter::getLeaseTermFrom));
            for (AddProjectInfoParameter parameter : parameterList) {
                String filingType = ProjectInfoUtil.getCompanyFilingTypeByCode(parameter.getCode());
                CrmCustomerIncomingProductPara ccipp = new CrmCustomerIncomingProductPara();
                ccipp.setProductParaName(parameter.getParameterName());
                ccipp.setProjectCode(parameter.getCode());
                for (Map.Entry<String, String> entry : ppc.entrySet()) {
                    if (entry.getKey().equals(parameter.getParameterName())){
                        ccipp.setProductParaCode(entry.getValue());
                    }
                }
                ccipp.setProductParaValue(parameter.getParameterValue());
                ccipp.setLeaseTermFrom(parameter.getLeaseTermFrom());
                ccipp.setLeaseTermTo(parameter.getLeaseTermTo());
                ccipp.setType(filingType);
                //获取根据产品code项目id
                List<String> proId = ProjectInfoUtil.getCompanyIdByCode(parameter.getCode());
                //租金信息阶段
                int i = 1;
                if (parameter.getParameterName().equals("设备单价(元/瓦)")){
//                    List<CrmProjectSetting> cps = ProjectInfoUtil.findProjectByCode(parameter.getCode());
//                    for (CrmProjectSetting projectSetting : cps) {
//                        projectSetting.setEpcPrice(new BigDecimal(parameter.getParameterValue()));
//                        projectSetting.setCreateBy(user.getId());
//                        projectSetting.setCreator(user.getUserName());
//                        projectSetting.setCreateTime(new Date());
//
//                        projectSettingDao.save(projectSetting);
//                    }
                    ccipp.setProductParaCode("EQUIPMENT_PRICE");
                    ProjectInfoUtil.updateEpc(new BigDecimal(parameter.getParameterValue()),user,parameter.getCode());
                }else if (parameter.getParameterName().equals("承租人收益(元/块光伏板/年)")){
                    ccipp.setProductParaCode("TENANT_INCOME_PRICE");
                    for (String s : proId) {
                        ProjectRentVariable projectRentVariable = new ProjectRentVariable();
                        projectRentVariable.setStage(i++);
                        projectRentVariable.setStartYear(Integer.parseInt(parameter.getLeaseTermFrom()));
                        projectRentVariable.setEndYear(Integer.parseInt(parameter.getLeaseTermTo()));
                        projectRentVariable.setUnitPrice(new BigDecimal(parameter.getParameterValue()));
                        projectRentVariable.setCreateTime(new Date());
                        projectRentVariable.setCreateBy(user.getId());
                        projectRentVariable.setCreateName(user.getUserName());
                        projectRentVariable.setStatus("0");
                        projectRentVariable.setProjectId(s);
                        variableDao.save(projectRentVariable);
                    }
                }
                if (!parameter.getParameterName().equals("电价补贴")){
                    paraDao.save(ccipp);
                }
            }
            retMap.put("pass", "y");
            retMap.put("materialList", handler.getParameterList());

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(" 导入产品参数信息异常,e:{}",e);
            throw new BusinessException(e.getMessage());
        }finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return retMap;
    }




    public Result checkImportProject(List<AddProjectInfoParameter> list, String paraName) {
        if (list.size() > 0) {
            list = list.stream()
                    .sorted(Comparator.comparing(p -> Integer.parseInt(p.getLeaseTermFrom())))
                    .collect(Collectors.toList());
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getLeaseTermFrom() == null && list.get(i).getLeaseTermFrom() =="" && list.get(i).getLeaseTermTo() == null && list.get(i).getLeaseTermTo() == ""){
                    break;
                }
                int leaseTermFrom = Integer.parseInt(list.get(i).getLeaseTermFrom());
                int leaseTermTo = Integer.parseInt(list.get(i).getLeaseTermTo());
                if (leaseTermTo < leaseTermFrom) {
                    return Result.fail(paraName + "，设置规则不匹配");
                }
                if (i == 0) {
                    if (leaseTermFrom != 1) {
                        return Result.fail(paraName + "，设置规则不匹配");
                    }
                }
                if (i == list.size() - 1) {
                    if (leaseTermTo != 25) {
                        return Result.fail(paraName + "，设置规则不匹配");
                    }
                }
                if (i > 0) {
                    int lastLeaseTermTo = Integer.parseInt(list.get(i-1).getLeaseTermTo());
                    if (leaseTermFrom - lastLeaseTermTo != 1) {
                        return Result.fail(paraName + "，设置规则不匹配");
                    }
                }
            }
        }
        return Result.ok();
    }

    public List<Record> getEntryProjectByEntryId(String entryId){
        return projectSettingDao.getEntryProjectByEntryId(entryId);
    }
}
