package com.sifang.modules.insurance.service;

import cn.hutool.core.util.ZipUtil;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.dao.CrmCustomerIncomingApplicationInsuranceDao;
import com.sifang.modules.customer.dao.CustomerEntryDao;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.insurance.constants.InsuranceOrderConstants;
import com.sifang.modules.insurance.dao.CustomerEntryInsuranceDao;
import com.sifang.modules.insurance.dao.CustomerEntryInsuranceInsuredDao;
import com.sifang.modules.insurance.dao.InsuranceListDao;
import com.sifang.modules.insurance.entity.CrmCustomerEntryInsurance;
import com.sifang.modules.insurance.entity.CrmCustomerEntryInsuranceInsured;
import com.sifang.modules.insurance.entity.CrmCustomerNoSystemEntryInsurance;
import com.sifang.modules.insurance.entity.CrmInsuranceList;
import com.sifang.modules.insurance.handler.InsuranceExcelImportHandler;
import com.sifang.modules.insurance.handler.InsuranceNoSystemExcelImportHandler;
import com.sifang.modules.insurance.request.EditInsurantOrderReq;
import com.sifang.modules.order.utils.Target;
import com.sifang.modules.order.utils.WebPageFunUtils;
import com.sifang.modules.order.utils.excelExt.ExcelReader;
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.ProjectInfoUtil;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.partnerManagement.dao.PartnerDao;
import com.sifang.modules.sunshine.partnerManagement.entity.CrmPartner;
import com.sifang.modules.supply.handler.BarcodeExcelImportHandler;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyBarcode;
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.DateUtils;
import com.sifang.modules.sys.common.utils.FileUtils;
import com.sifang.modules.sys.util.AsyncLoader;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import com.sifang.modules.sys.util.insurance.InsuranceBizService;
import okhttp3.OkHttpClient;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.nio.file.Files;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author DQChen
 * @date 2024-01-19 11:29
 */
@Service
public class CustomerEntryInsuranceService extends BaseService {

    @Autowired
    CustomerEntryInsuranceDao entryInsuranceDao;

    @Autowired
    InsuranceListDao insuranceListDao;

    @Autowired
    CustomerEntryInsuranceInsuredDao insuranceInsuredDao;

    @Autowired
    ProjectCompanyDao companyDao;

    @Autowired
    PartnerDao partnerDao;

    @Autowired
    ProjectSettingDao projectSettingDao;

    @Autowired
    OkHttpClient okHttpClient;

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

    @Autowired
    CustomerEntryDao entryDao;

    @Autowired
    private CrmCustomerIncomingApplicationInsuranceDao applicationInsuranceDao;

    @Autowired
    private InsuranceBizService insuranceBizService;


    /**
     * 保险记录列表
     *
     * @param queryParams
     * @param page
     */
    public void list(Map<String, String> queryParams, LayuiPage page) {
        page.setData(entryInsuranceDao.list(queryParams, page));
        page.setCount(entryInsuranceDao.queryCount(queryParams));
    }

    public void batchDownload(List<String> insuranceIds, OutputStream outputStream) throws IOException, InterruptedException {
        if (CollectionUtils.isEmpty(insuranceIds)) {
            throw new BusinessException("未指定下载目标");
        }
        List<Record> insuranceList = entryInsuranceDao.getByIds(insuranceIds);
        String tmpDir = Files.createTempDirectory("insuranceTmp").toFile().getAbsolutePath();
        File tmpSaveDir = new File(tmpDir, "保单");
        if (!tmpSaveDir.mkdirs()) {
            throw new BusinessException("创建下载目录失败");
        }
        try {
            AsyncLoader asyncLoader = new AsyncLoader(okHttpClient, tmpSaveDir);
            List<String> entryIds = insuranceList.stream().map(e -> e.getStr("entry_id")).collect(Collectors.toList());
            List<Record> tenantNameByIds = entryDao.selectTenantNameByIds(entryIds);
            Map<String, String> tenantNameByIdsMap = tenantNameByIds.stream()
                    .collect(Collectors.toMap(e -> e.getStr("id"), e -> e.getStr("tenant_name"), (a, b) -> a));

            int index = 0;
            for (Record ins : insuranceList) {
                String u = ins.getStr("down_url");
                if (StringUtils.isNotBlank(u) && !u.startsWith("http")) {
                    u = filePrePath + u;
                    index++;
                    asyncLoader.load(u, index + "_" + tenantNameByIdsMap.get(ins.getStr("entry_id")));
                }
            }
            asyncLoader.awaitResult();
            File zipFile = new File(tmpDir, "保单.zip");
            File zip = ZipUtil.zip(tmpSaveDir.getAbsolutePath(), zipFile.getAbsolutePath());
            try (FileInputStream inputStream = new FileInputStream(zip)) {
                IOUtils.copy(inputStream, outputStream);
            }
        } finally {
            FileUtils.deleteDir(new File(tmpDir));
        }
    }

    public CrmCustomerEntryInsurance get(String id) {
        return entryInsuranceDao.get(id);
    }

    public Record selectDetailById(String id, String status) {
        return entryInsuranceDao.selectDetailById(id, status);
    }

    public CrmCustomerEntryInsurance selectById(String id) {
        return entryInsuranceDao.get(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public Result doEdit(EditInsurantOrderReq orderReq) {
        User user = UserUtils.getUser();
        CrmCustomerEntryInsurance insurance = entryInsuranceDao.get(orderReq.getId());
        CustomerEntry customerEntry = entryDao.get(insurance.getEntryId());
        if(CustomerEntryConstants.ENTRY_STATUS_YWC.equals(customerEntry.getStatus()) ||
                (CustomerEntryConstants.ENTRY_STATUS_YWC.equals(customerEntry.getStatus()) &&
                        StringUtil.equalsAny(customerEntry.getMergeFlag(), CustomerEntryConstants.MERGE_FLAG_ZFSHZ,
                                CustomerEntryConstants.MERGE_FLAG_ZFSHTG))) {
            return Result.fail("电站已并网验收通过，不可再修改保单");
        }

        CrmInsuranceList insuranceSet = insuranceListDao.get(orderReq.getInsuranceId());
        CrmProjectSetting projectSetting = projectSettingDao.get(customerEntry.getProjectId());
        if (!projectSetting.getInsuranceId().equals(insuranceSet.getId())) {
            return Result.fail("选择的保险产品必须与产品信息设置的保持一致！");
        }
        //投保人
        ProjectCompanySettings projectCompanySettings = companyDao.get(insuranceSet.getPolicyholder());
        //被保人
        CrmPartner crmPartner = partnerDao.get(insuranceSet.getInsurant());
        //被保人2
        ProjectCompanySettings projectCompanySettings1 = companyDao.get(customerEntry.getProjectCompanyId());

        insurance.setNumber(orderReq.getNumber());
        insurance.setInsuranceId(orderReq.getInsuranceId());
        insurance.setInsuranceName(insuranceSet.getName());
        insurance.setInsuranceType(insuranceSet.getType());
        insurance.setInsuranceCompanyName(insuranceSet.getCompanyName());
        insurance.setPolicyholder(projectCompanySettings.getName());
        insurance.setInsurant(crmPartner.getName() + "," + projectCompanySettings1.getName());
        insurance.setInsuranceMoney(orderReq.getInsuranceMoney());
        insurance.setPrice(orderReq.getPrice());
        insurance.setStartTime(orderReq.getStartTime());
        insurance.setEndTime(orderReq.getEndTime());
        insurance.setUpdateBy(user.getId());
        insurance.setUpdateTime(new Date());
        insurance.setModifier(user.getUserName());
        if (StringUtil.isNotBlank(orderReq.getDownUrl())) {
            insurance.setDownUrl(orderReq.getDownUrl());
        }

        Target ta = new Target();
        ta.setD(DateUtils.getDateTime());
        ta.setP(user.getUserName());
        ta.setC("修改数据");
        String newProcess = WebPageFunUtils.appendOrderProcessDetail(ta, insurance.getProcessDetail());
        insurance.setProcessDetail(newProcess);
        entryInsuranceDao.save(insurance);

        //删除之前的记录
        insuranceInsuredDao.deleteByInsuranceId(insurance.getId());

        //投保人信息
        CrmCustomerEntryInsuranceInsured insuredPolicyholder = new CrmCustomerEntryInsuranceInsured();
        insuredPolicyholder.setInsuranceId(insurance.getId());
        insuredPolicyholder.setInsuredType(InsuranceOrderConstants.INSURED_TYPE_COMPANY);
        insuredPolicyholder.setMobile(projectCompanySettings.getTelephone());
        insuredPolicyholder.setIdentifyType(InsuranceOrderConstants.IDENTIFY_TYPE_BUSINESS_LICENSE);
        insuredPolicyholder.setIdentifyNumber(projectCompanySettings.getEnterpriseQualificationNumber());
        insuredPolicyholder.setInsuredNature("4");//法人
        insuredPolicyholder.setIsInsuredRelation("00");
        insuredPolicyholder.setInsuredFlag(InsuranceOrderConstants.INSURED_FLAG_POLICYHOLDER);
        insuredPolicyholder.setInsuredName(projectCompanySettings.getChargePerson());
        insuredPolicyholder.setTargetId(projectCompanySettings.getId());
        insuranceInsuredDao.save(insuredPolicyholder);

        //被保人信息
        CrmCustomerEntryInsuranceInsured insured = new CrmCustomerEntryInsuranceInsured();
        insured.setInsuranceId(insurance.getId());
        insured.setInsuredType(InsuranceOrderConstants.INSURED_TYPE_COMPANY);
        insured.setMobile(crmPartner.getMobile());
        insured.setIdentifyType(InsuranceOrderConstants.IDENTIFY_TYPE_BUSINESS_LICENSE);
        insured.setIdentifyNumber(crmPartner.getUnifiedCreditCode());
        insured.setIsInsuredRelation("99");
        insured.setInsuredFlag(InsuranceOrderConstants.INSURED_FLAG_INSURANT);
        insured.setInsuredNature("4");//法人
        insured.setInsuredName(crmPartner.getPersonInCharge());
        insured.setTargetId(crmPartner.getId());
        insuranceInsuredDao.save(insured);

        CrmCustomerEntryInsuranceInsured insured2 = new CrmCustomerEntryInsuranceInsured();
        insured2.setInsuranceId(insurance.getId());
        insured2.setInsuredType(InsuranceOrderConstants.INSURED_TYPE_COMPANY);
        insured2.setMobile(projectCompanySettings1.getTelephone());
        insured2.setIdentifyType(InsuranceOrderConstants.IDENTIFY_TYPE_BUSINESS_LICENSE);
        insured2.setIdentifyNumber(projectCompanySettings1.getEnterpriseQualificationNumber());
        insured2.setIsInsuredRelation("99");
        insured2.setInsuredFlag(InsuranceOrderConstants.INSURED_FLAG_INSURANT);
        insured2.setInsuredNature("4");//法人
        insured2.setInsuredName(projectCompanySettings1.getChargePerson());
        insured2.setTargetId(projectCompanySettings1.getId());
        insuranceInsuredDao.save(insured2);

        //原保单信息表同步
        // 删除之前的记录
        applicationInsuranceDao.deleteByInsuranceId(insurance.getId());
        applicationInsuranceDao.updateEntityInfo(insurance);
        return Result.ok();
    }

    /**
     * 推送记录列表
     */
    public void pushList(Map<String, String> queryParams, LayuiPage page) {
        page.setData(entryInsuranceDao.pushList(queryParams, page));
        page.setCount(entryInsuranceDao.pushListCount(queryParams));
    }
    @Transactional(rollbackFor = Exception.class)
    public Result doAdd(EditInsurantOrderReq orderReq) {
        User user = UserUtils.getUser();
        CustomerEntry customerEntry = entryDao.get(orderReq.getEntryId());
        CrmCustomerEntryInsurance insurance = new CrmCustomerEntryInsurance();
        CrmInsuranceList insuranceSet = insuranceListDao.get(orderReq.getInsuranceId());
        CrmProjectSetting projectSetting = projectSettingDao.get(customerEntry.getProjectId());
        if (!projectSetting.getInsuranceId().equals(insuranceSet.getId())) {
            return Result.fail("选择的保险产品必须与产品信息设置的保持一致！");
        }
        //投保人
        ProjectCompanySettings projectCompanySettings = companyDao.get(insuranceSet.getPolicyholder());
        //被保人1
        CrmPartner crmPartner = partnerDao.get(insuranceSet.getInsurant());
        //被保人2
        ProjectCompanySettings projectCompanySettings1 = companyDao.get(customerEntry.getProjectCompanyId());

        Date now = new Date();
        insurance.setEntryId(orderReq.getEntryId());
        insurance.setNumber(orderReq.getNumber());
        insurance.setInsuranceId(orderReq.getInsuranceId());
        insurance.setInsuranceName(insuranceSet.getName());
        insurance.setInsuranceType(insuranceSet.getType());
        insurance.setInsuranceCompanyName(insuranceSet.getCompanyName());
        insurance.setPolicyholder(projectCompanySettings.getName());
        insurance.setInsurant(crmPartner.getName() + "," + projectCompanySettings1.getName());
        insurance.setInsuranceMoney(orderReq.getInsuranceMoney());
        insurance.setPrice(orderReq.getPrice());
        insurance.setStartTime(orderReq.getStartTime());
        insurance.setEndTime(orderReq.getEndTime());
        insurance.setUpdateBy(user.getId());
        insurance.setUpdateTime(now);
        insurance.setModifier(user.getUserName());
        insurance.setDownUrl(orderReq.getDownUrl());
        insurance.setCreateBy(user.getId());
        insurance.setCreateTime(now);
        insurance.setCreator(user.getUserName());
        insurance.setNum(1);
        String address = "";
        if(StringUtil.isNotBlank(customerEntry.getProvince())){
            address += customerEntry.getProvince();
        }
        if(StringUtil.isNotBlank(customerEntry.getCity()) && !customerEntry.getProvince().equals(customerEntry.getCity())){
            address += customerEntry.getCity();
        }
        if(StringUtil.isNotBlank(customerEntry.getArea())){
            address += customerEntry.getArea();
        }
        insurance.setAddress(address);
        insurance.setSource(InsuranceOrderConstants.SOURCE_SELF);
        insurance.setStatus(InsuranceOrderConstants.STATUS_SUCCESS);

        Target ta = new Target();
        ta.setD(DateUtils.getDateTime());
        ta.setP(user.getUserName());
        ta.setC("购买保单");
        String newProcess = WebPageFunUtils.appendOrderProcessDetail(ta, insurance.getProcessDetail());
        insurance.setProcessDetail(newProcess);
        entryInsuranceDao.save(insurance);

        //投保人信息
        CrmCustomerEntryInsuranceInsured insuredPolicyholder = new CrmCustomerEntryInsuranceInsured();
        insuredPolicyholder.setInsuranceId(insurance.getId());
        insuredPolicyholder.setInsuredType(InsuranceOrderConstants.INSURED_TYPE_COMPANY);
        insuredPolicyholder.setMobile(projectCompanySettings.getTelephone());
        insuredPolicyholder.setIdentifyType(InsuranceOrderConstants.IDENTIFY_TYPE_BUSINESS_LICENSE);
        insuredPolicyholder.setIdentifyNumber(projectCompanySettings.getEnterpriseQualificationNumber());
        insuredPolicyholder.setInsuredNature("4");//法人
        insuredPolicyholder.setIsInsuredRelation("00");
        insuredPolicyholder.setInsuredFlag(InsuranceOrderConstants.INSURED_FLAG_POLICYHOLDER);
        insuredPolicyholder.setInsuredName(projectCompanySettings.getChargePerson());
        insuredPolicyholder.setTargetId(projectCompanySettings.getId());
        insuranceInsuredDao.save(insuredPolicyholder);

        //被保人信息
        CrmCustomerEntryInsuranceInsured insured = new CrmCustomerEntryInsuranceInsured();
        insured.setInsuranceId(insurance.getId());
        insured.setInsuredType(InsuranceOrderConstants.INSURED_TYPE_COMPANY);
        insured.setMobile(crmPartner.getMobile());
        insured.setIdentifyType(InsuranceOrderConstants.IDENTIFY_TYPE_BUSINESS_LICENSE);
        insured.setIdentifyNumber(crmPartner.getUnifiedCreditCode());
        insured.setIsInsuredRelation("99");
        insured.setInsuredFlag(InsuranceOrderConstants.INSURED_FLAG_INSURANT);
        insured.setInsuredNature("4");//法人
        insured.setInsuredName(crmPartner.getPersonInCharge());
        insured.setTargetId(crmPartner.getId());
        insuranceInsuredDao.save(insured);

        //被保人信息
        CrmCustomerEntryInsuranceInsured insured2 = new CrmCustomerEntryInsuranceInsured();
        insured2.setInsuranceId(insurance.getId());
        insured2.setInsuredType(InsuranceOrderConstants.INSURED_TYPE_COMPANY);
        insured2.setMobile(projectCompanySettings1.getTelephone());
        insured2.setIdentifyType(InsuranceOrderConstants.IDENTIFY_TYPE_BUSINESS_LICENSE);
        insured2.setIdentifyNumber(projectCompanySettings1.getEnterpriseQualificationNumber());
        insured2.setIsInsuredRelation("99");
        insured2.setInsuredFlag(InsuranceOrderConstants.INSURED_FLAG_INSURANT);
        insured2.setInsuredNature("4");//法人
        insured2.setInsuredName(projectCompanySettings1.getChargePerson());
        insured2.setTargetId(projectCompanySettings1.getId());
        insuranceInsuredDao.save(insured2);

        //原保单信息同步
        applicationInsuranceDao.updateEntityInfo(insurance);
        return Result.ok();
    }

    public List<Record> selectEntryForInsurance(String stationCode) {
        return entryInsuranceDao.selectEntryForInsurance(stationCode);
    }

    public List<Record> findEntryForInsurance() {
        return entryInsuranceDao.findEntryForInsurance();
    }

    @Transactional(rollbackFor = Exception.class)
    public void getlnsuranceTask(String id) throws ParseException {

        CrmCustomerEntryInsurance oldInsurance = entryInsuranceDao.get(id);
        Map<String, String> queryParams = new HashMap<>();
        queryParams.put("policyType","1");
        queryParams.put("status","1");
        queryParams.put("powerStationCode",oldInsurance.getItemNo());
        long num = entryInsuranceDao.pushListCount(queryParams);
        //设置日期格式
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前时间
        Date dt = new Date();
        String stringDate = formatter.format(dt);
        Date date = formatter.parse(String.valueOf(oldInsurance.getEndTime()));
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        //保险到期时间
        ca.add(Calendar.DAY_OF_MONTH, 1);
        //电站保险到期前7天生成待续保电站记录
        ca.add(Calendar.WEEK_OF_MONTH, -1);
        date = ca.getTime();
        String xbTime  = formatter.format(date);
        if(stringDate.equals(xbTime) && num == 0){
            CustomerEntry customerEntry = entryDao.get(oldInsurance.getEntryId());
            //标记拆除的电站不生成续保记录
            if ("1".equals(customerEntry.getRemoveSign())){
                return;
            }
            String insuranceId = ProjectInfoUtil.getInsuranceIdByName("户用财产险");
            CrmInsuranceList insuranceSet = insuranceListDao.get(insuranceId);
            //投保人
            ProjectCompanySettings projectCompanySettings = companyDao.get(insuranceSet.getPolicyholder());
            //被保人1
            CrmPartner crmPartner = partnerDao.get(insuranceSet.getInsurant());
            //被保人2
            ProjectCompanySettings projectCompanySettings1 = companyDao.get(customerEntry.getProjectCompanyId());


            CrmCustomerEntryInsurance newInsurance = new CrmCustomerEntryInsurance();
            Date now = new Date();
            newInsurance.setEntryId(oldInsurance.getEntryId());
            newInsurance.setNumber(oldInsurance.getNumber());
            newInsurance.setInsuranceId(insuranceId);
            newInsurance.setInsuranceName(insuranceSet.getName());
            newInsurance.setInsuranceType(insuranceSet.getType());
            newInsurance.setInsuranceCompanyName(oldInsurance.getInsuranceCompanyName());
            newInsurance.setPolicyholder(oldInsurance.getPolicyholder());
            newInsurance.setInsurant(oldInsurance.getInsurant());
            newInsurance.setInsuranceMoney(oldInsurance.getInsuranceMoney());
            newInsurance.setPrice(oldInsurance.getPrice());


            Date date1 = formatter.parse(String.valueOf(oldInsurance.getEndTime()));
            Calendar ca1 = Calendar.getInstance();
            ca1.setTime(date1);
            Calendar ca2 = Calendar.getInstance();
            ca2.setTime(date1);
            //保险到期时间
            ca1.add(Calendar.DAY_OF_MONTH, 1);
            newInsurance.setStartTime(ca1.getTime());
            //电站保险到期前7天生成待续保电站记录
            ca2.add(Calendar.YEAR, 1);
            newInsurance.setEndTime(ca2.getTime());

            newInsurance.setUpdateBy(oldInsurance.getId());
            newInsurance.setUpdateTime(now);
            newInsurance.setModifier("system");
            newInsurance.setDownUrl("");
            newInsurance.setCreateBy("1");
            newInsurance.setCreateTime(now);
            newInsurance.setCreator("system");
            newInsurance.setNum(1);
            newInsurance.setAddress(oldInsurance.getAddress());
            newInsurance.setSource(InsuranceOrderConstants.SOURCE_SELF);
            newInsurance.setStatus(InsuranceOrderConstants.STATUS_EXPIRE);
            newInsurance.setRenewalStatus("新建");

            Target ta = new Target();
            ta.setD(DateUtils.getDateTime());
            ta.setP("system");
            ta.setC("购买保单");
            String newProcess = WebPageFunUtils.appendOrderProcessDetail(ta, newInsurance.getProcessDetail());
            newInsurance.setProcessDetail(newProcess);
            //保单状态 0：首次投保 1：续保
            newInsurance.setPolicyType(InsuranceOrderConstants.POLICY_TYPE_CONTINUE);
            entryInsuranceDao.save(newInsurance);

            //投保人信息
            CrmCustomerEntryInsuranceInsured insuredPolicyholder = new CrmCustomerEntryInsuranceInsured();
            insuredPolicyholder.setInsuranceId(newInsurance.getId());
            insuredPolicyholder.setInsuredType(InsuranceOrderConstants.INSURED_TYPE_COMPANY);
            insuredPolicyholder.setMobile(projectCompanySettings.getTelephone());
            insuredPolicyholder.setIdentifyType(InsuranceOrderConstants.IDENTIFY_TYPE_BUSINESS_LICENSE);
            insuredPolicyholder.setIdentifyNumber(projectCompanySettings.getEnterpriseQualificationNumber());
            insuredPolicyholder.setInsuredNature("4");//法人
            insuredPolicyholder.setIsInsuredRelation("00");
            insuredPolicyholder.setInsuredFlag(InsuranceOrderConstants.INSURED_FLAG_POLICYHOLDER);
            insuredPolicyholder.setInsuredName(projectCompanySettings.getChargePerson());
            insuredPolicyholder.setTargetId(projectCompanySettings.getId());
            insuranceInsuredDao.save(insuredPolicyholder);

            //被保人信息
            CrmCustomerEntryInsuranceInsured insured = new CrmCustomerEntryInsuranceInsured();
            insured.setInsuranceId(newInsurance.getId());
            insured.setInsuredType(InsuranceOrderConstants.INSURED_TYPE_COMPANY);
            insured.setMobile(crmPartner.getMobile());
            insured.setIdentifyType(InsuranceOrderConstants.IDENTIFY_TYPE_BUSINESS_LICENSE);
            insured.setIdentifyNumber(crmPartner.getUnifiedCreditCode());
            insured.setIsInsuredRelation("99");
            insured.setInsuredFlag(InsuranceOrderConstants.INSURED_FLAG_INSURANT);
            insured.setInsuredNature("4");//法人
            insured.setInsuredName(crmPartner.getPersonInCharge());
            insured.setTargetId(crmPartner.getId());
            insuranceInsuredDao.save(insured);

            //被保人信息
            CrmCustomerEntryInsuranceInsured insured2 = new CrmCustomerEntryInsuranceInsured();
            insured2.setInsuranceId(newInsurance.getId());
            insured2.setInsuredType(InsuranceOrderConstants.INSURED_TYPE_COMPANY);
            insured2.setMobile(projectCompanySettings1.getTelephone());
            insured2.setIdentifyType(InsuranceOrderConstants.IDENTIFY_TYPE_BUSINESS_LICENSE);
            insured2.setIdentifyNumber(projectCompanySettings1.getEnterpriseQualificationNumber());
            insured2.setIsInsuredRelation("99");
            insured2.setInsuredFlag(InsuranceOrderConstants.INSURED_FLAG_INSURANT);
            insured2.setInsuredNature("4");//法人
            insured2.setInsuredName(projectCompanySettings1.getChargePerson());
            insured2.setTargetId(projectCompanySettings1.getId());
            insuranceInsuredDao.save(insured2);

            //原保单信息同步
            applicationInsuranceDao.updateEntityInfo(newInsurance);
        }
    }

    public void uploadInsuranceFile(String id, String downUrl) {
        CrmCustomerEntryInsurance insurance = entryInsuranceDao.get(id);
        insurance.setDownUrl(downUrl);
        entryInsuranceDao.save(insurance);
    }

    /**
     * 校验导入保单数据
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> checkImportInsurance(Map<String, String> params, InputStream in) {
        Map<String, Object> resultMap = Maps.newHashMap();
        resultMap.put("operType", "check");
        InsuranceExcelImportHandler handler = new InsuranceExcelImportHandler();
        handler.setStartSheet(1);
        handler.setStartRow(1);
        try {
            new ExcelReader().check(in, params.get("extName"), handler);
            Map<String, Object> map = (Map<String, Object>) handler.getHandlerResult();
            String errorMsg = (String) map.get("TemplateError");
            if (!handler.isCheckFlag()) {
                handler.appendErrorDetail("<p>未填充数据</p>");
            }
            List<String> existsCode = findPowerStationCodeNoSystem();
            List<CrmCustomerEntryInsurance> retList = handler.getRetList();
            Set<String> existCodeSet = new HashSet<>(existsCode);
            int i = 1;
            for(CrmCustomerEntryInsurance insurance :retList){
//                if(!existCodeSet.add(insurance.getPowerStationCode())){
//                    handler.appendErrorDetail("第" + (i + 1) + "行电站编码已存在</p>");
//                }
                i++;
            }
            String errorDetail = handler.getErrorDetail();
            if (StringUtils.isNotBlank(errorMsg)) {
                resultMap.put("errorDetail", errorMsg);
                resultMap.put("errorMessage", "y");
            } else if (StringUtils.isNotBlank(errorDetail)) {
                resultMap.put("errorDetail", errorDetail);
                resultMap.put("errorMessage", "y");
            } else if ("overLimit".equalsIgnoreCase((String) map.get("overLimit"))) {
                resultMap.put("overLimit", "y");
            } else {
                resultMap.put("pass", "y");
            }
        } catch (Exception e) {
            resultMap.put("errorDetail", "系统出错啦~");
            resultMap.put("errorMessage", "y");
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultMap;
    }

    public List<String> findPowerStationCodeNoSystem() {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT power_station_code")
                .line("from crm_customer_entry")
                .line("where 1=1 and status != 'b'");
        return Db.query(builder.build());
    }

    /**
     * 导入物料数据
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importInsurance(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "import");
        InsuranceExcelImportHandler handler = new InsuranceExcelImportHandler();
        handler.setStartSheet(1);
        handler.setStartRow(2);

        try {
            new ExcelReader().readExcel(in, params.get("fileName"), handler);

            retMap.put("pass", "y");
            List<CrmCustomerEntryInsurance> exeSqlParams = handler.getRetList();
            if (exeSqlParams != null && exeSqlParams.size() > 0) {
                importEntryInsurance(exeSqlParams);
            }
            retMap.put("successCount", exeSqlParams.size());//成功条数
        } catch (Exception e) {
            e.printStackTrace();
            retMap.put("pass", "no");
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return retMap;
    }

    public Result importEntryInsurance(List<CrmCustomerEntryInsurance> paramList) {
        Date time = new Date();
        User user = UserUtils.getUser();
        for (CrmCustomerEntryInsurance item : paramList) {
            item.setCreateBy(user.getId());
            item.setCreateTime(time);
            item.setStatus("2");
            item.setPolicyType("1");
            item.setSource("0");
            item.setNum(1);
            CustomerEntry customerEntry =  entryDao.findCustomerEntryById(item.getItemNo());
            CrmInsuranceList insuranceSetting = insuranceBizService.getInsuranceSetting(customerEntry);
            item.setInsuranceId(insuranceSetting.getId());
            item.setInsuranceName(insuranceSetting.getName());
            item.setInsuranceType(insuranceSetting.getType());
            item.setInsuranceCompanyName(insuranceSetting.getCompanyName());

            item.setEntryId(customerEntry.getId());
            item.setRequestNo(customerEntry.getId());
        }
        entryInsuranceDao.save(paramList);
        return Result.ok();
    }



}
