package com.yifu.cloud.plus.v1.yifu.insurances.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Sets;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.ArchivesDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.insurances.constants.InsurancesConstants;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.*;
import com.yifu.cloud.plus.v1.yifu.insurances.mapper.TInsuranceDetailMapper;
import com.yifu.cloud.plus.v1.yifu.insurances.service.*;
import com.yifu.cloud.plus.v1.yifu.insurances.util.BeanCopyUtils;
import com.yifu.cloud.plus.v1.yifu.insurances.util.LocalDateUtil;
import com.yifu.cloud.plus.v1.yifu.insurances.util.ValidityUtil;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author licancan
 * @description 针对表【t_insurance_detail(商险明细表)】的数据库操作Service实现
 * @date 2022-07-18 16:20:16
 */
@Service
public class TInsuranceDetailServiceImpl extends ServiceImpl<TInsuranceDetailMapper, TInsuranceDetail> implements TInsuranceDetailService {
	@Resource
	@Lazy
	private TInsuranceCompanyService tInsuranceCompanyService;
	@Resource
	@Lazy
	private TInsuranceTypeService tInsuranceTypeService;
	@Resource
	@Lazy
	private TInsuranceTypeStandardService tInsuranceTypeStandardService;
	@Resource
	private TInsuranceReplaceService tInsuranceReplaceService;
	@Resource
	private ArchivesDaprUtil archivesDaprUtil;

	/***********************商险办理********************************/
	/**
	 * 投保办理分页查询
	 *
	 * @param page
	 * @param param
	 * @return {@link IPage < InsuranceListVO >}
	 * @author licancan
	 */
	@Override
	public IPage<InsuranceListVO> getInsuranceListPage(Page<InsuranceListVO> page, InsuranceListParam param) {
		//todo 根据登录人获取数据权限
		IPage<InsuranceListVO> insuranceList = baseMapper.getInsuranceListPage(page,param);
		if (CollectionUtils.isNotEmpty(insuranceList.getRecords())){
			//根据项目编码获取项目名称
			List<String> collect = insuranceList.getRecords().stream().map(e -> e.getDeptNo()).distinct().collect(Collectors.toList());
			R<Map> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(collect);
			if (null != setInfoByCodes && setInfoByCodes.getCode() != CommonConstants.SUCCESS && MapUtils.isNotEmpty(setInfoByCodes.getData())) {
				Map data = setInfoByCodes.getData();
				for (InsuranceListVO record : insuranceList.getRecords()) {
					JSONObject jsonObject = (JSONObject) data.get(record.getDeptNo());
					if (null != jsonObject){
						record.setProjectName(Optional.ofNullable(jsonObject.getString("departName")).orElse(""));
					}
				}
			}
		}
		return insuranceList;
	}

	/**
	 * 投保办理不分页查询
	 *
	 * @param param
	 * @return {@link List<InsuranceListVO>}
	 * @author licancan
	 */
	@Override
	public List<InsuranceListVO> getInsuranceList(InsuranceListParam param) {
		//todo 根据登录人获取数据权限
		List<InsuranceListVO> insuranceList = baseMapper.getInsuranceList(param);
		if (CollectionUtils.isNotEmpty(insuranceList)){
			//根据项目编码获取项目名称
			List<String> collect = insuranceList.stream().map(e -> e.getDeptNo()).distinct().collect(Collectors.toList());
			R<Map> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(collect);
			if (null != setInfoByCodes && setInfoByCodes.getCode() != CommonConstants.SUCCESS && MapUtils.isNotEmpty(setInfoByCodes.getData())) {
				Map data = setInfoByCodes.getData();
				for (InsuranceListVO record : insuranceList) {
					JSONObject jsonObject = (JSONObject) data.get(record.getDeptNo());
					if (null != jsonObject){
						record.setProjectName(Optional.ofNullable(jsonObject.getString("departName")).orElse(""));
					}
				}
			}
		}
		return insuranceList;
	}

	/**
	 * 商险新增
	 *
	 * @param paramList
	 * @return {@link R <List<InsuranceAddParam>>}
	 * @author licancan
	 */
	@Override
	@Transactional(rollbackFor = {Exception.class})
	public R<List<InsuranceAddParam>> addInsurance(List<InsuranceAddParam> paramList) {
		if (CollectionUtils.isEmpty(paramList)){
			return R.failed(CommonConstants.DATA_CAN_NOT_EMPTY);
		}
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		Map<String, List<InsuranceAddParam>> map = addInsuranceCheck(paramList);
		//返回给前端的结果
		List<InsuranceAddParam> listResult = map.get("listResult");
		//保存到数据库中的结果
		List<InsuranceAddParam> listSuccess = map.get("listSuccess");
		if (CollectionUtils.isNotEmpty(listSuccess)){
			List<TInsuranceDetail> detailList = new ArrayList<>();
			for (InsuranceAddParam success : listSuccess) {
				TInsuranceDetail detail = new TInsuranceDetail();
				BeanCopyUtils.copyProperties(success,detail);
				//购买类型，默认为「新增」
				detail.setBuyType(CommonConstants.ONE_INT);
				//投保状态：待投保
				detail.setBuyHandleStatus(CommonConstants.ONE_INT);
				detail.setPolicyStart(LocalDateUtil.parseLocalDate(success.getPolicyStart()));
				detail.setPolicyEnd(LocalDateUtil.parseLocalDate(success.getPolicyEnd()));
				detail.setCreateBy(user.getId());
				detail.setCreateName(user.getNickname());
				detailList.add(detail);
			}
			this.saveBatch(detailList);
		}
		//todo 操作记录
		return R.ok(listResult,InsurancesConstants.ADD_SUCCESS);
	}

	/**
	 * 商险批增
	 *
	 * @param paramList
	 * @return {@link R<List<InsuranceBatchParam>>}
	 * @author licancan
	 */
	@Override
	@Transactional(rollbackFor = {Exception.class})
	public R<List<InsuranceBatchParam>> batchInsurance(List<InsuranceBatchParam> paramList) {
		if (CollectionUtils.isEmpty(paramList)){
			return R.failed(CommonConstants.DATA_CAN_NOT_EMPTY);
		}
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		Map<String, List<InsuranceBatchParam>> map = batchInsuranceCheck(paramList);
		//返回给前端的结果
		List<InsuranceBatchParam> listResult = map.get("listResult");
		//保存到数据库中的结果
		List<InsuranceBatchParam> listSuccess = map.get("listSuccess");
		if (CollectionUtils.isNotEmpty(listSuccess)){
			List<TInsuranceDetail> detailList = new ArrayList<>();
			for (InsuranceBatchParam success : listSuccess) {
				TInsuranceDetail detail = new TInsuranceDetail();
				BeanCopyUtils.copyProperties(success,detail);
				//购买类型，默认为「批增」
				detail.setBuyType(CommonConstants.THREE_INT);
				//投保状态：待投保???
				detail.setBuyHandleStatus(CommonConstants.ONE_INT);
				detail.setCreateBy(user.getId());
				detail.setCreateName(user.getNickname());
				detailList.add(detail);
			}
			this.saveBatch(detailList);
		}
		//todo 操作记录
		return R.ok(listResult,InsurancesConstants.BATCH_SUCCESS);
	}

	/**
	 * 商险替换
	 *
	 * @param paramList
	 * @return {@link R<List<InsuranceReplaceParam>>}
	 * @author licancan
	 */
	@Override
	@Transactional(rollbackFor = {Exception.class})
	public R<List<InsuranceReplaceParam>> replaceInsurance(List<InsuranceReplaceParam> paramList) {
		if (CollectionUtils.isEmpty(paramList)){
			return R.failed(CommonConstants.DATA_CAN_NOT_EMPTY);
		}
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		Map<String, List<InsuranceReplaceParam>> map = replaceInsuranceCheck(paramList);
		//返回给前端的结果
		List<InsuranceReplaceParam> listResult = map.get("listResult");
		//保存到数据库中的结果
		List<InsuranceReplaceParam> listSuccess = map.get("listSuccess");
		if (CollectionUtils.isNotEmpty(listSuccess)){
			for (InsuranceReplaceParam success : listSuccess) {
				//替换
				TInsuranceDetail newDetail  = new TInsuranceDetail();
				//原数据置为无效：姓名 + 身份证号 + 项目编码 + 保险公司 + 险种名称 + 保单开始时间 + 保单结束时间
				TInsuranceDetail detail = this.baseMapper.selectOne(Wrappers.<TInsuranceDetail>query().lambda()
						.eq(TInsuranceDetail::getEmpName, success.getEmpName())
						.eq(TInsuranceDetail::getEmpIdcardNo, success.getEmpIdcardNo())
						.eq(TInsuranceDetail::getDeptNo, success.getDeptNo())
						.eq(TInsuranceDetail::getInsuranceCompanyName, success.getInsuranceCompanyName())
						.eq(TInsuranceDetail::getInsuranceTypeName, success.getInsuranceTypeName())
						.eq(TInsuranceDetail::getPolicyStart, LocalDateUtil.parseLocalDate(success.getPolicyStart()))
						.eq(TInsuranceDetail::getPolicyEnd, LocalDateUtil.parseLocalDate(success.getPolicyEnd()))
						.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
				);
				BeanCopyUtils.copyProperties(detail,newDetail);
				detail.setIsEffect(CommonConstants.ONE_INT);
				this.updateById(detail);
				//新数据置为待办理
				newDetail.setId(null);
				newDetail.setBuyHandleStatus(CommonConstants.ONE_INT);
				newDetail.setBuyType(CommonConstants.FOUR_INT);
				newDetail.setEmpName(success.getReplaceEmpName());
				newDetail.setEmpIdcardNo(success.getReplaceEmpIdcardNo());
				newDetail.setDeptNo(success.getReplaceDeptNo());
				newDetail.setOrderNo(success.getOrderNo());
				newDetail.setPost(success.getPost());
				Boolean insert = this.save(newDetail);
				//替换记录
				if (insert){
					TInsuranceReplace replace = new TInsuranceReplace();
					replace.setFromInsuranceDetailId(detail.getId());
					replace.setToInsuranceDetailId(newDetail.getId());
					TInsuranceReplace one = tInsuranceReplaceService.getOne(Wrappers.<TInsuranceReplace>query().lambda()
							.eq(TInsuranceReplace::getToInsuranceDetailId, detail.getId())
							.last(CommonConstants.LAST_ONE_SQL)
					);
					if (Optional.ofNullable(one).isPresent()){
						replace.setOriginInsuranceDetailId(one.getOriginInsuranceDetailId());
					}else {
						replace.setOriginInsuranceDetailId(detail.getId());
					}
					replace.setReplaceStatus(CommonConstants.ONE_INT);
					replace.setReplaceTime(LocalDateTime.now());
					replace.setCreateBy(user.getId());
					replace.setCreateName(user.getNickname());
					replace.setCreateTime(LocalDateTime.now());
					tInsuranceReplaceService.save(replace);
				}
			}
		}
		//todo 操作记录
		return R.ok(listResult,InsurancesConstants.REPLACE_SUCCESS);
	}

	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return {@link R<String>}
	 * @author licancan
	 */
	@Override
	public R<String> deleteInsurance(String id) {
		TInsuranceDetail byId = this.getById(id);
		if (null == byId){
			return R.failed(InsurancesConstants.DATA_IS_NOT_EXIST);
		}
		if (byId.getBuyHandleStatus() != CommonConstants.FOUR_INT){
			return R.failed(InsurancesConstants.DELETE_ERROR);
		}
		byId.setDeleteFlag(CommonConstants.ONE_INT);
		this.updateById(byId);
		return R.ok(InsurancesConstants.OPERATE_SUCCESS);
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return {@link InsuranceDetailVO}
	 * @author licancan
	 */
	@Override
	public InsuranceDetailVO getInsuranceDetailById(String id) {
		InsuranceDetailVO insuranceDetailVO = this.baseMapper.getInsuranceDetailById(id);
		return insuranceDetailVO;
	}

	/**
	 * 商险新增校验
	 *
	 * @author licancan
	 * @param paramList
	 * @return {@link Map<String, List<InsuranceAddParam>>}
	 */
	private Map<String,List<InsuranceAddParam>> addInsuranceCheck(List<InsuranceAddParam> paramList){
		Map<String,List<InsuranceAddParam>> map = new HashMap<>();
		List<InsuranceAddParam> listResult = new ArrayList<>();
		List<InsuranceAddParam> listSuccess = new ArrayList<>();
		for (InsuranceAddParam param : paramList) {
			// 必填校验
			if (StringUtils.isBlank(param.getOrderNo())){
				param.setErrorMessage(InsurancesConstants.ORDER_NO_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getEmpName())){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getDeptNo())){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceCompanyName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceTypeName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_TYPE_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getPolicyStart())){
				param.setErrorMessage(InsurancesConstants.POLICY_START_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getPolicyEnd())){
				param.setErrorMessage(InsurancesConstants.POLICY_END_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getBuyStandard())){
				param.setErrorMessage(InsurancesConstants.BUY_STANDARD_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceProvinceName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_PROVINCE_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceCityName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_CITY_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceHandleProvinceName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_HANDLE_PROVINCE_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceHandleCityName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_HANDLE_CITY_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getSettleMonth())){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getPost())){
				param.setErrorMessage(InsurancesConstants.POST_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			// 身份证号位数校验（18 位合法）
			if (ValidityUtil.validateIDCard(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_LEGITIMATE);
				listResult.add(param);
				continue;
			}
			//根据项目编码查询项目是否存在
			R<Map> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(Arrays.asList(param.getDeptNo()));
			if (null != setInfoByCodes && setInfoByCodes.getCode() != CommonConstants.SUCCESS) {
				Map data = setInfoByCodes.getData();
				if (MapUtils.isEmpty(data)){
					param.setErrorMessage(InsurancesConstants.DEPT_NO_IS_NOT_EXIST);
					listResult.add(param);
					continue;
				}else {
					JSONObject jsonObject = (JSONObject) data.get(param.getDeptNo());
					if (null == jsonObject){
						param.setErrorMessage(InsurancesConstants.DEPT_NO_IS_NOT_EXIST);
						listResult.add(param);
						continue;
					}else {
						//结算类型，根据项目编码获取，并冗余到明细记录中
						String settleType = jsonObject.getString("insuranceSettleType");
						if (StringUtils.isEmpty(settleType)){
							param.setErrorMessage(InsurancesConstants.PROJECT_NOT_FIND_SETTLE_TYPE);
							listResult.add(param);
							continue;
						}else {
							param.setSettleType(Integer.parseInt(settleType));
						}
					}
				}
			}
			//todo 省市校验是否正确并设置对应code
			//param.setInsuranceProvince();
			//param.setInsuranceCity();
			//param.setInsuranceHandleProvince();
			//param.setInsuranceHandleCity();

			// 保单开始日期 > 当前派单日期
			if(!LocalDateUtil.isDate(param.getPolicyStart(),LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_START_PARSE_ERROR);
				listResult.add(param);
				continue;
			}
			if(!LocalDateUtil.isDate(param.getPolicyEnd(),LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_END_PARSE_ERROR);
				listResult.add(param);
				continue;
			}
			if(!LocalDateUtil.isFutureDate(param.getPolicyStart())){
				param.setErrorMessage(InsurancesConstants.POLICY_START_SHOULD_IS_FUTURE);
				listResult.add(param);
				continue;
			}
			// 保险公司-险种-购买标准 是否存在
			TInsuranceCompany insuranceCompany = tInsuranceCompanyService.getOne(Wrappers.<TInsuranceCompany>query().lambda()
					.eq(TInsuranceCompany::getCompanyName, param.getInsuranceCompanyName())
					.eq(TInsuranceCompany::getDeleteFlag, CommonConstants.ZERO_INT)
				);
			if (!Optional.ofNullable(insuranceCompany).isPresent()){
				param.setErrorMessage(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				TInsuranceType insuranceType = tInsuranceTypeService.getOne(Wrappers.<TInsuranceType>query().lambda()
						.eq(TInsuranceType::getName, param.getInsuranceTypeName())
						.eq(TInsuranceType::getInsuranceCompanyId, insuranceCompany.getId())
						.eq(TInsuranceType::getDeleteFlag, CommonConstants.ZERO_INT)
				);
				if (!Optional.ofNullable(insuranceType).isPresent()){
					param.setErrorMessage(InsurancesConstants.INSURANCE_TYPE_NAME_NOT_EXIST);
					listResult.add(param);
					continue;
				}else {
					TInsuranceTypeStandard typeStandard = tInsuranceTypeStandardService.getOne(Wrappers.<TInsuranceTypeStandard>query().lambda()
							.eq(TInsuranceTypeStandard::getBuyStandard, param.getBuyStandard())
							.eq(TInsuranceTypeStandard::getInsuranceTypeId, insuranceType.getId())
							.eq(TInsuranceTypeStandard::getDeleteFlag, CommonConstants.ZERO_INT)
					);
					if (!Optional.ofNullable(typeStandard).isPresent()){
						param.setErrorMessage(InsurancesConstants.BUY_STANDARD_NOT_EXIST);
						listResult.add(param);
						continue;
					}else {
						// "医疗额度" 和  "身故或残疾"，由系统根据 保险公司+险种+ 购买标准 关联查询，并补全
						// 这里计算好赋值，是为了方便入库
						param.setMedicalQuota(typeStandard.getMedicalQuota());
						param.setDieDisableQuota(typeStandard.getDieDisableQuota());
						param.setInsuranceTypeId(typeStandard.getInsuranceTypeId());
					}
				}
			}
			//记录查重校验：姓名 + 身份证号 + 保险公司 + 险种 + 保单开始日期~保单结束日期区间 是唯一（剔除退回、过期状态的记录）
			//todo 时间区间
			Set<Integer> setRStatus = Sets.newHashSet();
			setRStatus.add(CommonConstants.FOUR_INT);
			TInsuranceDetail insuranceDetail = this.baseMapper.selectOne(Wrappers.<TInsuranceDetail>query().lambda()
					.eq(TInsuranceDetail::getEmpName, param.getEmpName())
					.eq(TInsuranceDetail::getEmpIdcardNo, param.getEmpIdcardNo())
					.eq(TInsuranceDetail::getInsuranceCompanyName, param.getInsuranceCompanyName())
					.eq(TInsuranceDetail::getInsuranceTypeName, param.getInsuranceTypeName())
					.eq(TInsuranceDetail::getPolicyStart, param.getPolicyStart())
					.eq(TInsuranceDetail::getPolicyEnd, param.getPolicyEnd())
					.notIn(TInsuranceDetail::getBuyHandleStatus, setRStatus)
					.eq(TInsuranceDetail::getIsOverdue, CommonConstants.ZERO_INT)
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
			);
			if (Optional.ofNullable(insuranceDetail).isPresent()){
				param.setErrorMessage(InsurancesConstants.DATA_IS_EXIST);
				listResult.add(param);
				continue;
			}
			// 结算月份 >= 派单月份（结算月 < 派单月份的记录予以拦截，并提示）
			if(!LocalDateUtil.isDate(param.getSettleMonth(),LocalDateUtil.NORM_MONTH_PATTERN)){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_PARSE_ERROR);
				listResult.add(param);
				continue;
			}
			if(!LocalDateUtil.isCurrentOrFutureMonth(param.getSettleMonth())){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_SHOULD_IS_FUTURE);
				listResult.add(param);
				continue;
			}
			listSuccess.add(param);
		}
		map.put("listResult",listResult);
		map.put("listSuccess",listSuccess);
		return map;
	}

	/**
	 * 商险批增校验
	 *
	 * @author licancan
	 * @param paramList
	 * @return {@link Map< String, List< InsuranceBatchParam>>}
	 */
	private Map<String,List<InsuranceBatchParam>> batchInsuranceCheck(List<InsuranceBatchParam> paramList){
		Map<String,List<InsuranceBatchParam>> map = new HashMap<>();
		List<InsuranceBatchParam> listResult = new ArrayList<>();
		List<InsuranceBatchParam> listSuccess = new ArrayList<>();
		for (InsuranceBatchParam param : paramList) {
			// 必填校验
			if (StringUtils.isBlank(param.getOrderNo())){
				param.setErrorMessage(InsurancesConstants.ORDER_NO_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getDeptNo())){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getEmpName())){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getPost())){
				param.setErrorMessage(InsurancesConstants.POST_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getPolicyNo())){
				param.setErrorMessage(InsurancesConstants.POLICY_NO_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceCompanyName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceTypeName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_TYPE_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getBuyStandard())){
				param.setErrorMessage(InsurancesConstants.BUY_STANDARD_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceProvinceName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_PROVINCE_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceCityName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_CITY_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceHandleProvinceName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_HANDLE_PROVINCE_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceHandleCityName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_HANDLE_CITY_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getSettleMonth())){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			// 身份证号位数校验（18 位合法）
			if (ValidityUtil.validateIDCard(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_LEGITIMATE);
				listResult.add(param);
				continue;
			}
			//根据项目编码查询项目是否存在
			R<Map> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(Arrays.asList(param.getDeptNo()));
			if (null != setInfoByCodes && setInfoByCodes.getCode() != CommonConstants.SUCCESS) {
				Map data = setInfoByCodes.getData();
				if (MapUtils.isEmpty(data)){
					param.setErrorMessage(InsurancesConstants.DEPT_NO_IS_NOT_EXIST);
					listResult.add(param);
					continue;
				}else {
					JSONObject jsonObject = (JSONObject) data.get(param.getDeptNo());
					if (null == jsonObject){
						param.setErrorMessage(InsurancesConstants.DEPT_NO_IS_NOT_EXIST);
						listResult.add(param);
						continue;
					}else {
						//结算类型，根据项目编码获取，并冗余到明细记录中
						String settleType = jsonObject.getString("insuranceSettleType");
						if (StringUtils.isEmpty(settleType)){
							param.setErrorMessage(InsurancesConstants.PROJECT_NOT_FIND_SETTLE_TYPE);
							listResult.add(param);
							continue;
						}else {
							param.setSettleType(Integer.parseInt(settleType));
						}
					}
				}
			}
			//todo 省市校验是否正确并设置对应code
			//param.setInsuranceProvince();
			//param.setInsuranceCity();
			//param.setInsuranceHandleProvince();
			//param.setInsuranceHandleCity();

			// 保险公司-险种-购买标准 是否存在
			TInsuranceCompany insuranceCompany = tInsuranceCompanyService.getOne(Wrappers.<TInsuranceCompany>query().lambda()
					.eq(TInsuranceCompany::getCompanyName, param.getInsuranceCompanyName())
					.eq(TInsuranceCompany::getDeleteFlag, CommonConstants.ZERO_INT)
			);
			if (!Optional.ofNullable(insuranceCompany).isPresent()){
				param.setErrorMessage(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				TInsuranceType insuranceType = tInsuranceTypeService.getOne(Wrappers.<TInsuranceType>query().lambda()
						.eq(TInsuranceType::getName, param.getInsuranceTypeName())
						.eq(TInsuranceType::getInsuranceCompanyId, insuranceCompany.getId())
						.eq(TInsuranceType::getDeleteFlag, CommonConstants.ZERO_INT)
				);
				if (!Optional.ofNullable(insuranceType).isPresent()){
					param.setErrorMessage(InsurancesConstants.INSURANCE_TYPE_NAME_NOT_EXIST);
					listResult.add(param);
					continue;
				}else {
					TInsuranceTypeStandard typeStandard = tInsuranceTypeStandardService.getOne(Wrappers.<TInsuranceTypeStandard>query().lambda()
							.eq(TInsuranceTypeStandard::getBuyStandard, param.getBuyStandard())
							.eq(TInsuranceTypeStandard::getInsuranceTypeId, insuranceType.getId())
							.eq(TInsuranceTypeStandard::getDeleteFlag, CommonConstants.ZERO_INT)
					);
					if (!Optional.ofNullable(typeStandard).isPresent()){
						param.setErrorMessage(InsurancesConstants.BUY_STANDARD_NOT_EXIST);
						listResult.add(param);
						continue;
					}else {
						// "医疗额度" 和  "身故或残疾"，由系统根据 保险公司+险种+ 购买标准 关联查询，并补全
						// 这里计算好赋值，是为了方便入库
						param.setMedicalQuota(typeStandard.getMedicalQuota());
						param.setDieDisableQuota(typeStandard.getDieDisableQuota());
						param.setInsuranceTypeId(typeStandard.getInsuranceTypeId());
					}
				}
			}
			//记录查重校验：姓名 + 身份证号 + 保险公司 + 险种
			TInsuranceDetail insuranceDetail = this.baseMapper.selectOne(Wrappers.<TInsuranceDetail>query().lambda()
					.eq(TInsuranceDetail::getEmpName, param.getEmpName())
					.eq(TInsuranceDetail::getEmpIdcardNo, param.getEmpIdcardNo())
					.eq(TInsuranceDetail::getInsuranceCompanyName, param.getInsuranceCompanyName())
					.eq(TInsuranceDetail::getInsuranceTypeName, param.getInsuranceTypeName())
					//是否需要加状态过滤?
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
			);
			if (Optional.ofNullable(insuranceDetail).isPresent()){
				param.setErrorMessage(InsurancesConstants.DATA_IS_EXIST);
				listResult.add(param);
				continue;
			}
			//保单开始日期、结束日期，由系统根据保单号关联查询投保状态为 "已投保" 的商险记录的任意一条
			TInsuranceDetail limitOne = this.baseMapper.selectOne(Wrappers.<TInsuranceDetail>query().lambda()
					.eq(TInsuranceDetail::getPolicyNo, param.getPolicyNo())
					.eq(TInsuranceDetail::getBuyHandleStatus, CommonConstants.THREE_INT)
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (!Optional.ofNullable(limitOne).isPresent()){
				param.setErrorMessage(InsurancesConstants.POLICY_NO_EXIST);
				listResult.add(param);
				continue;
			}else {
				param.setPolicyStart(limitOne.getPolicyStart());
				param.setPolicyEnd(limitOne.getPolicyEnd());
			}

			// 结算月份 >= 派单月份（结算月 < 派单月份的记录予以拦截，并提示）
			if(!LocalDateUtil.isDate(param.getSettleMonth(),LocalDateUtil.NORM_MONTH_PATTERN)){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_PARSE_ERROR);
				listResult.add(param);
				continue;
			}
			if(!LocalDateUtil.isCurrentOrFutureMonth(param.getSettleMonth())){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_SHOULD_IS_FUTURE);
				listResult.add(param);
				continue;
			}
			listSuccess.add(param);
		}
		map.put("listResult",listResult);
		map.put("listSuccess",listSuccess);
		return map;
	}

	/**
	 * 商险替换校验
	 *
	 * @author licancan
	 * @param paramList
	 * @return {@link Map< String, List<InsuranceReplaceParam>>}
	 */
	private Map<String,List<InsuranceReplaceParam>> replaceInsuranceCheck(List<InsuranceReplaceParam> paramList){
		Map<String,List<InsuranceReplaceParam>> map = new HashMap<>();
		List<InsuranceReplaceParam> listResult = new ArrayList<>();
		List<InsuranceReplaceParam> listSuccess = new ArrayList<>();
		for (InsuranceReplaceParam param : paramList) {
			// 必填校验
			if (StringUtils.isBlank(param.getEmpName())){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getDeptNo())){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceCompanyName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceTypeName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_TYPE_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getPolicyStart())){
				param.setErrorMessage(InsurancesConstants.POLICY_START_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getPolicyEnd())){
				param.setErrorMessage(InsurancesConstants.POLICY_END_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getReplaceEmpName())){
				param.setErrorMessage(InsurancesConstants.REPLACE_EMP_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getReplaceEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.REPLACE_EMP_IDCARD_NO_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getReplaceDeptNo())){
				param.setErrorMessage(InsurancesConstants.REPLACE_DEPT_NO_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getOrderNo())){
				param.setErrorMessage(InsurancesConstants.ORDER_NO_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (StringUtils.isBlank(param.getPost())){
				param.setErrorMessage(InsurancesConstants.POST_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			// 身份证号位数校验（18 位合法）
			if (ValidityUtil.validateIDCard(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_LEGITIMATE);
				listResult.add(param);
				continue;
			}
			if (ValidityUtil.validateIDCard(param.getReplaceEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.REPLACE_EMP_IDCARD_NO_NOT_LEGITIMATE);
				listResult.add(param);
				continue;
			}
			if(!LocalDateUtil.isDate(param.getPolicyStart(),LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_START_PARSE_ERROR);
				listResult.add(param);
				continue;
			}
			if(!LocalDateUtil.isDate(param.getPolicyEnd(),LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_END_PARSE_ERROR);
				listResult.add(param);
				continue;
			}

			//原数据查重校验：姓名 + 身份证号 + 项目编码 + 保险公司 + 险种名称 + 保单开始时间 + 保单结束时间
			TInsuranceDetail detail = this.baseMapper.selectOne(Wrappers.<TInsuranceDetail>query().lambda()
					.eq(TInsuranceDetail::getEmpName, param.getEmpName())
					.eq(TInsuranceDetail::getEmpIdcardNo, param.getEmpIdcardNo())
					.eq(TInsuranceDetail::getDeptNo, param.getDeptNo())
					.eq(TInsuranceDetail::getInsuranceCompanyName, param.getInsuranceCompanyName())
					.eq(TInsuranceDetail::getInsuranceTypeName, param.getInsuranceTypeName())
					.eq(TInsuranceDetail::getPolicyStart, LocalDateUtil.parseLocalDate(param.getPolicyStart()))
					.eq(TInsuranceDetail::getPolicyEnd, LocalDateUtil.parseLocalDate(param.getPolicyEnd()))
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
			);
			if (!Optional.ofNullable(detail).isPresent()){
				param.setErrorMessage(InsurancesConstants.REPLACE_IS_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				// 无效、已过期、已出险、已减员的 不能替换
				if (detail.getBuyHandleStatus() == CommonConstants.FIVE_INT
						|| detail.getIsUse() == CommonConstants.ONE_INT
						|| detail.getIsOverdue() == CommonConstants.ONE_INT
						|| detail.getIsEffect() == CommonConstants.ONE_INT){
					param.setErrorMessage(InsurancesConstants.REPLACE_IS_NOT_ALLOW);
					listResult.add(param);
					continue;
				}
			}
			//替换者数据查重校验：替换姓名 + 替换身份证号 + 替换项目编码 + 保险公司 + 险种名称
			TInsuranceDetail replace = this.baseMapper.selectOne(Wrappers.<TInsuranceDetail>query().lambda()
					.eq(TInsuranceDetail::getEmpName, param.getReplaceEmpName())
					.eq(TInsuranceDetail::getEmpIdcardNo, param.getReplaceEmpIdcardNo())
					.eq(TInsuranceDetail::getDeptNo, param.getReplaceDeptNo())
					.eq(TInsuranceDetail::getInsuranceCompanyName, param.getInsuranceCompanyName())
					.eq(TInsuranceDetail::getInsuranceTypeName, param.getInsuranceTypeName())
					//加状态??
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
			);
			if (Optional.ofNullable(replace).isPresent()){
				param.setErrorMessage(InsurancesConstants.REPLACE_IS_EXIST);
				listResult.add(param);
				continue;
			}
			listSuccess.add(param);
		}
		map.put("listResult",listResult);
		map.put("listSuccess",listSuccess);
		return map;
	}

	/***********************减员办理********************************/
	@Override
	public R checkInsuranceRefundList(List<InsuranceRefundCheck> insuranceRefundCheckList) {
		if(!Common.isNotEmpty(insuranceRefundCheckList)){
			return R.failed("当前导入的减员信息为空");
		}
		List<InsuranceRefundCheck> refundErrorList = new ArrayList(128);
		for (InsuranceRefundCheck insuranceRefund : insuranceRefundCheckList) {

			boolean b = true;

			String empName = insuranceRefund.getEmpName();

			String empIdCardNo = insuranceRefund.getEmpIdCardNo();
			//保险公司名称
			String insuranceCompanyName = insuranceRefund.getInsuranceCompanyName();
			//险种名称
			String insuranceTypeName = insuranceRefund.getInsuranceTypeName();

			String refundMoney = insuranceRefund.getRefundMoney();

			String policyStart = insuranceRefund.getPolicyStart();

			String policyEnd = insuranceRefund.getPolicyEnd();

			String remark = insuranceRefund.getRemark();

			if (!b){
				refundErrorList.add(insuranceRefund);
			}
		}
		if (Common.isNotEmpty(refundErrorList)){
			return null;
		}
		return null;
	}

}
