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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.archives.vo.ProjectSetInfoVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.SetInfoVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
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.util.RedisUtil;
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.LocalDate;
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;
	@Resource
	private TInsuranceSettleService tInsuranceSettleService;

	@Resource
	private TInsuranceSettleService insuranceSettleService;


	/***********************商险办理********************************/
	/**
	 * 投保办理分页查询
	 *
	 * @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<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(collect);
			if (null != setInfoByCodes && setInfoByCodes.getCode() == CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
				Map<String, ProjectSetInfoVo> data = setInfoByCodes.getData().getProjectSetInfoVoMap();
				for (InsuranceListVO record : insuranceList.getRecords()) {
					ProjectSetInfoVo jsonObject = data.get(record.getDeptNo());
					if (null != jsonObject){
						record.setProjectName(Optional.ofNullable(jsonObject.getDepartName()).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<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(collect);
			if (null != setInfoByCodes && setInfoByCodes.getCode() == CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
				Map<String, ProjectSetInfoVo> data = setInfoByCodes.getData().getProjectSetInfoVoMap();
				for (InsuranceListVO record : insuranceList) {
					ProjectSetInfoVo jsonObject = data.get(record.getDeptNo());
					if (null != jsonObject){
						record.setProjectName(Optional.ofNullable(jsonObject.getDepartName()).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.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);
	}

	/**
	 * 编辑
	 *
	 * @param param
	 * @return {@link R<String>}
	 * @author licancan
	 */
	@Override
	public R<String> editInsurance(InsuranceEditParam param) {
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		TInsuranceDetail byId = this.getById(param.getId());
		if (null == byId){
			return R.failed(InsurancesConstants.DATA_IS_NOT_EXIST);
		}
		if (byId.getBuyHandleStatus() == CommonConstants.FOUR_INT && byId.getBuyType() != CommonConstants.FOUR_INT){
			// 身份证号位数校验（18 位合法）
			if (ValidityUtil.validateIDCard(param.getEmpIdcardNo())){
				return R.failed(InsurancesConstants.EMP_IDCARD_NO_NOT_LEGITIMATE);
			}
			// 保单开始日期 > 当前派单日期
			if(!LocalDateUtil.isDate(param.getPolicyStart(),LocalDateUtil.NORM_DATE_PATTERN)){
				return R.failed(InsurancesConstants.POLICY_START_PARSE_ERROR);
			}
			if(!LocalDateUtil.isDate(param.getPolicyEnd(),LocalDateUtil.NORM_DATE_PATTERN)){
				return R.failed(InsurancesConstants.POLICY_END_PARSE_ERROR);
			}
			if(!LocalDateUtil.isFutureDate(param.getPolicyStart())){
				return R.failed(InsurancesConstants.POLICY_START_SHOULD_IS_FUTURE);
			}
			// 保险公司-险种-购买标准 是否存在
			TInsuranceCompany insuranceCompany = tInsuranceCompanyService.getOne(Wrappers.<TInsuranceCompany>query().lambda()
					.eq(TInsuranceCompany::getCompanyName, param.getInsuranceCompanyName())
					.eq(TInsuranceCompany::getDeleteFlag, CommonConstants.ZERO_INT)
			);
			if (!Optional.ofNullable(insuranceCompany).isPresent()){
				return R.failed(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EXIST);
			}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()){
					return R.failed(InsurancesConstants.INSURANCE_TYPE_NAME_NOT_EXIST);
				}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()){
						return R.failed(InsurancesConstants.BUY_STANDARD_NOT_EXIST);
					}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()){
				return R.failed(InsurancesConstants.DATA_IS_EXIST);
			}
			BeanCopyUtils.copyProperties(param,byId);
			//投保状态：待投保
			byId.setBuyHandleStatus(CommonConstants.ONE_INT);
			byId.setPolicyStart(LocalDateUtil.parseLocalDate(param.getPolicyStart()));
			byId.setPolicyEnd(LocalDateUtil.parseLocalDate(param.getPolicyEnd()));
			byId.setUpdateBy(user.getId());
			byId.setUpdateTime(LocalDateTime.now());
			this.updateById(byId);
		}else {
			return R.failed(InsurancesConstants.EDIT_NOT_ALLOW);
		}
		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);
		if (null != insuranceDetailVO){
			R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(Arrays.asList(insuranceDetailVO.getDeptNo()));
			if (null != setInfoByCodes && setInfoByCodes.getCode() == CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
				Map<String, ProjectSetInfoVo> data = setInfoByCodes.getData().getProjectSetInfoVoMap();
				ProjectSetInfoVo jsonObject = data.get(insuranceDetailVO.getDeptNo());
				if (null != jsonObject){
					insuranceDetailVO.setProjectName(Optional.ofNullable(jsonObject.getDepartName()).orElse(""));
				}
			}
		}
		return insuranceDetailVO;
	}

	/**
	 * 导出办理
	 *
	 * @param param
	 * @return {@link List<InsuranceExportListVO>}
	 * @author licancan
	 */
	@Override
	public List<InsuranceExportListVO> getInsuranceExportList(InsuranceExportListParam param) {
		YifuUser user = SecurityUtils.getUser();
		List<InsuranceExportListVO> insuranceExportList;
		//todo 根据登录人获取数据权限

		//如勾选项不为空，则导出勾选记录；否则导出当前筛选条件下 && 「待投保」的结果集
		if (CollectionUtils.isNotEmpty(param.getIdList())){
			insuranceExportList =  baseMapper.getInsuranceExportListBySelect(param.getIdList());
		}else {
			insuranceExportList = baseMapper.getInsuranceExportList(param);
		}
		if (CollectionUtils.isNotEmpty(insuranceExportList)){
			List<TInsuranceDetail> detailList = new ArrayList<>();
			//根据项目编码获取项目名称
			List<String> collect = insuranceExportList.stream().map(e -> e.getDeptNo()).distinct().collect(Collectors.toList());
			R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(collect);
			if (null != setInfoByCodes && setInfoByCodes.getCode() == CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
				Map<String, ProjectSetInfoVo> data = setInfoByCodes.getData().getProjectSetInfoVoMap();
				for (InsuranceExportListVO record : insuranceExportList) {
					ProjectSetInfoVo jsonObject = data.get(record.getDeptNo());
					if (null != jsonObject){
						record.setProjectName(Optional.ofNullable(jsonObject.getDepartName()).orElse(""));
					}
					TInsuranceDetail detail = new TInsuranceDetail();
					detail.setId(record.getId());
					//update状态由「待投保」置为「投保中」
					detail.setBuyHandleStatus(CommonConstants.TWO_INT);
					if (record.getBuyType() == CommonConstants.ONE_INT){
						//  if 投保类型 == 新增，then 更新保单生效日期为：T+1，无需考虑节假日
						detail.setPolicyEffect(LocalDate.now().plusDays(CommonConstants.ONE_INT));
					}
					detail.setUpdateBy(user.getId());
					detail.setUpdateTime(LocalDateTime.now());
					detailList.add(detail);
				}
			}
			//批量更新
			if (CollectionUtils.isNotEmpty(detailList)){
				this.saveOrUpdateBatch(detailList);
			}
		}
		return insuranceExportList;
	}

	/**
	 * 投保退回
	 *
	 * @param idList
	 * @return {@link R<String>}
	 * @author licancan
	 */
	@Override
	public R<String> rollBackInsurance(List<String> idList) {
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		if (CollectionUtils.isEmpty(idList)){
			return R.failed(CommonConstants.PARAM_IS_NOT_EMPTY);
		}
		List<TInsuranceDetail> detailList = baseMapper.selectBatchIds(idList);
		if (CollectionUtils.isNotEmpty(detailList)){
			detailList.stream().forEach(e ->{
				// 记录状态置为「退回」
				e.setBuyHandleStatus(CommonConstants.FOUR_INT);
				e.setUpdateBy(user.getId());
				e.setUpdateTime(LocalDateTime.now());
			});
			//更新
			this.saveOrUpdateBatch(detailList);
		}
		return R.ok(InsurancesConstants.OPERATE_SUCCESS);
	}

	/**
	 * 办理成功
	 *
	 * @param idList
	 * @return {@link R<String>}
	 * @author licancan
	 */
	@Override
	public R<String> successfulInsurance(List<String> idList) {
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		if (CollectionUtils.isEmpty(idList)){
			return R.failed(CommonConstants.PARAM_IS_NOT_EMPTY);
		}
		List<TInsuranceDetail> detailList = baseMapper.selectBatchIds(idList);
		if (CollectionUtils.isNotEmpty(detailList)){
			for (TInsuranceDetail detail : detailList) {
				if (detail.getBuyType() == CommonConstants.THREE_INT){
					detail.setPolicyEffect(LocalDate.now().plusDays(CommonConstants.ONE_INT));
				}
				//记录状态均置为「已投保」
				detail.setBuyHandleStatus(CommonConstants.THREE_INT);
				//记录的有效状态，置为「有效」
				detail.setIsEffect(CommonConstants.ZERO_INT);
				detail.setIsOverdue(CommonConstants.ZERO_INT);
			}
			//更新
			this.saveOrUpdateBatch(detailList);
			//todo 根据结算类型推送ekp
		}
		return R.ok(InsurancesConstants.OPERATE_SUCCESS);
	}

	/**
	 * 登记保单保费
	 *
	 * @param paramList
	 * @return {@link R<List<InsuranceRegisterParam>>}
	 * @author licancan
	 */
	@Override
	public R<List<InsuranceRegisterParam>> registeredPolicyPremium(List<InsuranceRegisterParam> 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<InsuranceRegisterParam>> map = registeredPolicyPremiumCheck(paramList);
		//返回给前端的结果
		List<InsuranceRegisterParam> listResult = map.get("listResult");
		//保存到数据库中的结果
		List<InsuranceRegisterParam> listSuccess = map.get("listSuccess");
		if (CollectionUtils.isNotEmpty(listSuccess)){
			for (InsuranceRegisterParam success : listSuccess) {
				//登记保单保费
				//查数据：姓名 + 身份证号 + 保险公司 + 险种名称 + 保单开始时间 + 保单结束时间
				TInsuranceDetail detail = this.baseMapper.selectOne(Wrappers.<TInsuranceDetail>query().lambda()
						.eq(TInsuranceDetail::getEmpName, success.getEmpName())
						.eq(TInsuranceDetail::getEmpIdcardNo, success.getEmpIdcardNo())
						.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)
				);
				if (detail.getActualPremium() != null){
					// 已推送过，只更新发票号
					detail.setInvoiceNo(success.getInvoiceNo());
					detail.setUpdateBy(user.getId());
					detail.setUpdateTime(LocalDateTime.now());
					this.updateById(detail);
				}else {
					// todo 根据结算类型判断推送ekp

				}
			}
		}
		//todo 操作记录
		return R.ok(listResult,InsurancesConstants.OPERATE_SUCCESS);
	}

	/**
	 * 商险新增校验
	 *
	 * @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.stream().distinct().collect(Collectors.toList())) {
			// 必填校验
			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;
			}
			// todo 校验身份合法

			//根据项目编码查询项目是否存在
			R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(Arrays.asList(param.getDeptNo()));
			if (null != setInfoByCodes && setInfoByCodes.getCode() == CommonConstants.SUCCESS) {
				Map<String, ProjectSetInfoVo> data = setInfoByCodes.getData().getProjectSetInfoVoMap();
				if (MapUtils.isEmpty(data)){
					param.setErrorMessage(InsurancesConstants.DEPT_NO_IS_NOT_EXIST);
					listResult.add(param);
					continue;
				}else {
					ProjectSetInfoVo jsonObject = data.get(param.getDeptNo());
					if (null == jsonObject){
						param.setErrorMessage(InsurancesConstants.DEPT_NO_IS_NOT_EXIST);
						listResult.add(param);
						continue;
					}else {
						//结算类型，根据项目编码获取，并冗余到明细记录中
						String settleType = jsonObject.getInsuranceSettleType();
						if (StringUtils.isEmpty(settleType)){
							param.setErrorMessage(InsurancesConstants.PROJECT_NOT_FIND_SETTLE_TYPE);
							listResult.add(param);
							continue;
						}else {
							param.setSettleType(Integer.parseInt(settleType));
						}
					}
				}
			}

			//省市区域校验是否正确并设置对应id
			String redisProvinceName = getRedisAreaValue(param.getInsuranceProvinceName());
			if (Common.isEmpty(redisProvinceName)){
				param.setErrorMessage(InsurancesConstants.INSURANCE_PROVINCE_NAME_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				param.setInsuranceProvince(Integer.parseInt(redisProvinceName));
			}
			String redisCityName = getRedisAreaValue(param.getInsuranceCityName() + "_" + param.getInsuranceProvinceName());
			if (Common.isEmpty(redisCityName)){
				param.setErrorMessage(InsurancesConstants.INSURANCE_CITY_NAME_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				param.setInsuranceCity(Integer.parseInt(redisCityName));
			}
			String redisHandleProvinceName = getRedisAreaValue(param.getInsuranceHandleProvinceName());
			if (Common.isEmpty(redisHandleProvinceName)){
				param.setErrorMessage(InsurancesConstants.INSURANCE_HANDLE_PROVINCE_NAME_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				param.setInsuranceHandleProvince(Integer.parseInt(redisHandleProvinceName));
			}
			String redisHandleCityName = getRedisAreaValue(param.getInsuranceHandleCityName() + "_" + param.getInsuranceHandleProvinceName());
			if (Common.isEmpty(redisHandleCityName)){
				param.setErrorMessage(InsurancesConstants.INSURANCE_HANDLE_CITY_NAME_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				param.setInsuranceHandleCity(Integer.parseInt(redisHandleCityName));
			}

			// 保单开始日期 > 当前派单日期
			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::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.stream().distinct().collect(Collectors.toList())) {
			// 必填校验
			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;
			}

			//todo 检验身份合法

			//根据项目编码查询项目是否存在
			R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(Arrays.asList(param.getDeptNo()));
			if (null != setInfoByCodes && setInfoByCodes.getCode() == CommonConstants.SUCCESS) {
				Map<String, ProjectSetInfoVo> data = setInfoByCodes.getData().getProjectSetInfoVoMap();
				if (MapUtils.isEmpty(data)){
					param.setErrorMessage(InsurancesConstants.DEPT_NO_IS_NOT_EXIST);
					listResult.add(param);
					continue;
				}else {
					ProjectSetInfoVo jsonObject = data.get(param.getDeptNo());
					if (null == jsonObject){
						param.setErrorMessage(InsurancesConstants.DEPT_NO_IS_NOT_EXIST);
						listResult.add(param);
						continue;
					}else {
						//结算类型，根据项目编码获取，并冗余到明细记录中
						String settleType = jsonObject.getInsuranceSettleType();
						if (StringUtils.isEmpty(settleType)){
							param.setErrorMessage(InsurancesConstants.PROJECT_NOT_FIND_SETTLE_TYPE);
							listResult.add(param);
							continue;
						}else {
							param.setSettleType(Integer.parseInt(settleType));
						}
					}
				}
			}

			//省市区域校验是否正确并设置对应id
			String redisProvinceName = getRedisAreaValue(param.getInsuranceProvinceName());
			if (Common.isEmpty(redisProvinceName)){
				param.setErrorMessage(InsurancesConstants.INSURANCE_PROVINCE_NAME_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				param.setInsuranceProvince(Integer.parseInt(redisProvinceName));
			}
			String redisCityName = getRedisAreaValue(param.getInsuranceCityName() + "_" + param.getInsuranceProvinceName());
			if (Common.isEmpty(redisCityName)){
				param.setErrorMessage(InsurancesConstants.INSURANCE_CITY_NAME_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				param.setInsuranceCity(Integer.parseInt(redisCityName));
			}
			String redisHandleProvinceName = getRedisAreaValue(param.getInsuranceHandleProvinceName());
			if (Common.isEmpty(redisHandleProvinceName)){
				param.setErrorMessage(InsurancesConstants.INSURANCE_HANDLE_PROVINCE_NAME_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				param.setInsuranceHandleProvince(Integer.parseInt(redisHandleProvinceName));
			}
			String redisHandleCityName = getRedisAreaValue(param.getInsuranceHandleCityName() + "_" + param.getInsuranceHandleProvinceName());
			if (Common.isEmpty(redisHandleCityName)){
				param.setErrorMessage(InsurancesConstants.INSURANCE_HANDLE_CITY_NAME_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				param.setInsuranceHandleCity(Integer.parseInt(redisHandleCityName));
			}

			// 保险公司-险种-购买标准 是否存在
			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.stream().distinct().collect(Collectors.toList())) {
			// 必填校验
			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.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;
			}
			// todo校验身份合法
			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;
	}

	/**
	 * 登记保单保费校验
	 *
	 * @author licancan
	 * @param paramList
	 * @return {@link Map<String, List<InsuranceRegisterParam>>}
	 */
	private Map<String,List<InsuranceRegisterParam>> registeredPolicyPremiumCheck(List<InsuranceRegisterParam> paramList){
		Map<String,List<InsuranceRegisterParam>> map = new HashMap<>();
		List<InsuranceRegisterParam> listResult = new ArrayList<>();
		List<InsuranceRegisterParam> listSuccess = new ArrayList<>();
		for (InsuranceRegisterParam param : paramList.stream().distinct().collect(Collectors.toList())) {
			// 必填校验
			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.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;
			}
			// 身份证号位数校验（18 位合法）
			if (ValidityUtil.validateIDCard(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.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::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.DATA_IS_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				// 如果保费不存在，保单号、保费必填
				if (detail.getActualPremium() == null){
					if (StringUtils.isBlank(param.getPolicyNo())){
						param.setErrorMessage(InsurancesConstants.POLICY_NO_EMPTY);
						listResult.add(param);
						continue;
					}
					if (StringUtils.isBlank(param.getActualPremium())){
						param.setErrorMessage(InsurancesConstants.ACTUAL_PREMIUM_NO_EMPTY);
						listResult.add(param);
						continue;
					}
				}
			}
			listSuccess.add(param);
		}
		map.put("listResult",listResult);
		map.put("listSuccess",listSuccess);
		return map;
	}

	/**
	 * 根据区域名称获取区域id
	 *
	 * @author licancan
	 * @param areaString
	 * @return {@link String}
	 */
	private String getRedisAreaValue(String areaString) {
		return String.valueOf(RedisUtil.redis.opsForValue().get(CacheConstants.AREA_VALUE + areaString));
	}

	/***********************减员办理********************************/
	/**
	 * 减员导入校验
	 *
	 * @author zhaji
	 * @param insuranceRefundCheckList 减员表
	 * @return {@link R}
	 */
	@Override
	public R checkInsuranceRefundList(List<InsuranceRefundCheck> insuranceRefundCheckList) {
		YifuUser user = SecurityUtils.getUser();
		if(!Common.isNotEmpty(insuranceRefundCheckList)){
			return R.failed("当前导入的减员信息为空");
		}
		List<InsuranceRefundCheck> errorList = new ArrayList(128);
		List<TInsuranceDetail> successList = new ArrayList<>();
		for (InsuranceRefundCheck param : insuranceRefundCheckList) {
			//员工姓名
			String empName = param.getEmpName();
			if(StringUtils.isBlank(empName)){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			//员工身份证
			String empIdCardNo = param.getEmpIdCardNo();
			if(StringUtils.isBlank(empIdCardNo)){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			//保险公司名称
			String insuranceCompanyName = param.getInsuranceCompanyName();
			if(StringUtils.isBlank(insuranceCompanyName)){
				param.setErrorMessage(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			//险种名称
			String insuranceTypeName = param.getInsuranceTypeName();
			if(StringUtils.isBlank(insuranceTypeName)){
				param.setErrorMessage(InsurancesConstants.INSURANCE_TYPE_NAME_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			//保单开始日期
			String policyStart = param.getPolicyStart();
			if(StringUtils.isBlank(policyStart)){
				param.setErrorMessage(InsurancesConstants.POLICY_START_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			//保单结束日期
			String policyEnd = param.getPolicyEnd();
			if(StringUtils.isBlank(policyEnd)){
				param.setErrorMessage(InsurancesConstants.POLICY_END_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			// 身份证号位数校验（18 位合法）
			if (ValidityUtil.validateIDCard(param.getEmpIdCardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_LEGITIMATE);
				errorList.add(param);
				continue;
			}
			// 保单开始日期格式校验
			if(!LocalDateUtil.isDate(policyStart,LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_START_PARSE_ERROR);
				errorList.add(param);
				continue;
			}
			// 保单结束日期格式校验
			if(!LocalDateUtil.isDate(policyEnd,LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_END_PARSE_ERROR);
				errorList.add(param);
				continue;
			}
			LambdaQueryWrapper<TInsuranceDetail> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(TInsuranceDetail :: getDeleteFlag,CommonConstants.ZERO_INT).eq(TInsuranceDetail ::getEmpName,empName )
					.eq(TInsuranceDetail ::getEmpIdcardNo,empIdCardNo ).eq(TInsuranceDetail :: getInsuranceTypeName,insuranceCompanyName )
					.eq(TInsuranceDetail :: getPolicyStart,policyStart ).eq(TInsuranceDetail :: getPolicyEnd,policyEnd);
			TInsuranceDetail one = getOne(queryWrapper);
			if (Common.isEmpty(one)){
				param.setErrorMessage(InsurancesConstants.DATA_IS_NOT_EXIST);
				errorList.add(param);
				continue;
			}
			Integer buyHandleStatus = one.getBuyHandleStatus();
			if (CommonConstants.THREE_INT != buyHandleStatus){
				param.setErrorMessage(InsurancesConstants.REFUND_ERROR);
				errorList.add(param);
				continue;
			}
			Integer reduceHandleStatus = one.getReduceHandleStatus();
			//当前保单信息的减员状态不为空时不能进行导入
			if(reduceHandleStatus != null && CommonConstants.THREE_INT != reduceHandleStatus ){
				param.setErrorMessage(InsurancesConstants.REFUND_ERROR);
				errorList.add(param);
				continue;
			}
			//出险状态
			if(CommonConstants.ZERO_INT != one.getIsUse()){
				param.setErrorMessage(InsurancesConstants.IS_USE_ERROR);
				errorList.add(param);
				continue;
			}
			//有效状态
			if(CommonConstants.ZERO_INT != one.getIsEffect()){
				param.setErrorMessage(InsurancesConstants.IS_EFFECT_ERROR);
				errorList.add(param);
				continue;
			}
			//过期状态
			if (CommonConstants.ZERO_INT != one.getIsOverdue()){
				param.setErrorMessage(InsurancesConstants.IS_OVERDUE_ERROR);
				errorList.add(param);
				continue;
			}
			one.setReduceHandleStatus(CommonConstants.ONE_INT);
			one.setUpdateTime(LocalDateTime.now());
			one.setUpdateBy(user.getId());
			successList.add(one);
		}
		//批量更新减员状态
		if (CollectionUtils.isNotEmpty(successList)){
			this.updateBatchById(successList);
		}
		return R.ok(errorList);
	}

	/**
	 * 已投保列表分页查询
	 *
	 * @author zhaji
	 * @param page 分页参数
	 * @param param 查询参数
	 * @return {@link IPage< InsuredListVo>}
	 */
	@Override
	public IPage<InsuredListVo> getInsuredListPage(Page<InsuredListVo> page, InsuredParam param) {
		IPage<InsuredListVo> insuranceList = this.baseMapper.getInsuredListPage(page, param);
		if (CollectionUtils.isNotEmpty(insuranceList.getRecords())){
			//根据项目编码获取项目名称
			List<String> collect = insuranceList.getRecords().stream().map(e -> e.getDeptNo()).distinct().collect(Collectors.toList());
			R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(collect);
			if (null != setInfoByCodes && setInfoByCodes.getCode() != CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
				Map<String, ProjectSetInfoVo>  data = setInfoByCodes.getData().getProjectSetInfoVoMap();
				for (InsuredListVo record : insuranceList.getRecords()) {
					ProjectSetInfoVo jsonObject = data.get(record.getDeptNo());
					if (null != jsonObject){
						record.setProjectName(Optional.ofNullable(jsonObject.getDepartName()).orElse(""));
					}
				}
			}
		}
		return insuranceList;
	}

	/**
	 * 已投保列表不分页查询
	 *
	 * @author zhaji
	 * @param param 查询参数
	 * @return {@link List< InsuredListVo>}
	 */
	@Override
	public List<InsuredListVo> getInsuredList(InsuredParam param) {
		List<InsuredListVo> insuredList = this.baseMapper.getInsuredList(param);
		if (CollectionUtils.isNotEmpty(insuredList)){
			//根据项目编码获取项目名称
			List<String> collect = insuredList.stream().map(e -> e.getDeptNo()).distinct().collect(Collectors.toList());
			R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(collect);
			if (null != setInfoByCodes && setInfoByCodes.getCode() != CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
				Map<String, ProjectSetInfoVo>  data = setInfoByCodes.getData().getProjectSetInfoVoMap();
				for (InsuredListVo record : insuredList) {
					ProjectSetInfoVo jsonObject =  data.get(record.getDeptNo());
					if (null != jsonObject){
						record.setProjectName(Optional.ofNullable(jsonObject.getDepartName()).orElse(""));
					}
				}
			}
		}
		return insuredList;
	}

	/**
	 * 已减员列表分页查询
	 *
	 * @author zhaji
	 * @param page 分页数据
	 * @param param 查询参数
	 * @return {@link IPage<  InsuranceRefundListVo >}
	 */
	@Override
	public IPage<InsuranceRefundListVo> getInsuranceRefundPageList(Page<InsuranceRefundParam> page, InsuranceRefundParam param) {
		IPage<InsuranceRefundListVo> insuranceRefundPageList = this.baseMapper.getInsuranceRefundPageList(page, param);
		if (CollectionUtils.isNotEmpty(insuranceRefundPageList.getRecords())){
			//根据项目编码获取项目名称
			List<String> collect = insuranceRefundPageList.getRecords().stream().map(e -> e.getDeptNo()).distinct().collect(Collectors.toList());
			R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(collect);
			if (null != setInfoByCodes && setInfoByCodes.getCode() != CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
				Map<String, ProjectSetInfoVo> data = setInfoByCodes.getData().getProjectSetInfoVoMap();
				for (InsuranceRefundListVo record : insuranceRefundPageList.getRecords()) {
					ProjectSetInfoVo jsonObject = data.get(record.getDeptNo());
					if (null != jsonObject){
						record.setProjectName(Optional.ofNullable(jsonObject.getDepartName()).orElse(""));
					}
				}
			}
		}
		return insuranceRefundPageList;
	}

	/**
	 * 已减员列表不分页查询
	 *
	 * @author zhaji
	 * @param param 查询参数
	 * @return {@link List<  InsuranceRefundListVo >}
	 */
	@Override
	public List<InsuranceRefundListVo> getInsuranceRefundList(InsuranceRefundParam param) {
		List<InsuranceRefundListVo> insuranceRefundList = this.baseMapper.getInsuranceRefundList(param);
		if (CollectionUtils.isNotEmpty(insuranceRefundList)){
			//根据项目编码获取项目名称
			List<String> collect = insuranceRefundList.stream().map(e -> e.getDeptNo()).distinct().collect(Collectors.toList());
			R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(collect);
			if (null != setInfoByCodes && setInfoByCodes.getCode() != CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
				Map<String, ProjectSetInfoVo>  data = setInfoByCodes.getData().getProjectSetInfoVoMap();
				for (InsuranceRefundListVo record : insuranceRefundList) {
					ProjectSetInfoVo jsonObject = data.get(record.getDeptNo());
					if (null != jsonObject){
						record.setProjectName(Optional.ofNullable(jsonObject.getDepartName()).orElse(""));
					}
				}
			}
		}
		return insuranceRefundList;
	}

	/**
	 * 减员办理列表分页查询
	 *
	 * @author zhaji
	 * @param page 分页数据
	 * @param param 查询参数
	 * @return {@link IPage< InsuranceRefundHandlingListVo>}
	 */
	@Override
	public IPage<InsuranceRefundHandlingListVo> getInsuranceRefundHandlingPageList(Page<InsuranceRefundHandlingParam> page, InsuranceRefundHandlingParam param) {

		IPage<InsuranceRefundHandlingListVo> insuranceRefundHandlingPageList = this.baseMapper.getInsuranceRefundHandlingPageList(page, param);
		if (CollectionUtils.isNotEmpty(insuranceRefundHandlingPageList.getRecords())){
			//根据项目编码获取项目名称
			List<String> collect = insuranceRefundHandlingPageList.getRecords().stream().map(e -> e.getDeptNo()).distinct().collect(Collectors.toList());
			R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(collect);
			if (null != setInfoByCodes && setInfoByCodes.getCode() != CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
				Map<String, ProjectSetInfoVo> data = setInfoByCodes.getData().getProjectSetInfoVoMap();
				for (InsuranceRefundHandlingListVo record : insuranceRefundHandlingPageList.getRecords()) {
					ProjectSetInfoVo jsonObject = data.get(record.getDeptNo());
					if (null != jsonObject){
						record.setProjectName(Optional.ofNullable(jsonObject.getDepartName()).orElse(""));
					}
				}
			}
		}

		return insuranceRefundHandlingPageList;
	}

	/**
	 * 减员办理列表不分页查询
	 *
	 * @author zhaji
	 * @param param 查询参数
	 * @return {@link List< InsuranceRefundHandlingListVo>}
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public List<InsuranceRefundHandlingListVo> getInsuranceRefundHandlingList(InsuranceRefundHandlingParam param) {
		YifuUser user = SecurityUtils.getUser();
		List<InsuranceRefundHandlingListVo> insuranceRefundHandlingList = this.baseMapper.getInsuranceRefundHandlingList(param);
		if (CollectionUtils.isNotEmpty(insuranceRefundHandlingList)){
			//根据项目编码获取项目名称
			List<String> collect = insuranceRefundHandlingList.stream().map(e -> e.getDeptNo()).distinct().collect(Collectors.toList());
			R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(collect);
			if (null != setInfoByCodes && setInfoByCodes.getCode() != CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
				Map<String, ProjectSetInfoVo> data = setInfoByCodes.getData().getProjectSetInfoVoMap();
				for (InsuranceRefundHandlingListVo record : insuranceRefundHandlingList) {
					ProjectSetInfoVo jsonObject = data.get(record.getDeptNo());
					if (null != jsonObject){
						record.setProjectName(Optional.ofNullable(jsonObject.getDepartName()).orElse(""));
					}
				}
			}
		}
		for (InsuranceRefundHandlingListVo insuranceRefund : insuranceRefundHandlingList) {
			LambdaUpdateWrapper<TInsuranceDetail> updateWrapper = new LambdaUpdateWrapper<>();
			updateWrapper.eq(TInsuranceDetail :: getId,insuranceRefund.getId())
					.set(TInsuranceDetail :: getReduceHandleStatus,CommonConstants.TWO_INT)
					.set(TInsuranceDetail ::getUpdateTime,LocalDateTime.now())
					.set(TInsuranceDetail ::getUpdateBy,user.getId());
			update(updateWrapper);
		}
		return insuranceRefundHandlingList;
	}

	/**
	 * 减员办理
	 *
	 * @author zhaji
	 * @param insuranceDetail 办理类
	 * @return {@link R}
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R updateInsuranceRefund(InsuranceRefundListParam insuranceDetail) {
		YifuUser user = SecurityUtils.getUser();
		insuranceDetail.setUpdateBy(user.getId());
		insuranceDetail.setRefundCreateTime(LocalDateTime.now());
		String refundType = insuranceDetail.getRefundType();
		return R.ok(this.baseMapper.updateInsuranceRefund(insuranceDetail));
	}

	/**
	 * 结算月份校验
	 *
	 * @author zhaji
	 * @param settleMonthCheckList 变更列表
	 * @return {@link R}
	 */
	private Map<String,List<SettleMonthChangeCheckParam>> settleMonthChangeCheck(List<SettleMonthChangeCheckParam> settleMonthCheckList) {
		Map<String,List<SettleMonthChangeCheckParam>> map = new HashMap<>(16);
		List<SettleMonthChangeCheckParam> errorList = new ArrayList();
		List<SettleMonthChangeCheckParam> successList = new ArrayList<>();
		for (SettleMonthChangeCheckParam param : settleMonthCheckList) {
			//结算月
			String settleMonth = param.getSettleMonth();
			if(StringUtils.isBlank(settleMonth)){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//员工姓名
			String empName = param.getEmpName();
			if(StringUtils.isBlank(empName)){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			//员工身份证
			String empIdCardNo = param.getEmpIdCardNo();
			if(StringUtils.isBlank(empIdCardNo)){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			//保险公司名称
			String insuranceCompanyName = param.getInsuranceCompanyName();
			if(StringUtils.isBlank(insuranceCompanyName)){
				param.setErrorMessage(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			//险种名称
			String insuranceTypeName = param.getInsuranceTypeName();
			if(StringUtils.isBlank(insuranceTypeName)){
				param.setErrorMessage(InsurancesConstants.INSURANCE_TYPE_NAME_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			//保单开始日期
			String policyStart = param.getPolicyStart();
			if(StringUtils.isBlank(policyStart)){
				param.setErrorMessage(InsurancesConstants.POLICY_START_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			//保单结束日期
			String policyEnd = param.getPolicyEnd();
			if(StringUtils.isBlank(policyEnd)){
				param.setErrorMessage(InsurancesConstants.POLICY_END_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//所属项目
			String deptNo = param.getDeptNo();
			if(StringUtils.isBlank(deptNo)){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//购买标准
			String buyStandard = param.getBuyStandard();
			if(StringUtils.isBlank(buyStandard)){
				param.setErrorMessage(InsurancesConstants.BUY_STANDARD_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			// 身份证号位数校验（18 位合法）
			if (ValidityUtil.validateIDCard(param.getEmpIdCardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_LEGITIMATE);
				errorList.add(param);
				continue;
			}
			// 保单开始日期格式校验
			if(!LocalDateUtil.isDate(policyStart,LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_START_PARSE_ERROR);
				errorList.add(param);
				continue;
			}
			// 保单结束日期格式校验
			if(!LocalDateUtil.isDate(policyEnd,LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_END_PARSE_ERROR);
				errorList.add(param);
				continue;
			}

			// 结算月份 >= 派单月份（结算月 < 派单月份的记录予以拦截，并提示）
			if(!LocalDateUtil.isDate(param.getSettleMonth(),LocalDateUtil.NORM_MONTH_PATTERN)){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_PARSE_ERROR);
				errorList.add(param);
				continue;
			}
			if(!LocalDateUtil.isCurrentOrFutureMonth(param.getSettleMonth())){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_SHOULD_IS_FUTURE);
				errorList.add(param);
				continue;
			}
			//必填格式校通过后查询对应的保单信息
			LambdaQueryWrapper<TInsuranceDetail> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(TInsuranceDetail :: getDeleteFlag,CommonConstants.ZERO_INT).eq(TInsuranceDetail ::getEmpName,empName )
					.eq(TInsuranceDetail ::getEmpIdcardNo,empIdCardNo ).eq(TInsuranceDetail :: getInsuranceTypeName,insuranceCompanyName )
					.eq(TInsuranceDetail :: getDeptNo,deptNo).eq(TInsuranceDetail :: getBuyStandard,buyStandard)
					.eq(TInsuranceDetail :: getInsuranceCompanyName,insuranceCompanyName)
					.eq(TInsuranceDetail :: getPolicyStart,policyStart ).eq(TInsuranceDetail :: getPolicyEnd,policyEnd);
			TInsuranceDetail insuranceDetail = getOne(queryWrapper);
			//如果保单信息为空
			if (Common.isEmpty(insuranceDetail)){
				param.setErrorMessage(InsurancesConstants.DATA_IS_NOT_EXIST);
				errorList.add(param);
				continue;
			}
			Integer buyType = insuranceDetail.getBuyType();
			if (CommonConstants.FOUR_INT == buyType){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_CHANGE_IS_EFFECT_ERROR);
				errorList.add(param);
				continue;
			}
			//如果结算月份相同
			if (settleMonth.equals(insuranceDetail.getSettleMonth())){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_IDENTICAL);
				errorList.add(param);
				continue;
			}
			//非已办理状态
			Integer buyHandleStatus = insuranceDetail.getBuyHandleStatus();
			if (CommonConstants.THREE_INT != buyHandleStatus){
				param.setErrorMessage(InsurancesConstants.REFUND_ERROR);
				errorList.add(param);
				continue;
			}
			//查询结算状态
			LambdaQueryWrapper<TInsuranceSettle> insuranceSettleQuery = new LambdaQueryWrapper<>();
			insuranceSettleQuery.eq(TInsuranceSettle :: getInsDetailId,insuranceDetail.getId());
			TInsuranceSettle insuranceSettle = insuranceSettleService.getOne(insuranceSettleQuery);
			//当前结算状态为已结算时，不能变更结算月
			if (CommonConstants.FOUR_STRING.equals(insuranceSettle.getSettleHandleStatus())){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_CHANGE_SETTLE_HANDLE_STATUS_ERROR);
				errorList.add(param);
				continue;
			}
			Integer reduceHandleStatus = insuranceDetail.getReduceHandleStatus();
			//当前保单信息的减员状态不为空时不能进行导入
			if(reduceHandleStatus != null && CommonConstants.THREE_INT != reduceHandleStatus ){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_CHANGE_REDUCE_HANDLE_STATUS_ERROR);
				errorList.add(param);
				continue;
			}
			//有效状态
			if(CommonConstants.ZERO_INT != insuranceDetail.getIsEffect()){
				param.setErrorMessage(InsurancesConstants.IS_EFFECT_ERROR);
				errorList.add(param);
				continue;
			}
			//判断当前数据中是否存在重复数据
			boolean b = successList.stream().anyMatch(u -> u.getEmpName().equals(param.getEmpName())
					&& u.getEmpIdCardNo().equals(param.getEmpIdCardNo())&& u.getDeptNo().equals(param.getDeptNo())
					&& u.getInsuranceCompanyName().equals(param.getInsuranceCompanyName())&& u.getInsuranceTypeName().equals(param.getInsuranceTypeName())
					&& u.getPolicyStart().equals(param.getPolicyStart())&& u.getPolicyEnd().equals(param.getPolicyEnd())
					&& u.getSettleMonth().equals(param.getSettleMonth())&& u.getBuyStandard().equals(param.getBuyStandard()));
			if(!b){
				successList.add(param);
			}else{
				param.setErrorMessage(InsurancesConstants.DUPLICATE_DATA_ERROR);
				errorList.add(param);
			}
		}
		map.put("errorList",errorList);
		map.put("successList",successList);
		return map;
	}
	/**
	 * 变更结算月份
	 *
	 * @author zhaji
	 * @param
	 * @return void
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public R settleMonthChange(List<SettleMonthChangeCheckParam> settleMonthCheckList) {
		YifuUser user = SecurityUtils.getUser();
		if(!Common.isNotEmpty(settleMonthCheckList)){
			return R.failed(InsurancesConstants.SETTLE_MONTH_CHANGE_LIST_IS_EMPTY);
		}
		Map<String, List<SettleMonthChangeCheckParam>> map = settleMonthChangeCheck(settleMonthCheckList);
		//todo 生成EKP通知，通知ekp变更结算月份
		List<SettleMonthChangeCheckParam> successList = map.get("successList");
		for (SettleMonthChangeCheckParam success : successList) {
			LambdaUpdateWrapper<TInsuranceDetail> updateWrapper = new LambdaUpdateWrapper<>();
			updateWrapper.eq(TInsuranceDetail :: getDeleteFlag,CommonConstants.ZERO_INT).eq(TInsuranceDetail ::getEmpName,success.getEmpName())
					.eq(TInsuranceDetail ::getEmpIdcardNo,success.getEmpIdCardNo()).eq(TInsuranceDetail :: getInsuranceTypeName,success.getInsuranceTypeName() )
					.eq(TInsuranceDetail :: getDeptNo,success.getDeptNo()).eq(TInsuranceDetail :: getBuyStandard,success.getBuyStandard())
					.eq(TInsuranceDetail :: getInsuranceCompanyName,success.getInsuranceCompanyName())
					.eq(TInsuranceDetail :: getPolicyStart,success.getPolicyStart() ).eq(TInsuranceDetail :: getPolicyEnd,success.getPolicyEnd())
					.set(TInsuranceDetail :: getSettleMonth,success.getSettleMonth())
					.set(TInsuranceDetail :: getUpdateBy,user.getId())
					.set(TInsuranceDetail :: getUpdateTime,LocalDateTime.now());
			update(updateWrapper);
		}
		List<SettleMonthChangeCheckParam> errorList = map.get("errorList");
		//判断当前变更是否全部成功
		return R.ok(errorList);

	}

	/**
	 * 变更所属项目
	 *
	 * @author zhaji
	 * @param deptChangeCheckList 变更列表
	 * @return {@link R}
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R deptChange(List<DeptChangeCheckParam> deptChangeCheckList) {
		YifuUser user = SecurityUtils.getUser();
		if(!Common.isNotEmpty(deptChangeCheckList)){
			return R.failed("当前变更所属项目列表为空");
		}
		Map<String, List<DeptChangeCheckParam>> stringListMap = deptChangeCheck(deptChangeCheckList);
		//todo 生成EKP通知，通知ekp变更结算所属项目
		List<DeptChangeCheckParam> successList = stringListMap.get("successList");
		for (DeptChangeCheckParam success : successList) {
			LambdaUpdateWrapper<TInsuranceDetail> updateWrapper = new LambdaUpdateWrapper<>();
			updateWrapper.eq(TInsuranceDetail :: getDeleteFlag,CommonConstants.ZERO_INT).eq(TInsuranceDetail ::getEmpName,success.getEmpName())
					.eq(TInsuranceDetail ::getEmpIdcardNo,success.getEmpIdCardNo()).eq(TInsuranceDetail :: getInsuranceTypeName,success.getInsuranceTypeName() )
					.eq(TInsuranceDetail :: getDeptNo,success.getOldDeptNo()).eq(TInsuranceDetail :: getBuyStandard,success.getBuyStandard())
					.eq(TInsuranceDetail :: getInsuranceCompanyName,success.getInsuranceCompanyName())
					.eq(TInsuranceDetail :: getPolicyStart,success.getPolicyStart() ).eq(TInsuranceDetail :: getPolicyEnd,success.getPolicyEnd())
					.set(TInsuranceDetail :: getDeptNo,success.getNewDeptNo())
					.set(TInsuranceDetail :: getSettleType,success.getSettleType())
					.set(TInsuranceDetail :: getUpdateBy,user.getId())
					.set(TInsuranceDetail :: getUpdateTime,LocalDateTime.now());
			update(updateWrapper);
		}
		List<DeptChangeCheckParam> errorList = stringListMap.get("errorList");
		return R.ok(errorList);
	}
	
	/**
	 * 根据保险公司名称查询保单明细
	 *
	 * @author zhaji
	 * @param companyName 保险公司名称
	 * @return {@link R}
	 */
	@Override
	public R selectByCompanyName(String companyName) {
		LambdaQueryWrapper<TInsuranceDetail> typeWrapper = new LambdaQueryWrapper<>();
		typeWrapper.eq(TInsuranceDetail :: getInsuranceCompanyName ,companyName).eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT);
		return R.ok(list(typeWrapper));
	}

	/**
	 * 根据险种id查询保单明细
	 *
	 * @author zhaji
	 * @param id
	 * @return {@link R}
	 */
	@Override
	public R selectByTypeId(String id) {
		LambdaQueryWrapper<TInsuranceDetail> typeWrapper = new LambdaQueryWrapper<>();
		typeWrapper.eq(TInsuranceDetail :: getInsuranceTypeId ,id).eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT);
		return R.ok(list(typeWrapper));
	}

	/**
	 * 校验所属项目
	 *
	 * @author zhaji
	 * @param deptChangeCheckList 变更列表
	 * @return {@link R}
	 */
	public Map<String,List<DeptChangeCheckParam>> deptChangeCheck(List<DeptChangeCheckParam> deptChangeCheckList) {
		Map<String,List<DeptChangeCheckParam>> map = new HashMap<>(16);
		List<DeptChangeCheckParam> errorList = new ArrayList();
		List<DeptChangeCheckParam> successList = new ArrayList<>();
		for (DeptChangeCheckParam param : deptChangeCheckList) {
			String newDeptNo = param.getNewDeptNo();
			if(StringUtils.isBlank(newDeptNo)){
				param.setErrorMessage(InsurancesConstants.REPLACE_DEPT_NO_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//员工姓名
			String empName = param.getEmpName();
			if(StringUtils.isBlank(empName)){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//员工身份证
			String empIdCardNo = param.getEmpIdCardNo();
			if(StringUtils.isBlank(empIdCardNo)){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//保险公司名称
			String insuranceCompanyName = param.getInsuranceCompanyName();
			if(StringUtils.isBlank(insuranceCompanyName)){
				param.setErrorMessage(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//险种名称
			String insuranceTypeName = param.getInsuranceTypeName();
			if(StringUtils.isBlank(insuranceTypeName)){
				param.setErrorMessage(InsurancesConstants.INSURANCE_TYPE_NAME_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			//保单开始日期
			String policyStart = param.getPolicyStart();
			if(StringUtils.isBlank(policyStart)){
				param.setErrorMessage(InsurancesConstants.POLICY_START_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//保单结束日期
			String policyEnd = param.getPolicyEnd();
			if(StringUtils.isBlank(policyEnd)){
				param.setErrorMessage(InsurancesConstants.POLICY_END_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//所属项目
			String oldDeptNo = param.getOldDeptNo();
			if(StringUtils.isBlank(oldDeptNo)){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//新老项目id相同
			if (oldDeptNo.equals(newDeptNo)){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_IDENTICAL);
				errorList.add(param);
				continue;
			}
			//购买标准
			String buyStandard = param.getBuyStandard();
			if(StringUtils.isBlank(buyStandard)){
				param.setErrorMessage(InsurancesConstants.BUY_STANDARD_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			// 身份证号位数校验（18 位合法）
			if (ValidityUtil.validateIDCard(param.getEmpIdCardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_LEGITIMATE);
				errorList.add(param);
				continue;
			}
			// 保单开始日期格式校验
			if(!LocalDateUtil.isDate(policyStart,LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_START_PARSE_ERROR);
				errorList.add(param);
				continue;
			}
			// 保单结束日期格式校验
			if(!LocalDateUtil.isDate(policyEnd,LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_END_PARSE_ERROR);
				errorList.add(param);
				continue;
			}
			//必填格式校通过后查询对应的保单信息
			LambdaQueryWrapper<TInsuranceDetail> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(TInsuranceDetail :: getDeleteFlag,CommonConstants.ZERO_INT).eq(TInsuranceDetail ::getEmpName,empName )
					.eq(TInsuranceDetail ::getEmpIdcardNo,empIdCardNo ).eq(TInsuranceDetail :: getInsuranceTypeName,insuranceCompanyName )
					.eq(TInsuranceDetail :: getBuyStandard,buyStandard)
					.eq(TInsuranceDetail :: getInsuranceCompanyName,insuranceCompanyName)
					.eq(TInsuranceDetail :: getPolicyStart,policyStart ).eq(TInsuranceDetail :: getPolicyEnd,policyEnd);
			TInsuranceDetail insuranceDetail = getOne(queryWrapper);

			Integer buyType = insuranceDetail.getBuyType();
			if (CommonConstants.FOUR_INT == buyType){
				param.setErrorMessage(InsurancesConstants.DEPT_CHANGE_IS_EFFECT_ERROR);
				errorList.add(param);
				continue;
			}
			//根据项目编码查询项目是否存在
			R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(Arrays.asList(newDeptNo));
			if (null != setInfoByCodes && setInfoByCodes.getCode() != CommonConstants.SUCCESS) {
				Map<String, ProjectSetInfoVo>  data = setInfoByCodes.getData().getProjectSetInfoVoMap();
				if (MapUtils.isEmpty(data)){
					param.setErrorMessage(InsurancesConstants.DEPT_NO_IS_NOT_EXIST);
					errorList.add(param);
					continue;
				}else {
					ProjectSetInfoVo jsonObject =  data.get(newDeptNo);
					if (null == jsonObject){
						param.setErrorMessage(InsurancesConstants.DEPT_NO_IS_NOT_EXIST);
						errorList.add(param);
						continue;
					}else {
						//结算类型，根据项目编码获取，并冗余到明细记录中
						String settleType = jsonObject.getInsuranceSettleType();
						if (StringUtils.isEmpty(settleType)){
							param.setErrorMessage(InsurancesConstants.PROJECT_NOT_FIND_SETTLE_TYPE);
							errorList.add(param);
							continue;
						}else {
							param.setSettleType(Integer.parseInt(settleType));
						}
					}
				}
			}
			//判断当前数据中是否存在重复数据
			boolean b = successList.stream().anyMatch(u -> u.getEmpName().equals(param.getEmpName())
					&& u.getEmpIdCardNo().equals(param.getEmpIdCardNo())&& u.getOldDeptNo().equals(param.getOldDeptNo())
					&& u.getInsuranceCompanyName().equals(param.getInsuranceCompanyName())&& u.getInsuranceTypeName().equals(param.getInsuranceTypeName())
					&& u.getPolicyStart().equals(param.getPolicyStart())&& u.getPolicyEnd().equals(param.getPolicyEnd())
					&& u.getNewDeptNo().equals(param.getNewDeptNo())&& u.getBuyStandard().equals(param.getBuyStandard()));
			if(!b){
				successList.add(param);
			}else{
				param.setErrorMessage(InsurancesConstants.DUPLICATE_DATA_ERROR);
				errorList.add(param);
			}
		}
		map.put("errorList",errorList);
		map.put("successList",successList);
		return map;
	}
}
