package com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.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.check.entity.TCheckIdCard;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TSettleDomain;
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.archives.vo.TSettleDomainListVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainSelectVo;
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.constant.SecurityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprArchivesProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.*;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.ekp.constant.EkpConstants;
import com.yifu.cloud.plus.v1.yifu.ekp.util.EkpInsuranceUtil;
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.insurances.TInsuranceDetailMapper;
import com.yifu.cloud.plus.v1.yifu.insurances.service.ekp.EkpSettleService;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.*;
import com.yifu.cloud.plus.v1.yifu.insurances.util.BeanCopyUtils;
import com.yifu.cloud.plus.v1.yifu.insurances.util.BigDecimalUtils;
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 com.yifu.cloud.plus.v1.yifu.social.entity.TIncomeDetail;
import com.yifu.cloud.plus.v1.yifu.social.vo.TIncomeDetailReturnVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author licancan
 * @description 针对表【t_insurance_detail(商险明细表)】的数据库操作Service实现
 * @date 2022-07-18 16:20:16
 */
@Service
@Slf4j
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
	@Lazy
	private TInsuranceTypeRateService tInsuranceTypeRateService;
	@Resource
	private TInsuranceReplaceService tInsuranceReplaceService;
	@Resource
	private ArchivesDaprUtil archivesDaprUtil;
	@Resource
	private CheckDaprUtil checkDaprUtil;
	@Resource
	private TInsuranceSettleService tInsuranceSettleService;
	@Resource
	private TInsuranceOperateService tInsuranceOperateService;
	@Resource
	private TInsuranceRefundService tInsuranceRefundService;
	@Resource
	private TInsuranceEkpService tInsuranceEkpService;
	@Resource
	private EkpInsuranceUtil eKPInsuranceUtil;

	@Resource
	private EkpSettleService ekpSettleService;

	@Resource
	private TInsuranceSettleCancelService tInsuranceSettleCancelService;

	@Resource
	private SocialDaprUtils socialDaprUtils;

	@Resource
	private MenuUtil menuUtil;
	@Resource
	private DaprArchivesProperties daprArchivesProperties;

	/***********************商险办理********************************/
	/**
	 * 每日定时刷新商险到期数据
	 *
	 * @return void
	 * @author licancan
	 */
	@Override
	public void updateOverdueByTask() {
		// 获取未过期的所有明细数据
		List<TInsuranceDetail> list = this.baseMapper.selectList(Wrappers.<TInsuranceDetail>query().lambda()
				.eq(TInsuranceDetail::getIsOverdue, CommonConstants.ZERO_INT)
				.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
		);
		if (CollectionUtils.isNotEmpty(list)){
			log.info("定时任务扫描到的未过期数据是：{}条",list.size());
			list.stream().forEach(e -> {
				if (!LocalDateUtil.isOverdueDate(e.getPolicyEnd().toString())){
					e.setIsOverdue(CommonConstants.ONE_INT);
					e.setUpdateTime(LocalDateTime.now());
				}
			});
			List<TInsuranceDetail> collect = list.stream().filter(e -> e.getIsOverdue() == CommonConstants.ONE_INT).collect(Collectors.toList());
			if (CollectionUtils.isNotEmpty(collect)){
				log.info("定时任务扫描到的已过期数据是：{}条",collect.size());
				this.updateBatchById(collect);
			}
		}
	}

	/**
	 * EKP2INSURANCES 更新结算状态
	 *
	 * @param param
	 * @return {@link R<String>}
	 * @author licancan
	 */
	@Override
	public R<String> updateInsuranceSettle(UpdateInsuranceSettleParam param) {
		if(!Optional.ofNullable(param).isPresent()){
			return R.failed(CommonConstants.PARAM_IS_NOT_EMPTY);
		}
		if (CollectionUtils.isEmpty(param.getSettleData())){
			return R.failed(InsurancesConstants.SETTLE_DATA_IS_NOT_EXIST);
		}
		if (!Optional.ofNullable(param.getPushData()).isPresent()){
			return R.failed(InsurancesConstants.PUSH_DATA_IS_NOT_EXIST);
		}
		try {
			LocalDateTime pushTime = param.getPushData().getPushTime();
			List<UpdateInsuranceSettleParam.SettleData> settleData = param.getSettleData();
			List<TInsuranceSettle> list = new ArrayList<>();
			for (UpdateInsuranceSettleParam.SettleData settleDatum : settleData) {
				String settleId = settleDatum.getSn().split("_")[1];
				if (StringUtils.isNotBlank(settleId)){
					TInsuranceSettle byId = tInsuranceSettleService.getById(settleId);
					if (!Optional.ofNullable(byId).isPresent()){
						continue;
					}
					byId.setUpdateTime(pushTime);
					byId.setSettleHandleStatus(settleDatum.getSettleStatus());
					if (CommonConstants.THREE_STRING.equals(settleDatum.getSettleStatus())){
						byId.setSettleDoneTime(pushTime);
					}
					list.add(byId);
				}
			}
			if (CollectionUtils.isNotEmpty(list)){
				tInsuranceSettleService.saveOrUpdateBatch(list);
			}
		}catch (Exception e){
			e.printStackTrace();
			return R.failed();
		}
		return R.ok();
	}

	/**
	 * 投保分页查询
	 *
	 * @param page
	 * @param param
	 * @return {@link IPage < InsuranceListVO >}
	 * @author licancan
	 */
	@Override
	public IPage<InsuranceListVO> getInsuranceListPage(Page<InsuranceListVO> page, InsuranceListParam param, String mId) {
		YifuUser user = SecurityUtils.getUser();
		if (!Common.isEmpty(mId)) {
			param.setMId(mId);
		}
		param.setCreateBy(user.getId());
		menuUtil.setAuthSql(user, param);
		if (Common.isNotNull(param.getAuthSql()) && param.getAuthSql().contains("1=2 CONCAT")) {
			param.setAuthSql(param.getAuthSql().replace("1=2 CONCAT", "CONCAT"));
		}
		IPage<InsuranceListVO> insuranceList;
		insuranceList = baseMapper.getInsuranceListPage(page,param);
		// 购买月数
		if (CollectionUtils.isNotEmpty(insuranceList.getRecords())){
			insuranceList.getRecords().stream().forEach(e ->{
				e.setBuyMonth(LocalDateUtil.betweenMonth(e.getPolicyStart().toString(),e.getPolicyEnd().toString()));
			});
		}
		return insuranceList;
	}

	/**
	 * 投保不分页查询
	 *
	 * @param param
	 * @return {@link R<List<InsuranceListVO>>}
	 * @author licancan
	 */
	@Override
	public R<List<InsuranceListVO>> getInsuranceList(InsuranceListParam param, String mId) {
		YifuUser user = SecurityUtils.getUser();
		if (!Common.isEmpty(mId)) {
			param.setMId(mId);
		}
		param.setCreateBy(user.getId());
		menuUtil.setAuthSql(user, param);
		if (Common.isNotNull(param.getAuthSql()) && param.getAuthSql().contains("1=2 CONCAT")) {
			param.setAuthSql(param.getAuthSql().replace("1=2 CONCAT", "CONCAT"));
		}
		List<InsuranceListVO> insuranceList;
		insuranceList = baseMapper.getInsuranceList(param);
		// 购买月数
		if (CollectionUtils.isNotEmpty(insuranceList)){
			if(insuranceList.size() > CommonConstants.EXPORT_TWENTY_THOUSAND){
				return R.failed(InsurancesConstants.EXPORT_TOO_LONG);
			}
			insuranceList.stream().forEach(e ->{
				e.setBuyMonth(LocalDateUtil.betweenMonth(e.getPolicyStart().toString(),e.getPolicyEnd().toString()));
			});
			for (InsuranceListVO listVO : insuranceList) {
				if (CommonConstants.FOUR_INT == listVO.getBuyHandleStatus()) {
					TInsuranceOperate tInsuranceOperate = tInsuranceOperateService.getOne(Wrappers.<TInsuranceOperate>query().lambda()
							.eq(TInsuranceOperate::getInsuranceDetailId,listVO.getId())
							.eq(TInsuranceOperate::getDisplayFlag,CommonConstants.ONE_INT)
							.orderByDesc(TInsuranceOperate::getCreateTime)
							.last(CommonConstants.LAST_ONE_SQL)
					);
					if (Common.isNotNull(tInsuranceOperate)) {
						listVO.setRemark(tInsuranceOperate.getRemark());
					}
				}
			}
		}
		return R.ok(insuranceList);
	}
	/**
	 * 投保办理分页查询
	 *
	 * @param page
	 * @param param
	 * @return {@link IPage < InsuranceListVO >}
	 * @author licancan
	 */
	@Override
	public IPage<InsuranceListVO> getInsuranceHandleListPage(Page<InsuranceListVO> page, InsuranceListParam param, String mId) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isNotNull(mId)) {
			param.setMId(mId);
		}
		param.setCreateBy(user.getId());
		menuUtil.setAuthSql(user, param);
		if (Common.isNotNull(param.getAuthSql()) && param.getAuthSql().contains("1=2 CONCAT")) {
			param.setAuthSql(param.getAuthSql().replace("1=2 CONCAT", "CONCAT"));
		}
		Integer buyHandleStatus = param.getBuyHandleStatus();
		if(buyHandleStatus == CommonConstants.TWO_INT || buyHandleStatus == CommonConstants.THREE_INT){
			param.setUpdateBy(user.getId());
		}
		IPage<InsuranceListVO> insuranceList = baseMapper.getInsuranceHandleListPage(page,param);
		// 购买月数
		if (CollectionUtils.isNotEmpty(insuranceList.getRecords())){
			insuranceList.getRecords().stream().forEach(e ->{
				e.setBuyMonth(LocalDateUtil.betweenMonth(e.getPolicyStart().toString(),e.getPolicyEnd().toString()));
			});
		}
		return insuranceList;
	}

	/**
	 * 商险新增
	 *
	 * @param paramList
	 * @return {@link R <List<InsuranceAddParam>>}
	 * @author licancan
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R<List<InsuranceAddParam>> addInsurance(List<InsuranceAddParam> paramList,String orderNo) {
		if (CollectionUtils.isEmpty(paramList)){
			return R.failed(CommonConstants.DATA_CAN_NOT_EMPTY);
		}
		if(paramList.size() > CommonConstants.IMPORT_TWENTY_THOUSAND){
			return R.failed(InsurancesConstants.IMPORT_TOO_LONG);
		}
		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,user);
		//返回给前端的结果
		List<InsuranceAddParam> listResult = map.get("listResult");
		//保存到数据库中的结果
		List<InsuranceAddParam> listSuccess = map.get("listSuccess");
		List<TInsuranceDetail> detailList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(listSuccess)){
			for (InsuranceAddParam success : listSuccess) {
				TInsuranceDetail detail = new TInsuranceDetail();
				BeanCopyUtils.copyProperties(success,detail);
				//购买类型，默认为「新增」
				detail.setOrderNo(orderNo);
				detail.setBuyType(CommonConstants.ONE_INT);
				detail.setCreateUserDeptId(user.getDeptId().toString());
				detail.setCreateUserDeptName(user.getDeptName());
				//投保状态：待投保
				detail.setBuyHandleStatus(CommonConstants.ONE_INT);
				detail.setPolicyStart(LocalDateUtil.parseLocalDate(success.getPolicyStart()));
				detail.setPolicyEnd(LocalDateUtil.parseLocalDate(success.getPolicyEnd()));
				//保费都默认是0
				detail.setActualPremium(new BigDecimal("0.00"));
				detail.setEstimatePremium(new BigDecimal("0.00"));
				detail.setCreateBy(user.getId());
				detail.setCreateName(user.getNickname());
				detailList.add(detail);
			}
			this.saveBatch(detailList);
		}
		//操作记录
		addOperate(detailList,user,InsurancesConstants.ADD,null,CommonConstants.ONE_INT);
		return R.ok(listResult,InsurancesConstants.ADD_SUCCESS);
	}

	/**
	 * 商险批增
	 *
	 * @param paramList
	 * @return {@link R<List<InsuranceBatchParam>>}
	 * @author licancan
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R<List<InsuranceBatchParam>> batchInsurance(List<InsuranceBatchParam> paramList,String orderNo) {
		if (CollectionUtils.isEmpty(paramList)){
			return R.failed(CommonConstants.DATA_CAN_NOT_EMPTY);
		}
		if(paramList.size() > CommonConstants.IMPORT_TWENTY_THOUSAND){
			return R.failed(InsurancesConstants.IMPORT_TOO_LONG);
		}
		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,user);
		//返回给前端的结果
		List<InsuranceBatchParam> listResult = map.get("listResult");
		//保存到数据库中的结果
		List<InsuranceBatchParam> listSuccess = map.get("listSuccess");
		List<TInsuranceDetail> detailList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(listSuccess)){
			TInsuranceDetail detail;
			for (InsuranceBatchParam success : listSuccess) {
				detail = new TInsuranceDetail();
				BeanCopyUtils.copyProperties(success,detail);
				//购买类型，默认为「批增」
				detail.setBuyType(CommonConstants.THREE_INT);
				//投保状态：待投保
				detail.setBuyHandleStatus(CommonConstants.ONE_INT);
				//保费都默认是0
				detail.setOrderNo(orderNo);
				detail.setCreateUserDeptId(user.getDeptId().toString());
				detail.setCreateUserDeptName(user.getDeptName());
				detail.setActualPremium(new BigDecimal("0.00"));
				detail.setEstimatePremium(new BigDecimal("0.00"));
				detail.setCreateBy(user.getId());
				detail.setCreateName(user.getNickname());
				detailList.add(detail);
			}
			this.saveBatch(detailList);
		}
		//操作记录
		addOperate(detailList,user,InsurancesConstants.BATCH,null,CommonConstants.ONE_INT);
		return R.ok(listResult,InsurancesConstants.BATCH_SUCCESS);
	}

	/**
	 * 商险替换
	 *
	 * @param paramList
	 * @return {@link R<List<InsuranceReplaceParam>>}
	 * @author licancan
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R<List<InsuranceReplaceParam>> replaceInsurance(List<InsuranceReplaceParam> paramList,String orderNo) {
		if (CollectionUtils.isEmpty(paramList)){
			return R.failed(CommonConstants.DATA_CAN_NOT_EMPTY);
		}
		if(paramList.size() > CommonConstants.IMPORT_TWENTY_THOUSAND){
			return R.failed(InsurancesConstants.IMPORT_TOO_LONG);
		}
		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,user);
		//返回给前端的结果
		List<InsuranceReplaceParam> listResult = map.get("listResult");
		//保存到数据库中的结果
		List<InsuranceReplaceParam> listSuccess = map.get("listSuccess");
		List<TInsuranceDetail> detailList = new ArrayList<>();
		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)
						.orderByDesc(TInsuranceDetail::getUpdateTime)
						.last(CommonConstants.LAST_ONE_SQL)
				);
				BeanCopyUtils.copyProperties(detail,newDetail);
				detail.setIsEffect(CommonConstants.ONE_INT);
				detail.setIsOverdue(null);
				detail.setUpdateTime(LocalDateTime.now());
				this.updateById(detail);
				//新数据置为待办理
				newDetail.setId(null);
				newDetail.setOrderNo(orderNo);
				newDetail.setBuyHandleStatus(CommonConstants.ONE_INT);
				newDetail.setBuyType(CommonConstants.FOUR_INT);
				newDetail.setEmpName(success.getReplaceEmpName());
				newDetail.setEmpIdcardNo(success.getReplaceEmpIdcardNo());
				newDetail.setDeptNo(success.getReplaceDeptNo());
				newDetail.setDeptId(success.getDeptId());
				newDetail.setBpoFlag(success.getBpoFlag());
				newDetail.setDeptName(success.getDeptName());
				newDetail.setUnitId(success.getUnitId());
				newDetail.setUnitName(success.getUnitName());
				newDetail.setUnitNo(success.getUnitNo());
				//替换项目的结算方式
				newDetail.setSettleType(success.getSettleType());
				newDetail.setPost(success.getPost());
				//其他状态置为空
				newDetail.setIsOverdue(null);
				newDetail.setIsUse(null);
				newDetail.setIsEffect(null);
				newDetail.setReduceHandleStatus(null);
				newDetail.setCreateUserDeptId(user.getDeptId().toString());
				newDetail.setCreateUserDeptName(user.getDeptName());
				newDetail.setSignFlag(CommonConstants.ZERO_INT);
				//创建时间是新数据插入时间
				newDetail.setCreateTime(LocalDateTime.now());
				newDetail.setCreateBy(user.getId());
				newDetail.setCreateName(user.getNickname());
				//替换不参与结算
				newDetail.setDefaultSettleId(null);
				//替换不继承备注
				newDetail.setRemark(null);
				//替换不继承保单生效日期
				newDetail.setPolicyEffect(null);
				//保费都默认是0
				newDetail.setActualPremium(new BigDecimal("0.00"));
				newDetail.setEstimatePremium(new BigDecimal("0.00"));
				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);
				}
				detailList.add(newDetail);
			}
		}
		//操作记录
		addOperate(detailList,user,InsurancesConstants.REPLACE,null,CommonConstants.ONE_INT);
		return R.ok(listResult,InsurancesConstants.REPLACE_SUCCESS);
	}

	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return {@link R<String>}
	 * @author licancan
	 */
	@Override
	public R<String> deleteInsurance(String id) {
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		TInsuranceDetail byId = this.getById(id);
		if (null == byId){
			return R.failed(InsurancesConstants.DATA_IS_NOT_EXIST);
		}
		//校验当前保单信息是否由当前登录人创建
		String createBy = byId.getCreateBy();
		if(!createBy.equals(user.getId())){
			return R.failed(InsurancesConstants.NOT_CREATE_USER_DELETE_ERROR);
		}
		if (byId.getBuyHandleStatus() != CommonConstants.FOUR_INT){
			return R.failed(InsurancesConstants.DELETE_ERROR);
		}
		byId.setDeleteFlag(CommonConstants.ONE_INT);
		this.updateById(byId);
		//操作记录
		addOperate(Arrays.asList(byId),user,InsurancesConstants.DELETE,null,CommonConstants.ONE_INT);
		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);
		}
		//校验当前保单信息是否由当前登录人创建
		String createBy = byId.getCreateBy();
		if(!createBy.equals(user.getId())){
			return R.failed(InsurancesConstants.NOT_CREATE_USER_UPDATE_ERROR);
		}
		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);
			}
			//校验身份合法
			TCheckIdCard checkIdCard = new TCheckIdCard();
			checkIdCard.setName(param.getEmpName());
			checkIdCard.setIdCard(param.getEmpIdcardNo());
			R<TCheckIdCard> tCheckIdCardR = checkDaprUtil.checkIdCardSingle(checkIdCard);
			if (null != tCheckIdCardR && tCheckIdCardR.getCode() == CommonConstants.SUCCESS){
				TCheckIdCard data = tCheckIdCardR.getData();
				if (CommonConstants.ONE_INT != data.getIsTrue()){
					return R.failed(InsurancesConstants.EMP_ID_CARD_NO_NOT_FIT);
				}
			}

			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.compareDate(param.getPolicyStart(),param.getPolicyEnd())){
				return R.failed(InsurancesConstants.POLICY_START_SHOULD_LESS_THAN_POLICY_END);
			}

			//如果不是补单的，需要校验：保单开始日期 > 当前派单日期
			if (byId.getSignFlag() == CommonConstants.ZERO_INT){
				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)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (!Optional.ofNullable(insuranceCompany).isPresent()){
				return R.failed(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EXIST);
			}else {
				//冗余保险公司计费方式
				byId.setBillingType(Integer.valueOf(insuranceCompany.getBillingType()));

				TInsuranceType insuranceType = tInsuranceTypeService.getOne(Wrappers.<TInsuranceType>query().lambda()
						.eq(TInsuranceType::getName, param.getInsuranceTypeName())
						.eq(TInsuranceType::getInsuranceCompanyId, insuranceCompany.getId())
						.eq(TInsuranceType::getDeleteFlag, CommonConstants.ZERO_INT)
						.last(CommonConstants.LAST_ONE_SQL)
				);
				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)
							.last(CommonConstants.LAST_ONE_SQL)
					);
					if (!Optional.ofNullable(typeStandard).isPresent()){
						return R.failed(InsurancesConstants.BUY_STANDARD_NOT_EXIST);
					}else {
						// "医疗额度" 和  "身故或残疾"，由系统根据 保险公司+险种+ 购买标准 关联查询，并补全
						// 这里计算好赋值，是为了方便入库
						param.setMedicalQuota(typeStandard.getMedicalQuota());
						param.setDieDisableQuota(typeStandard.getDieDisableQuota());
						param.setInsuranceTypeId(Long.parseLong(typeStandard.getInsuranceTypeId()));
					}

					//按月查费率
					if (CommonConstants.ONE_STRING.equals(insuranceCompany.getBillingType())){
						//计算起止时间的月数
						long month = LocalDateUtil.betweenMonth(param.getPolicyStart(), param.getPolicyEnd());
						TInsuranceTypeRate typeRate = tInsuranceTypeRateService.getOne(Wrappers.<TInsuranceTypeRate>query().lambda()
								.eq(TInsuranceTypeRate::getInsuranceTypeId, insuranceType.getId())
								.eq(TInsuranceTypeRate::getMonth, month)
								.eq(TInsuranceTypeRate::getDeleteFlag, CommonConstants.ZERO_INT)
								.last(CommonConstants.LAST_ONE_SQL)
						);
						if (!Optional.ofNullable(typeRate).isPresent()){
							return R.failed(InsurancesConstants.INSURANCE_TYPE_RATE_NOT_EXIST);
						}else {
							//冗余费率
							byId.setRate(new BigDecimal(typeRate.getRate()));
						}
					}
				}
			}
			//记录查重校验：姓名 + 身份证号 + 保险公司 + 险种 + 保单开始日期~保单结束日期区间 是唯一（剔除退回、过期状态的记录）
			//待投保、投保中、已投保(有效、未过期)
			Set<Integer> setRStatus = Sets.newHashSet();
			setRStatus.add(CommonConstants.FOUR_INT);
			setRStatus.add(CommonConstants.FIVE_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)
					//有效
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsEffect,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsEffect)
					)
					//未过期
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsOverdue,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsOverdue)
					)
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (Optional.ofNullable(insuranceDetail).isPresent() && !insuranceDetail.getId().equals(param.getId())){
				return R.failed(InsurancesConstants.DATA_IS_EXIST);
			}
			//时间区间
			TInsuranceDetail insuranceDetailBetween = 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())
					.notIn(TInsuranceDetail::getBuyHandleStatus, setRStatus)
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
					.and(
							wrapper -> 	wrapper.and(
											s -> s.le(TInsuranceDetail::getPolicyStart,LocalDateUtil.parseLocalDate(param.getPolicyStart()))
													.ge(TInsuranceDetail::getPolicyEnd,LocalDateUtil.parseLocalDate(param.getPolicyStart()))
									)
									.or(e -> e.le(TInsuranceDetail::getPolicyStart,LocalDateUtil.parseLocalDate(param.getPolicyEnd()))
											.ge(TInsuranceDetail::getPolicyEnd,LocalDateUtil.parseLocalDate(param.getPolicyEnd())))
									.or(s -> s.ge(TInsuranceDetail::getPolicyStart,LocalDateUtil.parseLocalDate(param.getPolicyStart()))
											.le(TInsuranceDetail::getPolicyStart,LocalDateUtil.parseLocalDate(param.getPolicyEnd())))
									.or(s -> s.ge(TInsuranceDetail::getPolicyEnd,LocalDateUtil.parseLocalDate(param.getPolicyStart()))
											.le(TInsuranceDetail::getPolicyEnd,LocalDateUtil.parseLocalDate(param.getPolicyEnd())))
					)
					//有效
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsEffect,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsEffect)
					)
					//未过期
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsOverdue,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsOverdue)
					)
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL)
			);

			if (Optional.ofNullable(insuranceDetailBetween).isPresent() && !insuranceDetailBetween.getId().equals(param.getId())){
				return R.failed("当前员工在["+insuranceDetailBetween.getPolicyStart()+"-"+insuranceDetailBetween.getPolicyEnd()+"]期间内有投保记录");
			}
			BeanCopyUtils.copyProperties(param,byId);
			//投保状态：待投保
			byId.setBuyHandleStatus(CommonConstants.ONE_INT);
			byId.setPolicyStart(LocalDateUtil.parseLocalDate(param.getPolicyStart()));
			byId.setPolicyEnd(LocalDateUtil.parseLocalDate(param.getPolicyEnd()));
			byId.setCreateBy(user.getId());
			byId.setCreateTime(LocalDateTime.now());
			byId.setUpdateBy(user.getId());
			byId.setUpdateTime(LocalDateTime.now());
			this.updateById(byId);
		}else 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);
			}
			//校验身份合法
			TCheckIdCard checkIdCard = new TCheckIdCard();
			checkIdCard.setName(param.getEmpName());
			checkIdCard.setIdCard(param.getEmpIdcardNo());
			R<TCheckIdCard> tCheckIdCardR = checkDaprUtil.checkIdCardSingle(checkIdCard);
			if (null != tCheckIdCardR && tCheckIdCardR.getCode() == CommonConstants.SUCCESS){
				TCheckIdCard data = tCheckIdCardR.getData();
				if (CommonConstants.ONE_INT != data.getIsTrue()){
					return R.failed(InsurancesConstants.EMP_ID_CARD_NO_NOT_FIT);
				}
			}

			TInsuranceReplace one = tInsuranceReplaceService.getOne(Wrappers.<TInsuranceReplace>query().lambda()
					.eq(TInsuranceReplace::getToInsuranceDetailId, byId.getId())
					.last(CommonConstants.LAST_ONE_SQL));
			if (Optional.ofNullable(one).isPresent()){
				TInsuranceDetail insuranceDetail = this.getById(one.getFromInsuranceDetailId());
				if (Optional.ofNullable(insuranceDetail).isPresent()){
					if (insuranceDetail.getIsUse() == CommonConstants.ONE_INT){
						return R.failed("员工"+insuranceDetail.getEmpName()+"的投保记录已出险，无法替换");
					}
					if (insuranceDetail.getIsEffect() == CommonConstants.ONE_INT){
						return R.failed("员工"+insuranceDetail.getEmpName()+"的投保记录无效，无法替换");
					}
					//被替换者无效
					insuranceDetail.setIsEffect(CommonConstants.ONE_INT);
					insuranceDetail.setIsOverdue(null);
					insuranceDetail.setUpdateTime(LocalDateTime.now());
					this.updateById(insuranceDetail);
					//替换记录成功
					one.setReplaceStatus(CommonConstants.ONE_INT);
					tInsuranceReplaceService.updateById(one);

					//替换状态下目前只能编辑姓名、身份证、岗位
					//投保状态：待投保
					byId.setBuyHandleStatus(CommonConstants.ONE_INT);
					byId.setEmpName(param.getEmpName());
					byId.setEmpIdcardNo(param.getEmpIdcardNo());
					byId.setPost(param.getPost());
					byId.setCreateBy(user.getId());
					byId.setCreateTime(LocalDateTime.now());
					byId.setUpdateBy(user.getId());
					byId.setUpdateTime(LocalDateTime.now());
					this.updateById(byId);
				}
			}
		} else {
			return R.failed(InsurancesConstants.EDIT_NOT_ALLOW);
		}
		//操作记录
		addOperate(Arrays.asList(byId),user,getOperateDescByBuyType(byId.getBuyType()),null,CommonConstants.ONE_INT);
		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){
			long day = LocalDateUtil.betweenDay(insuranceDetailVO.getPolicyStart().toString(),insuranceDetailVO.getPolicyEnd().toString());
			long month = LocalDateUtil.betweenMonth(insuranceDetailVO.getPolicyStart().toString(),insuranceDetailVO.getPolicyEnd().toString());
			String defaultSettleId = insuranceDetailVO.getDefaultSettleId();
			if(StringUtils.isNotBlank(defaultSettleId)){
				SettleVo settleVo = getInsuranceDetailSettleStatus(id, defaultSettleId);
				if(!Common.isEmpty(settleVo)){
					insuranceDetailVO.setEstimateSettleStatus(settleVo.getEstimateStatus());
					insuranceDetailVO.setActualSettleStatus(settleVo.getActualStatus());
				}
			}
			//购买周期
			String buyCycle = month + "个月/" + day + "天";
			insuranceDetailVO.setBuyCycle(buyCycle);
			//派单类型
			insuranceDetailVO.setDistributeType(insuranceDetailVO.getReduceHandleStatus() == null?insuranceDetailVO.getBuyType():CommonConstants.FIVE_INT);
			//派单状态
			insuranceDetailVO.setDistributeStatus(insuranceDetailVO.getDistributeType() == CommonConstants.FIVE_INT?insuranceDetailVO.getReduceHandleStatus():insuranceDetailVO.getBuyHandleStatus());
			//替换类型
			if (insuranceDetailVO.getBuyType() == CommonConstants.FOUR_INT){
				TInsuranceReplace one = tInsuranceReplaceService.getOne(Wrappers.<TInsuranceReplace>query().lambda()
						.eq(TInsuranceReplace::getToInsuranceDetailId, insuranceDetailVO.getId())
						.last(CommonConstants.LAST_ONE_SQL));
				if (Optional.ofNullable(one).isPresent()) {
					TInsuranceDetail byId = this.getById(one.getFromInsuranceDetailId());
					if (Optional.ofNullable(byId).isPresent()) {
						insuranceDetailVO.setCoverEmpName(byId.getEmpName());
						insuranceDetailVO.setCoverEmpIdcardNo(byId.getEmpIdcardNo());
						R<SetInfoVo> infoByCodes = archivesDaprUtil.getSetInfoByCodes(Arrays.asList(byId.getDeptNo()));
						if (null != infoByCodes && infoByCodes.getCode() == CommonConstants.SUCCESS && Common.isNotNull(infoByCodes.getData())) {
							Map<String, ProjectSetInfoVo> data = infoByCodes.getData().getProjectSetInfoVoMap();
							ProjectSetInfoVo setInfoVo = data.get(byId.getDeptNo());
							if (null != setInfoVo){
								insuranceDetailVO.setCoverProjectName(Optional.ofNullable(setInfoVo.getDepartName()).orElse(""));
								insuranceDetailVO.setCoveInvoiceTitle(Optional.ofNullable(setInfoVo.getInvoiceTitleInsurance()).orElse(""));
							}
						}
					}
				}
			}

			//减员类型 处理创建人、创建时间、备注
			if(CommonConstants.FIVE_INT == insuranceDetailVO.getDistributeType()){
				TInsuranceRefund refund = tInsuranceRefundService.getOne(Wrappers.<TInsuranceRefund>query().lambda()
						.eq(TInsuranceRefund::getInsDetailId, insuranceDetailVO.getId())
						.orderByDesc(TInsuranceRefund::getUpdateTime)
						.last(CommonConstants.LAST_ONE_SQL)
				);
				if (Optional.ofNullable(refund).isPresent()){
					insuranceDetailVO.setCreateName(refund.getCreateName());
					insuranceDetailVO.setCreateTime(refund.getCreateTime());
					insuranceDetailVO.setRemark(refund.getRemark());
				}
			}

			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.setInvoiceTitle(Optional.ofNullable(jsonObject.getInvoiceTitleInsurance()).orElse(""));
				}
			}
		}
		return insuranceDetailVO;
	}

	/**
	 * 通过商险id查询操作记录
	 *
	 * @param id
	 * @return {@link List<TInsuranceOperate>}
	 * @author licancan
	 */
	@Override
	public List<TInsuranceOperate> getInsuranceOperateList(String id) {
		List<TInsuranceOperate> list = tInsuranceOperateService.list(Wrappers.<TInsuranceOperate>query().lambda()
				.eq(TInsuranceOperate::getInsuranceDetailId,id)
				.eq(TInsuranceOperate::getDisplayFlag,CommonConstants.ONE_INT)
				.orderByAsc(TInsuranceOperate::getCreateTime)
		);
		return list;
	}

	/**
	 * 导出办理
	 *
	 * @param param
	 * @return {@link List<InsuranceExportListVO>}
	 * @author licancan
	 */
	@Override
	public R<List<InsuranceExportListVO>> getInsuranceExportList(InsuranceExportListParam param, String mId) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isNotNull(mId)) {
			param.setMId(mId);
		}
		param.setCreateBy(user.getId());
		menuUtil.setAuthSql(user, param);
		if (Common.isNotNull(param.getAuthSql()) && param.getAuthSql().contains("1=2 CONCAT")) {
			param.setAuthSql(param.getAuthSql().replace("1=2 CONCAT", "CONCAT"));
		}
		List<InsuranceExportListVO> insuranceExportList;
		//如勾选项不为空，则导出勾选记录；否则导出当前筛选条件下 && 「待投保」的结果集
		if (CollectionUtils.isNotEmpty(param.getIdList())){
			insuranceExportList =  baseMapper.getInsuranceExportListBySelect(param.getIdList());

			if (CollectionUtils.isNotEmpty(insuranceExportList)){
				for (InsuranceExportListVO exportListVO : insuranceExportList) {
					if (exportListVO.getBuyHandleStatus() != CommonConstants.ONE_INT){
						return R.failed(InsurancesConstants.CHANGE_ERROR);
					}
				}
			}
		}else {
			insuranceExportList = baseMapper.getInsuranceExportList(param);
		}
		if (CollectionUtils.isNotEmpty(insuranceExportList)){
			if(insuranceExportList.size() > CommonConstants.EXPORT_TWENTY_THOUSAND){
				return R.failed(InsurancesConstants.EXPORT_TOO_LONG);
			}
			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();
				ProjectSetInfoVo jsonObject;
				for (InsuranceExportListVO record : insuranceExportList) {
					jsonObject = null;
					if (data != null) {
						jsonObject = data.get(record.getDeptNo());
						if (null != jsonObject) {
							record.setInvoiceTitle(Optional.ofNullable(jsonObject.getInvoiceTitleInsurance()).orElse(""));
						}
					}
					//购买月数
					record.setBuyMonth(LocalDateUtil.betweenMonth(record.getPolicyStart().toString(),record.getPolicyEnd().toString()));
					//购买天数
					record.setBuyDay(LocalDateUtil.betweenDay(record.getPolicyStart().toString(),record.getPolicyEnd().toString()));
					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.setHandledBy(user.getId());
					detail.setHandledTime(LocalDateTime.now());
					detail.setUpdateBy(user.getId());
					detail.setUpdateTime(LocalDateTime.now());
					if (Common.isNotNull(jsonObject)){
						detail.setDeptId(jsonObject.getId());
						detail.setDeptName(jsonObject.getDepartName());
						detail.setUnitId(jsonObject.getCustomerId());
						detail.setUnitName(jsonObject.getCustomerName());
						detail.setUnitNo(jsonObject.getCustomerCode());
					}
					detailList.add(detail);
				}
			}
			//批量更新
			if (CollectionUtils.isNotEmpty(detailList)){
				this.saveOrUpdateBatch(detailList);
			}
			//操作记录
			addOperate(detailList,user,InsurancesConstants.EXPORT,null,CommonConstants.ONE_INT);

			//针对是替换类型的做处理,每一条替换数据对应一条被替换数据
			List<InsuranceExportListVO> listVOS = insuranceExportList.stream().filter(e -> e.getBuyType() == CommonConstants.FOUR_INT).collect(Collectors.toList());
			List<InsuranceExportListVO> list = new ArrayList<>();
			if(CollectionUtils.isNotEmpty(listVOS)){
				for (InsuranceExportListVO listVO : listVOS) {
					listVO.setRemark(InsurancesConstants.INSERT);
					TInsuranceReplace one = tInsuranceReplaceService.getOne(Wrappers.<TInsuranceReplace>query().lambda()
							.eq(TInsuranceReplace::getToInsuranceDetailId, listVO.getId())
							.last(CommonConstants.LAST_ONE_SQL));
					if (Optional.ofNullable(one).isPresent()){
						TInsuranceDetail byId = this.getById(one.getFromInsuranceDetailId());
						if (Optional.ofNullable(byId).isPresent()){
							InsuranceExportListVO vo = new InsuranceExportListVO();
							BeanCopyUtils.copyProperties(byId,vo);
							if (StringUtils.isNotBlank(byId.getPolicyNo())){
								listVO.setPolicyNo(byId.getPolicyNo());
							}
							//购买月数
							vo.setBuyMonth(LocalDateUtil.betweenMonth(vo.getPolicyStart().toString(),vo.getPolicyEnd().toString()));
							//购买天数
							vo.setBuyDay(LocalDateUtil.betweenDay(vo.getPolicyStart().toString(),vo.getPolicyEnd().toString()));
							vo.setRemark(InsurancesConstants.QUIT);
							vo.setBuyType(CommonConstants.FOUR_INT);
							vo.setProjectName(byId.getDeptName());
							list.add(vo);
						}
					}
				}
				if (CollectionUtils.isNotEmpty(list)){
					//根据项目编码获取项目名称
					List<String> collectList = list.stream().map(e -> e.getDeptNo()).distinct().collect(Collectors.toList());
					try{
						R<SetInfoVo> setInfoByCodesList = archivesDaprUtil.getSetInfoByCodes(collectList);
						if (null != setInfoByCodesList && setInfoByCodesList.getCode() == CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodesList.getData())) {
							Map<String, ProjectSetInfoVo> data = setInfoByCodesList.getData().getProjectSetInfoVoMap();
							if (data != null) {
								for (InsuranceExportListVO record : list) {
									ProjectSetInfoVo jsonObject = data.get(record.getDeptNo());
									if (null != jsonObject) {
										record.setInvoiceTitle(Optional.ofNullable(jsonObject.getInvoiceTitleInsurance()).orElse(""));
									}
								}
							}
						}
					}catch (Exception e){
						for (InsuranceExportListVO record : list) {
							record.setProjectName(CommonConstants.EMPTY_STRING);
							record.setInvoiceTitle(CommonConstants.EMPTY_STRING);
						}
						log.error(InsurancesConstants.GET_DEPT_DETAIL_ERROR+e);
					}
					insuranceExportList.removeAll(listVOS);
					insuranceExportList.addAll(crossMerger(list,listVOS));
				}
			}

		}
		return R.ok(insuranceExportList);
	}

	/**
	 * 投保退回
	 *
	 * @param user
	 * @param paramList
	 * @return {@link R<List<InsuranceListVO>>}
	 * @author licancan
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R<List<InsuranceListVO>> rollBackInsurance(YifuUser user, List<InsuranceHandleParam> paramList) {
		//解析参数里的商险id
		List<String> idList = new ArrayList<>();
		Map<String,String> remarkMap = new HashMap<>();
		if (paramList != null) {
			for (InsuranceHandleParam param : paramList) {
				idList.add(param.getId());
				remarkMap.put(param.getId(), param.getRemark());
			}
		}
		//操作日志对象
		List<InsuranceHandleParam> operateList = new ArrayList<>();

		List<TInsuranceDetail> detailList = baseMapper.selectBatchIds(idList);
		//返回给前端的数据
		List<InsuranceListVO> errorList = new ArrayList<>();
		//后端处理的数据
		List<TInsuranceDetail> successList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(detailList)){
			for (TInsuranceDetail detail : detailList) {
				if (detail.getBuyHandleStatus() == CommonConstants.FOUR_INT
						|| detail.getBuyHandleStatus() == CommonConstants.FIVE_INT){
					InsuranceListVO listVO = new InsuranceListVO();
					BeanCopyUtils.copyProperties(detail,listVO);
					listVO.setProjectName(detail.getDeptName());
					listVO.setErrorMessage(InsurancesConstants.REDUCE_ROLLBACK_IS_NOT_ALLOW);
					errorList.add(listVO);
				}else if(detail.getBuyHandleStatus() == CommonConstants.THREE_INT
						&& (detail.getReduceHandleStatus() != null && (detail.getReduceHandleStatus() == CommonConstants.ONE_INT
						|| detail.getReduceHandleStatus() == CommonConstants.TWO_INT))){
					InsuranceListVO listVO = new InsuranceListVO();
					BeanCopyUtils.copyProperties(detail,listVO);
					listVO.setProjectName(detail.getDeptName());
					listVO.setErrorMessage(InsurancesConstants.REDUCE_ROLLBACK_REDUCE_IS_NOT_ALLOW);
					errorList.add(listVO);
				}else{
					//判断是否是替换类型的退回，如果是，需要将被替换者激活，替换者有效状态为空
					if(detail.getBuyType() == CommonConstants.FOUR_INT){
						//替换者有效状态为空
						detail.setIsEffect(null);
						TInsuranceReplace one = tInsuranceReplaceService.getOne(Wrappers.<TInsuranceReplace>query().lambda()
								.eq(TInsuranceReplace::getToInsuranceDetailId, detail.getId())
								.last(CommonConstants.LAST_ONE_SQL));
						if (Optional.ofNullable(one).isPresent()){
							//替换记录变为失败
							one.setReplaceStatus(CommonConstants.ZERO_INT);
							tInsuranceReplaceService.updateById(one);
							TInsuranceDetail byId = this.getById(one.getFromInsuranceDetailId());
							if (Optional.ofNullable(byId).isPresent()){
								//被替换者激活
								byId.setIsEffect(CommonConstants.ZERO_INT);
								byId.setIsOverdue(CommonConstants.ZERO_INT);
								this.updateById(byId);
							}
						}
					}
					// 记录状态置为「退回」
					detail.setBuyHandleStatus(CommonConstants.FOUR_INT);
					//投保成功后再次投保退回，需要将保单生效日期、是否有效、是否过期置为空
					if (detail.getSignFlag() == CommonConstants.ONE_INT){
						detail.setHandledTime(null);
						detail.setHandledBy(null);
						detail.setPolicyEffect(null);
						detail.setIsEffect(null);
						detail.setIsOverdue(null);
					}
					detail.setUpdateBy(user.getId());
					detail.setUpdateTime(LocalDateTime.now());
					detail.setBackRemark(remarkMap.get(detail.getId()));
					successList.add(detail);
				}
			}
		}
		if (CollectionUtils.isNotEmpty(successList)){
			for (TInsuranceDetail detail : successList) {
				if (StringUtils.isNotBlank(detail.getDefaultSettleId())){
					TInsuranceSettle settle = tInsuranceSettleService.getById(detail.getDefaultSettleId());
					if (Optional.ofNullable(settle).isPresent()){
						TInsuranceSettle burden = new TInsuranceSettle();
						BeanCopyUtils.copyProperties(settle,burden);
						burden.setId(null);
						burden.setCreateTime(LocalDateTime.now());
						burden.setUpdateTime(LocalDateTime.now());
						if (burden.getActualPremium() != null){
							burden.setActualPremium(burden.getActualPremium().negate());
							burden.setActualPushTime(LocalDateTime.now());
							detail.setActualPremium(new BigDecimal("0.00"));
						}
						if (burden.getEstimatePremium() != null){
							burden.setEstimatePremium(burden.getEstimatePremium().negate());
							burden.setEstimatePushTime(LocalDateTime.now());
							detail.setEstimatePremium(new BigDecimal("0.00"));
						}
						tInsuranceSettleService.save(burden);
						SettleVo settleVo = getInsuranceDetailSettleStatus(detail.getId(), detail.getDefaultSettleId());
						if(!Common.isEmpty(settleVo) ){
							//预估推送标识
							Integer isEstimatePush = settle.getIsEstimatePush();
							//实缴推送标识
							Integer isActualPush = settle.getIsActualPush();
							//预估结算状态
							String estimateStatus = settleVo.getEstimateStatus();
							//实缴结算状态
							String actualStatus = settleVo.getActualStatus();
							String pushResult = null;
							//预估已推送，实缴未推送
							if(isEstimatePush == CommonConstants.ONE_INT && isActualPush == CommonConstants.ZERO_INT){
								//预估未结算，推送作废
								if(InsurancesConstants.SETTLE_ZERO.equals(estimateStatus)){
									pushResult= pushEstimate(detail, CommonConstants.FIVE_INT);
								}else {
									//预估结算中已结算，推送预估红冲
									detail.setDefaultSettleId(burden.getId());
									pushResult = pushEstimate(detail, CommonConstants.THREE_INT);
								}
							}
							//预估已推送，实缴已推送
							if(isEstimatePush == CommonConstants.ONE_INT && isActualPush == CommonConstants.ONE_INT){
								//预估未结算，实缴未结算推送作废
								if(InsurancesConstants.SETTLE_ZERO.equals(estimateStatus) && InsurancesConstants.SETTLE_ZERO.equals(actualStatus)){
									pushResult= pushEstimate(detail, CommonConstants.FIVE_INT);
								}else{
									//预估结算中，已结算，实缴已推送，推送实缴红冲信息
									detail.setDefaultSettleId(burden.getId());
									pushResult= pushEstimate(detail, CommonConstants.SIX_INT);
								}
							}
							//预估未推送，实缴已推送
							if(isEstimatePush == CommonConstants.ZERO_INT && isActualPush == CommonConstants.ONE_INT){
								//实缴未结算推送作废
								if(InsurancesConstants.SETTLE_ZERO.equals(actualStatus)){
									pushResult= pushEstimate(detail, CommonConstants.FIVE_INT);
								}else{
									//实缴结算中，已结算，推送实缴红冲信息
									detail.setDefaultSettleId(burden.getId());
									pushResult= pushEstimate(detail, CommonConstants.SIX_INT);
								}
							}
							if(StringUtils.isNotBlank(pushResult)){
								detail.setDefaultSettleId(null);
							}
							//已投保退回，收入数据同步处理
							try{
								updateInsuranceInfo(detail);
							}catch (Exception e){
								log.error("收入数据同步处理失败："+e);
							}

						}
					}
				}
				//获取成功数据的remark
				paramList.stream().forEach(e ->{
					if (detail.getId().equals(e.getId())){
						operateList.add(e);
					}
				});
			}
			//更新状态
			this.saveOrUpdateBatch(successList);
		}
		//操作记录
		addOperate(operateList,user,InsurancesConstants.ROLLBACK);
		return R.ok(errorList,InsurancesConstants.OPERATE_SUCCESS);
	}

	/**
	 * 投保成功/退回办理导入
	 *
	 * @param user
	 * @param param
	 * @return {@link R<List<InsuranceHandleImportParam>>}
	 * @author licancan
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R<List<InsuranceHandleImportParam>> insuranceHandleImport(YifuUser user, List<InsuranceHandleImportParam> param) {
		Map<String, List<InsuranceHandleImportParam>> map = insuranceChangeCheck(param, user,false);
		//检验成功的数据
		List<InsuranceHandleImportParam> successList = map.get(InsurancesConstants.SUCCESS_LIST);
		//校验失败的数据
		List<InsuranceHandleImportParam> errorList = map.get(InsurancesConstants.ERROR_LIST);
		if (CollectionUtils.isNotEmpty(successList)){
			//投保成功的数据
			List<InsuranceHandleImportParam> collectSuccess = successList.stream().filter(e -> InsurancesConstants.SUCCESS.equals(e.getHandType())).collect(Collectors.toList());
			//投保退回的数据
			List<InsuranceHandleImportParam> collectRollBack = successList.stream().filter(e -> InsurancesConstants.FAILED.equals(e.getHandType())).collect(Collectors.toList());

			//投保成功
			if (CollectionUtils.isNotEmpty(collectSuccess)){
				List<InsuranceHandleParam> list = new ArrayList<>();
				collectSuccess.stream().forEach(e ->{
					InsuranceHandleParam handleParam = new InsuranceHandleParam();
					handleParam.setId(e.getId());
					handleParam.setRemark(e.getRemark());
					list.add(handleParam);
				});
				this.successfulInsurance(user,list);
			}

			//投保退回
			if (CollectionUtils.isNotEmpty(collectRollBack)){
				List<InsuranceHandleParam> list = new ArrayList<>();
				collectRollBack.stream().forEach(e ->{
					InsuranceHandleParam handleParam = new InsuranceHandleParam();
					handleParam.setId(e.getId());
					handleParam.setRemark(e.getRemark());
					list.add(handleParam);
				});
				this.rollBackInsurance(user,list);
			}
		}
		return R.ok(errorList,InsurancesConstants.IMPORT_SUCCESS);
	}

	/**
	 * 办理成功
	 *
	 * @param user
	 * @param paramList
	 * @return {@link R<List<InsuranceListVO>>}
	 * @author licancan
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R<List<InsuranceListVO>> successfulInsurance(YifuUser user, List<InsuranceHandleParam> paramList) {
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(50, 50, 100, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
		//解析参数里的商险id
		List<String> idList = paramList.stream().map(e -> e.getId()).distinct().collect(Collectors.toList());
		//操作日志对象
		List<InsuranceHandleParam> operateList = new ArrayList<>();

		List<TInsuranceDetail> detailList = baseMapper.selectBatchIds(idList);
		//返回给前端的数据
		List<InsuranceListVO> errorList = new ArrayList<>();
		//后端处理的数据
		List<TInsuranceDetail> successList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(detailList)){
			for (TInsuranceDetail detail : detailList) {
				//先判断投保状态是不是投保中，如果不是不给标记办理成功，防止重复推数据
				if(detail.getBuyHandleStatus() != CommonConstants.TWO_INT){
					InsuranceListVO listVO = new InsuranceListVO();
					BeanCopyUtils.copyProperties(detail,listVO);
					listVO.setProjectName(detail.getDeptName());
					listVO.setErrorMessage(InsurancesConstants.INSURANCE_BUY_STATUS_NOT_TWO);
					errorList.add(listVO);
				}else {
					//替换类型不参与结算
					if(detail.getBuyType() == CommonConstants.FOUR_INT){
						//记录状态均置为「已投保」
						detail.setBuyHandleStatus(CommonConstants.THREE_INT);
						detail.setSignFlag(CommonConstants.ONE_INT);
						//记录的有效状态，置为「有效」
						detail.setIsEffect(CommonConstants.ZERO_INT);
						detail.setIsOverdue(CommonConstants.ZERO_INT);
						detail.setIsUse(CommonConstants.ZERO_INT);
						detail.setUpdateTime(LocalDateTime.now());
						detail.setUpdateBy(user.getId());
						//替换类型，保单生效日期：T + 1
						detail.setPolicyEffect(LocalDate.now().plusDays(CommonConstants.ONE_INT));
						successList.add(detail);
					}else{
						//根据结算类型判断是否需要计算预估保费
						//预估
						if (detail.getSettleType() == CommonConstants.ZERO_INT){
							if (CommonConstants.ONE_INT == detail.getBillingType()){
								// 按月查费率
								// 预估保费 = 费率 * 购买标准
								BigDecimal estimatePremium = new BigDecimal(detail.getBuyStandard()).multiply(detail.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP);
								detail.setEstimatePremium(estimatePremium);
								if (detail.getBuyType() == CommonConstants.THREE_INT){
									detail.setPolicyEffect(LocalDate.now().plusDays(CommonConstants.ONE_INT));
								}
								//记录状态均置为「已投保」
								detail.setBuyHandleStatus(CommonConstants.THREE_INT);
								detail.setSignFlag(CommonConstants.ONE_INT);
								//记录的有效状态，置为「有效」
								detail.setIsEffect(CommonConstants.ZERO_INT);
								detail.setIsOverdue(CommonConstants.ZERO_INT);
								detail.setIsUse(CommonConstants.ZERO_INT);
								detail.setUpdateTime(LocalDateTime.now());

								//保费存储
								TInsuranceSettle settle = new TInsuranceSettle();
								settle.setInsDetailId(detail.getId());
								settle.setSettleType(detail.getSettleType());
								settle.setSettleHandleStatus(CommonConstants.ONE_STRING);
								settle.setCreateTime(LocalDateTime.now());
								settle.setEstimatePremium(estimatePremium);
								//调完ekp接口才会是1
								settle.setIsEstimatePush(CommonConstants.ZERO_INT);
								tInsuranceSettleService.save(settle);
								detail.setDefaultSettleId(settle.getId());
								successList.add(detail);
								//生成收入数据
								createInsuranceInfo(detail);
							}else {
								//按天
								//计算起止时间的天数
								long day = LocalDateUtil.betweenDay(detail.getPolicyStart().toString(), detail.getPolicyEnd().toString());
								//预估保费 = (购买标准 / 365) * 天数
								BigDecimal estimatePremium = new BigDecimal(detail.getBuyStandard()).multiply(new BigDecimal(day)).divide(new BigDecimal("365"),CommonConstants.TWO_INT,BigDecimal.ROUND_HALF_UP);
								detail.setEstimatePremium(estimatePremium);
								if (detail.getBuyType() == CommonConstants.THREE_INT){
									detail.setPolicyEffect(LocalDate.now().plusDays(CommonConstants.ONE_INT));
								}
								//记录状态均置为「已投保」
								detail.setBuyHandleStatus(CommonConstants.THREE_INT);
								detail.setSignFlag(CommonConstants.ONE_INT);
								//记录的有效状态，置为「有效」
								detail.setIsEffect(CommonConstants.ZERO_INT);
								detail.setIsOverdue(CommonConstants.ZERO_INT);
								detail.setIsUse(CommonConstants.ZERO_INT);
								detail.setUpdateTime(LocalDateTime.now());

								//保费存储
								TInsuranceSettle settle = new TInsuranceSettle();
								settle.setInsDetailId(detail.getId());
								settle.setSettleType(detail.getSettleType());
								settle.setSettleHandleStatus(CommonConstants.ONE_STRING);
								settle.setEstimatePremium(estimatePremium);
								//调完ekp接口才会是1
								settle.setIsEstimatePush(CommonConstants.ONE_INT);
								settle.setEstimatePushTime(LocalDateTime.now());
								settle.setCreateTime(LocalDateTime.now());
								tInsuranceSettleService.save(settle);
								detail.setDefaultSettleId(settle.getId());
								successList.add(detail);
								//生成收入数据
								createInsuranceInfo(detail);
							}
						}
						//实缴
						if(detail.getSettleType() == CommonConstants.ONE_INT){
							if (detail.getBuyType() == CommonConstants.THREE_INT){
								detail.setPolicyEffect(LocalDate.now().plusDays(CommonConstants.ONE_INT));
							}
							//记录状态均置为「已投保」
							detail.setBuyHandleStatus(CommonConstants.THREE_INT);
							detail.setSignFlag(CommonConstants.ONE_INT);
							//记录的有效状态，置为「有效」
							detail.setIsEffect(CommonConstants.ZERO_INT);
							detail.setIsOverdue(CommonConstants.ZERO_INT);
							detail.setIsUse(CommonConstants.ZERO_INT);
							detail.setUpdateTime(LocalDateTime.now());
							successList.add(detail);
						}
					}
				}
			}
		}
		updateBatchById(successList);
		if (CollectionUtils.isNotEmpty(successList)){
			threadPool.execute(() -> {
				//根据结算类型是合并结算，推送预估保费到ekp(上面已经算好，这里直接判断有预估保费的就推送)
				for (TInsuranceDetail tInsuranceDetail : successList) {
					Integer settleType = tInsuranceDetail.getSettleType();
					//如果是合并计算则推送至EKP
					if(CommonConstants.ZERO_INT == settleType){
						//存储成功后发送给EKP
						String s = pushEstimate(tInsuranceDetail,CommonConstants.ONE_INT);
						if(StringUtils.isNotBlank(s)){
							LambdaUpdateWrapper<TInsuranceSettle> settleWrapper = new LambdaUpdateWrapper<>();
							settleWrapper.eq(TInsuranceSettle :: getId,tInsuranceDetail.getDefaultSettleId())
									.set(TInsuranceSettle :: getIsEstimatePush,CommonConstants.ONE_INT)
									.set(TInsuranceSettle :: getEstimatePushTime,LocalDateTime.now());
							//更新结算信息表
							tInsuranceSettleService.update(settleWrapper);
						}
					}
				}
			});
		}
		//操作记录
		if (CollectionUtils.isNotEmpty(successList)){
			for (TInsuranceDetail detail : successList) {
				//获取成功数据的remark
				paramList.stream().forEach(e ->{
					if (detail.getId().equals(e.getId())){
						operateList.add(e);
					}
				});
			}
		}
		addOperate(operateList,user,InsurancesConstants.SUCCESSFUL);
		return R.ok(errorList, InsurancesConstants.OPERATE_SUCCESS);
	}

	/**
	 * 登记保单保费
	 *
	 * @param paramList
	 * @return {@link R<List<InsuranceRegisterParam>>}
	 * @author licancan
	 */
	@Override
	public R<List<InsuranceRegisterParam>> registeredPolicyPremium(List<InsuranceRegisterParam> paramList) {
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(50, 50, 100, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
		if (CollectionUtils.isEmpty(paramList)){
			return R.failed(CommonConstants.DATA_CAN_NOT_EMPTY);
		}
		if(paramList.size() > CommonConstants.IMPORT_TWENTY_THOUSAND){
			return R.failed(InsurancesConstants.IMPORT_TOO_LONG);
		}
		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,user);
		//返回给前端的结果
		List<InsuranceRegisterParam> listResult = map.get("listResult");
		//保存到数据库中的结果
		List<InsuranceRegisterParam> listSuccess = map.get("listSuccess");
		List<TInsuranceDetail> detailList = new ArrayList<>();
		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)
						.orderByDesc(TInsuranceDetail::getUpdateTime)
						.last(CommonConstants.LAST_ONE_SQL)
				);
				BigDecimal actualMoney;
				actualMoney = detail.getActualPremium();
				if (StringUtils.isNotBlank(success.getInvoiceNo())){
					detail.setInvoiceNo(success.getInvoiceNo());
					//如果发票号不为空，将替换类型的发票号也全部更新
					List<TInsuranceReplace> list = tInsuranceReplaceService.list(Wrappers.<TInsuranceReplace>query().lambda()
							.eq(TInsuranceReplace::getOriginInsuranceDetailId, detail.getId()));
					if (CollectionUtils.isNotEmpty(list)){
						List<String> collect = list.stream().map(TInsuranceReplace::getToInsuranceDetailId).distinct().collect(Collectors.toList());
						List<TInsuranceDetail> details = this.baseMapper.selectBatchIds(collect);
						if (CollectionUtils.isNotEmpty(details)){
							details.stream().forEach(e -> e.setInvoiceNo(success.getInvoiceNo()));
							//这里自己写sql更新发票号，防止用mybatisPlus批量更新，把updateTime更新了（updateTime不能更新）
							baseMapper.updateInvoiceNoBatch(details);
						}
					}
				}
				detail.setUpdateBy(user.getId());
				detail.setUpdateTime(LocalDateTime.now());
				//如果当前为合并结算，判断预估是否已发送
				if(StringUtils.isNotBlank(detail.getDefaultSettleId()) && detail.getSettleType() == CommonConstants.ZERO_INT){
					TInsuranceSettle settle = tInsuranceSettleService.getById(detail.getDefaultSettleId());
					Integer isEstimatePush = settle.getIsEstimatePush();
					//如果未推送则推送预估新增
					if(isEstimatePush == CommonConstants.ZERO_INT){
						String s = pushEstimate(detail, CommonConstants.ONE_INT);
						if(StringUtils.isNotBlank(s)){
							settle.setIsEstimatePush(CommonConstants.ONE_INT);
							settle.setEstimatePushTime(LocalDateTime.now());
							tInsuranceSettleService.updateById(settle);
						}
					}

				}
				if (StringUtils.isNotBlank(success.getPolicyNo())){
					detail.setPolicyNo(success.getPolicyNo());
					//如果保单号不为空，将替换类型的保单号也全部更新
					List<TInsuranceReplace> list = tInsuranceReplaceService.list(Wrappers.<TInsuranceReplace>query().lambda()
							.eq(TInsuranceReplace::getOriginInsuranceDetailId, detail.getId()));
					if (CollectionUtils.isNotEmpty(list)){
						List<String> collect = list.stream().map(TInsuranceReplace::getToInsuranceDetailId).distinct().collect(Collectors.toList());
						List<TInsuranceDetail> details = this.baseMapper.selectBatchIds(collect);
						if (CollectionUtils.isNotEmpty(details)){
							details.stream().forEach(e -> e.setPolicyNo(success.getPolicyNo()));
							//这里自己写sql更新保单号，防止用mybatisPlus批量更新，把updateTime更新了（updateTime不能更新）
							baseMapper.updatePolicyNoBatch(details);
						}
					}
				}
				//如果保费不为空
				if (StringUtils.isNotBlank(success.getActualPremium())){
					Integer settleType = detail.getSettleType();
					String defaultSettleId = detail.getDefaultSettleId();
					//如果当前保单为合并结算
					if(settleType == CommonConstants.ZERO_INT){
						if(StringUtils.isNotBlank(defaultSettleId)){
							TInsuranceSettle settle = tInsuranceSettleService.getById(detail.getDefaultSettleId());
							if(Optional.ofNullable(settle).isPresent()){
								Integer isActualPush = settle.getIsActualPush();
								//如果当前实缴信息未推送，则新增实缴单推送
								if(CommonConstants.ZERO_INT == isActualPush){
									//保费存储
									settle.setActualPremium(new BigDecimal(success.getActualPremium()));
									settle.setIsActualPush(CommonConstants.ZERO_INT);
									settle.setUpdateTime(LocalDateTime.now());
									tInsuranceSettleService.updateById(settle);
									//调EKP新增实际保费
									detail.setActualPremium(new BigDecimal(success.getActualPremium()));
									threadPool.execute(() ->{
										String s = pushEstimate(detail, CommonConstants.TWO_INT);
										//如果推送成功则更改推送状态
										if(StringUtils.isNotBlank(s)){
											settle.setActualPushTime(LocalDateTime.now());
											settle.setIsActualPush(CommonConstants.ONE_INT);
											tInsuranceSettleService.updateById(settle);
										}
									});
								}
								//如果当前实缴信息已推送，且金额与本次不一致，则推送实缴更新
								BigDecimal bigDecimal = new BigDecimal(success.getActualPremium());
								boolean c = !Common.isNotNull(detail.getActualPremium()) ||
										bigDecimal.compareTo(detail.getActualPremium()) != 0;
								if(CommonConstants.ONE_INT == isActualPush && c){
									//推送保费更新
									settle.setActualPremium(bigDecimal);
									settle.setIsActualPush(CommonConstants.ZERO_INT);
									settle.setUpdateTime(LocalDateTime.now());
									tInsuranceSettleService.updateById(settle);
									//调EKP更新实际保费
									detail.setActualPremium(new BigDecimal(success.getActualPremium()));
									threadPool.execute(() ->{
										String s = pushEstimate(detail,CommonConstants.FOUR_INT);
										if(StringUtils.isNotBlank(s)){
											settle.setActualPushTime(LocalDateTime.now());
											settle.setIsActualPush(CommonConstants.ONE_INT);
											tInsuranceSettleService.updateById(settle);
										}
									});
								}else{
									//推送保费更新
									settle.setActualPremium(bigDecimal);
									settle.setIsActualPush(CommonConstants.ZERO_INT);
									settle.setUpdateTime(LocalDateTime.now());
									tInsuranceSettleService.updateById(settle);
									//调EKP更新实际保费
									detail.setActualPremium(bigDecimal);
									threadPool.execute(() ->{
										String s = pushEstimate(detail,CommonConstants.FOUR_INT);
										if(StringUtils.isNotBlank(s)){
											settle.setActualPushTime(LocalDateTime.now());
											settle.setIsActualPush(CommonConstants.ONE_INT);
											tInsuranceSettleService.updateById(settle);
										}});
								}
							}
						}
					}
					//如果当前保单为单独结算
					if(settleType == CommonConstants.ONE_INT){
						//推送过实缴信息且金额与本次不一致，则推送更新
						boolean c = !Common.isNotNull(detail.getActualPremium()) ||
								new BigDecimal(success.getActualPremium()).compareTo(detail.getActualPremium()) != 0;
						if(StringUtils.isNotBlank(defaultSettleId) && c){
							//推送保费更新
							TInsuranceSettle settle = tInsuranceSettleService.getById(detail.getDefaultSettleId());
							settle.setActualPremium(new BigDecimal(success.getActualPremium()));
							settle.setIsActualPush(CommonConstants.ZERO_INT);
							settle.setUpdateTime(LocalDateTime.now());
							tInsuranceSettleService.updateById(settle);
							//调EKP更新实际保费
							detail.setActualPremium(new BigDecimal(success.getActualPremium()));
							threadPool.execute(() ->{
								String s = pushEstimate(detail,CommonConstants.FOUR_INT);
								if(StringUtils.isNotBlank(s)){
									settle.setActualPushTime(LocalDateTime.now());
									settle.setIsActualPush(CommonConstants.ONE_INT);
									tInsuranceSettleService.updateById(settle);
								}
							});
						}
						//未推送过实缴信息，则推送新增
						if(StringUtils.isBlank(defaultSettleId)){
							//保费存储
							TInsuranceSettle settle = new TInsuranceSettle();
							settle.setInsDetailId(detail.getId());
							settle.setSettleType(detail.getSettleType());
							settle.setSettleHandleStatus(CommonConstants.ONE_STRING);
							settle.setActualPremium(new BigDecimal(success.getActualPremium()));
							settle.setIsActualPush(CommonConstants.ZERO_INT);
							//调完ekp接口才会是1
							settle.setCreateTime(LocalDateTime.now());
							tInsuranceSettleService.save(settle);
							detail.setDefaultSettleId(settle.getId());
							//调EKP新增实际保费
							detail.setActualPremium(new BigDecimal(success.getActualPremium()));
							threadPool.execute(() ->{
								String s = pushEstimate(detail, CommonConstants.TWO_INT);
								//如果推送成功则更改推送状态
								if(StringUtils.isNotBlank(s)){
									settle.setActualPushTime(LocalDateTime.now());
									settle.setIsActualPush(CommonConstants.ONE_INT);
									tInsuranceSettleService.updateById(settle);
								}
							});
						}
					}
				}
				String invoiceNo = success.getInvoiceNo();
				String policyNo = success.getPolicyNo();
				boolean booleanInvoiceNo = StringUtils.isNotBlank(invoiceNo) && !invoiceNo.equals(detail.getInvoiceNo());
				boolean booleanPolicyNo = StringUtils.isNotBlank(policyNo) && !policyNo.equals(detail.getPolicyNo());
				boolean isEquals = Common.isNotNull(detail.getActualPremium()) && new BigDecimal(success.getActualPremium()).compareTo(detail.getActualPremium()) == 0;
				//如果当前保费为空，且保单号或发票号不一样
				if((StringUtils.isBlank(success.getActualPremium()) || isEquals) && (booleanInvoiceNo || booleanPolicyNo)){
					if(StringUtils.isNotBlank(detail.getDefaultSettleId())){
						TInsuranceSettle settle = tInsuranceSettleService.getById(detail.getDefaultSettleId());
						if(Optional.ofNullable(settle).isPresent()){
							//如果当前实缴信息未推送，则新增实缴单推送
							threadPool.execute(() ->{
								if(StringUtils.isNotBlank(invoiceNo)){
									detail.setInvoiceNo(invoiceNo);
								}
								if(StringUtils.isNotBlank(policyNo)){
									detail.setPolicyNo(policyNo);
								}
								String s = pushEstimate(detail, CommonConstants.FOUR_INT);
								//如果推送成功则更改推送状态
								if(StringUtils.isNotBlank(s)){
									settle.setActualPushTime(LocalDateTime.now());
									settle.setIsActualPush(CommonConstants.ONE_INT);
									tInsuranceSettleService.updateById(settle);
								}
							});
						}
					}
				}
				//可以改成批量更新
				this.updateById(detail);
				detailList.add(detail);
				try {
					if (detail.getBuyType() != CommonConstants.FOUR_INT &&
							CommonConstants.ONE_INT == detail.getSettleType() &&
							new BigDecimal(success.getActualPremium()).compareTo(actualMoney) != 0) {
						//获取项目信息
						TSettleDomain settleDomain = new TSettleDomain();
						List<TSettleDomainSelectVo> settleDomainR = null;
						R<TSettleDomainListVo> listVo = null;
						listVo = archivesDaprUtil.selectSettleDomainSelectVoByNo(detail.getDeptNo());
						if (Common.isNotNull(listVo)) {
							TSettleDomainListVo tSettleDomainListVo = listVo.getData();
							if (Common.isNotNull(tSettleDomainListVo) && Common.isNotEmpty(tSettleDomainListVo.getListSelectVO())) {
								settleDomainR = tSettleDomainListVo.getListSelectVO();
								for (TSettleDomainSelectVo vo : settleDomainR) {
									BeanUtils.copyProperties(vo, settleDomain);
								}
							}
						}
						BigDecimal gMoney = BigDecimal.ZERO;
						boolean isBl = false;
						if (Common.isNotNull(settleDomain)) {
							// 含有商险，则计算收入
							if (settleDomain.getMrSettleType().equals(CommonConstants.TWO_STRING)) {
								if (Common.isNotNull(settleDomain.getManageServerItem()) && settleDomain.getManageServerItem()
										.contains(CommonConstants.THREE_STRING) && CommonConstants.ZERO_STRING.equals(settleDomain.getManagementTag())) {
									if (CommonConstants.ONE_STRING.equals(settleDomain.getManagementType())) {
										gMoney = BigDecimalUtils.safeMultiply(actualMoney,
												settleDomain.getManagementFee().divide(new BigDecimal("100"),
														CommonConstants.FIVE_INT, BigDecimal.ROUND_HALF_UP));
										isBl = true;
									}
									//判断是否存在当月的商险收入数据
									TIncomeDetail incomeDetail = new TIncomeDetail();
									incomeDetail.setSourceId(detail.getId());
									if (isBl) {
										incomeDetail.setMoney(gMoney);
									} else {
										incomeDetail.setMoney(actualMoney);
									}
									incomeDetail.setFeeType(CommonConstants.ONE_STRING);
									//判断是否存在当月的商险收入数据
									R<TIncomeDetailReturnVo> detailInfoList = socialDaprUtils.getTIncomeDetailList(incomeDetail);
									if (Common.isNotNull(detailInfoList) && detailInfoList.getCode() == CommonConstants.SUCCESS
											&& !detailInfoList.getData().getDetailList().isEmpty()) {
										//生成红冲数据
										for (TIncomeDetail detailInfo : detailInfoList.getData().getDetailList()) {
											TIncomeDetail detail1 = new TIncomeDetail();
											BeanCopyUtils.copyProperties(detailInfo, detail1);
											detail1.setId(CommonConstants.NULL);
											detail1.setRedData(CommonConstants.ONE_STRING);
											detail1.setMoney(detailInfo.getMoney().negate());
											socialDaprUtils.createTIncomeDetail(detail1);
											break;
										}
									}
								}
								if (Common.isNotNull(settleDomain.getRiskServerItem()) && settleDomain.getRiskServerItem()
										.contains(CommonConstants.THREE_STRING) && CommonConstants.ZERO_STRING.equals(settleDomain.getRiskFundTag())) {
									if (CommonConstants.ONE_STRING.equals(settleDomain.getRiskFundType())) {
										gMoney = BigDecimalUtils.safeMultiply(actualMoney,
												settleDomain.getRiskFundFee().divide(new BigDecimal("100"),
														CommonConstants.FIVE_INT, BigDecimal.ROUND_HALF_UP));
										isBl = true;
									}
									//判断是否存在当月的商险收入数据
									TIncomeDetail incomeDetail = new TIncomeDetail();
									incomeDetail.setSourceId(detail.getId());
									incomeDetail.setFeeType(CommonConstants.TWO_STRING);
									if (isBl) {
										incomeDetail.setMoney(gMoney);
									} else {
										incomeDetail.setMoney(actualMoney);
									}
									//判断是否存在当月的商险收入数据
									R<TIncomeDetailReturnVo> detailInfoList = socialDaprUtils.getTIncomeDetailList(incomeDetail);
									if (Common.isNotNull(detailInfoList) && detailInfoList.getCode() == CommonConstants.SUCCESS
											&& !detailInfoList.getData().getDetailList().isEmpty()) {
										//生成红冲数据
										for (TIncomeDetail detailInfo : detailInfoList.getData().getDetailList()) {
											TIncomeDetail detail1 = new TIncomeDetail();
											BeanCopyUtils.copyProperties(detailInfo, detail1);
											detail1.setId(CommonConstants.NULL);
											detail1.setRedData(CommonConstants.ONE_STRING);
											detail1.setMoney(detailInfo.getMoney().negate());
											socialDaprUtils.createTIncomeDetail(detail1);
											break;
										}
									}
								}
							}
						}
						//生成收入数据
						createInsuranceInfo(detail);
					}
				}catch (Exception e){
					log.error("收入数据同步处理失败："+e);
				}
			}
		}
		//操作记录
		addOperate(detailList,user,InsurancesConstants.REGISTERED,null,CommonConstants.ONE_INT);
		return R.ok(listResult,InsurancesConstants.OPERATE_SUCCESS);
	}

	/*
	 * 获取当前保单的结算状态
	 *
	 * @author zhaji
	 * @param
	 * @return {@link String}
	 */
	@Override
	public void pushActualPremium(){
		List<TInsuranceDetail> list = baseMapper.selectList(Wrappers.<TInsuranceDetail>query().lambda()
						.isNotNull(TInsuranceDetail::getDefaultSettleId)
						.isNotNull(TInsuranceDetail::getActualPremium));
		for (TInsuranceDetail detail: list){
			TInsuranceSettle settle = tInsuranceSettleService.getById(detail.getDefaultSettleId());
			String s = pushEstimate(detail, CommonConstants.TWO_INT);
			//如果推送成功则更改推送状态
			if (StringUtils.isNotBlank(s) && Common.isNotNull(settle)) {
				settle.setActualPushTime(LocalDateTime.now());
				settle.setIsActualPush(CommonConstants.ONE_INT);
				tInsuranceSettleService.updateById(settle);
			}
		}
	}

	/**
	 * 商险新增校验
	 *
	 * @author licancan
	 * @param paramList
	 * @return {@link Map<String, List<InsuranceAddParam>>}
	 */
	private Map<String,List<InsuranceAddParam>> addInsuranceCheck(List<InsuranceAddParam> paramList,YifuUser user){
		List<String> deptNoList = getDeptNoList(user);
		Map<String,List<InsuranceAddParam>> map = new HashMap<>();
		List<InsuranceAddParam> listResult = new ArrayList<>();
		List<InsuranceAddParam> listSuccess = new ArrayList<>();
		List<InsuranceAddParam> distinctList = paramList.stream().distinct().collect(Collectors.toList());
		//定义外层循环标识，方便去重的时候跳出
		outer:
		for (int i = 0; i < distinctList.size(); i++) {
			InsuranceAddParam param = distinctList.get(i);
			// 必填校验
			if (StringUtils.isBlank(param.getEmpName())){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_NOT_EMPTY);
				listResult.add(param);
				continue;
			}
			if (!ValidityUtil.validate20(param.getEmpName())){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_MORE_THAN_20);
				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;
			}

			if (!ValidityUtil.validate32(param.getPost())){
				param.setErrorMessage(InsurancesConstants.POST_NOT_MORE_THAN_32);
				listResult.add(param);
				continue;
			}

			if (StringUtils.isNotBlank(param.getRemark())){
				if (!ValidityUtil.validate50(param.getRemark())){
					param.setErrorMessage(InsurancesConstants.REMARK_NOT_MORE_THAN_50);
					listResult.add(param);
					continue;
				}
			}

			// 身份证号位数校验（18 位合法）
			if (!ValidityUtil.validateIDCard(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_LEGITIMATE);
				listResult.add(param);
				continue;
			}
			//年龄是否在16-70之间
			if (IdCardUtil.getFullAge(param.getEmpIdcardNo()) < CommonConstants.SIXTEEN_INT || IdCardUtil.getFullAge(param.getEmpIdcardNo()) > CommonConstants.SEVENTY){
				param.setErrorMessage(InsurancesConstants.EMP_AGE_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;
			}
			if(!LocalDateUtil.isFutureDate(param.getPolicyStart())){
				param.setErrorMessage(InsurancesConstants.POLICY_START_SHOULD_IS_FUTURE);
				listResult.add(param);
				continue;
			}
			if (!LocalDateUtil.compareDate(param.getPolicyStart(),param.getPolicyEnd())){
				param.setErrorMessage(InsurancesConstants.POLICY_START_SHOULD_LESS_THAN_POLICY_END);
				listResult.add(param);
				continue;
			}
			if (LocalDateUtil.betweenDay(param.getPolicyStart(),param.getPolicyEnd()) > CommonConstants.ONE_YEAR){
				param.setErrorMessage(InsurancesConstants.POLICY_DATE_NOT_MORE_THAN_365);
				listResult.add(param);
				continue;
			}

			//表内数据重复 员工姓名、员工身份证号码、保险公司、险种、起止时间（有交叉）
			for (int j = 0; j < distinctList.size(); j++) {
				InsuranceAddParam repeat = distinctList.get(j);
				if (param.getEmpName().equals(repeat.getEmpName())
						&& param.getEmpIdcardNo().equals(repeat.getEmpIdcardNo())
						&& param.getInsuranceCompanyName().equals(repeat.getInsuranceCompanyName())
						&& param.getInsuranceTypeName().equals(repeat.getInsuranceTypeName())
						&& LocalDateUtil.hasOverlap(LocalDateUtil.parseLocalDate(param.getPolicyStart()),LocalDateUtil.parseLocalDate(param.getPolicyEnd()),LocalDateUtil.parseLocalDate(repeat.getPolicyStart()),LocalDateUtil.parseLocalDate(repeat.getPolicyEnd()))
						&& i != j){
					param.setErrorMessage(InsurancesConstants.DUPLICATE_DATA_ERROR);
					listResult.add(param);
					continue outer;
				}
			}

			//校验身份合法
			TCheckIdCard checkIdCard = new TCheckIdCard();
			checkIdCard.setName(param.getEmpName());
			checkIdCard.setIdCard(param.getEmpIdcardNo());
			R<TCheckIdCard> tCheckIdCardR = checkDaprUtil.checkIdCardSingle(checkIdCard);
			if (null != tCheckIdCardR && tCheckIdCardR.getCode() == CommonConstants.SUCCESS){
				TCheckIdCard data = tCheckIdCardR.getData();
				if (CommonConstants.ONE_INT != data.getIsTrue()){
					param.setErrorMessage(InsurancesConstants.EMP_ID_CARD_NO_NOT_FIT);
					listResult.add(param);
					continue;
				}
			}

			//根据项目编码查询项目是否存在
			try{
				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 projectSetInfoVo = data.get(param.getDeptNo());
						if (null == projectSetInfoVo){
							param.setErrorMessage(InsurancesConstants.DEPT_NO_IS_NOT_EXIST);
							listResult.add(param);
							continue;
						}else {
							//结算类型，根据项目编码获取，并冗余到明细记录中
							String settleType = projectSetInfoVo.getInsuranceSettleType();
							if (StringUtils.isEmpty(settleType)){
								param.setErrorMessage(InsurancesConstants.PROJECT_NOT_FIND_SETTLE_TYPE);
								listResult.add(param);
								continue;
							}else {
								param.setBpoFlag(projectSetInfoVo.getBpoFlag());
								param.setSettleType(Integer.parseInt(settleType));
							}
							param.setBpoFlag(projectSetInfoVo.getBpoFlag());
							param.setDeptId(projectSetInfoVo.getId());
							param.setDeptName(projectSetInfoVo.getDepartName());
							param.setUnitId(projectSetInfoVo.getCustomerId());
							param.setUnitName(projectSetInfoVo.getCustomerName());
							param.setUnitNo(projectSetInfoVo.getCustomerCode());
						}
					}
				}
			}catch (Exception e){
				log.error(InsurancesConstants.GET_DEPT_DETAIL_ERROR+e);
				param.setErrorMessage(InsurancesConstants.GET_DEPT_DETAIL_ERROR);
				listResult.add(param);
				continue;
			}
			//校验当前项目是否在权限范围内
			if(!deptNoList.stream().anyMatch(u ->u.equals(param.getDeptNo()))){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_IN_USER_DEPT_LIST);
				listResult.add(param);
				continue;
			}
			//省市区域校验是否正确并设置对应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)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (!Optional.ofNullable(insuranceCompany).isPresent()){
				param.setErrorMessage(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				//冗余保险公司计费方式
				param.setBillingType(Integer.valueOf(insuranceCompany.getBillingType()));

				TInsuranceType insuranceType = tInsuranceTypeService.getOne(Wrappers.<TInsuranceType>query().lambda()
						.eq(TInsuranceType::getName, param.getInsuranceTypeName())
						.eq(TInsuranceType::getInsuranceCompanyId, insuranceCompany.getId())
						.eq(TInsuranceType::getDeleteFlag, CommonConstants.ZERO_INT)
						.last(CommonConstants.LAST_ONE_SQL)
				);
				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)
							.last(CommonConstants.LAST_ONE_SQL)
					);
					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(Long.parseLong(typeStandard.getInsuranceTypeId()));
					}

					//按月查费率
					if (CommonConstants.ONE_STRING.equals(insuranceCompany.getBillingType())){
						//计算起止时间的月数
						long month = LocalDateUtil.betweenMonth(param.getPolicyStart(), param.getPolicyEnd());
						TInsuranceTypeRate typeRate = tInsuranceTypeRateService.getOne(Wrappers.<TInsuranceTypeRate>query().lambda()
								.eq(TInsuranceTypeRate::getInsuranceTypeId, insuranceType.getId())
								.eq(TInsuranceTypeRate::getMonth, month)
								.eq(TInsuranceTypeRate::getDeleteFlag, CommonConstants.ZERO_INT)
								.last(CommonConstants.LAST_ONE_SQL)
						);
						if (!Optional.ofNullable(typeRate).isPresent()){
							param.setErrorMessage(InsurancesConstants.INSURANCE_TYPE_RATE_NOT_EXIST);
							listResult.add(param);
							continue;
						}else {
							//冗余费率
							param.setRate(new BigDecimal(typeRate.getRate()));
						}
					}
				}
			}

			// 结算月份 >= 派单月份（结算月 < 派单月份的记录予以拦截，并提示）
			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;
			}

			//记录查重校验：姓名 + 身份证号 + 保险公司 + 险种 + 保单开始日期~保单结束日期区间 是唯一（剔除退回、过期状态的记录）
			//待投保、投保中、已投保(有效、未过期)
			Set<Integer> setRStatus = Sets.newHashSet();
			setRStatus.add(CommonConstants.FOUR_INT);
			setRStatus.add(CommonConstants.FIVE_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)
					//有效
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsEffect,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsEffect)
					)
					//未过期
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsOverdue,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsOverdue)
					)
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (Optional.ofNullable(insuranceDetail).isPresent()){
				param.setErrorMessage(InsurancesConstants.DATA_IS_EXIST);
				listResult.add(param);
				continue;
			}

			//时间区间
			TInsuranceDetail insuranceDetailBetween = 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())
					.notIn(TInsuranceDetail::getBuyHandleStatus, setRStatus)
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
					.and(
							wrapper -> 	wrapper.and(
											s -> s.le(TInsuranceDetail::getPolicyStart,LocalDateUtil.parseLocalDate(param.getPolicyStart()))
													.ge(TInsuranceDetail::getPolicyEnd,LocalDateUtil.parseLocalDate(param.getPolicyStart()))
									)
									.or(e -> e.le(TInsuranceDetail::getPolicyStart,LocalDateUtil.parseLocalDate(param.getPolicyEnd()))
											.ge(TInsuranceDetail::getPolicyEnd,LocalDateUtil.parseLocalDate(param.getPolicyEnd())))
									.or(s -> s.ge(TInsuranceDetail::getPolicyStart,LocalDateUtil.parseLocalDate(param.getPolicyStart()))
											.le(TInsuranceDetail::getPolicyStart,LocalDateUtil.parseLocalDate(param.getPolicyEnd())))
									.or(s -> s.ge(TInsuranceDetail::getPolicyEnd,LocalDateUtil.parseLocalDate(param.getPolicyStart()))
											.le(TInsuranceDetail::getPolicyEnd,LocalDateUtil.parseLocalDate(param.getPolicyEnd())))
					)
					//有效
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsEffect,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsEffect)
					)
					//未过期
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsOverdue,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsOverdue)
					)
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL)
			);

			if (Optional.ofNullable(insuranceDetailBetween).isPresent()){
				param.setErrorMessage("当前员工在["+insuranceDetailBetween.getPolicyStart()+"-"+insuranceDetailBetween.getPolicyEnd()+"]期间内有投保记录");
				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,YifuUser user){
		List<String> deptNoList = getDeptNoList(user);
		Map<String,List<InsuranceBatchParam>> map = new HashMap<>();
		List<InsuranceBatchParam> listResult = new ArrayList<>();
		List<InsuranceBatchParam> listSuccess = new ArrayList<>();
		List<InsuranceBatchParam> distinctList = paramList.stream().distinct().collect(Collectors.toList());
		//定义外层循环标识，方便去重的时候跳出
		outer:
		for (int i = 0; i < distinctList.size(); i++) {
			InsuranceBatchParam param = distinctList.get(i);
			// 必填校验
			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 (!ValidityUtil.validate20(param.getEmpName())){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_MORE_THAN_20);
				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 (!ValidityUtil.validate32(param.getPost())){
				param.setErrorMessage(InsurancesConstants.POST_NOT_MORE_THAN_32);
				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;
			}
			if (StringUtils.isNotBlank(param.getRemark())){
				if (!ValidityUtil.validate50(param.getRemark())){
					param.setErrorMessage(InsurancesConstants.REMARK_NOT_MORE_THAN_50);
					listResult.add(param);
					continue;
				}
			}
			// 身份证号位数校验（18 位合法）
			if (!ValidityUtil.validateIDCard(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_LEGITIMATE);
				listResult.add(param);
				continue;
			}
			//年龄是否在16-70之间
			if (IdCardUtil.getFullAge(param.getEmpIdcardNo()) < CommonConstants.SIXTEEN_INT || IdCardUtil.getFullAge(param.getEmpIdcardNo()) > CommonConstants.SEVENTY){
				param.setErrorMessage(InsurancesConstants.EMP_AGE_NOT_LEGITIMATE);
				listResult.add(param);
				continue;
			}
			//表内数据重复 员工姓名、员工身份证号码、保险公司、险种
			for (int j = 0; j < distinctList.size(); j++) {
				InsuranceBatchParam repeat = distinctList.get(j);
				if (param.getEmpName().equals(repeat.getEmpName())
						&& param.getEmpIdcardNo().equals(repeat.getEmpIdcardNo())
						&& param.getInsuranceCompanyName().equals(repeat.getInsuranceCompanyName())
						&& param.getInsuranceTypeName().equals(repeat.getInsuranceTypeName())
						&& i != j){
					param.setErrorMessage(InsurancesConstants.DUPLICATE_DATA_ERROR);
					listResult.add(param);
					continue outer;
				}
			}

			//校验身份合法
			TCheckIdCard checkIdCard = new TCheckIdCard();
			checkIdCard.setName(param.getEmpName());
			checkIdCard.setIdCard(param.getEmpIdcardNo());
			R<TCheckIdCard> tCheckIdCardR = checkDaprUtil.checkIdCardSingle(checkIdCard);
			if (null != tCheckIdCardR && tCheckIdCardR.getCode() == CommonConstants.SUCCESS){
				TCheckIdCard data = tCheckIdCardR.getData();
				if (CommonConstants.ONE_INT != data.getIsTrue()){
					param.setErrorMessage(InsurancesConstants.EMP_ID_CARD_NO_NOT_FIT);
					listResult.add(param);
					continue;
				}
			}

			//根据项目编码查询项目是否存在
			try{
				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 projectSetInfoVo = data.get(param.getDeptNo());
						if (null == projectSetInfoVo){
							param.setErrorMessage(InsurancesConstants.DEPT_NO_IS_NOT_EXIST);
							listResult.add(param);
							continue;
						}else {
							//结算类型，根据项目编码获取，并冗余到明细记录中
							String settleType = projectSetInfoVo.getInsuranceSettleType();
							if (StringUtils.isEmpty(settleType)){
								param.setErrorMessage(InsurancesConstants.PROJECT_NOT_FIND_SETTLE_TYPE);
								listResult.add(param);
								continue;
							}else {
								param.setSettleType(Integer.parseInt(settleType));
							}
							param.setBpoFlag(projectSetInfoVo.getBpoFlag());
							param.setDeptId(projectSetInfoVo.getId());
							param.setDeptName(projectSetInfoVo.getDepartName());
							param.setUnitId(projectSetInfoVo.getCustomerId());
							param.setUnitName(projectSetInfoVo.getCustomerName());
							param.setUnitNo(projectSetInfoVo.getCustomerCode());
						}
					}
				}
			}catch (Exception e){
				log.error("查询项目信息出错："+e);
				param.setErrorMessage(InsurancesConstants.GET_DEPT_DETAIL_ERROR);
				listResult.add(param);
				continue;
			}

			//校验当前项目是否在权限范围内
			if(!deptNoList.stream().anyMatch(u ->u.equals(param.getDeptNo()))){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_IN_USER_DEPT_LIST);
				listResult.add(param);
				continue;
			}
			//省市区域校验是否正确并设置对应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));
			}
			//保单开始日期、结束日期，由系统根据保单号关联查询投保状态为 "已投保" 的商险记录的任意一条
			TInsuranceDetail limitOne = getOne(Wrappers.<TInsuranceDetail>query().lambda()
					.eq(TInsuranceDetail::getPolicyNo, param.getPolicyNo())
					.eq(TInsuranceDetail::getBuyHandleStatus, CommonConstants.THREE_INT)
					//有效
					/*.and(
					wrapper -> wrapper.eq(TInsuranceDetail::getIsEffect,CommonConstants.ZERO_INT)
							.or().isNull(TInsuranceDetail::getIsEffect)
					)*/
					//未过期
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsOverdue,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsOverdue)
					)
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.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());
			}

			// 保险公司-险种-购买标准 是否存在
			TInsuranceCompany insuranceCompany = tInsuranceCompanyService.getOne(Wrappers.<TInsuranceCompany>query().lambda()
					.eq(TInsuranceCompany::getCompanyName, param.getInsuranceCompanyName())
					.eq(TInsuranceCompany::getDeleteFlag, CommonConstants.ZERO_INT)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (!Optional.ofNullable(insuranceCompany).isPresent()){
				param.setErrorMessage(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				//冗余保险公司计费方式
				param.setBillingType(Integer.valueOf(insuranceCompany.getBillingType()));

				TInsuranceType insuranceType = tInsuranceTypeService.getOne(Wrappers.<TInsuranceType>query().lambda()
						.eq(TInsuranceType::getName, param.getInsuranceTypeName())
						.eq(TInsuranceType::getInsuranceCompanyId, insuranceCompany.getId())
						.eq(TInsuranceType::getDeleteFlag, CommonConstants.ZERO_INT)
						.last(CommonConstants.LAST_ONE_SQL)
				);
				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)
							.last(CommonConstants.LAST_ONE_SQL)
					);
					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(Long.parseLong(typeStandard.getInsuranceTypeId()));
					}

					//按月查费率
					if (CommonConstants.ONE_STRING.equals(insuranceCompany.getBillingType())){
						//计算起止时间的月数
						long month = LocalDateUtil.betweenMonth(param.getPolicyStart().toString(), param.getPolicyEnd().toString());
						TInsuranceTypeRate typeRate = tInsuranceTypeRateService.getOne(Wrappers.<TInsuranceTypeRate>query().lambda()
								.eq(TInsuranceTypeRate::getInsuranceTypeId, insuranceType.getId())
								.eq(TInsuranceTypeRate::getMonth, month)
								.eq(TInsuranceTypeRate::getDeleteFlag, CommonConstants.ZERO_INT)
								.last(CommonConstants.LAST_ONE_SQL)
						);
						if (!Optional.ofNullable(typeRate).isPresent()){
							param.setErrorMessage(InsurancesConstants.INSURANCE_TYPE_RATE_NOT_EXIST);
							listResult.add(param);
							continue;
						}else {
							//冗余费率
							param.setRate(new BigDecimal(typeRate.getRate()));
						}
					}
				}
			}

			if(!limitOne.getInsuranceCompanyName().equals(param.getInsuranceCompanyName())){
				param.setErrorMessage(InsurancesConstants.POLICY_NO_COMPANY_NAME_NOT_SAME);
				listResult.add(param);
				continue;
			}

			if (!limitOne.getInsuranceTypeName().equals(param.getInsuranceTypeName())){
				param.setErrorMessage(InsurancesConstants.POLICY_NO_TYPE_NAME_NOT_SAME);
				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;
			}

			//记录查重校验：姓名 + 身份证号 + 保险公司 + 险种
			//待投保、投保中、已投保(有效、未过期)
			Set<Integer> setRStatus = Sets.newHashSet();
			setRStatus.add(CommonConstants.FOUR_INT);
			setRStatus.add(CommonConstants.FIVE_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())
					.notIn(TInsuranceDetail::getBuyHandleStatus, setRStatus)
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
					//有效
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsEffect,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsEffect)
					)
					//未过期
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsOverdue,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsOverdue)
					)
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (Optional.ofNullable(insuranceDetail).isPresent()){
				param.setErrorMessage(InsurancesConstants.DATA_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<InsuranceReplaceParam>>}
	 */
	private Map<String,List<InsuranceReplaceParam>> replaceInsuranceCheck(List<InsuranceReplaceParam> paramList,YifuUser user){
		List<String> deptNoList = getDeptNoList(user);
		Map<String,List<InsuranceReplaceParam>> map = new HashMap<>();
		List<InsuranceReplaceParam> listResult = new ArrayList<>();
		List<InsuranceReplaceParam> listSuccess = new ArrayList<>();
		List<InsuranceReplaceParam> distinctList = paramList.stream().distinct().collect(Collectors.toList());
		//定义外层循环标识，方便去重的时候跳出
		outer:
		for (int i = 0; i < distinctList.size(); i++) {
			InsuranceReplaceParam param = distinctList.get(i);
			// 必填校验
			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 (!ValidityUtil.validate20(param.getReplaceEmpName())){
				param.setErrorMessage(InsurancesConstants.REPLACE_EMP_NAME_MORE_THAN_20);
				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;
			}

			if (!ValidityUtil.validate32(param.getPost())){
				param.setErrorMessage(InsurancesConstants.POST_NOT_MORE_THAN_32);
				listResult.add(param);
				continue;
			}

			// 身份证号位数校验（18 位合法）
			if (!ValidityUtil.validateIDCard(param.getReplaceEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.REPLACE_EMP_IDCARD_NO_NOT_LEGITIMATE);
				listResult.add(param);
				continue;
			}
			//年龄是否在16-70之间
			if (IdCardUtil.getFullAge(param.getReplaceEmpIdcardNo()) < CommonConstants.SIXTEEN_INT || IdCardUtil.getFullAge(param.getReplaceEmpIdcardNo()) > CommonConstants.SEVENTY){
				param.setErrorMessage(InsurancesConstants.REPLACE_EMP_AGE_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;
			}
			if (!LocalDateUtil.compareDate(param.getPolicyStart(),param.getPolicyEnd())){
				param.setErrorMessage(InsurancesConstants.POLICY_START_SHOULD_LESS_THAN_POLICY_END);
				listResult.add(param);
				continue;
			}
			if (LocalDateUtil.betweenDay(param.getPolicyStart(),param.getPolicyEnd()) > CommonConstants.ONE_YEAR){
				param.setErrorMessage(InsurancesConstants.POLICY_DATE_NOT_MORE_THAN_365);
				listResult.add(param);
				continue;
			}

			//表内数据重复 员工姓名、员工身份证号码、保险公司、险种、起止时间（有交叉）
			for (int j = 0; j < distinctList.size(); j++) {
				InsuranceReplaceParam repeat = distinctList.get(j);
				if (((param.getEmpName().equals(repeat.getEmpName()) && param.getEmpIdcardNo().equals(repeat.getEmpIdcardNo()))
						||(param.getReplaceEmpName().equals(repeat.getReplaceEmpName()) && param.getReplaceEmpIdcardNo().equals(repeat.getReplaceEmpIdcardNo())))
						&& param.getInsuranceCompanyName().equals(repeat.getInsuranceCompanyName())
						&& param.getInsuranceTypeName().equals(repeat.getInsuranceTypeName())
						&& LocalDateUtil.hasOverlap(LocalDateUtil.parseLocalDate(param.getPolicyStart()),LocalDateUtil.parseLocalDate(param.getPolicyEnd()),LocalDateUtil.parseLocalDate(repeat.getPolicyStart()),LocalDateUtil.parseLocalDate(repeat.getPolicyEnd()))
						&& i != j){
					param.setErrorMessage(InsurancesConstants.DUPLICATE_DATA_ERROR);
					listResult.add(param);
					continue outer;
				}
			}

			//校验身份合法
			TCheckIdCard checkIdCard = new TCheckIdCard();
			checkIdCard.setName(param.getReplaceEmpName());
			checkIdCard.setIdCard(param.getReplaceEmpIdcardNo());
			R<TCheckIdCard> tCheckIdCardR = checkDaprUtil.checkIdCardSingle(checkIdCard);
			if (null != tCheckIdCardR && tCheckIdCardR.getCode() == CommonConstants.SUCCESS){
				TCheckIdCard data = tCheckIdCardR.getData();
				if (CommonConstants.ONE_INT != data.getIsTrue()){
					param.setErrorMessage(InsurancesConstants.REPLACE_EMP_ID_CARD_NO_NOT_FIT);
					listResult.add(param);
					continue;
				}
			}

			if (param.getEmpName().equals(param.getReplaceEmpName()) && param.getEmpIdcardNo().equals(param.getReplaceEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.REPLACE_EMP_INFO_SAME);
				listResult.add(param);
				continue;
			}
			//根据项目编码查询项目是否存在
			try{
				R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(Arrays.asList(param.getReplaceDeptNo()));
				if (null != setInfoByCodes && setInfoByCodes.getCode() == CommonConstants.SUCCESS) {
					Map<String, ProjectSetInfoVo> data = setInfoByCodes.getData().getProjectSetInfoVoMap();
					if (MapUtils.isEmpty(data)){
						param.setErrorMessage(InsurancesConstants.REPLACE_DEPT_NO_IS_NOT_EXIST);
						listResult.add(param);
						continue;
					}else {
						ProjectSetInfoVo projectSetInfoVo = data.get(param.getReplaceDeptNo());
						if (null == projectSetInfoVo){
							param.setErrorMessage(InsurancesConstants.REPLACE_DEPT_NO_IS_NOT_EXIST);
							listResult.add(param);
							continue;
						}else {
							//结算类型，根据项目编码获取，并冗余到明细记录中
							String settleType = projectSetInfoVo.getInsuranceSettleType();
							if (StringUtils.isEmpty(settleType)){
								param.setErrorMessage(InsurancesConstants.REPLACE_PROJECT_NOT_FIND_SETTLE_TYPE);
								listResult.add(param);
								continue;
							}else {
								param.setSettleType(Integer.parseInt(settleType));
								param.setDeptId(projectSetInfoVo.getId());
								param.setBpoFlag(projectSetInfoVo.getBpoFlag());
								param.setDeptName(projectSetInfoVo.getDepartName());
								param.setUnitId(projectSetInfoVo.getCustomerId());
								param.setUnitName(projectSetInfoVo.getCustomerName());
								param.setUnitNo(projectSetInfoVo.getCustomerCode());
							}
						}
					}
				}
			}catch (Exception e){
				log.error("查询项目信息出错："+e);
				param.setErrorMessage(InsurancesConstants.GET_DEPT_DETAIL_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)
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (!Optional.ofNullable(detail).isPresent()){
				param.setErrorMessage(InsurancesConstants.REPLACE_IS_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				//校验当前项目是否在权限范围内
				if(deptNoList.stream().noneMatch(u ->u.equals(param.getDeptNo()))){
					param.setErrorMessage(InsurancesConstants.OLD_DEPT_NO_NOT_IN_DEPT_LIST);
					listResult.add(param);
					continue;
				}
				//校验当前项目是否在权限范围内
				if(deptNoList.stream().noneMatch(u ->u.equals(param.getReplaceDeptNo()))){
					param.setErrorMessage(InsurancesConstants.NEW_DEPT_NO_NOT_IN_DEPT_LIST);
					listResult.add(param);
					continue;
				}
				// 投保状态 待投保 不能替换
				if (detail.getBuyHandleStatus() == CommonConstants.ONE_INT){
					param.setErrorMessage(InsurancesConstants.ONE_REPLACE_IS_NOT_ALLOW);
					listResult.add(param);
					continue;
				}
				// 投保状态 投保中 不能替换
				if (detail.getBuyHandleStatus() == CommonConstants.TWO_INT){
					param.setErrorMessage(InsurancesConstants.TWO_REPLACE_IS_NOT_ALLOW);
					listResult.add(param);
					continue;
				}
				// 投保状态 投保退回 不能替换
				if (detail.getBuyHandleStatus() == CommonConstants.FOUR_INT){
					param.setErrorMessage(InsurancesConstants.FOUR_REPLACE_IS_NOT_ALLOW);
					listResult.add(param);
					continue;
				}
				// 投保状态 已投保 已出险 不能替换
				if (detail.getBuyHandleStatus() == CommonConstants.THREE_INT
						&& detail.getIsUse() != null && detail.getIsUse() == CommonConstants.ONE_INT){
					param.setErrorMessage(InsurancesConstants.USE_REPLACE_IS_NOT_ALLOW);
					listResult.add(param);
					continue;
				}
				// 投保状态 已投保 已失效 不能替换
				if (detail.getBuyHandleStatus() == CommonConstants.THREE_INT
						&& detail.getIsEffect() != null && detail.getIsEffect() == CommonConstants.ONE_INT){
					param.setErrorMessage(InsurancesConstants.EFFECT_REPLACE_IS_NOT_ALLOW);
					listResult.add(param);
					continue;
				}
				// 投保状态 已投保 已过期 不能替换
				if (detail.getBuyHandleStatus() == CommonConstants.THREE_INT
						&& detail.getIsOverdue() != null && detail.getIsOverdue() == CommonConstants.ONE_INT){
					param.setErrorMessage(InsurancesConstants.OVERDUE_REPLACE_IS_NOT_ALLOW);
					listResult.add(param);
					continue;
				}
				// 投保状态 已减员 不能替换
				if (detail.getBuyHandleStatus() == CommonConstants.FIVE_INT){
					param.setErrorMessage(InsurancesConstants.FIVE_REPLACE_IS_NOT_ALLOW);
					listResult.add(param);
					continue;
				}
				// 投保状态 已投保 减员状态 待减员/减员中 不能替换
				if (detail.getBuyHandleStatus() == CommonConstants.THREE_INT
						&& (detail.getReduceHandleStatus() != null && (detail.getReduceHandleStatus() == CommonConstants.ONE_INT
						|| detail.getReduceHandleStatus() == CommonConstants.TWO_INT))){
					param.setErrorMessage(InsurancesConstants.REDUCE_REPLACE_IS_NOT_ALLOW);
					listResult.add(param);
					continue;
				}
			}
			//替换者数据查重校验：替换姓名 + 替换身份证号 + 替换项目编码? + 保险公司 + 险种名称
			//待投保、投保中、已投保(有效、未过期)
			Set<Integer> setRStatus = Sets.newHashSet();
			setRStatus.add(CommonConstants.FOUR_INT);
			setRStatus.add(CommonConstants.FIVE_INT);
			TInsuranceDetail replace = this.baseMapper.selectOne(Wrappers.<TInsuranceDetail>query().lambda()
					.eq(TInsuranceDetail::getEmpName, param.getReplaceEmpName())
					.eq(TInsuranceDetail::getEmpIdcardNo, param.getReplaceEmpIdcardNo())
					.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)
					//有效
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsEffect,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsEffect)
					)
					//未过期
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsOverdue,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsOverdue)
					)
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (Optional.ofNullable(replace).isPresent()){
				param.setErrorMessage(InsurancesConstants.REPLACE_IS_EXIST);
				listResult.add(param);
				continue;
			}
			//时间区间
			TInsuranceDetail insuranceDetailBetween = this.baseMapper.selectOne(Wrappers.<TInsuranceDetail>query().lambda()
					.eq(TInsuranceDetail::getEmpName, param.getReplaceEmpName())
					.eq(TInsuranceDetail::getEmpIdcardNo, param.getReplaceEmpIdcardNo())
					.eq(TInsuranceDetail::getInsuranceCompanyName, param.getInsuranceCompanyName())
					.eq(TInsuranceDetail::getInsuranceTypeName, param.getInsuranceTypeName())
					.notIn(TInsuranceDetail::getBuyHandleStatus, setRStatus)
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
					.and(
							wrapper -> 	wrapper.and(
											s -> s.le(TInsuranceDetail::getPolicyStart,LocalDateUtil.parseLocalDate(param.getPolicyStart()))
													.ge(TInsuranceDetail::getPolicyEnd,LocalDateUtil.parseLocalDate(param.getPolicyStart()))
									)
									.or(e -> e.le(TInsuranceDetail::getPolicyStart,LocalDateUtil.parseLocalDate(param.getPolicyEnd()))
											.ge(TInsuranceDetail::getPolicyEnd,LocalDateUtil.parseLocalDate(param.getPolicyEnd())))
									.or(s -> s.ge(TInsuranceDetail::getPolicyStart,LocalDateUtil.parseLocalDate(param.getPolicyStart()))
											.le(TInsuranceDetail::getPolicyStart,LocalDateUtil.parseLocalDate(param.getPolicyEnd())))
									.or(s -> s.ge(TInsuranceDetail::getPolicyEnd,LocalDateUtil.parseLocalDate(param.getPolicyStart()))
											.le(TInsuranceDetail::getPolicyEnd,LocalDateUtil.parseLocalDate(param.getPolicyEnd())))
					)
					//有效
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsEffect,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsEffect)
					)
					//未过期
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsOverdue,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsOverdue)
					)
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL)
			);

			if (Optional.ofNullable(insuranceDetailBetween).isPresent()){
				param.setErrorMessage("替换员工在["+insuranceDetailBetween.getPolicyStart()+"-"+insuranceDetailBetween.getPolicyEnd()+"]期间内有投保记录");
				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,YifuUser user){
		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;
			}
			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 (StringUtils.isNotBlank(param.getPolicyNo())){
				if (!ValidityUtil.validate50(param.getPolicyNo())){
					param.setErrorMessage(InsurancesConstants.POLICY_NO_MORE_THAN_50);
					listResult.add(param);
					continue;
				}
			}
			if (StringUtils.isNotBlank(param.getActualPremium())){
				if(!ValidityUtil.validateMoney(param.getActualPremium())){
					param.setErrorMessage(InsurancesConstants.ACTUAL_PREMIUM_PARSE_ERROR);
					listResult.add(param);
					continue;
				}
			}
			if (StringUtils.isNotBlank(param.getInvoiceNo())){
				if (!ValidityUtil.validate50(param.getInvoiceNo())){
					param.setErrorMessage(InsurancesConstants.INVOICE_NO_MORE_THAN_50);
					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)
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (!Optional.ofNullable(detail).isPresent()){
				param.setErrorMessage(InsurancesConstants.DATA_IS_NOT_EXIST);
				listResult.add(param);
				continue;
			}else {
				LambdaQueryWrapper<TInsuranceEkp> ekpLambdaQueryWrapper = new LambdaQueryWrapper<>();
				ekpLambdaQueryWrapper.eq(TInsuranceEkp :: getDetailId,detail.getId()).eq(TInsuranceEkp ::getResendFlag,CommonConstants.ZERO_INT);
				List<TInsuranceEkp> ekpList = tInsuranceEkpService.list(ekpLambdaQueryWrapper);
				if(CollectionUtils.isNotEmpty(ekpList)){
					param.setErrorMessage(InsurancesConstants.EKP_SEND_ERROR);
					listResult.add(param);
					continue;
				}
				// 如果保费不存在，保单号、保费必填
				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_EMPTY);
						listResult.add(param);
						continue;
					}
				}

				//批增类型，保单号不存在
				if (detail.getBuyType() == CommonConstants.THREE_INT){
					if (StringUtils.isNotBlank(param.getPolicyNo())){
						TInsuranceDetail batchPolicyNo = this.baseMapper.selectOne(Wrappers.<TInsuranceDetail>query().lambda()
								.eq(TInsuranceDetail::getPolicyNo, param.getPolicyNo())
								.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
								.orderByDesc(TInsuranceDetail::getUpdateTime)
								.last(CommonConstants.LAST_ONE_SQL)
						);
						if (!Optional.ofNullable(batchPolicyNo).isPresent()){
							param.setErrorMessage(InsurancesConstants.POLICY_NO_NOT_EXIST);
							listResult.add(param);
							continue;
						}else {
							//批增类型，保单号已存在但是和派单时填写的不一致
							if (!detail.getPolicyNo().equals(param.getPolicyNo())){
								param.setErrorMessage(InsurancesConstants.POLICY_NO_ERROR);
								listResult.add(param);
								continue;
							}
						}
					}
				}

				//新增类型，保单号已存在但是和填写的保险公司不一致
				if (detail.getBuyType() == CommonConstants.ONE_INT){
					if (StringUtils.isNotBlank(param.getPolicyNo())){
						TInsuranceDetail addPolicyNo = this.baseMapper.selectOne(Wrappers.<TInsuranceDetail>query().lambda()
								.eq(TInsuranceDetail::getPolicyNo, param.getPolicyNo())
								.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
								.orderByDesc(TInsuranceDetail::getUpdateTime)
								.last(CommonConstants.LAST_ONE_SQL)
						);
						if (Optional.ofNullable(addPolicyNo).isPresent()){
							if (!addPolicyNo.getInsuranceCompanyName().equals(param.getInsuranceCompanyName())){
								param.setErrorMessage(InsurancesConstants.POLICY_NO_COMPANY_NAME_NOT_SAME);
								listResult.add(param);
								continue;
							}
							if (!addPolicyNo.getInsuranceTypeName().equals(param.getInsuranceTypeName())){
								param.setErrorMessage(InsurancesConstants.POLICY_NO_TYPE_NAME_NOT_SAME);
								listResult.add(param);
								continue;
							}
						}
					}
				}

				if (detail.getBuyType() == CommonConstants.FOUR_INT){
					param.setErrorMessage(InsurancesConstants.BUY_TYPE_FOUR_NOT_REGISTERED);
					listResult.add(param);
					continue;
				}
				if (detail.getBuyHandleStatus() == CommonConstants.ONE_INT){
					param.setErrorMessage(InsurancesConstants.BUY_HANDLE_ONE_NOT_REGISTERED);
					listResult.add(param);
					continue;
				}
				if (detail.getBuyHandleStatus() == CommonConstants.TWO_INT){
					param.setErrorMessage(InsurancesConstants.BUY_HANDLE_TWO_NOT_REGISTERED);
					listResult.add(param);
					continue;
				}
				if (detail.getBuyHandleStatus() == CommonConstants.FOUR_INT){
					param.setErrorMessage(InsurancesConstants.BUY_HANDLE_FOUR_NOT_REGISTERED);
					listResult.add(param);
					continue;
				}
				//保单号是否更新
				boolean booleanPolicyNo = StringUtils.isNotBlank(param.getPolicyNo()) && !param.getPolicyNo().equals(detail.getPolicyNo());
				//发票号是否更新
				boolean booleanInvoiceNo = StringUtils.isNotBlank(param.getInvoiceNo()) && !param.getInvoiceNo().equals(detail.getInvoiceNo());
				//保费是否更新
				boolean booleanActualPremium = true;
				if (Common.isNotNull(detail.getActualPremium())) {
					booleanActualPremium = StringUtils.isNotBlank(param.getActualPremium()) && detail.getActualPremium().compareTo(new BigDecimal(param.getActualPremium())) != 0;
				}
				//如果当前为合并结算
				if (CommonConstants.ZERO_INT == detail.getSettleType() && StringUtils.isNotBlank(detail.getDefaultSettleId())){
					TInsuranceSettle settle = tInsuranceSettleService.getById(detail.getDefaultSettleId());
					if (Optional.ofNullable(settle).isPresent()){
						SettleVo settleVo = getInsuranceDetailSettleStatus(detail.getId(), detail.getDefaultSettleId());
						if(!Common.isEmpty(settleVo)){
							String estimateStatus = settleVo.getEstimateStatus();
							String actualStatus = settleVo.getActualStatus();
							//保费更新，保单号，发票号不更新
							if(booleanActualPremium && !booleanPolicyNo && !booleanInvoiceNo){
								if ( InsurancesConstants.SETTLE_TWO.equals(actualStatus)){
									param.setErrorMessage(InsurancesConstants.SETTLE_HANDLE_THREE_NOT_REGISTERED);
									listResult.add(param);
									continue;
								}
								if (InsurancesConstants.SETTLE_ONE.equals(actualStatus)){
									param.setErrorMessage(InsurancesConstants.SETTLE_HANDLE_TWO_NOT_REGISTERED);
									listResult.add(param);
									continue;
								}
							}
							//
							if(!booleanPolicyNo || !booleanInvoiceNo){
								if (InsurancesConstants.SETTLE_TWO.equals(estimateStatus) || InsurancesConstants.SETTLE_TWO.equals(actualStatus)){
									param.setErrorMessage(InsurancesConstants.SETTLE_HANDLE_THREE_NOT_REGISTERED);
									listResult.add(param);
									continue;
								}
								if (InsurancesConstants.SETTLE_ONE.equals(estimateStatus) || InsurancesConstants.SETTLE_ONE.equals(actualStatus)){
									param.setErrorMessage(InsurancesConstants.SETTLE_HANDLE_TWO_NOT_REGISTERED);
									listResult.add(param);
									continue;
								}
							}
						}

					}
				}
				//如果当前为单独结算，判断实缴有没有结算
				if (CommonConstants.ONE_INT == detail.getSettleType() && StringUtils.isNotBlank(detail.getDefaultSettleId())){
					TInsuranceSettle settle = tInsuranceSettleService.getById(detail.getDefaultSettleId());
					if (Optional.ofNullable(settle).isPresent()){
						SettleVo settleVo = getInsuranceDetailSettleStatus(detail.getId(), detail.getDefaultSettleId());
						if(!Common.isEmpty(settleVo)){
							String actualStatus = settleVo.getActualStatus();
							//判断实缴是否结算中
							if(booleanActualPremium && !booleanPolicyNo && !booleanInvoiceNo){
								if ( InsurancesConstants.SETTLE_TWO.equals(actualStatus)){
									param.setErrorMessage(InsurancesConstants.SETTLE_HANDLE_THREE_NOT_REGISTERED);
									listResult.add(param);
									continue;
								}
								if (InsurancesConstants.SETTLE_ONE.equals(actualStatus)){
									param.setErrorMessage(InsurancesConstants.SETTLE_HANDLE_TWO_NOT_REGISTERED);
									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));
	}

	/**
	 * 操作记录(无审批remark)
	 *
	 * @author licancan
	 * @param detailList 商险明细集合
	 * @param user 登录用户
	 * @param operateDesc 操作描述
	 * @param displayFlag 是否显示 0不显示/1显示
	 * @return void
	 */
	public void addOperate(List<TInsuranceDetail> detailList,YifuUser user,String operateDesc,String remark,Integer displayFlag){
		if (CollectionUtils.isNotEmpty(detailList)){
			List<TInsuranceOperate> operateList = new ArrayList<>();
			for (TInsuranceDetail detail : detailList) {
				TInsuranceOperate operate = new TInsuranceOperate();
				operate.setRemark(remark);
				operate.setDisplayFlag(displayFlag);
				operate.setInsuranceDetailId(detail.getId());
				operate.setOperateDesc(operateDesc);
				operate.setCreateBy(user.getId());
				operate.setCreateName(user.getNickname());
				operate.setCreateTime(LocalDateTime.now());
				operateList.add(operate);
			}
			tInsuranceOperateService.saveBatch(operateList);
		}
	}

	/**
	 * 操作记录(有审批remark)
	 *
	 * @author licancan
	 * @param paramList 操作集合
	 * @param user 登录用户
	 * @param operateDesc 操作描述
	 * @return void
	 */
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public void addOperate(List<InsuranceHandleParam> paramList,YifuUser user,String operateDesc){
		if (CollectionUtils.isNotEmpty(paramList)){
			try {
				List<TInsuranceOperate> operateList = new ArrayList<>();
				for (InsuranceHandleParam param : paramList) {
					TInsuranceOperate operate = new TInsuranceOperate();
					operate.setRemark(param.getRemark());
					operate.setDisplayFlag(CommonConstants.ONE_INT);
					operate.setInsuranceDetailId(param.getId());
					operate.setOperateDesc(operateDesc);
					operate.setCreateBy(user.getId());
					operate.setCreateName(user.getNickname());
					operate.setCreateTime(LocalDateTime.now());
					operateList.add(operate);
				}
				tInsuranceOperateService.saveBatch(operateList);
			}catch (Exception e){
				e.getStackTrace();
			}
		}
	}

	/**
	 * 根据购买类型获取操作类型
	 *
	 * @author licancan
	 * @param buyType
	 * @return {@link String}
	 */
	private String getOperateDescByBuyType(Integer buyType){
		String result;
		switch (buyType){
			case 1:
				result = InsurancesConstants.ADD;
				break;
			case 3:
				result = InsurancesConstants.BATCH;
				break;
			case 4:
				result = InsurancesConstants.REPLACE;
				break;
			default:
				result = "";
		}
		return result;
	}

	/**
	 * 将集合交叉合并，list1 是第一个顺序 list2 是第二个顺序
	 *
	 * @author licancan
	 * @param list1
	 * @param list2
	 * @return {@link List<InsuranceExportListVO>}
	 */
	private List<InsuranceExportListVO> crossMerger (List<InsuranceExportListVO> list1, List<InsuranceExportListVO> list2){
		//将list放入到链表队列
		LinkedList<InsuranceExportListVO> st1 = new LinkedList<>(list1);
		LinkedList<InsuranceExportListVO> st2 = new LinkedList<>(list2);
		//计算较大的数组长度
		int max = list1.size() > list2.size() ? list1.size() : list2.size();
		//新建一个最终结果的list
		List<InsuranceExportListVO> list = new ArrayList<>(list1.size() + list2.size());
		for ( int i = 0; i < max;i++){
			//如果队列没取完，继续取
			if (!st1.isEmpty()){
				list.add(st1.poll());
			}
			//如果队列没取完，继续取
			if (!st2.isEmpty()){
				list.add(st2.poll());
			}
		}
		return list;
	}

	/***********************减员办理********************************/

	/**
	 * 减员导入
	 *
	 * @author zhaji
	 * @param insuranceRefundCheckList 减员表
	 * @return {@link R}
	 */
	@Override
	public R saveInsuranceRefund(List<InsuranceRefundCheck> insuranceRefundCheckList,String orderNo) {
		YifuUser user = SecurityUtils.getUser();
		if(!Common.isNotEmpty(insuranceRefundCheckList)){
			return R.failed("当前导入的减员信息为空");
		}
		if(insuranceRefundCheckList.size() > CommonConstants.IMPORT_TWENTY_THOUSAND){
			return R.failed(InsurancesConstants.IMPORT_TOO_LONG);
		}
		Map<String, List<InsuranceRefundCheck>> refundMap = checkInsuranceRefundList(insuranceRefundCheckList,user);
		List<InsuranceRefundCheck> successList = refundMap.get(InsurancesConstants.SUCCESS_LIST);
		List<TInsuranceOperate> operateList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(successList)){
			for (InsuranceRefundCheck refund : successList){
				TInsuranceRefund insuranceRefund = new TInsuranceRefund();
				TInsuranceOperate insuranceOperate = new TInsuranceOperate();
				insuranceRefund.setInsDetailId(refund.getId());
				insuranceRefund.setBuyType(CommonConstants.FIVE_INT);
				insuranceRefund.setReduceHandleStatus(CommonConstants.ONE_INT);
				insuranceRefund.setCreateBy(user.getId());
				insuranceRefund.setCreateName(user.getNickname());
				insuranceRefund.setCreateTime(LocalDateTime.now());
				insuranceRefund.setUpdateTime(LocalDateTime.now());
				insuranceRefund.setUpdateBy(user.getId());
				insuranceRefund.setOrderNo(orderNo);
				insuranceRefund.setCreateUserDeptId(user.getDeptId().toString());
				insuranceRefund.setCreateUserDeptName(user.getDeptName());
				if(StringUtils.isNotBlank(refund.getRemark())){
					insuranceRefund.setRemark(refund.getRemark());
				}
				tInsuranceRefundService.save(insuranceRefund);
				LambdaUpdateWrapper<TInsuranceDetail> updateWrapper = new LambdaUpdateWrapper<>();
				updateWrapper.set(TInsuranceDetail :: getUpdateBy,user.getId())
						.set(TInsuranceDetail :: getUpdateTime,LocalDateTime.now())
						.set(TInsuranceDetail :: getRefundId,insuranceRefund.getId())
						.set(TInsuranceDetail :: getReduceHandleStatus,CommonConstants.ONE_INT);
				updateWrapper.eq(TInsuranceDetail :: getId,refund.getId());
				update(updateWrapper);
				insuranceOperate.setInsuranceDetailId(refund.getId());
				insuranceOperate.setCreateBy(user.getId());
				insuranceOperate.setCreateName(user.getNickname());
				insuranceOperate.setCreateTime(LocalDateTime.now());
				insuranceOperate.setDisplayFlag(CommonConstants.ONE_INT);
				insuranceOperate.setOperateDesc(InsurancesConstants.INSURANCE_REFUND_IMPORT);
				operateList.add(insuranceOperate);
			}
		}
		tInsuranceOperateService.saveBatch(operateList);
		List<InsuranceRefundCheck> errorList = refundMap.get(InsurancesConstants.ERROR_LIST);
		return R.ok(errorList,"校验完成");
	}

	/**
	 * 已投保列表分页查询
	 *
	 * @author zhaji
	 * @param page 分页参数
	 * @param param 查询参数
	 * @return {@link IPage< InsuredListVo>}
	 */
	@Override
	public IPage<InsuredListVo> getInsuredListPage(Page<InsuredListVo> page, InsuredParam param, String mId) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isNotNull(mId)) {
			param.setMId(mId);
		}
		param.setCreateBy(user.getId());
		menuUtil.setAuthSql(user, param);
		if (Common.isNotNull(param.getAuthSql()) && param.getAuthSql().contains("1=2 CONCAT")) {
			param.setAuthSql(param.getAuthSql().replace("1=2 CONCAT", "CONCAT"));
		}
		IPage<InsuredListVo> insuranceList;
		insuranceList = this.baseMapper.getInsuredListPage(page, param);
		if (CollectionUtils.isNotEmpty(insuranceList.getRecords())){
			//根据项目编码获取项目名称
			for (InsuredListVo record : insuranceList.getRecords()) {
				//购买月数
				record.setBuyMonth(LocalDateUtil.betweenMonth(record.getPolicyStart().toString(),record.getPolicyEnd().toString()));
			}
		}
		return insuranceList;
	}

	/**
	 * 已投保列表不分页查询
	 *
	 * @author zhaji
	 * @param param 查询参数
	 * @return {@link List< InsuredListVo>}
	 */
	@Override
	public R getInsuredList(InsuredParam param) {
		YifuUser user = SecurityUtils.getUser();
		param.setCreateBy(user.getId());
		menuUtil.setAuthSql(user, param);
		if (Common.isNotNull(param.getAuthSql()) && param.getAuthSql().contains("1=2 CONCAT")) {
			param.setAuthSql(param.getAuthSql().replace("1=2 CONCAT", "CONCAT"));
		}
		List<InsuredListVo> insuredList;
		insuredList = this.baseMapper.getInsuredList(param);
		if (CollectionUtils.isNotEmpty(insuredList)){
			if(insuredList.size() > CommonConstants.EXPORT_TWENTY_THOUSAND){
				return R.failed(InsurancesConstants.IMPORT_TOO_LONG);
			}
			//根据项目编码获取项目名称
			List<String> collect = insuredList.stream().map(InsuredListVo::getDeptNo).distinct().collect(Collectors.toList());
			try{
				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) {
						//购买月数
						record.setBuyMonth(LocalDateUtil.betweenMonth(record.getPolicyStart().toString(), record.getPolicyEnd().toString()));
						if (data != null) {
							ProjectSetInfoVo jsonObject = data.get(record.getDeptNo());
							if (null != jsonObject) {
								record.setInvoiceTitle(Optional.ofNullable(jsonObject.getInvoiceTitleInsurance()).orElse(""));
							}
						}
					}
				}
			}catch (Exception e){
				for (InsuredListVo record : insuredList) {
					record.setProjectName(CommonConstants.EMPTY_STRING);
				}
			}
		}
		return R.ok(insuredList);
	}

	/**
	 * 已减员列表分页查询
	 *
	 * @author zhaji
	 * @param page 分页数据
	 * @param param 查询参数
	 * @return {@link IPage<  InsuranceRefundListVo >}
	 */
	@Override
	public R getInsuranceRefundPageList(Page<InsuranceRefundParam> page, InsuranceRefundParam param, String mId) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isNotNull(mId)) {
			param.setMId(mId);
		}
		param.setCreateBy(user.getId());
		menuUtil.setAuthSql(user, param);
		if (Common.isNotNull(param.getAuthSql()) && param.getAuthSql().contains("1=2 CONCAT")) {
			param.setAuthSql(param.getAuthSql().replace("1=2 CONCAT", "CONCAT"));
		}
		IPage<InsuranceRefundListVo> insuranceRefundPageList = this.baseMapper.getInsuranceRefundPageList(page, param);
		if (CollectionUtils.isNotEmpty(insuranceRefundPageList.getRecords())){
			//根据项目编码获取项目名称
			try {
				for (InsuranceRefundListVo record : insuranceRefundPageList.getRecords()) {
					//购买月数
					record.setBuyMonth(LocalDateUtil.betweenMonth(record.getPolicyStart().toString(),record.getPolicyEnd().toString()));
				}
			}catch (Exception e){
				log.error(InsurancesConstants.GET_DEPT_DETAIL_ERROR+e);
			}
		}
		return R.ok(insuranceRefundPageList);
	}

	/**
	 * 已减员列表导出
	 *
	 * @author zhaji
	 * @param param 查询参数
	 * @return {@link List<  InsuranceRefundListVo >}
	 */
	@Override
	public R getInsuranceRefundList(InsuranceRefundParam param) {
		YifuUser user = SecurityUtils.getUser();
		param.setCreateBy(user.getId());
		menuUtil.setAuthSql(user, param);
		if (Common.isNotNull(param.getAuthSql()) && param.getAuthSql().contains("1=2 CONCAT")) {
			param.setAuthSql(param.getAuthSql().replace("1=2 CONCAT", "CONCAT"));
		}
		List<InsuranceRefundListVo> insuranceRefundList = this.baseMapper.getInsuranceRefundList(param);
		if (CollectionUtils.isNotEmpty(insuranceRefundList)){
			if(insuranceRefundList.size() > CommonConstants.EXPORT_TWENTY_THOUSAND){
				return R.failed(InsurancesConstants.EXPORT_TOO_LONG);
			}
			//根据项目编码获取项目名称
			List<String> collect = insuranceRefundList.stream().map(InsuranceRefundListVo::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) {
					//购买月数
					record.setBuyMonth(LocalDateUtil.betweenMonth(record.getPolicyStart().toString(),record.getPolicyEnd().toString()));
					if (data != null) {
						ProjectSetInfoVo jsonObject = data.get(record.getDeptNo());
						if (null != jsonObject) {
							record.setInvoiceTitle(Optional.ofNullable(jsonObject.getInvoiceTitleInsurance()).orElse(""));
						}
					}
				}
			}
		}
		return  R.ok(insuranceRefundList);
	}

	/**
	 * 减员办理列表分页查询
	 *
	 * @author zhaji
	 * @param page 分页数据
	 * @param param 查询参数
	 * @return {@link IPage<  RefundExportListVo >}
	 */
	@Override
	public IPage<RefundExportListVo> getInsuranceRefundHandlingPageList(Page<InsuranceRefundHandlingParam> page, InsuranceRefundHandlingParam param,
																		String mId) {
		YifuUser user = SecurityUtils.getUser();
		if (!Common.isEmpty(mId)) {
			param.setMId(mId);
		}
		param.setCreateBy(user.getId());
		menuUtil.setAuthSql(user, param);
		if (Common.isNotNull(param.getAuthSql()) && param.getAuthSql().contains("1=2 CONCAT")) {
			param.setAuthSql(param.getAuthSql().replace("1=2 CONCAT", "CONCAT"));
		}
		String id = user.getId();
		Integer reduceHandleStatus = param.getReduceHandleStatus();
		if(null != reduceHandleStatus && reduceHandleStatus != CommonConstants.ONE_INT){
			param.setUpdateBy(id);
		}
		IPage<RefundExportListVo> insuranceRefundHandlingPageList = this.baseMapper.getInsuranceRefundHandlingPageList(page, param);
		if (CollectionUtils.isNotEmpty(insuranceRefundHandlingPageList.getRecords())){
			//根据项目编码获取项目名称
			for (RefundExportListVo record : insuranceRefundHandlingPageList.getRecords()) {
				//购买月数
				record.setBuyMonth(LocalDateUtil.betweenMonth(record.getPolicyStart().toString(), record.getPolicyEnd().toString()));
			}
		}

		return insuranceRefundHandlingPageList;
	}

	/**
	 * 导出减员办理列表
	 *
	 * @author zhaji
	 * @param param 查询参数
	 * @return {@link List<  RefundExportListVo >}
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R getInsuranceRefundHandlingList(RefundExportListParam param, String mId){
		YifuUser user = SecurityUtils.getUser();
		if (!Common.isEmpty(mId)) {
			param.setMId(mId);
		}
		param.setCreateBy(user.getId());
		menuUtil.setAuthSql(user, param);
		if (Common.isNotNull(param.getAuthSql()) && param.getAuthSql().contains("1=2 CONCAT")) {
			param.setAuthSql(param.getAuthSql().replace("1=2 CONCAT", "CONCAT"));
		}
		List<RefundExportListVo> refundExportList;
		//如勾选项不为空，则导出勾选记录；否则导出当前筛选条件下 && 「待减员」的结果集
		if (CollectionUtils.isNotEmpty(param.getIdList())){
			refundExportList =  baseMapper.getRefundExportListBySelect(param.getIdList());
		}else {
			refundExportList = baseMapper.getRefundExportList(param);
		}
		if (CollectionUtils.isNotEmpty(refundExportList)){
			if(refundExportList.size() > CommonConstants.EXPORT_TWENTY_THOUSAND){
				return R.failed(InsurancesConstants.EXPORT_TOO_LONG);
			}
			List<TInsuranceDetail> detailList = new ArrayList<>();
			List<TInsuranceRefund> refundList = new ArrayList<>();
			//根据项目编码获取项目名称
			List<String> collect = refundExportList.stream().map(RefundExportListVo::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 (RefundExportListVo record : refundExportList) {
					//购买月数
					record.setBuyMonth(LocalDateUtil.betweenMonth(record.getPolicyStart().toString(),record.getPolicyEnd().toString()));
					//购买天数
					record.setBuyDay(LocalDateUtil.betweenDay(record.getPolicyStart().toString(),record.getPolicyEnd().toString()));
					if (data != null) {
						ProjectSetInfoVo jsonObject = data.get(record.getDeptNo());
						if (null != jsonObject) {
							record.setInvoiceTitle(Optional.ofNullable(jsonObject.getInvoiceTitleInsurance()).orElse(""));
						}
					}
					TInsuranceDetail detail = getById(record.getId());
					TInsuranceRefund refund = new TInsuranceRefund();
					detail.setId(record.getId());
					//update状态由「待减员」置为「减员中」
					detail.setUpdateBy(user.getId());
					detail.setUpdateTime(LocalDateTime.now());
					detail.setReduceHandleStatus(CommonConstants.TWO_INT);

					detailList.add(detail);
					refund.setId(detail.getRefundId());
					refund.setReduceHandleStatus(CommonConstants.TWO_INT);
					refund.setUpdateBy(user.getId());
					refund.setUpdateTime(LocalDateTime.now());
					refundList.add(refund);
				}
			}
			//批量更新
			if (CollectionUtils.isNotEmpty(detailList)){
				for (TInsuranceDetail s : detailList) {
					LambdaUpdateWrapper<TInsuranceDetail> updateWrapper = new LambdaUpdateWrapper<>();
					updateWrapper.eq(TInsuranceDetail :: getId,s.getId()).set(TInsuranceDetail :: getReduceHandleStatus,CommonConstants.TWO_INT);
					update(updateWrapper);
				}
			}
			//批量更新
			if (CollectionUtils.isNotEmpty(refundList)){
				for (TInsuranceRefund refund : refundList) {
					tInsuranceRefundService.updateByInsDetailId(refund);
				}
			}
			//操作记录
			addOperate(detailList,user,InsurancesConstants.INSURANCE_REFUND_EXPORT,null,CommonConstants.ONE_INT);
		}
		return R.ok(refundExportList);
	}

	/**
	 * 减员办理
	 *
	 * @author zhaji
	 * @param insuranceDetail 办理类
	 * @return {@link R}
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R updateInsuranceRefund(InsuranceRefundListParam insuranceDetail) {
		Integer refundType = insuranceDetail.getRefundType();
		if(CommonConstants.THREE_INT != refundType && CommonConstants.FOUR_INT != refundType){
			return R.failed(InsurancesConstants.OPERATION_TYPE_ERROR);
		}
		YifuUser user = SecurityUtils.getUser();
		List<String> insuranceDetailList = insuranceDetail.getInsuranceDetailList();
		if (CollectionUtils.isEmpty(insuranceDetailList)){
			return R.failed(InsurancesConstants.OPERATION_LIST_IS_EMPTY);
		}
		String remark = insuranceDetail.getRemark();
		if(CommonConstants.THREE_INT == refundType && Common.isEmpty(remark)){
			return R.failed(InsurancesConstants.REMARK_IS_EMPTY);
		}
		List<RefundErrorVo> errorList = new ArrayList<>();
		List<TInsuranceDetail> successList = new ArrayList<>();
		List<TInsuranceDetail> tInsuranceDetails = this.listByIds(insuranceDetailList);
		List<TInsuranceRefund> refundList = new ArrayList<>();
		for (TInsuranceDetail tInsuranceDetail : tInsuranceDetails) {
			TInsuranceRefund refund = new TInsuranceRefund();
			RefundErrorVo refundErrorVo = new RefundErrorVo();
			BeanCopyUtils.copyProperties(tInsuranceDetail,refundErrorVo);
			Integer deleteFlag = tInsuranceDetail.getDeleteFlag();
			if(refundType.equals(tInsuranceDetail.getReduceHandleStatus())){
				if(CommonConstants.THREE_INT == refundType){
					refundErrorVo.setErrorMessage(InsurancesConstants.INSURANCE_DETAIL_IS_REFUND_FAIL);
					errorList.add(refundErrorVo);
				}else{
					refundErrorVo.setErrorMessage(InsurancesConstants.INSURANCE_DETAIL_IS_REFUND_SUCCESS);
					errorList.add(refundErrorVo);
				}
			}else{
				if (CommonConstants.ZERO_INT == deleteFlag ){
					tInsuranceDetail.setReduceHandleStatus(refundType);
					if(CommonConstants.FOUR_INT == refundType){
						tInsuranceDetail.setIsOverdue(null);
						tInsuranceDetail.setIsEffect(null);
						tInsuranceDetail.setBuyHandleStatus(CommonConstants.FIVE_INT);
					}else {
						tInsuranceDetail.setBuyHandleStatus(CommonConstants.THREE_INT);
					}
					tInsuranceDetail.setUpdateBy(user.getId());
					tInsuranceDetail.setUpdateTime(LocalDateTime.now());
					successList.add(tInsuranceDetail);
					//更新减员记录
					refund.setId(tInsuranceDetail.getRefundId());
					refund.setUpdateBy(user.getId());
					refund.setUpdateTime(LocalDateTime.now());
					refund.setReduceHandleStatus(refundType);
					refundList.add(refund);
				}else{
					refundErrorVo.setErrorMessage(InsurancesConstants.INSURANCES_IS_DELETE);
					errorList.add(refundErrorVo);
				}
			}
		}
		for (TInsuranceRefund refund : refundList) {
			tInsuranceRefundService.updateByInsDetailId(refund);
		}
		updateBatchById(successList);
		//操作记录
		if(CommonConstants.FOUR_INT == refundType){
			addOperate(successList,user,InsurancesConstants.INSURANCE_REFUND_SUCCESS,remark,CommonConstants.ONE_INT);
		}else{
			addOperate(successList,user,InsurancesConstants.INSURANCE_REFUND_FAILED,remark,CommonConstants.ONE_INT);
		}
		return R.ok(errorList,InsurancesConstants.OPERATE_SUCCESS);
	}

	/**
	 * 减员办理导入
	 *
	 * @author zhaji
	 * @param
	 * @return void
	 */
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	@Override
	public R insuranceRefundImport(List<InsuranceHandleImportParam> insuranceRefundImportList) {
		YifuUser user = SecurityUtils.getUser();
		if (CollectionUtils.isEmpty(insuranceRefundImportList)) {
			return R.failed(InsurancesConstants.INSURANCE_REFUND_IMPORT_LIST_IS_EMPTY);
		}
		if(insuranceRefundImportList.size() > CommonConstants.IMPORT_TWENTY_THOUSAND){
			return R.failed(InsurancesConstants.IMPORT_TOO_LONG);
		}
		Map<String, List<InsuranceHandleImportParam>> map = insuranceChangeCheck(insuranceRefundImportList, user,true);
		List<InsuranceHandleImportParam> successList = map.get(InsurancesConstants.SUCCESS_LIST);
		List<InsuranceHandleImportParam> errorList = map.get(InsurancesConstants.ERROR_LIST);
		//减员退回
		List<TInsuranceOperate> operateList =new ArrayList<>(16);
		if (CollectionUtils.isNotEmpty(successList)) {
			for (InsuranceHandleImportParam param : successList) {
				TInsuranceOperate operate = new TInsuranceOperate();
				LambdaUpdateWrapper<TInsuranceRefund> refund = new LambdaUpdateWrapper<>();
				refund.eq(TInsuranceRefund :: getInsDetailId ,param.getId())
						.set(TInsuranceRefund :: getRemark,param.getRemark())
						.set(TInsuranceRefund :: getUpdateTime,LocalDateTime.now())
						.set(TInsuranceRefund :: getUpdateBy,user.getId());
				LambdaUpdateWrapper<TInsuranceDetail> updateWrapper = new LambdaUpdateWrapper<>();
				updateWrapper.eq(TInsuranceDetail::getId, param.getId())
						.set(TInsuranceDetail::getUpdateBy, user.getId())
						.set(TInsuranceDetail::getUpdateTime, LocalDateTime.now());
				if(InsurancesConstants.SUCCESS.equals(param.getHandType())){
					updateWrapper.set(TInsuranceDetail :: getReduceHandleStatus,CommonConstants.FOUR_INT);
					updateWrapper.set(TInsuranceDetail :: getBuyHandleStatus,CommonConstants.FIVE_INT);
					refund.set(TInsuranceRefund :: getReduceHandleStatus,CommonConstants.FOUR_INT);
				}else{
					updateWrapper.set(TInsuranceDetail:: getReduceHandleStatus,CommonConstants.THREE_INT);
					refund.set(TInsuranceRefund :: getReduceHandleStatus,CommonConstants.THREE_INT);
				}
				update(updateWrapper);
				tInsuranceRefundService.update(refund);
				operate.setInsuranceDetailId(param.getId());
				operate.setRemark(param.getRemark());
				operate.setDisplayFlag(CommonConstants.ONE_INT);
				operate.setCreateName(user.getNickname());
				operate.setCreateTime(LocalDateTime.now());
				operate.setCreateBy(user.getId());
				if(InsurancesConstants.SUCCESS.equals(param.getHandType())){
					operate.setOperateDesc(InsurancesConstants.INSURANCE_REFUND_SUCCESS);
				}else{
					operate.setOperateDesc(InsurancesConstants.INSURANCE_REFUND_FAILED);
				}
				operateList.add(operate);
			}
		}
		tInsuranceOperateService.saveBatch(operateList);
		return R.ok(errorList, InsurancesConstants.IMPORT_SUCCESS);
	}

	/**
	 * 变更结算月份
	 *
	 * @author zhaji
	 * @param
	 * @return void
	 */
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	@Override
	public R settleMonthChange(List<SettleMonthChangeCheckParam> settleMonthCheckList) {
		//初始化线程池
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 10, 100, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
		YifuUser user = SecurityUtils.getUser();
		List<TInsuranceDetail> detailList =new ArrayList<>();
		if (!Common.isNotEmpty(settleMonthCheckList)) {
			return R.failed(InsurancesConstants.SETTLE_MONTH_CHANGE_LIST_IS_EMPTY);
		}
		if(settleMonthCheckList.size() > CommonConstants.IMPORT_TWENTY_THOUSAND){
			return R.failed(InsurancesConstants.IMPORT_TOO_LONG);
		}
		Map<String, List<SettleMonthChangeCheckParam>> map = settleMonthChangeCheck(settleMonthCheckList, user);
		List<SettleMonthChangeCheckParam> successList = map.get(InsurancesConstants.SUCCESS_LIST);
		List<SettleMonthChangeCheckParam> errorList = map.get(InsurancesConstants.ERROR_LIST);
		List<SettleMonthChangeCheckParam> ekpList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(successList)){
			for (SettleMonthChangeCheckParam settleMonthChangeCheckParam : successList) {
				LambdaUpdateWrapper<TInsuranceDetail> updateWrapper = new LambdaUpdateWrapper<>();
				updateWrapper.eq(TInsuranceDetail::getId, settleMonthChangeCheckParam.getId())
						.set(TInsuranceDetail::getSettleMonth, settleMonthChangeCheckParam.getSettleMonth())
						.set(TInsuranceDetail::getUpdateBy, user.getId())
						.set(TInsuranceDetail::getUpdateTime, LocalDateTime.now());
				update(updateWrapper);
				TInsuranceOperate insuranceOperate = new TInsuranceOperate();
				insuranceOperate.setInsuranceDetailId(settleMonthChangeCheckParam.getId());
				insuranceOperate.setCreateBy(user.getId());
				insuranceOperate.setCreateName(user.getNickname());
				insuranceOperate.setCreateTime(LocalDateTime.now());
				insuranceOperate.setOperateDesc(InsurancesConstants.MONTH_CHANGE);
				insuranceOperate.setDisplayFlag(CommonConstants.ZERO_INT);
				tInsuranceOperateService.save(insuranceOperate);
				TInsuranceDetail byId = getById(settleMonthChangeCheckParam.getId());
				String defaultSettleId = byId.getDefaultSettleId();
				if (StringUtils.isNotBlank(defaultSettleId)){
					TInsuranceSettle settle = tInsuranceSettleService.getById(defaultSettleId);
					if (settle.getIsActualPush() == CommonConstants.ONE_INT || settle.getIsEstimatePush() == CommonConstants.ONE_INT) {
						ekpList.add(settleMonthChangeCheckParam);
					}
				}
			}
			//先更新本地状态再集中推送至EKP
			//当前保单结算信息不为空且已推送的情况下，推送EKP进行变更
			threadPool.execute(()->{
				List<EkpInteractiveParam> deptDetail = getDeptDetail(ekpList);
				for (EkpInteractiveParam ekpInteractiveParam : deptDetail) {
					TInsuranceDetail byId = getById(ekpInteractiveParam.getDetailId());
					BeanCopyUtils.copyProperties(byId,ekpInteractiveParam);
					ekpInteractiveParam.setInteractiveType(InsurancesConstants.UPDATE_SETTLE_BILL);
					if (byId.getSettleType() == CommonConstants.ZERO_INT){
						ekpInteractiveParam.setEstimateStatus(EkpConstants.HAVE);
					}else{
						ekpInteractiveParam.setEstimateStatus(EkpConstants.NOTHING);
					}
					String body = eKPInsuranceUtil.sendToEkp(ekpInteractiveParam);
					if (!StringUtils.isBlank(body)){
						TInsuranceOperate insuranceOperate = new TInsuranceOperate();
						insuranceOperate.setInsuranceDetailId(ekpInteractiveParam.getDetailId());
						insuranceOperate.setCreateBy(user.getId());
						insuranceOperate.setCreateName(user.getNickname());
						insuranceOperate.setCreateTime(LocalDateTime.now());
						insuranceOperate.setOperateDesc(InsurancesConstants.MONTH_CHANGE);
						insuranceOperate.setDisplayFlag(CommonConstants.ZERO_INT);
						tInsuranceOperateService.save(insuranceOperate);
					} else {
						saveInsuranceEkp(ekpInteractiveParam,CommonConstants.THREE_INT);
						for (SettleMonthChangeCheckParam success : successList) {
							if (success.getId().equals(ekpInteractiveParam.getDetailId())) {
								success.setErrorMessage(InsurancesConstants.EKP_UPDATE_SETTLE_MONTH_ERROR);
								errorList.add(success);
							}
						}
					}
				}
			});
		}
		//操作记录
		addOperate(detailList,user,InsurancesConstants.MONTH_CHANGE,null,CommonConstants.ZERO_INT);
		return R.ok(errorList, InsurancesConstants.IMPORT_SUCCESS );
	}
	/**
	 * 变更所属项目
	 *
	 * @author zhaji
	 * @param deptChangeCheckList 变更列表
	 * @return {@link R}
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R deptChange(List<DeptChangeCheckParam> deptChangeCheckList) {
		//初始化线程池
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(50, 50, 100, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
		YifuUser user = SecurityUtils.getUser();
		if(!Common.isNotEmpty(deptChangeCheckList)){
			return R.failed(InsurancesConstants.OPERATION_LIST_IS_EMPTY);
		}
		if(deptChangeCheckList.size() > CommonConstants.IMPORT_TWENTY_THOUSAND){
			return R.failed(InsurancesConstants.IMPORT_TOO_LONG);
		}
		Map<String, List<DeptChangeCheckParam>> stringListMap = deptChangeCheck(deptChangeCheckList,user);
		List<DeptChangeCheckParam> successList = stringListMap.get(InsurancesConstants.SUCCESS_LIST);
		List<TInsuranceOperate> operateList = new ArrayList<>(16);
		if(CollectionUtils.isNotEmpty(successList)){
			threadPool.execute(() -> {
				for (DeptChangeCheckParam success : successList) {
					//新的结算信息
					TInsuranceSettle newInsuranceSettle = new TInsuranceSettle();
					//实际保费
					BigDecimal actualPremium = success.getActualPremium();
					//预估保费
					BigDecimal estimatePremium = success.getEstimatePremium();
					//EKP推送类
					EkpInteractiveParam interactiveParam = new EkpInteractiveParam();
					TInsuranceDetail one = getOne(lambdaQuery().getWrapper().eq(TInsuranceDetail::getId, success.getId()));
					BeanCopyUtils.copyProperties(one,interactiveParam);
					interactiveParam.setDetailId(success.getId());
					LambdaUpdateWrapper<TInsuranceDetail> updateWrapper = new LambdaUpdateWrapper<>();
					Integer oldSettleType = success.getOldSettleType();
					Integer newSettleType = success.getNewSettleType();
					//更新新的项目编码，结算方式，预估保费，实际保费
					updateWrapper.eq(TInsuranceDetail :: getId,success.getId())
							.set(TInsuranceDetail :: getDeptNo,success.getNewDeptNo())
							.set(TInsuranceDetail :: getSettleType,newSettleType)
							.set(TInsuranceDetail :: getActualPremium,actualPremium)
							.set(TInsuranceDetail :: getEstimatePremium,estimatePremium)
							.set(TInsuranceDetail :: getUpdateBy,user.getId())
							.set(TInsuranceDetail :: getUpdateTime,LocalDateTime.now());
					//更新项目编码
					update(updateWrapper);
					//更换项目更新收入
					TInsuranceDetail income = getOne(lambdaQuery().getWrapper().eq(TInsuranceDetail::getId, success.getId()));
					if (Common.isNotNull(income)) {
						if (income.getBuyType() != CommonConstants.FOUR_INT) {
							//判断是否存在当月的商险收入数据
							TIncomeDetail incomeDetail = new TIncomeDetail();
							incomeDetail.setSourceId(income.getId());
							R<TIncomeDetailReturnVo> detailList = socialDaprUtils.getTIncomeDetailList(incomeDetail);
							if (Common.isNotNull(detailList) && detailList.getCode() == CommonConstants.SUCCESS
									&& detailList.getData().getDetailList().size() > 0) {
								//原项目生成红冲数据
								for (TIncomeDetail detail : detailList.getData().getDetailList()) {
									TIncomeDetail detail1 = new TIncomeDetail();
									BeanCopyUtils.copyProperties(detail,detail1);
									detail1.setId(CommonConstants.NULL);
									detail1.setRedData(CommonConstants.ONE_STRING);
									detail1.setMoney(detail.getMoney().negate());
									socialDaprUtils.createTIncomeDetail(detail1);
								}
								//新项目下生成收入数据
								createInsuranceInfo(income);
							}
						}
					}
					//商险id
					String insuranceDetailId = success.getId();
					//旧结算信息id
					String oldDefaultSettleId = success.getDefaultSettleId();
					//如果变更前为单独结算
					if(CommonConstants.ONE_INT == oldSettleType){
						//登记了保单保费
						if (!BigDecimalUtils.isNullOrZero(actualPremium)) {
							newInsuranceSettle.setInsDetailId(insuranceDetailId);
							newInsuranceSettle.setSettleType(newSettleType);
							newInsuranceSettle.setIsEstimatePush(CommonConstants.ZERO_INT);
							newInsuranceSettle.setIsActualPush(CommonConstants.ZERO_INT);
							newInsuranceSettle.setSettleHandleStatus(CommonConstants.ONE_STRING);
							newInsuranceSettle.setCreateTime(LocalDateTime.now());
							newInsuranceSettle.setActualPremium(actualPremium);
							newInsuranceSettle.setEstimatePremium(estimatePremium);
							//存储新的结算信息
							tInsuranceSettleService.save(newInsuranceSettle);
							updateWrapper.set(TInsuranceDetail::getDefaultSettleId, newInsuranceSettle.getId());
							//更新新的结算信息
							update(updateWrapper);
							//根据旧的结算id获取旧的结算信息
							TInsuranceSettle byId = tInsuranceSettleService.getById(oldDefaultSettleId);
							//作废旧的数据，生成作废结算信息记录
							TInsuranceSettleCancel cancel = new TInsuranceSettleCancel();
							cancel.setDeptNo(success.getOldDeptNo());
							cancel.setInsDetailId(insuranceDetailId);
							cancel.setSettleId(oldDefaultSettleId);
							cancel.setCreateUesr(user.getId());
							cancel.setCreateTime(LocalDateTime.now());
							cancel.setDeptName(success.getOldDeptName());
							cancel.setIsCancelPush(CommonConstants.ZERO_INT);
							tInsuranceSettleCancelService.save(cancel);
							//如果已经推送过实际保费，则先作废，再推送新的实际保费
							if (byId.getIsActualPush() == CommonConstants.ONE_INT) {
								//推送至EKP执行作废操作
								interactiveParam.setActualPremium(one.getActualPremium());
								interactiveParam.setCustomerCode(success.getOldCustomerCode());
								interactiveParam.setCustomerName(success.getOldCustomerName());
								interactiveParam.setDeptNo(success.getOldDeptNo());
								interactiveParam.setDeptName(success.getOldDeptName());
								interactiveParam.setInteractiveType(InsurancesConstants.ABOLISH_SETTLE_BILL);
								String deleteBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
								if (StringUtils.isNotBlank(deleteBody)) {
									//推送成功更新作废推送状态
									cancel.setIsCancelPush(CommonConstants.ONE_INT);
									tInsuranceSettleCancelService.updateById(cancel);
									//变更后为单独结算
									if (CommonConstants.ONE_INT == newSettleType) {
										//推送新的结算信息至EKP
										interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
										interactiveParam.setEstimateStatus(EkpConstants.NOTHING);
										interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
										interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
										interactiveParam.setCustomerCode(success.getNewCustomerCode());
										interactiveParam.setCustomerName(success.getNewCustomerName());
										interactiveParam.setDeptNo(success.getNewDeptNo());
										interactiveParam.setDeptName(success.getNewDeptName());
										interactiveParam.setActualPremium(success.getActualPremium());
										interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
										String pushResult = eKPInsuranceUtil.sendToEkp(interactiveParam);
										if (StringUtils.isNotBlank(pushResult)){
											newInsuranceSettle.setActualPushTime(LocalDateTime.now());
											newInsuranceSettle.setIsActualPush(CommonConstants.ONE_INT);
											newInsuranceSettle.setUpdateTime(LocalDateTime.now());
											tInsuranceSettleService.updateById(newInsuranceSettle);
										}else {
											//异常处理
											saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
										}
									}
									//变更后为合并结算
									if (CommonConstants.ZERO_INT == newSettleType) {
										//先推送预估，再推送实际
										interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
										interactiveParam.setEstimateStatus(EkpConstants.HAVE);
										interactiveParam.setCustomerCode(success.getNewCustomerCode());
										interactiveParam.setCustomerName(success.getNewCustomerName());
										interactiveParam.setDeptNo(success.getNewDeptNo());
										interactiveParam.setDeptName(success.getNewDeptName());
										interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
										//推送预估单
										interactiveParam.setEstimatePremium(success.getEstimatePremium());
										interactiveParam.setActualPremium(success.getActualPremium());
										interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
										String estimateBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
										if (StringUtils.isNotBlank(estimateBody)) {
											newInsuranceSettle.setEstimatePushTime(LocalDateTime.now());
											newInsuranceSettle.setIsEstimatePush(CommonConstants.ONE_INT);
											newInsuranceSettle.setUpdateTime(LocalDateTime.now());
											tInsuranceSettleService.updateById(newInsuranceSettle);
											//推送实缴单
											interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
											interactiveParam.setEstimatePremium(success.getEstimatePremium());
											interactiveParam.setActualPremium(success.getActualPremium());
											String actualBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
											if (StringUtils.isNotBlank(actualBody)) {
												//推送成功后更新本地推送状态
												newInsuranceSettle.setActualPushTime(LocalDateTime.now());
												newInsuranceSettle.setIsActualPush(CommonConstants.ONE_INT);
												newInsuranceSettle.setUpdateTime(LocalDateTime.now());
												tInsuranceSettleService.updateById(newInsuranceSettle);
											}else{
												//异常处理
												saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
											}
										}else{
											//异常处理
											saveInsuranceEkp(interactiveParam,CommonConstants.ONE_INT);
											//推送实缴单
											interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
											interactiveParam.setEstimatePremium(success.getEstimatePremium());
											interactiveParam.setActualPremium(success.getActualPremium());
											saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
										}
									}
								}else{
									//保存作废信息
									saveInsuranceEkp(interactiveParam,CommonConstants.FOUR_INT);
									//保存预估信息
									//变更后为单独结算
									if (CommonConstants.ONE_INT == newSettleType) {
										//推送新的结算信息至EKP
										interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
										interactiveParam.setEstimateStatus(EkpConstants.NOTHING);
										interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
										interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
										interactiveParam.setCustomerCode(success.getNewCustomerCode());
										interactiveParam.setCustomerName(success.getNewCustomerName());
										interactiveParam.setDeptNo(success.getNewDeptNo());
										interactiveParam.setDeptName(success.getNewDeptName());
										interactiveParam.setActualPremium(success.getActualPremium());
										interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
										//保存实缴信息
										saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
									}
									//变更后为单独结算
									if (CommonConstants.ZERO_INT == newSettleType) {
										//先推送预估，再推送实际
										interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
										interactiveParam.setEstimateStatus(EkpConstants.HAVE);
										interactiveParam.setCustomerCode(success.getNewCustomerCode());
										interactiveParam.setCustomerName(success.getNewCustomerName());
										interactiveParam.setDeptNo(success.getNewDeptNo());
										interactiveParam.setDeptName(success.getNewDeptName());
										interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
										interactiveParam.setEstimatePremium(success.getEstimatePremium());
										interactiveParam.setActualPremium(success.getActualPremium());
										interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
										//保存预估信息
										saveInsuranceEkp(interactiveParam,CommonConstants.ONE_INT);
										interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
										interactiveParam.setEstimatePremium(success.getEstimatePremium());
										interactiveParam.setActualPremium(success.getActualPremium());
										//保存实缴信息
										saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
									}
								}
							}else{
								//变更后为单独结算
								if (CommonConstants.ONE_INT == newSettleType) {
									//推送新的结算信息至EKP
									interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
									interactiveParam.setEstimateStatus(EkpConstants.NOTHING);
									interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
									interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
									interactiveParam.setCustomerCode(success.getNewCustomerCode());
									interactiveParam.setCustomerName(success.getNewCustomerName());
									interactiveParam.setDeptNo(success.getNewDeptNo());
									interactiveParam.setDeptName(success.getNewDeptName());
									interactiveParam.setActualPremium(success.getActualPremium());
									String addBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
									if (StringUtils.isNotBlank(addBody)){
										newInsuranceSettle.setActualPushTime(LocalDateTime.now());
										newInsuranceSettle.setIsActualPush(CommonConstants.ONE_INT);
										newInsuranceSettle.setUpdateTime(LocalDateTime.now());
										tInsuranceSettleService.updateById(newInsuranceSettle);
									}else {
										//异常处理
										saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
									}
								}
								//变更后为合并结算
								if (CommonConstants.ZERO_INT == newSettleType) {
									//先推送预估，再推送实际
									interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
									interactiveParam.setEstimateStatus(EkpConstants.HAVE);
									interactiveParam.setCustomerCode(success.getNewCustomerCode());
									interactiveParam.setCustomerName(success.getNewCustomerName());
									interactiveParam.setDeptNo(success.getNewDeptNo());
									interactiveParam.setDeptName(success.getNewDeptName());
									interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
									//推送预估单
									interactiveParam.setEstimatePremium(success.getEstimatePremium());
									interactiveParam.setActualPremium(success.getActualPremium());
									interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
									String estimateBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
									if (StringUtils.isNotBlank(estimateBody)) {
										newInsuranceSettle.setEstimatePushTime(LocalDateTime.now());
										newInsuranceSettle.setIsEstimatePush(CommonConstants.ONE_INT);
										newInsuranceSettle.setUpdateTime(LocalDateTime.now());
										tInsuranceSettleService.updateById(newInsuranceSettle);
										//推送实缴单
										interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
										interactiveParam.setEstimatePremium(success.getEstimatePremium());
										interactiveParam.setActualPremium(success.getActualPremium());
										String actualBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
										if (StringUtils.isNotBlank(actualBody)) {
											//推送成功后更新本地推送状态
											newInsuranceSettle.setActualPushTime(LocalDateTime.now());
											newInsuranceSettle.setIsActualPush(CommonConstants.ONE_INT);
											newInsuranceSettle.setUpdateTime(LocalDateTime.now());
											tInsuranceSettleService.updateById(newInsuranceSettle);
										}else{
											//异常处理
											saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
										}
									}else{
										//异常处理
										saveInsuranceEkp(interactiveParam,CommonConstants.ONE_INT);
										//推送实缴单
										interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
										interactiveParam.setEstimatePremium(success.getEstimatePremium());
										interactiveParam.setActualPremium(success.getActualPremium());
										saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
									}
								}
							}
						}
						//未登记保单保费
						if(BigDecimalUtils.isNullOrZero(actualPremium)){
							//变更后为单独结算
							if (CommonConstants.ONE_INT == newSettleType){
								//变更项目且不做处理
							}
							//变更后为合并结算
							if (CommonConstants.ZERO_INT == newSettleType){
								//生成预估结算信息
								TInsuranceSettle tInsuranceSettle = new TInsuranceSettle();
								tInsuranceSettle.setInsDetailId(success.getId());
								tInsuranceSettle.setSettleType(success.getNewSettleType());
								tInsuranceSettle.setSettleHandleStatus(CommonConstants.ONE_STRING);
								tInsuranceSettle.setEstimatePremium(estimatePremium);
								tInsuranceSettle.setIsActualPush(CommonConstants.ZERO_INT);
								tInsuranceSettle.setIsEstimatePush(CommonConstants.ZERO_INT);
								tInsuranceSettle.setCreateTime(LocalDateTime.now());
								tInsuranceSettleService.save(tInsuranceSettle);
								//将结算id赋值给保单信息,并新增预估费用
								updateWrapper.set(TInsuranceDetail :: getDefaultSettleId,tInsuranceSettle.getId());
								update(updateWrapper);
								//推送结算信息至EKP
								interactiveParam.setDefaultSettleId(tInsuranceSettle.getId());
								interactiveParam.setEstimateStatus(EkpConstants.HAVE);
								interactiveParam.setCustomerCode(success.getNewCustomerCode());
								interactiveParam.setCustomerName(success.getNewCustomerName());
								interactiveParam.setDeptNo(success.getNewDeptNo());
								interactiveParam.setDeptName(success.getNewDeptName());
								interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
								interactiveParam.setEstimatePremium(success.getEstimatePremium());
								interactiveParam.setActualPremium(success.getActualPremium());
								interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
								String estimateBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
								if(StringUtils.isNotBlank(estimateBody)){
									//推送成功后更新本地推送状态
									tInsuranceSettle.setIsEstimatePush(CommonConstants.ONE_INT);
									tInsuranceSettle.setEstimatePushTime(LocalDateTime.now());
									tInsuranceSettle.setUpdateTime(LocalDateTime.now());
									tInsuranceSettleService.updateById(tInsuranceSettle);
								}else{
									//异常处理
									saveInsuranceEkp(interactiveParam,CommonConstants.ONE_INT);
								}
							}
						}
					}
					//变更前为合并结算
					if(CommonConstants.ZERO_INT == oldSettleType){
						//作废旧的结算信息
						TInsuranceSettleCancel cancel = new TInsuranceSettleCancel();
						cancel.setDeptNo(success.getOldDeptNo());
						cancel.setInsDetailId(success.getId());
						cancel.setSettleId(oldDefaultSettleId);
						cancel.setCreateUesr(user.getId());
						cancel.setCreateTime(LocalDateTime.now());
						cancel.setDeptName(success.getOldDeptName());
						cancel.setIsCancelPush(CommonConstants.ZERO_INT);
						tInsuranceSettleCancelService.save(cancel);
						TInsuranceSettle byId = tInsuranceSettleService.getById(oldDefaultSettleId);
						//如果已经登记保费
						if (!BigDecimalUtils.isNullOrZero(actualPremium)){
							//新增新的结算信息
							newInsuranceSettle.setInsDetailId(insuranceDetailId);
							newInsuranceSettle.setSettleType(newSettleType);
							newInsuranceSettle.setIsEstimatePush(CommonConstants.ZERO_INT);
							newInsuranceSettle.setIsActualPush(CommonConstants.ZERO_INT);
							newInsuranceSettle.setSettleHandleStatus(CommonConstants.ONE_STRING);
							newInsuranceSettle.setCreateTime(LocalDateTime.now());
							newInsuranceSettle.setActualPremium(success.getActualPremium());
							newInsuranceSettle.setEstimatePremium(success.getEstimatePremium());
							tInsuranceSettleService.save(newInsuranceSettle);
							updateWrapper.set(TInsuranceDetail :: getDefaultSettleId,newInsuranceSettle.getId());
							update(updateWrapper);
							//如果预估和实缴都推送了
							if(byId.getIsActualPush() == CommonConstants.ONE_INT && byId.getIsEstimatePush() == CommonConstants.ONE_INT){
								//推送作废结算信息至EKP
								interactiveParam.setCustomerCode(success.getOldCustomerCode());
								interactiveParam.setCustomerName(success.getOldCustomerName());
								interactiveParam.setDeptNo(success.getOldDeptNo());
								interactiveParam.setDeptName(success.getOldDeptName());
								interactiveParam.setInteractiveType(InsurancesConstants.ABOLISH_SETTLE_BILL);
								interactiveParam.setEstimatePremium(one.getEstimatePremium());
								interactiveParam.setActualPremium(one.getActualPremium());
								interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
								String deleteBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
								if(StringUtils.isNotBlank(deleteBody)){
									//推送成功更新作废推送状态
									cancel.setIsCancelPush(CommonConstants.ONE_INT);
									tInsuranceSettleCancelService.updateById(cancel);
									//变更为单独结算
									if (CommonConstants.ONE_INT == newSettleType){
										//更新预估费用为0.00
										updateWrapper.set(TInsuranceDetail ::getEstimatePremium,new BigDecimal("0.00"));
										update(updateWrapper);
										//推送新的结算信息至EKP,推实际保费
										interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
										interactiveParam.setEstimateStatus(EkpConstants.NOTHING);
										interactiveParam.setCustomerCode(success.getNewCustomerCode());
										interactiveParam.setCustomerName(success.getNewCustomerName());
										interactiveParam.setDeptNo(success.getNewDeptNo());
										interactiveParam.setDeptName(success.getNewDeptName());
										interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
										interactiveParam.setEstimatePremium(success.getEstimatePremium());
										interactiveParam.setActualPremium(success.getActualPremium());
										interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
										String actualBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
										if(StringUtils.isNotBlank(actualBody)){
											//推送成功，更新推送状态
											newInsuranceSettle.setIsActualPush(CommonConstants.ONE_INT);
											newInsuranceSettle.setActualPushTime(LocalDateTime.now());
											newInsuranceSettle.setUpdateTime(LocalDateTime.now());
											tInsuranceSettleService.updateById(newInsuranceSettle);
										}else{
											//异常处理
											saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
										}
									}
									//变更为合并结算
									if (CommonConstants.ZERO_INT == newSettleType){
										// 推送新的结算信息
										interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
										interactiveParam.setEstimateStatus(EkpConstants.HAVE);
										interactiveParam.setCustomerCode(success.getNewCustomerCode());
										interactiveParam.setCustomerName(success.getNewCustomerName());
										interactiveParam.setDeptNo(success.getNewDeptNo());
										interactiveParam.setDeptName(success.getNewDeptName());
										interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
										interactiveParam.setEstimatePremium(success.getEstimatePremium());
										interactiveParam.setActualPremium(success.getActualPremium());
										interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
										String estimateBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
										//推送成功，更新预估和实际保费的推送状态
										if (StringUtils.isNotBlank(estimateBody)) {
											newInsuranceSettle.setEstimatePushTime(LocalDateTime.now());
											newInsuranceSettle.setIsEstimatePush(CommonConstants.ONE_INT);
											newInsuranceSettle.setUpdateTime(LocalDateTime.now());
											tInsuranceSettleService.updateById(newInsuranceSettle);
											//推送实缴单
											interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
											interactiveParam.setEstimatePremium(success.getEstimatePremium());
											interactiveParam.setActualPremium(success.getActualPremium());
											String actualBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
											if (StringUtils.isNotBlank(actualBody)) {
												//推送成功后更新本地推送状态
												newInsuranceSettle.setActualPushTime(LocalDateTime.now());
												newInsuranceSettle.setIsActualPush(CommonConstants.ONE_INT);
												newInsuranceSettle.setUpdateTime(LocalDateTime.now());
												tInsuranceSettleService.updateById(newInsuranceSettle);
											}else{
												//异常处理
												saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
											}
										}else{
											//异常处理
											saveInsuranceEkp(interactiveParam,CommonConstants.ONE_INT);
											//推送实缴单
											interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
											interactiveParam.setEstimatePremium(success.getEstimatePremium());
											interactiveParam.setActualPremium(success.getActualPremium());
											saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
										}
									}
								}else{
									//异常处理
									saveInsuranceEkp(interactiveParam,CommonConstants.FOUR_INT);
									//变更为单独结算
									if (CommonConstants.ONE_INT == newSettleType){
										//推送新的结算信息至EKP,推实际保费
										interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
										interactiveParam.setEstimateStatus(EkpConstants.NOTHING);
										interactiveParam.setCustomerCode(success.getNewCustomerCode());
										interactiveParam.setCustomerName(success.getNewCustomerName());
										interactiveParam.setDeptNo(success.getNewDeptNo());
										interactiveParam.setDeptName(success.getNewDeptName());
										interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
										interactiveParam.setEstimatePremium(success.getEstimatePremium());
										interactiveParam.setActualPremium(success.getActualPremium());
										interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
										saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
									}
									//变更为单独结算
									if (CommonConstants.ZERO_INT == newSettleType){
										// 推送新的结算信息
										interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
										interactiveParam.setEstimateStatus(EkpConstants.HAVE);
										interactiveParam.setCustomerCode(success.getNewCustomerCode());
										interactiveParam.setCustomerName(success.getNewCustomerName());
										interactiveParam.setDeptNo(success.getNewDeptNo());
										interactiveParam.setDeptName(success.getNewDeptName());
										interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
										interactiveParam.setEstimatePremium(success.getEstimatePremium());
										interactiveParam.setActualPremium(success.getActualPremium());
										interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
										saveInsuranceEkp(interactiveParam,CommonConstants.ONE_INT);
										//推送实缴单
										interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
										interactiveParam.setEstimatePremium(success.getEstimatePremium());
										interactiveParam.setActualPremium(success.getActualPremium());
										saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
									}

								}
							}
							//如果预估已推送和实缴未推送
							if(byId.getIsActualPush() == CommonConstants.ZERO_INT && byId.getIsEstimatePush() == CommonConstants.ONE_INT){
								//推送作废结算信息至EKP
								interactiveParam.setCustomerCode(success.getOldCustomerCode());
								interactiveParam.setCustomerName(success.getOldCustomerName());
								interactiveParam.setDeptNo(success.getOldDeptNo());
								interactiveParam.setDeptName(success.getOldDeptName());
								interactiveParam.setInteractiveType(InsurancesConstants.ABOLISH_SETTLE_BILL);
								interactiveParam.setEstimatePremium(one.getEstimatePremium());
								interactiveParam.setActualPremium(one.getActualPremium());
								interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
								String deleteBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
								if(StringUtils.isNotBlank(deleteBody)){
									//先推送预估，再推送实际
									interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
									interactiveParam.setEstimateStatus(EkpConstants.HAVE);
									interactiveParam.setCustomerCode(success.getNewCustomerCode());
									interactiveParam.setCustomerName(success.getNewCustomerName());
									interactiveParam.setDeptNo(success.getNewDeptNo());
									interactiveParam.setDeptName(success.getNewDeptName());
									interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
									//推送预估单
									interactiveParam.setEstimatePremium(success.getEstimatePremium());
									interactiveParam.setActualPremium(success.getActualPremium());
									interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
									String estimateBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
									if (StringUtils.isNotBlank(estimateBody)) {
										newInsuranceSettle.setEstimatePushTime(LocalDateTime.now());
										newInsuranceSettle.setIsEstimatePush(CommonConstants.ONE_INT);
										newInsuranceSettle.setUpdateTime(LocalDateTime.now());
										tInsuranceSettleService.updateById(newInsuranceSettle);
										//推送实缴单
										interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
										interactiveParam.setEstimatePremium(success.getEstimatePremium());
										interactiveParam.setActualPremium(success.getActualPremium());
										String actualBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
										if (StringUtils.isNotBlank(actualBody)) {
											//推送成功后更新本地推送状态
											newInsuranceSettle.setActualPushTime(LocalDateTime.now());
											newInsuranceSettle.setIsActualPush(CommonConstants.ONE_INT);
											newInsuranceSettle.setUpdateTime(LocalDateTime.now());
											tInsuranceSettleService.updateById(newInsuranceSettle);
										}else{
											//异常处理
											saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
										}
									}else{
										//异常处理
										saveInsuranceEkp(interactiveParam,CommonConstants.ONE_INT);
										//推送实缴单
										interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
										interactiveParam.setEstimatePremium(success.getEstimatePremium());
										interactiveParam.setActualPremium(success.getActualPremium());
										saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
									}
								}else{
									//保存预估推送失败的数据
									interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
									interactiveParam.setEstimateStatus(EkpConstants.HAVE);
									interactiveParam.setCustomerCode(success.getNewCustomerCode());
									interactiveParam.setCustomerName(success.getNewCustomerName());
									interactiveParam.setDeptNo(success.getNewDeptNo());
									interactiveParam.setDeptName(success.getNewDeptName());
									interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
									interactiveParam.setEstimatePremium(success.getEstimatePremium());
									interactiveParam.setActualPremium(success.getActualPremium());
									interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
									saveInsuranceEkp(interactiveParam,CommonConstants.ONE_INT);
									//保存实缴推送失败的数据
									interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
									interactiveParam.setEstimatePremium(success.getEstimatePremium());
									interactiveParam.setActualPremium(success.getActualPremium());
									saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
								}
							}
							//如果预估和实缴均未推送
							if(byId.getIsActualPush() == CommonConstants.ZERO_INT && byId.getIsEstimatePush() == CommonConstants.ONE_INT){
								//先推送预估，再推送实际
								interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
								interactiveParam.setEstimateStatus(EkpConstants.HAVE);
								interactiveParam.setCustomerCode(success.getNewCustomerCode());
								interactiveParam.setCustomerName(success.getNewCustomerName());
								interactiveParam.setDeptNo(success.getNewDeptNo());
								interactiveParam.setDeptName(success.getNewDeptName());
								interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
								//推送预估单
								interactiveParam.setEstimatePremium(success.getEstimatePremium());
								interactiveParam.setActualPremium(success.getActualPremium());
								interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
								String estimateBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
								if (StringUtils.isNotBlank(estimateBody)) {
									newInsuranceSettle.setEstimatePushTime(LocalDateTime.now());
									newInsuranceSettle.setIsEstimatePush(CommonConstants.ONE_INT);
									newInsuranceSettle.setUpdateTime(LocalDateTime.now());
									tInsuranceSettleService.updateById(newInsuranceSettle);
									//推送实缴单
									interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
									interactiveParam.setEstimatePremium(success.getEstimatePremium());
									interactiveParam.setActualPremium(success.getActualPremium());
									String actualBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
									if (StringUtils.isNotBlank(actualBody)) {
										//推送成功后更新本地推送状态
										newInsuranceSettle.setActualPushTime(LocalDateTime.now());
										newInsuranceSettle.setIsActualPush(CommonConstants.ONE_INT);
										newInsuranceSettle.setUpdateTime(LocalDateTime.now());
										tInsuranceSettleService.updateById(newInsuranceSettle);
									}else{
										//异常处理
										saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
									}
								}else{
									//异常处理
									saveInsuranceEkp(interactiveParam,CommonConstants.ONE_INT);
									interactiveParam.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
									interactiveParam.setEstimatePremium(success.getEstimatePremium());
									interactiveParam.setActualPremium(success.getActualPremium());
									saveInsuranceEkp(interactiveParam,CommonConstants.TWO_INT);
								}
							}
						}
						//如果没有登记保费
						if (BigDecimalUtils.isNullOrZero(actualPremium)){
							if(byId.getIsEstimatePush() == CommonConstants.ONE_INT){
								interactiveParam.setCustomerCode(success.getOldCustomerCode());
								interactiveParam.setCustomerName(success.getOldCustomerName());
								interactiveParam.setDeptNo(success.getOldDeptNo());
								interactiveParam.setDeptName(success.getOldDeptName());
								interactiveParam.setInteractiveType(InsurancesConstants.ABOLISH_SETTLE_BILL);
								interactiveParam.setEstimatePremium(one.getEstimatePremium());
								interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
								String deleteBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
								if (StringUtils.isNotBlank(deleteBody)){
									//推送成功后更新作废信息推送状态
									cancel.setIsCancelPush(CommonConstants.ONE_INT);
									tInsuranceSettleCancelService.updateById(cancel);
									//变更为单独结算
									if (CommonConstants.ONE_INT == newSettleType){
										//删除预估费用和结算id
										updateWrapper.set(TInsuranceDetail ::getEstimatePremium,new BigDecimal("0.00"));
										updateWrapper.set(TInsuranceDetail :: getDefaultSettleId,null);
										update(updateWrapper);
									}
									//变更为合并结算
									if (CommonConstants.ZERO_INT == newSettleType){
										//新增新的结算信息
										newInsuranceSettle.setInsDetailId(insuranceDetailId);
										newInsuranceSettle.setSettleType(newSettleType);
										newInsuranceSettle.setIsEstimatePush(CommonConstants.ZERO_INT);
										newInsuranceSettle.setIsActualPush(CommonConstants.ZERO_INT);
										newInsuranceSettle.setSettleHandleStatus(CommonConstants.ONE_STRING);
										newInsuranceSettle.setCreateTime(LocalDateTime.now());
										newInsuranceSettle.setEstimatePremium(success.getEstimatePremium());
										tInsuranceSettleService.save(newInsuranceSettle);
										//更新结算信息
										updateWrapper.set(TInsuranceDetail :: getDefaultSettleId,newInsuranceSettle.getId());
										update(updateWrapper);
										//推送新的结算信息至EKP
										interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
										interactiveParam.setEstimateStatus(EkpConstants.HAVE);
										interactiveParam.setCustomerCode(success.getNewCustomerCode());
										interactiveParam.setCustomerName(success.getNewCustomerName());
										interactiveParam.setDeptNo(success.getNewDeptNo());
										interactiveParam.setDeptName(success.getNewDeptName());
										interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
										interactiveParam.setEstimatePremium(success.getEstimatePremium());
										interactiveParam.setActualPremium(success.getActualPremium());
										interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
										String estimateBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
										if(StringUtils.isNotBlank(estimateBody)){
											//推送成功更新预估推送状态
											newInsuranceSettle.setIsEstimatePush(CommonConstants.ONE_INT);
											newInsuranceSettle.setEstimatePushTime(LocalDateTime.now());
											newInsuranceSettle.setUpdateTime(LocalDateTime.now());
											tInsuranceSettleService.updateById(newInsuranceSettle);
										}else{
											saveInsuranceEkp(interactiveParam,CommonConstants.ONE_INT);
										}
									}
								}else{
									saveInsuranceEkp(interactiveParam,CommonConstants.FOUR_INT);
									//变更为合并结算
									if (CommonConstants.ZERO_INT == newSettleType){
										//推送新的结算信息至EKP
										interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
										interactiveParam.setEstimateStatus(EkpConstants.HAVE);
										interactiveParam.setCustomerCode(success.getNewCustomerCode());
										interactiveParam.setCustomerName(success.getNewCustomerName());
										interactiveParam.setDeptNo(success.getNewDeptNo());
										interactiveParam.setDeptName(success.getNewDeptName());
										interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
										interactiveParam.setEstimatePremium(success.getEstimatePremium());
										interactiveParam.setActualPremium(success.getActualPremium());
										interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
										saveInsuranceEkp(interactiveParam,CommonConstants.ONE_INT);
									}
								}
							}else{
								//推送新的结算信息至EKP
								interactiveParam.setDefaultSettleId(newInsuranceSettle.getId());
								interactiveParam.setEstimateStatus(EkpConstants.HAVE);
								interactiveParam.setCustomerCode(success.getNewCustomerCode());
								interactiveParam.setCustomerName(success.getNewCustomerName());
								interactiveParam.setDeptNo(success.getNewDeptNo());
								interactiveParam.setDeptName(success.getNewDeptName());
								interactiveParam.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
								interactiveParam.setEstimatePremium(success.getEstimatePremium());
								interactiveParam.setActualPremium(success.getActualPremium());
								interactiveParam.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
								String estimateBody = eKPInsuranceUtil.sendToEkp(interactiveParam);
								if(StringUtils.isNotBlank(estimateBody)){
									//推送成功更新预估推送状态
									newInsuranceSettle.setIsEstimatePush(CommonConstants.ONE_INT);
									newInsuranceSettle.setEstimatePushTime(LocalDateTime.now());
									newInsuranceSettle.setUpdateTime(LocalDateTime.now());
									tInsuranceSettleService.updateById(newInsuranceSettle);
								}else{
									saveInsuranceEkp(interactiveParam,CommonConstants.ONE_INT);
								}
							}
						}
					}
					//新增操作信息
					TInsuranceOperate insuranceOperate = new TInsuranceOperate();
					insuranceOperate.setInsuranceDetailId(success.getId());
					insuranceOperate.setCreateBy(user.getId());
					insuranceOperate.setCreateName(user.getNickname());
					insuranceOperate.setCreateTime(LocalDateTime.now());
					insuranceOperate.setDisplayFlag(CommonConstants.ZERO_INT);
					insuranceOperate.setOperateDesc(InsurancesConstants.DEPT_CHANGE);
					operateList.add(insuranceOperate);
				}
			});
		}
		tInsuranceOperateService.saveBatch(operateList);
		List<DeptChangeCheckParam> errorList = stringListMap.get(InsurancesConstants.ERROR_LIST);
		return R.ok(errorList,InsurancesConstants.IMPORT_SUCCESS);
	}

	/**
	 * 根据保险公司名称查询保单明细
	 *
	 * @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 id
	 * @return {@link R}
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R updateIsUse(String id) {
		YifuUser user = SecurityUtils.getUser();
		TInsuranceDetail insuranceDetail = getById(id);
		if(Common.isEmpty(insuranceDetail) || CommonConstants.ONE_INT == insuranceDetail.getDeleteFlag()){
			return R.failed(InsurancesConstants.INSURANCES_IS_DELETE);
		}
		Integer reduceHandleStatus = insuranceDetail.getReduceHandleStatus();
		Integer buyHandleStatus = insuranceDetail.getBuyHandleStatus();
		if(CommonConstants.ONE_INT == buyHandleStatus || CommonConstants.TWO_INT == buyHandleStatus ||CommonConstants.FOUR_INT == buyHandleStatus){
			return R.failed("当前员工未投保成功，不能进行出险操作");
		}
		if(CommonConstants.FIVE_INT == buyHandleStatus){
			return R.failed("当前员工已减员，不能进行出险操作");
		}
		if(null != reduceHandleStatus && CommonConstants.THREE_INT != reduceHandleStatus){
			return R.failed("当前员工在减员中，不能进行出险操作");
		}
		Integer isEffect = insuranceDetail.getIsEffect();
		if(CommonConstants.ZERO_INT != isEffect){
			return R.failed("保单信息已被替换，不能进行出险操作");
		}
		Integer isUse = insuranceDetail.getIsUse();
		if(CommonConstants.ZERO_INT != isUse){
			return R.failed("保单信息已出险，不能进行出险操作");
		}
		Integer isOverdue = insuranceDetail.getIsOverdue();
		if(CommonConstants.ZERO_INT != isOverdue){
			return R.failed("保单信息已过期，不能进行出险操作");
		}
		LambdaUpdateWrapper<TInsuranceDetail> updateWrapper = new LambdaUpdateWrapper<TInsuranceDetail>();
		updateWrapper.eq(TInsuranceDetail::getId,id)
				.set(TInsuranceDetail::getUpdateTime,LocalDateTime.now())
				.set(TInsuranceDetail::getIsUse,CommonConstants.ONE_INT)
				.set(TInsuranceDetail::getUpdateBy,user.getId());
		update(updateWrapper);
		return R.ok("出险成功");
	}

	/**
	 * 更新减员退费
	 *
	 * @author zhaji
	 * @param paramList
	 * @return {@link R}
	 */
	@Override
	public R updateRefundMoney(List<RefundMoneyParam> paramList) {
		YifuUser user = SecurityUtils.getUser();
		Map<String, List<RefundMoneyParam>> map = refundMoneyCheck(paramList);
		List<RefundMoneyParam> successList = map.get(InsurancesConstants.SUCCESS_LIST);
		if (CollectionUtils.isNotEmpty(successList)){
			for (RefundMoneyParam param : successList) {
				TInsuranceRefund insuranceRefund = new TInsuranceRefund();
				insuranceRefund.setInsDetailId(param.getId());
				insuranceRefund.setRefundMoney(new BigDecimal(param.getRefundMoney()));
				insuranceRefund.setReduceHandleStatus(CommonConstants.FOUR_INT);
				insuranceRefund.setCreateBy(user.getId());
				insuranceRefund.setCreateName(user.getNickname());
				insuranceRefund.setCreateTime(LocalDateTime.now());
				tInsuranceRefundService.updateRefundMoney(insuranceRefund);
			}
		}
		return R.ok(map.get(InsurancesConstants.ERROR_LIST));
	}

	/**
	 * 减员导入校验
	 *
	 * @author zhaji
	 * @param insuranceRefundCheckList 减员表
	 * @return {@link R}
	 */
	public Map<String,List<InsuranceRefundCheck>> checkInsuranceRefundList(List<InsuranceRefundCheck> insuranceRefundCheckList,YifuUser user){
		List<String> deptNoList = getDeptNoList(user);
		List<InsuranceRefundCheck> errorList = new ArrayList<>(128);
		List<InsuranceRefundCheck> successList = new ArrayList<>();
		Map<String,List<InsuranceRefundCheck>> map = new HashMap<>();
		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;
			}
			//备注格式校验
			String remark = param.getRemark();
			if(StringUtils.isNotBlank(remark) && !ValidityUtil.validate50(remark)){
				param.setErrorMessage(InsurancesConstants.REMARK_NOT_MORE_THAN_50);
				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 :: getInsuranceCompanyName,insuranceCompanyName )
					.eq(TInsuranceDetail :: getInsuranceTypeName,insuranceTypeName)
					.eq(TInsuranceDetail :: getPolicyStart,LocalDateUtil.parseLocalDate(policyStart))
					.eq(TInsuranceDetail :: getPolicyEnd,LocalDateUtil.parseLocalDate(policyEnd))
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL);
			List<TInsuranceDetail> list = list(queryWrapper);
			if (list.size()>1){
				param.setErrorMessage(InsurancesConstants.MULTIPLE_RECORDS_UNDER_WARRANTY);
				errorList.add(param);
				continue;
			}
			TInsuranceDetail one = getOne(queryWrapper);
			//员工投保记录不存在
			if (Common.isEmpty(one)){
				param.setErrorMessage(InsurancesConstants.USER_DATA_IS_NOT_EXIST);
				errorList.add(param);
				continue;
			}
			if(deptNoList.stream().noneMatch(u -> u.equals(one.getDeptNo()))){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_IN_DEPT_LIST);
				errorList.add(param);
				continue;
			}
			//当前保单信息的不是已投保状态不能导入
			Integer buyHandleStatus = one.getBuyHandleStatus();
			//商险待投保，无法减员
			if (CommonConstants.ONE_INT == buyHandleStatus){
				param.setErrorMessage(InsurancesConstants.INSURANCE_BUY_STATUS_ONE_ERROR);
				errorList.add(param);
				continue;
			}
			//商险投保中，无法减员
			if (CommonConstants.TWO_INT == buyHandleStatus){
				param.setErrorMessage(InsurancesConstants.INSURANCE_BUY_STATUS_TWO_ERROR);
				errorList.add(param);
				continue;
			}
			//商险投保退回，无法减员
			if (CommonConstants.FOUR_INT == buyHandleStatus){
				param.setErrorMessage(InsurancesConstants.INSURANCE_BUY_STATUS_FOUR_ERROR);
				errorList.add(param);
				continue;
			}
			Integer reduceHandleStatus = one.getReduceHandleStatus();
			if ( null != reduceHandleStatus){
				//当前保单信息的减员状态不为空且不为减员退回时时不能进行导入
				if(CommonConstants.ONE_INT == reduceHandleStatus ){
					param.setErrorMessage(InsurancesConstants.INSURANCE_REFUND_STATUS_ONE_ERROR);
					errorList.add(param);
					continue;
				}
				if(CommonConstants.TWO_INT == reduceHandleStatus ){
					param.setErrorMessage(InsurancesConstants.INSURANCE_REFUND_STATUS_TWO_ERROR);
					errorList.add(param);
					continue;
				}
				if(CommonConstants.FOUR_INT == reduceHandleStatus ){
					param.setErrorMessage(InsurancesConstants.INSURANCE_REFUND_STATUS_FOUR_ERROR);
					errorList.add(param);
					continue;
				}
			}
			//出险状态
			if(null != one.getIsUse() && CommonConstants.ZERO_INT != one.getIsUse()){
				param.setErrorMessage(InsurancesConstants.INSURANCE_IS_USE_ERROR);
				errorList.add(param);
				continue;
			}
			//有效状态
			if(null != one.getIsEffect() && CommonConstants.ZERO_INT != one.getIsEffect()){
				param.setErrorMessage(InsurancesConstants.INSURANCE_IS_EFFECT_ERROR);
				errorList.add(param);
				continue;
			}
			//过期状态
			if (null != one.getIsOverdue() &&  CommonConstants.ZERO_INT != one.getIsOverdue()){
				param.setErrorMessage(InsurancesConstants.INSURANCE_IS_OVERDUE_ERROR);
				errorList.add(param);
				continue;
			}
			param.setId(one.getId());
			param.setReduceHandleStatus(one.getReduceHandleStatus());
			boolean b = successList.stream().anyMatch(
					u -> u.getEmpName().equals(param.getEmpName())
							&& u.getEmpIdcardNo().equals(param.getEmpIdcardNo())
							&& u.getInsuranceCompanyName().equals(param.getInsuranceCompanyName())
							&& u.getInsuranceTypeName().equals(param.getInsuranceTypeName())
							&& u.getPolicyStart().equals(param.getPolicyStart())
							&& u.getPolicyEnd().equals(param.getPolicyEnd())
			);
			if(!b){
				successList.add(param);
			}
		}
		map.put(InsurancesConstants.SUCCESS_LIST,successList);
		map.put(InsurancesConstants.ERROR_LIST,errorList);
		return map;
	};
	/**
	 * 校验保单退费
	 *
	 * @author zhaji
	 * @param paramList 变更列表
	 * @return {@link R}
	 */
	public Map<String,List<RefundMoneyParam>> refundMoneyCheck(List<RefundMoneyParam> paramList){

		Map<String,List<RefundMoneyParam>> map = new HashMap<>(16);
		List<RefundMoneyParam> errorList = new ArrayList<>();
		List<RefundMoneyParam> successList = new ArrayList<>();
		for (RefundMoneyParam param : paramList) {
			String refundMoney = param.getRefundMoney();
			String policyNo = param.getPolicyNo();
			String empName = param.getEmpName();
			String empIdcardNo = param.getEmpIdcardNo();
			//退费金额
			if(StringUtils.isBlank(refundMoney)){
				param.setErrorMessage(InsurancesConstants.REFUND_MONEY_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//保单号
			if(StringUtils.isBlank(policyNo)){
				param.setErrorMessage(InsurancesConstants.POLICY_NO_EMPTY);
				errorList.add(param);
				continue;
			}
			//姓名
			if(StringUtils.isBlank(empName)){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//身份证号
			if(StringUtils.isBlank(empIdcardNo)){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			if(!ValidityUtil.validateMoney(refundMoney)){
				param.setErrorMessage(InsurancesConstants.REFUND_MONEY_PARSE_ERROR);
				errorList.add(param);
				continue;
			}
			//必填格式校通过后查询对应的保单信息
			TInsuranceRefundDetail refundDetail = new TInsuranceRefundDetail();
			refundDetail.setEmpName(empName);
			refundDetail.setEmpIdcardNo(empIdcardNo);
			refundDetail.setPolicyNo(policyNo);
			TInsuranceRefundDetail tInsuranceRefundDetail = this.baseMapper.selectRefundDetail(refundDetail);
			if(Common.isEmpty(tInsuranceRefundDetail)){
				param.setErrorMessage(InsurancesConstants.REFUND_IS_NULL);
				errorList.add(param);
				continue;
			}
			param.setId(tInsuranceRefundDetail.getInsDetailId());
			successList.add(param);
		}
		map.put(InsurancesConstants.ERROR_LIST,errorList);
		map.put(InsurancesConstants.SUCCESS_LIST,successList);
		return map;
	}
	/**
	 * 结算月份校验
	 *
	 * @author zhaji
	 * @param settleMonthCheckList 变更列表
	 * @return {@link R}
	 */
	private Map<String,List<SettleMonthChangeCheckParam>> settleMonthChangeCheck(List<SettleMonthChangeCheckParam> settleMonthCheckList,YifuUser user) {
		List<String> deptNoList = getDeptNoList(user);
		Map<String,List<SettleMonthChangeCheckParam>> map = new HashMap<>(16);
		List<SettleMonthChangeCheckParam> errorList = new ArrayList<>();
		List<SettleMonthChangeCheckParam> successList = new ArrayList<>();
		for (SettleMonthChangeCheckParam param : settleMonthCheckList) {
			//员工姓名
			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 deptNo = param.getDeptNo();
			if(StringUtils.isBlank(deptNo)){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//项目所属权限验证
			if(deptNoList.stream().noneMatch(u ->u.equals(deptNo))){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_IN_USER_DEPT_LIST);
				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 buyStandard = param.getBuyStandard();
			if(StringUtils.isBlank(buyStandard)){
				param.setErrorMessage(InsurancesConstants.BUY_STANDARD_NOT_EMPTY);
				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;
			}
			//结算月
			String settleMonth = param.getSettleMonth();
			if(StringUtils.isBlank(settleMonth)){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_NOT_EMPTY);
				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 :: getInsuranceCompanyName,insuranceCompanyName )
					.eq(TInsuranceDetail :: getDeptNo,deptNo)
					.eq(TInsuranceDetail :: getBuyStandard,buyStandard)
					.eq(TInsuranceDetail :: getInsuranceTypeName,insuranceTypeName)
					.eq(TInsuranceDetail :: getPolicyStart,LocalDateUtil.parseLocalDate(policyStart) )
					.eq(TInsuranceDetail :: getPolicyEnd,LocalDateUtil.parseLocalDate(policyEnd))
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL);
			List<TInsuranceDetail> list = list(queryWrapper);
			if (list.size()>1){
				param.setErrorMessage(InsurancesConstants.MULTIPLE_RECORDS_UNDER_WARRANTY);
				errorList.add(param);
				continue;
			}
			TInsuranceDetail insuranceDetail = getOne(queryWrapper);
			LambdaQueryWrapper<TInsuranceEkp> ekpLambdaQueryWrapper = new LambdaQueryWrapper<>();
			ekpLambdaQueryWrapper.eq(TInsuranceEkp :: getDetailId,insuranceDetail.getId()).eq(TInsuranceEkp ::getResendFlag,CommonConstants.ZERO_INT);
			List<TInsuranceEkp> ekpList = tInsuranceEkpService.list(ekpLambdaQueryWrapper);
			if(CollectionUtils.isNotEmpty(ekpList)){
				param.setErrorMessage(InsurancesConstants.EKP_SEND_ERROR);
				errorList.add(param);
				continue;
			}
			//如果保单信息为空
			if (Common.isEmpty(insuranceDetail)){
				param.setErrorMessage(InsurancesConstants.USER_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;
			}
			Integer buyHandleStatus = insuranceDetail.getBuyHandleStatus();
			//商险待投保，无法变更结算月
			if (CommonConstants.ONE_INT == buyHandleStatus){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_CHANGE_BUY_STATUS_ONE_ERROR);
				errorList.add(param);
				continue;
			}
			//商险投保中，无法变更结算月
			if (CommonConstants.TWO_INT == buyHandleStatus){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_CHANGE_BUY_STATUS_TWO_ERROR);
				errorList.add(param);
				continue;
			}
			//商险投保退回，无法变更结算月
			if (CommonConstants.FOUR_INT == buyHandleStatus){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_CHANGE_BUY_STATUS_FOUR_ERROR);
				errorList.add(param);
				continue;
			}
			//如果结算月份相同
			if (settleMonth.equals(insuranceDetail.getSettleMonth())){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_IDENTICAL);
				errorList.add(param);
				continue;
			}
			//如果结算月份小于当前月份
			if(!LocalDateUtil.isCurrentOrFutureMonth(param.getSettleMonth())){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_SHOULD_IS_FUTURE);
				errorList.add(param);
				continue;
			}
			String defaultSettleId = insuranceDetail.getDefaultSettleId();
			if(StringUtils.isNotEmpty(defaultSettleId)){
				//查询结算状态
				TInsuranceSettle settle = tInsuranceSettleService.getById(defaultSettleId);
				if (Optional.ofNullable(settle).isPresent()){
					SettleVo settleVo = getInsuranceDetailSettleStatus(insuranceDetail.getId(), defaultSettleId);
					if(!Common.isEmpty(settleVo)){
						if (InsurancesConstants.SETTLE_TWO.equals(settleVo.getEstimateStatus()) || InsurancesConstants.SETTLE_TWO.equals(settleVo.getActualStatus())){
							param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_CHANGE_SETTLE_STATUS_THREE_ERROR);
							errorList.add(param);
							continue;
						}
						if (InsurancesConstants.SETTLE_ONE.equals(settleVo.getEstimateStatus()) || InsurancesConstants.SETTLE_ONE.equals(settleVo.getActualStatus())){
							param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_CHANGE_SETTLE_STATUS_TWO_ERROR);
							errorList.add(param);
							continue;
						}
					}
				}
			}
			//当前保单信息的为已减员时不能变更结算月
			if(null != insuranceDetail.getReduceHandleStatus()){
				if( CommonConstants.FOUR_INT == insuranceDetail.getReduceHandleStatus() ){
					param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_CHANGE_REFUND_STATUS_FOUR_ERROR);
					errorList.add(param);
					continue;
				}
				//减员流程中，无法变更结算月
				if(CommonConstants.ONE_INT == insuranceDetail.getReduceHandleStatus()
						|| CommonConstants.TWO_INT == insuranceDetail.getReduceHandleStatus()){
					param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_CHANGE_REFUND_STATUS_ONE_ERROR);
					errorList.add(param);
					continue;
				}
			}
			param.setId(insuranceDetail.getId());
			successList.add(param);
		}
		map.put(InsurancesConstants.ERROR_LIST,errorList);
		map.put(InsurancesConstants.SUCCESS_LIST,successList);
		return map;
	}

	/**
	 * 投保成功/退回/减员办理校验
	 *
	 * @author zhaji
	 * @param checkList 投保成功/退回/减员办理校验
	 * @param user
	 * @param flag true 减员 false 投保成功/退回
	 * @return {@link Map<String, List<InsuranceHandleImportParam>}
	 */
	private Map<String,List<InsuranceHandleImportParam>> insuranceChangeCheck(List<InsuranceHandleImportParam> checkList, YifuUser user,Boolean flag) {
		Map<String,List<InsuranceHandleImportParam>> map = new HashMap<>(16);
		List<InsuranceHandleImportParam> errorList = new ArrayList<>();
		List<InsuranceHandleImportParam> successList = new ArrayList<>();
		List<InsuranceHandleImportParam> distinctList = checkList.stream().distinct().collect(Collectors.toList());
		//定义外层循环标识，方便去重的时候跳出
		outer:
		for (int i = 0; i < distinctList.size(); i++) {
			InsuranceHandleImportParam param = distinctList.get(i);
			//办理结果
			String handType = param.getHandType();
			if(StringUtils.isBlank(handType)){
				param.setErrorMessage(InsurancesConstants.HAND_RESULT_IS_EMPTY);
				errorList.add(param);
				continue;
			}
			if(!InsurancesConstants.SUCCESS.equals(handType) && !InsurancesConstants.FAILED.equals(handType)){
				param.setErrorMessage(InsurancesConstants.HAND_RESULT_ERROR);
				errorList.add(param);
				continue;
			}
			//办理意见
			String remark = param.getRemark();
			if(InsurancesConstants.FAILED.equals(handType) && StringUtils.isBlank(remark)){
				param.setErrorMessage(InsurancesConstants.ROLLBACK_MESSAGE_IS_EMPTY);
				errorList.add(param);
				continue;
			}
			if(StringUtils.isNotBlank(remark) && !ValidityUtil.validate50(remark)){
				param.setErrorMessage(InsurancesConstants.HAND_REMARK_NOT_MORE_THAN_50);
				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 buyStandard = param.getBuyStandard();
			if(StringUtils.isBlank(buyStandard)){
				param.setErrorMessage(InsurancesConstants.BUY_STANDARD_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;
			}

			//表内数据重复 员工姓名、员工身份证号码、保险公司名称、险种名称、保单开始日期、保单结束日期、购买标准 去重
			for (int j = 0; j < distinctList.size(); j++) {
				InsuranceHandleImportParam repeat = distinctList.get(j);
				if (param.getEmpName().equals(repeat.getEmpName())
						&& param.getEmpIdcardNo().equals(repeat.getEmpIdcardNo())
						&& param.getInsuranceCompanyName().equals(repeat.getInsuranceCompanyName())
						&& param.getInsuranceTypeName().equals(repeat.getInsuranceTypeName())
						&& param.getPolicyStart().equals(repeat.getPolicyStart())
						&& param.getPolicyEnd().equals(repeat.getPolicyEnd())
						&& param.getBuyStandard().equals(repeat.getBuyStandard())
						&& i != j){
					param.setErrorMessage(InsurancesConstants.DUPLICATE_DATA_ERROR);
					errorList.add(param);
					continue outer;
				}
			}

			LambdaQueryWrapper<TInsuranceDetail> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(TInsuranceDetail::getDeleteFlag,CommonConstants.ZERO_INT)
					.eq(TInsuranceDetail::getEmpName,empName)
					.eq(TInsuranceDetail::getEmpIdcardNo,empIdCardNo)
					.eq(TInsuranceDetail::getInsuranceTypeName,insuranceTypeName)
					.eq(TInsuranceDetail::getInsuranceCompanyName,insuranceCompanyName)
					.eq(TInsuranceDetail::getBuyStandard,buyStandard)
					.eq(TInsuranceDetail::getPolicyStart,LocalDateUtil.parseLocalDate(policyStart) )
					.eq(TInsuranceDetail::getPolicyEnd,LocalDateUtil.parseLocalDate(policyEnd))
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL);
			TInsuranceDetail insuranceDetail = getOne(queryWrapper);
			//如果保单信息为空
			if (Common.isEmpty(insuranceDetail)){
				param.setErrorMessage(InsurancesConstants.USER_DATA_IS_NOT_EXIST);
				errorList.add(param);
				continue;
			}
			String detailId = insuranceDetail.getId();
			if (flag){
				//减员办理
				//投保办理状态
				Integer buyHandleStatus = insuranceDetail.getBuyHandleStatus();
				//减员状态
				Integer reduceHandleStatus = insuranceDetail.getReduceHandleStatus();
				//商险待投保，无法办理
				if (CommonConstants.ONE_INT == buyHandleStatus){
					param.setErrorMessage(InsurancesConstants.BUY_HANDLE_STATUS_ONE_HANDLE_ERROR);
					errorList.add(param);
					continue;
				}
				//商险投保中，无法办理
				if (CommonConstants.TWO_INT == buyHandleStatus){
					param.setErrorMessage(InsurancesConstants.BUY_HANDLE_STATUS_TWO_HANDLE_ERROR);
					errorList.add(param);
					continue;
				}
				//商险投保成功，无法办理
				if (CommonConstants.THREE_INT == buyHandleStatus && null == reduceHandleStatus){
					param.setErrorMessage(InsurancesConstants.BUY_HANDLE_STATUS_THREE_HANDLE_ERROR);
					errorList.add(param);
					continue;
				}
				//商险投保退回，无法办理
				if (CommonConstants.FOUR_INT == buyHandleStatus){
					param.setErrorMessage(InsurancesConstants.BUY_HANDLE_STATUS_FOUR_HANDLE_ERROR);
					errorList.add(param);
					continue;
				}
				if ( null != reduceHandleStatus){
					//待减员
					if(CommonConstants.ONE_INT == reduceHandleStatus ){
						param.setErrorMessage(InsurancesConstants.REFUND_STATUS_ONE_HANDLE_ERROR);
						errorList.add(param);
						continue;
					}
					//减员退回
					if(CommonConstants.THREE_INT == reduceHandleStatus ){
						param.setErrorMessage(InsurancesConstants.REFUND_STATUS_FOUR_HANDLE_ERROR);
						errorList.add(param);
						continue;
					}
					//已减员
					if(CommonConstants.FOUR_INT== reduceHandleStatus ){
						param.setErrorMessage(InsurancesConstants.REFUND_STATUS_THREE_HANDLE_ERROR);
						errorList.add(param);
						continue;
					}
				}
			}else {
				//投保成功/退回办理
				//商险不是投保中，无法办理
				if (CommonConstants.TWO_INT != insuranceDetail.getBuyHandleStatus()){
					String buyHandleStatus = getBuyHandleStatus(insuranceDetail.getBuyHandleStatus());
					param.setErrorMessage("当前为"+buyHandleStatus+"状态，不可办理");
					errorList.add(param);
					continue;
				}
			}
			param.setId(detailId);
			successList.add(param);
		}
		map.put(InsurancesConstants.SUCCESS_LIST,successList);
		map.put(InsurancesConstants.ERROR_LIST,errorList);
		return map;
	}

	/**
	 * 获取投保状态的值
	 *
	 * @author licancan
	 * @param buyHandleStatus
	 * @return {@link String}
	 */
	private String getBuyHandleStatus(Integer buyHandleStatus){
		String result;
		switch (buyHandleStatus){
			case 1:
				result = "待投保";
				break;
			case 2:
				result = "投保中";
				break;
			case 3:
				result = "已投保";
				break;
			case 4:
				result = "投保退回";
				break;
			case 5:
				result = "已减员";
				break;
			default:
				result = "";
		}
		return result;
	}

	/**
	 * 校验所属项目
	 *
	 * @author zhaji
	 * @param deptChangeCheckList 变更列表
	 * @return {@link R}
	 */
	public Map<String,List<DeptChangeCheckParam>> deptChangeCheck(List<DeptChangeCheckParam> deptChangeCheckList,YifuUser user) {
		List<String> deptNoList = getDeptNoList(user);
		Map<String,List<DeptChangeCheckParam>> map = new HashMap<>(16);
		List<DeptChangeCheckParam> errorList = new ArrayList<>();
		List<DeptChangeCheckParam> successList = new ArrayList<>();
		for (int i =0 ;i< deptChangeCheckList.size();i++) {
			DeptChangeCheckParam param = deptChangeCheckList.get(i);
			//变更后的项目
			String newDeptNo = param.getNewDeptNo();
			if(StringUtils.isBlank(newDeptNo)){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_CHANGE_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 oldDeptNo = param.getOldDeptNo();
			if(StringUtils.isBlank(oldDeptNo)){
				param.setErrorMessage(InsurancesConstants.DEPT_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;
			}
			//新老项目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;
			}
			// 保单开始日期格式校验
			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;
			}
			//根据项目编码查询项目是否存在
			R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(Arrays.asList(newDeptNo,oldDeptNo));
			if (null != setInfoByCodes && setInfoByCodes.getCode() == CommonConstants.SUCCESS) {
				Map<String, ProjectSetInfoVo> data = setInfoByCodes.getData().getProjectSetInfoVoMap();
				if (MapUtils.isEmpty(data)){
					param.setErrorMessage(InsurancesConstants.DEPT_NO_CHANGE_NEW_IS_NOT_EXIST);
					errorList.add(param);
					continue;
				}else {
					//结算类型，根据项目编码获取，并冗余到明细记录中
					ProjectSetInfoVo jsonObject =  data.get(newDeptNo);
					if(Common.isEmpty(jsonObject)){
						param.setErrorMessage(InsurancesConstants.DEPT_NO_CHANGE_NEW_IS_NOT_EXIST);
						errorList.add(param);
						continue;
					}
					ProjectSetInfoVo oldJsonObject =  data.get(oldDeptNo);
					if(Common.isEmpty(oldJsonObject)){
						param.setErrorMessage(InsurancesConstants.DEPT_NO_CHANGE_OLD_IS_NOT_EXIST);
						errorList.add(param);
						continue;
					}
					param.setOldDeptName(oldJsonObject.getDepartName());
					param.setOldCustomerCode(oldJsonObject.getCustomerCode());
					param.setOldCustomerName(oldJsonObject.getCustomerName());
					param.setNewDeptName(jsonObject.getDepartName());
					param.setNewCustomerName(jsonObject.getCustomerName());
					param.setNewCustomerCode(jsonObject.getCustomerCode());
					String settleType = jsonObject.getInsuranceSettleType();
					if (StringUtils.isEmpty(settleType)){
						param.setErrorMessage(InsurancesConstants.PROJECT_NOT_FIND_SETTLE_TYPE);
						errorList.add(param);
						continue;
					}else {
						param.setNewSettleType(Integer.parseInt(settleType));
					}
				}
			}
			//必填格式校通过后查询对应的保单信息
			LambdaQueryWrapper<TInsuranceDetail> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(TInsuranceDetail :: getDeleteFlag,CommonConstants.ZERO_INT)
					.eq(TInsuranceDetail ::getEmpName,empName )
					.eq(TInsuranceDetail ::getEmpIdcardNo,empIdCardNo )
					.eq(TInsuranceDetail :: getInsuranceTypeName,insuranceTypeName )
					.eq(TInsuranceDetail :: getBuyStandard,buyStandard)
					.eq(TInsuranceDetail::getDeptNo,oldDeptNo)
					.eq(TInsuranceDetail :: getInsuranceCompanyName,insuranceCompanyName)
					.eq(TInsuranceDetail :: getPolicyStart,LocalDateUtil.parseLocalDate(policyStart))
					.eq(TInsuranceDetail :: getPolicyEnd,LocalDateUtil.parseLocalDate(policyEnd))
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL);
			List<TInsuranceDetail> list = list(queryWrapper);
			if (list.size()>1){
				param.setErrorMessage(InsurancesConstants.MULTIPLE_RECORDS_UNDER_WARRANTY);
				errorList.add(param);
				continue;
			}
			TInsuranceDetail insuranceDetail = getOne(queryWrapper);
			LambdaQueryWrapper<TInsuranceEkp> ekpLambdaQueryWrapper = new LambdaQueryWrapper<>();
			ekpLambdaQueryWrapper.eq(TInsuranceEkp :: getDetailId,insuranceDetail.getId()).eq(TInsuranceEkp ::getResendFlag,CommonConstants.ZERO_INT);
			List<TInsuranceEkp> ekpList = tInsuranceEkpService.list(ekpLambdaQueryWrapper);
			if(CollectionUtils.isNotEmpty(ekpList)){
				param.setErrorMessage(InsurancesConstants.EKP_SEND_ERROR);
				errorList.add(param);
				continue;
			}
			//如果保单信息为空
			if (Common.isEmpty(insuranceDetail)){
				param.setErrorMessage(InsurancesConstants.USER_DATA_IS_NOT_EXIST);
				errorList.add(param);
				continue;
			}
			//旧项目ID不在当前权限范围内
			if(deptNoList.stream().noneMatch(u ->u.equals(oldDeptNo))){
				param.setErrorMessage(InsurancesConstants.OLD_DEPT_NO_NOT_IN_DEPT_LIST);
				errorList.add(param);
				continue;
			}
			//新项目ID不在当前权限范围内
			if(deptNoList.stream().noneMatch(u ->u.equals(newDeptNo))){
				param.setErrorMessage(InsurancesConstants.NEW_DEPT_NO_NOT_IN_DEPT_LIST);
				errorList.add(param);
				continue;
			}
			//替换类型的保单不能变更所属项目
			Integer buyType = insuranceDetail.getBuyType();
			if (CommonConstants.FOUR_INT == buyType){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_CHANGE_IS_EFFECT_ERROR);
				errorList.add(param);
				continue;
			}
			Integer buyHandleStatus = insuranceDetail.getBuyHandleStatus();
			//商险待投保，无法变更项目
			if (CommonConstants.ONE_INT == buyHandleStatus){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_CHANGE_BUY_STATUS_ONE_ERROR);
				errorList.add(param);
				continue;
			}
			//商险投保中，无法变更项目
			if (CommonConstants.TWO_INT == buyHandleStatus){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_CHANGE_BUY_STATUS_TWO_ERROR);
				errorList.add(param);
				continue;
			}
			//商险投保退回，无法变更项目
			if (CommonConstants.FOUR_INT == buyHandleStatus){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_CHANGE_BUY_STATUS_FOUR_ERROR);
				errorList.add(param);
				continue;
			}
			//当前保单信息的为已减员时，不能变更结算项目
			if( null != insuranceDetail.getReduceHandleStatus()){
				if (CommonConstants.FOUR_INT == insuranceDetail.getReduceHandleStatus()){
					param.setErrorMessage(InsurancesConstants.DEPT_NO_CHANGE_REFUND_STATUS_FOUR_ERROR);
					errorList.add(param);
					continue;
				}
				if(CommonConstants.ONE_INT == insuranceDetail.getReduceHandleStatus() || CommonConstants.TWO_INT == insuranceDetail.getReduceHandleStatus()){
					param.setErrorMessage(InsurancesConstants.DEPT_NO_CHANGE_REFUND_STATUS_ONE_ERROR);
					errorList.add(param);
					continue;
				}
			}
			String defaultSettleId = insuranceDetail.getDefaultSettleId();
			if (StringUtils.isNotBlank(defaultSettleId)){
				//查询结算状态
				TInsuranceSettle settle = tInsuranceSettleService.getById(defaultSettleId);
				if (Optional.ofNullable(settle).isPresent()){
					SettleVo settleVo = getInsuranceDetailSettleStatus(insuranceDetail.getId(), defaultSettleId);
					if(!Common.isEmpty(settleVo)){
						if (InsurancesConstants.SETTLE_TWO.equals(settleVo.getEstimateStatus()) || InsurancesConstants.SETTLE_TWO.equals(settleVo.getActualStatus())){
							param.setErrorMessage(InsurancesConstants.DEPT_NO_CHANGE_SETTLE_STATUS_THREE_ERROR);
							errorList.add(param);
							continue;
						}
						if (InsurancesConstants.SETTLE_ONE.equals(settleVo.getEstimateStatus()) || InsurancesConstants.SETTLE_ONE.equals(settleVo.getActualStatus())){
							param.setErrorMessage(InsurancesConstants.DEPT_NO_CHANGE_SETTLE_STATUS_TWO_ERROR);
							errorList.add(param);
							continue;
						}
					}
				}
			}
			//预估
			if (param.getNewSettleType() == CommonConstants.ZERO_INT){
				//按月
				if (CommonConstants.ONE_INT == insuranceDetail.getBillingType()){
					// 预估保费 = 费率 * 购买标准
					BigDecimal estimatePremium = new BigDecimal(insuranceDetail.getBuyStandard()).multiply(insuranceDetail.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP);
					param.setEstimatePremium(estimatePremium);
				}else {
					//按天
					//计算起止时间的天数
					long day = LocalDateUtil.betweenDay(insuranceDetail.getPolicyStart().toString(), insuranceDetail.getPolicyEnd().toString());
					//预估保费 = (购买标准 / 365) * 天数
					BigDecimal estimatePremium = new BigDecimal(insuranceDetail.getBuyStandard()).multiply(new BigDecimal(day)).divide(new BigDecimal("365"),CommonConstants.TWO_INT,BigDecimal.ROUND_HALF_UP);
					param.setEstimatePremium(estimatePremium);
				}
			}
			//去重
			for (int j =0 ;j< deptChangeCheckList.size();j++) {
				DeptChangeCheckParam CheckParam = deptChangeCheckList.get(j);
				if(CheckParam.getEmpName().equals(param.getEmpName())
						&&CheckParam.getEmpIdCardNo().equals(param.getEmpIdCardNo())
						&&CheckParam.getOldDeptNo().equals(param.getOldDeptNo())
						&&CheckParam.getInsuranceTypeName().equals(param.getInsuranceTypeName())
						&&CheckParam.getInsuranceCompanyName().equals(param.getInsuranceCompanyName())
						&&CheckParam.getPolicyStart().equals(param.getPolicyStart())
						&&CheckParam.getPolicyEnd().equals(param.getPolicyEnd())
						&& i!=j)
				{
					param.setErrorMessage(InsurancesConstants.DUPLICATE_DATA_ERROR);
					errorList.add(param);
					//确定为重复数据则跳出循环
					break;
				}
			}
			param.setOldSettleType(insuranceDetail.getSettleType());
			param.setDefaultSettleId(insuranceDetail.getDefaultSettleId());
			param.setActualPremium(insuranceDetail.getActualPremium());
			param.setId(insuranceDetail.getId());
			successList.add(param);
		}
		map.put(InsurancesConstants.ERROR_LIST,errorList);
		map.put(InsurancesConstants.SUCCESS_LIST,successList);
		return map;
	}

	/**
	 * 查询项目列表
	 *
	 * @author zhaji
	 * @param
	 * @return {@link R}
	 */
	@Override
	public R getDeptList(){
		List<Dept> deptList = new ArrayList<>();
		R<TSettleDomainListVo> tSettleDomainListVoR = archivesDaprUtil.selectAllSettleDomainSelectVos();
		if (null != tSettleDomainListVoR && tSettleDomainListVoR.getCode() == CommonConstants.SUCCESS && Common.isNotNull(tSettleDomainListVoR.getData())) {
			TSettleDomainListVo data = tSettleDomainListVoR.getData();
			List<TSettleDomainSelectVo> listSelectVO = data.getListSelectVO();
			if(CollectionUtils.isNotEmpty(listSelectVO)){
				//listSelectVO.stream().filter(item->deptList.add(new Dept(item.getDepartNo(),item.getDepartName())));
				for (TSettleDomainSelectVo tSettleDomainSelectVo : listSelectVO) {
					deptList.add(new Dept(tSettleDomainSelectVo.getDepartNo(),tSettleDomainSelectVo.getDepartName()));
				}
			}
		}

		return R.ok(deptList);
	}

	/**
	 * 获取当前登录人的项目列表
	 *
	 * @author zhaji
	 * @param
	 * @return {@link R}
	 */
	@Override
	public R getDeptListByUser(){
		YifuUser user = SecurityUtils.getUser();
		//根据当前登录人获取其拥有的项目列表权限
		List<String> deptNoList = getDeptNoList(user);
		List<Dept> deptList = new ArrayList<>(16);
		R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(deptNoList);
		if (null != setInfoByCodes && setInfoByCodes.getCode() == CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
			SetInfoVo data = setInfoByCodes.getData();
			Map<String, ProjectSetInfoVo> projectSetInfoVoMap = data.getProjectSetInfoVoMap();
			for (String deptNo : deptNoList) {
				ProjectSetInfoVo projectSetInfoVo = projectSetInfoVoMap.get(deptNo);
				if(!Common.isEmpty(projectSetInfoVo)){
					deptList.add(new Dept(projectSetInfoVo.getDepartNo(),projectSetInfoVo.getDepartName()));
				}
			}
		}
		return R.ok(deptList,"查询项目列表成功");
	}

	/**
	 * EKP紧急出险
	 *
	 * @author zhaji
	 * @param empIdcardNo
	 * @return {@link R}
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R urgentUpdateIsUse(String empIdcardNo) {
		//员工身份证
		if(StringUtils.isBlank(empIdcardNo)){
			return R.failed("身份证号为空");
		}
		// 身份证号位数校验（18 位合法）
		if (!ValidityUtil.validateIDCard(empIdcardNo)){
			return R.failed("身份证格式不正确");
		}
		//查询所有在保，未出险，未过期，未失效，未减员的保单信息
		List<TInsuranceDetail> list = this.baseMapper.selectListByEmpIdcardNo(empIdcardNo);
		if (CollectionUtils.isEmpty(list)){
			return R.failed("无可出险的保单");
		}
		List<TInsuranceOperate> operateList = new ArrayList<>();
		LambdaUpdateWrapper<TInsuranceDetail>  updateWrapper = new LambdaUpdateWrapper<>();
		for (TInsuranceDetail tInsuranceDetail : list) {
			TInsuranceOperate operate = new TInsuranceOperate();
			updateWrapper.eq(TInsuranceDetail :: getId,tInsuranceDetail.getId())
					.set(TInsuranceDetail :: getIsUse,CommonConstants.ONE_INT)
					.set(TInsuranceDetail :: getUpdateTime,LocalDateTime.now());
			update(updateWrapper);
			operate.setOperateDesc(InsurancesConstants.URGENT_UPDATE_IS_USE);
			operate.setCreateName(InsurancesConstants.SYSTEM_TRIGGER);
			operate.setInsuranceDetailId(tInsuranceDetail.getId());
			operate.setDisplayFlag(CommonConstants.ONE_INT);
			operate.setCreateTime(LocalDateTime.now());
			operate.setCreateBy(CommonConstants.ZERO_STRING);
			operateList.add(operate);
		}
		tInsuranceOperateService.saveBatch(operateList);
		return R.ok("EKP紧急出险成功");

	}

	/**
	 * 根据身份证查询商险列表
	 *
	 * @author huyc
	 * @param
	 * @return {@link R}
	 */
	@Override
	public IPage<InsuranceListByIdCardVo> getInsuranceListByIdCard(Page<TInsuranceDetail> page, String idCard,String deptNo) {
		IPage<InsuranceListByIdCardVo> insuranceListByIdCard = baseMapper.getInsuranceListByIdCard(page, idCard,deptNo);
		List<InsuranceListByIdCardVo> records = insuranceListByIdCard.getRecords();
		if (CollectionUtils.isNotEmpty(records)){
			for (InsuranceListByIdCardVo record : records) {
				record.setBuyMonth(LocalDateUtil.betweenMonth(record.getPolicyStart().toString(), record.getPolicyEnd().toString()));
			}
			insuranceListByIdCard.setRecords(records);
		}
		return insuranceListByIdCard;

	}

	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R<List<InsuranceAddParam>> addOrderInsurance(InsuranceListOrderParam paramList) {
		String orderNo = paramList.getOrderNo();
		if (StringUtils.isBlank(orderNo)) {
			return R.failed(InsurancesConstants.ORDER_NO_IS_EMPTY);
		}
		return addInsurance(paramList.getData(),paramList.getOrderNo());
	}

	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R<List<InsuranceBatchParam>> batchOrderInsurance(InsuranceOrderBatchParam paramList) {
		String orderNo = paramList.getOrderNo();
		if (StringUtils.isBlank(orderNo)) {
			return R.failed(InsurancesConstants.ORDER_NO_IS_EMPTY);
		}
		return batchInsurance(paramList.getData(),paramList.getOrderNo());
	}

	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R<List<InsuranceReplaceParam>> replaceOrderInsurance(InsuranceOrderReplaceParam paramList) {
		String orderNo = paramList.getOrderNo();
		if (StringUtils.isBlank(orderNo)) {
			return R.failed(InsurancesConstants.ORDER_NO_IS_EMPTY);
		}
		return replaceInsurance(paramList.getData(),paramList.getOrderNo());
	}

	@Override
	public R refundOrderInsurance(InsuranceOrderRefundParam paramList) {
		String orderNo = paramList.getOrderNo();
		if (StringUtils.isBlank(orderNo)) {
			return R.failed(InsurancesConstants.ORDER_NO_IS_EMPTY);
		}
		return saveInsuranceRefund(paramList.getData(),paramList.getOrderNo());
	}

	/**
	 * 订单商险列表查询
	 *
	 * @author zhaji
	 * @param page
	 * @param param
	 * @return {@link IPage< InsuredOrderListVo>}
	 */
	@Override
	public R getOrderInsuredListPage(Page<InsuredOrderListVo> page, InsuredOrderParam param) {
		YifuUser user = SecurityUtils.getUser();

		String orderNo = param.getOrderNo();
		if (StringUtils.isBlank(orderNo)) {
			return R.failed(InsurancesConstants.ORDER_NO_IS_EMPTY);
		}

		if (user != null && Common.isNotNull(user.getId()) && CommonConstants.ONE_STRING.equals(user.getSystemFlag())) {
			String sql;
			// 获取人员项目权限
			R<TSettleDomainListVo> res = HttpDaprUtil.invokeMethodPost(daprArchivesProperties.getAppUrl()
					, daprArchivesProperties.getAppId(), "/tsettledomain/getSettleDomainIdsByUserId"
					, user.getId(), TSettleDomainListVo.class, SecurityConstants.FROM_IN);
			StringBuilder deptStr = new StringBuilder();
			if (res != null && CommonConstants.SUCCESS == res.getCode()
					&& res.getData() != null && res.getData().getDeptIds() != null
					&& !res.getData().getDeptIds().isEmpty()) {
				for (String deptId : res.getData().getDeptIds()) {
					deptStr.append(",'").append(deptId).append("'");
				}
			}
			sql = "and (1=2 or a.dept_id in ('0'#settleDomainId))";
			sql = sql.replace("#settleDomainId", deptStr.toString());
			param.setAuthSql(sql);
		}
		//查询所有保单信息
		IPage<InsuredOrderListVo> orderInsuredList = baseMapper.getOrderInsuredListPage(page, param);
		return R.ok(orderInsuredList);
	}

	/**
	 * 获取项目权限
	 *
	 * @author zhaji
	 * @param user
	 * @return {@link List< String>}
	 */
	public List<String> getDeptNoList(YifuUser user){
		//todo 根据登录人获取其项目权限列表
		List<String> deptList = new ArrayList<>(16);
		String id = user.getId();
		//周日琴12，徐燕13
		if (CommonConstants.TWELVE_STRING.equals(id)){
			deptList.add("A0001");
			deptList.add("皖M02002");
			deptList.add("皖A12345678");
			deptList.add("皖B29203");
			deptList.add("皖AFA10M");
			deptList.add("皖AFA11F");
			deptList.add("皖M02023");
			deptList.add("皖M02045");
		} else if(CommonConstants.THIRTEEN_STRING.equals(id)){
			deptList.add("皖A12345678");
			deptList.add("皖B29203");
			deptList.add("皖M02023");
			deptList.add("皖M02002");
		}else{
			R<TSettleDomainListVo> tSettleDomainListVoR = archivesDaprUtil.selectAllSettleDomainSelectVos();
			if (null != tSettleDomainListVoR && tSettleDomainListVoR.getCode() == CommonConstants.SUCCESS && Common.isNotNull(tSettleDomainListVoR.getData())) {
				TSettleDomainListVo data = tSettleDomainListVoR.getData();
				List<TSettleDomainSelectVo> listSelectVO = data.getListSelectVO();
				for (TSettleDomainSelectVo tSettleDomainSelectVo : listSelectVO) {
					if (Common.isNotNull(tSettleDomainSelectVo.getDepartNo())) {
						deptList.add(tSettleDomainSelectVo.getDepartNo());
					}
				}
			}
		}
		return deptList;
	}

	/**
	 * 获取项目名称，客户编码，客户名称
	 *
	 * @author zhaji
	 * @param list
	 * @return {@link List<  EkpInteractiveParam >}
	 */
	public List<EkpInteractiveParam> getDeptDetail(List<SettleMonthChangeCheckParam> list){
		//根据项目编码获取项目名称
		List<String> collect = list.stream().map(SettleMonthChangeCheckParam::getDeptNo).distinct().collect(Collectors.toList());
		List<EkpInteractiveParam> ekpInteractiveParams = new ArrayList<>();
		R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(collect);
		if (null != setInfoByCodes && setInfoByCodes.getCode() == CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
			EkpInteractiveParam ekpInteractiveParam = new EkpInteractiveParam();
			Map<String, ProjectSetInfoVo> data = setInfoByCodes.getData().getProjectSetInfoVoMap();
			for (SettleMonthChangeCheckParam param : list) {
				ProjectSetInfoVo projectSetInfoVo = data.get(param.getDeptNo());
				ekpInteractiveParam.setDetailId(param.getId());
				ekpInteractiveParam.setSettleMonth(param.getSettleMonth());
				ekpInteractiveParam.setDeptName(projectSetInfoVo.getDepartName());
				ekpInteractiveParam.setCustomerName(projectSetInfoVo.getCustomerName());
				ekpInteractiveParam.setCustomerCode(projectSetInfoVo.getCustomerCode());
				ekpInteractiveParams.add(ekpInteractiveParam);
			}
		}
		return ekpInteractiveParams;
	}


	/**
	 * 推送EKP
	 *
	 * @author zhaji
	 * @param
	 * @return {@link String}
	 */
	public String pushEstimate(TInsuranceDetail tInsuranceDetail,Integer type){
		YifuUser user = SecurityUtils.getUser();
		Integer pushType = null;
		//1,推送预估保费，2，推送实际保费，3推送预估冲正保费，4更新实际保费
		EkpInteractiveParam param = new EkpInteractiveParam();
		List<String> deptNoList =new ArrayList<>();
		TInsuranceSettleCancel cancel = new TInsuranceSettleCancel();
		deptNoList.add(tInsuranceDetail.getDeptNo());
		BeanCopyUtils.copyProperties(tInsuranceDetail,param);
		param.setDetailId(tInsuranceDetail.getId());
		Integer settleType = tInsuranceDetail.getSettleType();
		if(CommonConstants.ZERO_INT == settleType){
			param.setEstimateStatus(EkpConstants.HAVE);
		}else {
			param.setEstimateStatus(EkpConstants.NOTHING);
		}
		//获取当前项目的名称，客户名称和客户编码
		R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(deptNoList);
		if (null != setInfoByCodes && setInfoByCodes.getCode() == CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
			SetInfoVo data = setInfoByCodes.getData();
			Map<String, ProjectSetInfoVo> projectSetInfoVoMap = data.getProjectSetInfoVoMap();
			ProjectSetInfoVo projectSetInfoVo = projectSetInfoVoMap.get(tInsuranceDetail.getDeptNo());
			param.setDeptName(projectSetInfoVo.getDepartName());
			param.setCustomerName(projectSetInfoVo.getCustomerName());
			param.setCustomerCode(projectSetInfoVo.getCustomerCode());
		}
		//1,推送预估保费(用户办理成功，推送预估保费)
		if(CommonConstants.ONE_INT == type){
			param.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
			param.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
			pushType = CommonConstants.ONE_INT;
		}
		//2，推送实际保费(用于登记保单保费未推送过实缴保费)
		if(CommonConstants.TWO_INT == type){
			param.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
			param.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
			pushType = CommonConstants.TWO_INT;
		}
		//3推送预估冲正保费(用于投保退回场景)
		if(CommonConstants.THREE_INT == type){
			String defaultSettleId = tInsuranceDetail.getDefaultSettleId();
			TInsuranceSettle byId = tInsuranceSettleService.getById(defaultSettleId);
			//冲正取负数
			if(null != byId.getEstimatePremium()){
				param.setEstimatePremium(byId.getEstimatePremium());
			}
			param.setInteractiveType(InsurancesConstants.CORRECT_SETTLE_BILL);
			param.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
			pushType = CommonConstants.FIVE_INT;
		}
		//6推送实缴红冲(用于投保退回场景)
		if(CommonConstants.SIX_INT == type){
			String defaultSettleId = tInsuranceDetail.getDefaultSettleId();
			TInsuranceSettle byId = tInsuranceSettleService.getById(defaultSettleId);
			//冲正取负数
			if(null != byId.getActualPremium()){
				param.setActualPremium(byId.getActualPremium());
			}
			param.setInteractiveType(InsurancesConstants.CORRECT_SETTLE_BILL);
			param.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
			pushType = CommonConstants.SIX_INT;
		}
		//4更新实际保费(用于登记保单保费场景推送过实缴保费)
		if(CommonConstants.FOUR_INT == type){
			param.setInteractiveType(InsurancesConstants.UPDATE_SETTLE_BILL);
			param.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
			pushType = CommonConstants.THREE_INT;
		}
		//作废
		if(CommonConstants.FIVE_INT == type){
			cancel.setDeptNo(tInsuranceDetail.getDeptNo());
			cancel.setInsDetailId(tInsuranceDetail.getId());
			cancel.setSettleId(tInsuranceDetail.getDefaultSettleId());
			cancel.setCreateUesr(user.getId());
			cancel.setCreateTime(LocalDateTime.now());
			cancel.setDeptName(param.getDeptName());
			cancel.setIsCancelPush(CommonConstants.ZERO_INT);
			tInsuranceSettleCancelService.save(cancel);
			param.setInteractiveType(InsurancesConstants.ABOLISH_SETTLE_BILL);
			param.setSettleType(CommonConstants.EMPTY_STRING);
			pushType = CommonConstants.FOUR_INT;
		}
		String s = eKPInsuranceUtil.sendToEkp(param);
		if(StringUtils.isBlank(s)){
			saveInsuranceEkp(param,pushType);
			return null;
		}else {
			return s;
		}
	}

	/**
	 * 获取当前保单的结算状态
	 *
	 * @author zhaji
	 * @param
	 * @return {@link String}
	 */
	@Override
	public SettleVo getInsuranceDetailSettleStatus(String detailId,String settleId){
		String id = detailId+CommonConstants.DOWN_LINE_STRING+settleId;
		//获取ekp结算信息
		return ekpSettleService.getSettle(id);
	}

	/**
	 * 保存失败信息
	 *
	 * @author zhaji
	 * @param
	 * @return {@link String}
	 */
	public Boolean saveInsuranceEkp(EkpInteractiveParam param, Integer pushType){
		TInsuranceEkp ekp = new TInsuranceEkp();
		BeanCopyUtils.copyProperties(param,ekp);
		ekp.setId(null);
		ekp.setCreateTime(LocalDateTime.now());
		ekp.setPushType(pushType);
		TInsuranceDetail byId = getById(param.getDetailId());
		ekp.setSettleType(byId.getSettleType().toString());
		tInsuranceEkpService.save(ekp);
		return Boolean.TRUE;
	}

	//商险预估
	public void createInsuranceInfo(TInsuranceDetail insuranceDetail) {
		//获取项目信息
		TSettleDomain settleDomain = new TSettleDomain();
		List<TSettleDomainSelectVo> settleDomainR;
		R<TSettleDomainListVo> listVo;
		listVo = archivesDaprUtil.selectSettleDomainSelectVoByNo(insuranceDetail.getDeptNo());
		if (Common.isNotNull(listVo)) {
			TSettleDomainListVo tSettleDomainListVo = listVo.getData();
			if (Common.isNotNull(tSettleDomainListVo) && Common.isNotEmpty(tSettleDomainListVo.getListSelectVO())) {
				settleDomainR = tSettleDomainListVo.getListSelectVO();
				for (TSettleDomainSelectVo vo :settleDomainR) {
					BeanUtils.copyProperties(vo,settleDomain);
				}
			}
		}
		//判断是否存在当月的商险收入数据
		Boolean isExist = false;
		List<TIncomeDetail> incomeDetailList = new ArrayList<>();
		TIncomeDetail incomeDetail = new TIncomeDetail();
		incomeDetail.setEmpIdcard(insuranceDetail.getEmpIdcardNo());
		incomeDetail.setCreateMonth(DateUtil.getYearAndMonth(insuranceDetail.getHandledTime(),0));
		incomeDetail.setDeptNo(insuranceDetail.getDeptNo());
		incomeDetail.setSourceType(CommonConstants.THREE_STRING);
		R<TIncomeDetailReturnVo> detailList = socialDaprUtils.getTIncomeDetailList(incomeDetail);
		if(Common.isNotNull(detailList) && detailList.getCode() == CommonConstants.SUCCESS
				&& !detailList.getData().getDetailList().isEmpty()){
			incomeDetailList = detailList.getData().getDetailList();
			BigDecimal sumMoney = BigDecimal.ZERO;
			for (TIncomeDetail income : incomeDetailList) {
				sumMoney = BigDecimalUtils.safeAdd(income.getMoney(), sumMoney);
			}
			if (sumMoney.compareTo(BigDecimal.ZERO) > 0) {
				isExist = true;
			}
		}

		//预估或者实缴保费
		BigDecimal fee;
		if (CommonConstants.ONE_INT == insuranceDetail.getSettleType()) {
			fee = insuranceDetail.getActualPremium();
		} else {
			fee = insuranceDetail.getEstimatePremium();
		}

		//判断是否为按人次收费
		int isSum = 0;
		if (Common.isNotNull(settleDomain)) {
			// 含有商险，则计算收入
			if (Common.isNotNull(settleDomain.getManageServerItem()) && settleDomain.getManageServerItem()
					.contains(CommonConstants.THREE_STRING)) {
				//预估模式
				if (CommonConstants.ZERO_STRING.equals(settleDomain.getManagementTag())) {
					if (CommonConstants.ONE_STRING.equals(settleDomain.getMrSettleType())) {
						//预估模式只有按人次和人数收费
						if (CommonConstants.THREE_STRING.equals(settleDomain.getManagementType())) {
							if (Common.isNotNull(incomeDetailList)) {
								for (TIncomeDetail incomeDetailSum: incomeDetailList) {
									if (!(incomeDetailSum.getSourceId().equals(insuranceDetail.getId()) &&
											CommonConstants.ONE_STRING.equals(incomeDetailSum.getFeeType()) &&
											CommonConstants.ONE_STRING.equals(incomeDetailSum.getMrSettleType()))) {
										isSum = 1;
										break;
									}
								}
							}
						}
						if (!isExist || isSum == 1) {
							createIncomeInsurance(insuranceDetail, settleDomain, CommonConstants.ONE_STRING,
									settleDomain.getManagementFee().toString(), settleDomain.getManagementType(),
									settleDomain.getManagementFee());
						}
					} else {
						BigDecimal gMoney;
						if (CommonConstants.TWO_STRING.equals(settleDomain.getManagementType())) {
							gMoney = settleDomain.getManagementFee();
						} else if (CommonConstants.THREE_STRING.equals(settleDomain.getManagementType())) {
							gMoney = settleDomain.getManagementFee();
							if (Common.isNotNull(incomeDetailList)) {
								for (TIncomeDetail incomeDetailSum: incomeDetailList) {
									if (incomeDetailSum.getSourceId().equals(insuranceDetail.getId()) &&
											CommonConstants.ONE_STRING.equals(incomeDetailSum.getFeeType()) &&
											CommonConstants.TWO_STRING.equals(incomeDetailSum.getMrSettleType()) &&
											CommonConstants.THREE_STRING.equals(incomeDetailSum.getFeeMode())) {
										isSum = 6;
										break;
									} else {
										isSum = 2;
									}
								}
							}
						} else {
							isSum = 2;
							gMoney = BigDecimalUtils.safeMultiply(fee, settleDomain.getManagementFee().divide(
									new BigDecimal("100"), CommonConstants.FIVE_INT, BigDecimal.ROUND_HALF_UP));
						}
						if (!isExist || isSum == 2) {
							createIncomeInsurance(insuranceDetail, settleDomain, CommonConstants.ONE_STRING,
									settleDomain.getManagementFee().toString(), settleDomain.getManagementType(), gMoney);
						}
					}
				}
			}
			if (Common.isNotNull(settleDomain.getRiskServerItem()) && settleDomain.getRiskServerItem()
					.contains(CommonConstants.THREE_STRING)) {
				//预估模式
				if (CommonConstants.ZERO_STRING.equals(settleDomain.getRiskFundTag())) {
					if (CommonConstants.ONE_STRING.equals(settleDomain.getMrSettleType())) {
						if (CommonConstants.THREE_STRING.equals(settleDomain.getRiskFundType())) {
							if (Common.isNotNull(incomeDetailList)) {
								for (TIncomeDetail incomeDetailSum: incomeDetailList) {
									if (!(incomeDetailSum.getSourceId().equals(insuranceDetail.getId()) &&
											CommonConstants.TWO_STRING.equals(incomeDetailSum.getFeeType()) &&
											CommonConstants.ONE_STRING.equals(incomeDetailSum.getMrSettleType()))) {
										isSum = 3;
										break;
									}
								}
							}
						}
						if (!isExist || isSum == 3) {
							createIncomeInsurance(insuranceDetail, settleDomain, CommonConstants.TWO_STRING,
									settleDomain.getRiskFundFee().toString(), settleDomain.getRiskFundType(),
									settleDomain.getRiskFundFee());
						}
					} else {
						if (CommonConstants.ZERO_STRING.equals(settleDomain.getRiskFundTag())) {
							BigDecimal money;
							if (CommonConstants.TWO_STRING.equals(settleDomain.getRiskFundType())) {
								money = settleDomain.getRiskFundFee();
							} else if (CommonConstants.THREE_STRING.equals(settleDomain.getRiskFundType())) {
								money = settleDomain.getRiskFundFee();
								if (Common.isNotNull(incomeDetailList)) {
									for (TIncomeDetail incomeDetailSum: incomeDetailList) {
										if (incomeDetailSum.getSourceId().equals(insuranceDetail.getId()) &&
												CommonConstants.TWO_STRING.equals(incomeDetailSum.getFeeType()) &&
												CommonConstants.TWO_STRING.equals(incomeDetailSum.getMrSettleType()) &&
												CommonConstants.THREE_STRING.equals(incomeDetailSum.getFeeMode())) {
											isSum = 5;
											break;
										} else {
											isSum = 4;
										}
									}
								}
							} else {
								isSum = 4;
								money = BigDecimalUtils.safeMultiply(fee, settleDomain.getRiskFundFee().divide(
										new BigDecimal("100"), CommonConstants.FIVE_INT, BigDecimal.ROUND_HALF_UP));
							}
							if (!isExist || isSum == 4) {
								createIncomeInsurance(insuranceDetail, settleDomain, CommonConstants.TWO_STRING,
										settleDomain.getRiskFundFee().toString(), settleDomain.getRiskFundType(), money);
							}
						}
					}
				}
			}
		}
	}

	public void createIncomeInsurance(TInsuranceDetail insuranceDetail, TSettleDomain settleDomain, String feeType,
									  String charges, String feeMode, BigDecimal money) {
		//生成收入数据
		TIncomeDetail detail = new TIncomeDetail();
		detail.setCreateTime(DateUtil.getCurrentDateTime());
		detail.setDeptName(settleDomain.getDepartName());
		detail.setDeptNo(settleDomain.getDepartNo());
		detail.setDeptId(settleDomain.getId());
		detail.setEmpIdcard(insuranceDetail.getEmpIdcardNo());
		detail.setEmpName(insuranceDetail.getEmpName());
		detail.setUnitNo(settleDomain.getCustomerNo());
		detail.setUnitId(settleDomain.getCustomerId());
		detail.setUnitName(settleDomain.getCustomerName());
		detail.setDataCreateMonth(DateUtil.addMonth(0));
		detail.setSourceId(insuranceDetail.getId());
		detail.setSourceType(CommonConstants.THREE_STRING);
		detail.setCreateMonth(DateUtil.addMonth(0));
		detail.setPayMonth(DateUtil.addMonth(0));
		detail.setMoney(money);
		detail.setFeeType(feeType);
		detail.setFeeMode(feeMode);
		detail.setCharges(charges);
		detail.setMrSettleType(settleDomain.getMrSettleType());
		detail.setId(CommonConstants.NULL);
		detail.setRedData(CommonConstants.ZERO_STRING);
		socialDaprUtils.createTIncomeDetail(detail);
	}

	//更新收入信息
	public void updateInsuranceInfo(TInsuranceDetail insuranceDetail) {
		TIncomeDetail incomeDetail = new TIncomeDetail();
		incomeDetail.setSourceId(insuranceDetail.getId());
		R<TIncomeDetailReturnVo> detailList = socialDaprUtils.getTIncomeDetailList(incomeDetail);
		if (Common.isNotNull(detailList) && detailList.getCode() == CommonConstants.SUCCESS) {
			for (TIncomeDetail detail : detailList.getData().getDetailList()) {
				TIncomeDetail detail1 = new TIncomeDetail();
				BeanCopyUtils.copyProperties(detail, detail1);
				detail1.setId(CommonConstants.NULL);
				detail1.setRedData(CommonConstants.ONE_STRING);
				detail1.setMoney(detail1.getMoney().negate());
				socialDaprUtils.createTIncomeDetail(detail1);
			}
		}
	}
}
