package com.sifang.modules.insurance.service;

import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.dao.CrmCustomerIncomingApplicationDao;
import com.sifang.modules.customer.utils.CustomerEntryUtil;
import com.sifang.modules.insurance.dao.CrmCustomerNoSystemEntryInsuranceDao;
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.CrmCustomerNoSystemEntryInsurance;
import com.sifang.modules.insurance.entity.CrmInsuranceList;
import com.sifang.modules.insurance.handler.InsuranceNoSystemExcelImportHandler;
import com.sifang.modules.order.utils.excelExt.ExcelReader;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
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.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import com.sifang.modules.sys.util.insurance.InsuranceBizService;
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 java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class CrmCustomerNoSystemEntryInsuranceService extends BaseService {

    @Autowired
    CrmCustomerNoSystemEntryInsuranceDao noSystemEntryInsuranceDao;

    @Autowired
    CustomerEntryInsuranceDao entryInsuranceDao;

    @Autowired
    InsuranceListDao insuranceListDao;

    @Autowired
    CrmCustomerIncomingApplicationDao incomingApplicationDao;

    @Autowired
    InsuranceBizService insuranceBizService;

    @Autowired
    CustomerEntryInsuranceInsuredDao insuranceInsuredDao;

    public void list(Map<String, String> queryParams, LayuiPage page) {
        page.setData(noSystemEntryInsuranceDao.list(queryParams, page));
        page.setCount(noSystemEntryInsuranceDao.queryCount(queryParams));
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeSign(String id, String removeSign) {
        CrmCustomerNoSystemEntryInsurance insurance = noSystemEntryInsuranceDao.get(id);
        insurance.setRemoveSign(removeSign);
        noSystemEntryInsuranceDao.save(insurance);
    }

    /**
     * 校验导入非本系统电站保单数据
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> checkImportInsuranceNoSystem(Map<String, String> params, InputStream in) {
        Map<String, Object> resultMap = Maps.newHashMap();
        resultMap.put("operType", "check");
        InsuranceNoSystemExcelImportHandler handler = new InsuranceNoSystemExcelImportHandler();
        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 = findPowerStationCode();
            List<CrmCustomerNoSystemEntryInsurance> retList = handler.getRetList();
            Set<String> existCodeSet = new HashSet<>(existsCode);
            int i = 1;
            for(CrmCustomerNoSystemEntryInsurance insurance :retList){
                if(!existCodeSet.add(insurance.getItemNo())){
                    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> findPowerStationCode() {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT item_no")
                .line("from crm_customer_no_system_entry_insurance")
                .line("where 1=1");
        return Db.query(builder.build());
    }

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

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

            retMap.put("pass", "y");
            List<CrmCustomerNoSystemEntryInsurance> exeSqlParams = handler.getRetList();
            if (exeSqlParams != null && exeSqlParams.size() > 0) {
                importEntryInsuranceNoSystemData(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 importEntryInsuranceNoSystemData(List<CrmCustomerNoSystemEntryInsurance> paramList) {
        Date time = new Date();
        User user = UserUtils.getUser();
        for (CrmCustomerNoSystemEntryInsurance item : paramList) {
            item.setCreateBy(user.getId());
            item.setCreateTime(time);
            item.setStatus("2");
            item.setPolicyType("1");
            item.setSource("0");
            item.setRemoveSign("0");
            item.setNum(1);
            CrmInsuranceList insuranceSetting = insuranceListDao.findInsuranceByName("户用财产险");
            item.setInsuranceId(insuranceSetting.getId());
            item.setInsuranceName(insuranceSetting.getName());
            item.setInsuranceType(insuranceSetting.getType());
            item.setInsuranceCompanyName(insuranceSetting.getCompanyName());
            item.setRequestNo(UUID.randomUUID().toString());

            if(item.getPartnerName().contains("越秀")){
                Long maxVersion = incomingApplicationDao.getMaxVersion("01");
                String inputPieceId= "NOSYS"+CustomerEntryUtil.addZero(CustomerEntryUtil.getJJPrefix("01"),maxVersion+1);
                item.setInputPieceId(inputPieceId);
            }
        }
        noSystemEntryInsuranceDao.save(paramList);
        return Result.ok();
    }

    public CrmCustomerNoSystemEntryInsurance get(String id) {
        return noSystemEntryInsuranceDao.get(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Void> rePushNoSystemEntryInsurance(CrmCustomerNoSystemEntryInsurance insurance) {
        String processDetail = insurance.getProcessDetail();
        String insuranceId = insurance.getId();
        insuranceInsuredDao.deleteByInsuranceId(insuranceId);
        return insuranceBizService.rePushNoSystemEntryInsurance(processDetail, insurance, UserUtils.getUser());
    }

    public Record selectDetailById(String id) {
        return noSystemEntryInsuranceDao.selectDetailById(id);
    }

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

}
