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

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
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.admin.api.entity.SysUser;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.SysUserListVo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TSettleDomain;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ClientNameConstants;
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.exception.CheckedException;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.util.equator.HrEquator;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.BaseSearchListVO;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.BaseSearchVO;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.BaseServiceParamListVO;
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.mybatis.base.BaseEntity;
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.insurances.config.WxConfig;
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.ekp.EkpInsurancesInfoMapper;
import com.yifu.cloud.plus.v1.yifu.insurances.mapper.insurances.*;
import com.yifu.cloud.plus.v1.yifu.insurances.service.TInsuranceAreaResService;
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.BigDecimalUtils;
import com.yifu.cloud.plus.v1.yifu.insurances.util.*;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.*;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryAccount;
import com.yifu.cloud.plus.v1.yifu.salary.vo.SalaryRiskListVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.SalaryRiskVo;
import com.yifu.cloud.plus.v1.yifu.social.entity.TIncomeDetail;
import com.yifu.cloud.plus.v1.yifu.social.vo.ChangeDeptDetailVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.ChangeDeptVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TEmployeeInsuranceWorkDayVo;
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.lang.ArrayUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.alibaba.fastjson.serializer.SerializerFeature.*;

/**
 * @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 EkpSettleService ekpSettleService;

	@Resource
	private TInsuranceSettleCancelService tInsuranceSettleCancelService;

	@Resource
	private SocialDaprUtils socialDaprUtils;

	@Resource
	private ArchivesDaprUtil archivesDaprUtils;

	@Resource
	private MenuUtil menuUtil;
	@Resource
	private DaprArchivesProperties daprArchivesProperties;
	@Resource
	@Lazy
	private DoJointInsuranceTask doJointInsuranceTask;
	@Resource
	private TInsurancePolicyService tInsurancePolicyService;
	@Resource
	private TBusinessOperateService tBusinessOperateService;
	@Resource
	private  TInsuranceAreaResService tInsuranceAreaResService;
	@Resource
	private TUpdateStatusErrorMapper updateStatusErrorMapper;
	@Resource
	private TInsuranceAreaResMapper insuranceAreaResMapper;
	@Resource
	private TEmployeeInsurancePreMapper employeeInsurancePreMapper;
	@Resource
	private TInsurancePreRenewDetailMapper tInsurancePreRenewDetailMapper;
	@Resource
	private TInsuranceWarnMapper tInsuranceWarnMapper;
	@Resource
	private TInsurancesChangeLogService insurancesChangeLogService;

	@Resource
	private TInsurancePreRenewDetailQwService tInsurancePreRenewDetailQwService;
	@Resource
	private TInsurancePreRenewDetailQwDetailService tInsurancePreRenewDetailQwDetailService;

	@Autowired
	private UpmsDaprUtils upmsDaprUtils;

	@Autowired
	private WxConfig wxConfig;

	@Autowired
	private CspDaprUtils cspDaprUtil;

	@Autowired
	private EkpInsurancesInfoMapper ekpInsurancesInfoMapper;


	/***********************商险办理********************************/
	/**
	 * 每日定时刷新商险到期数据
	 *
	 * @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<String> sourceIdCardList = new ArrayList<>();
			List<String> replaceIdList = new ArrayList<>();
			List<TInsuranceDetail> changeList = new ArrayList<>();
			list.forEach(e -> {
				if (!LocalDateUtil.isOverdueDate(e.getPolicyEnd().toString())){
					e.setIsOverdue(CommonConstants.ONE_INT);
					e.setUpdateTime(LocalDateTime.now());
					if (Common.isEmpty(e.getBuyHandleStatus()) || e.getBuyHandleStatus() != CommonConstants.FOUR_INT) {
						changeList.add(e);
						sourceIdCardList.add(e.getEmpIdcardNo());
						replaceIdList.add(e.getId());
					}
				}
			});

			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);
			}
			this.doFailInfo(changeList, sourceIdCardList, replaceIdList, CommonConstants.THREE_STRING);
		}
	}

	/**
	 * 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().forEach(e -> e.setBuyMonth(null==e.getPurchaseCycle()?String.valueOf(LocalDateUtil.betweenMonth(e.getPolicyStart().toString(),e.getPolicyEnd().toString())):(e.getPurchaseCycle().indexOf("个月")==-1?e.getPurchaseCycle():e.getPurchaseCycle().indexOf("个月")==-1?e.getPurchaseCycle():e.getPurchaseCycle().substring(0,e.getPurchaseCycle().indexOf("个月")))));
		}
		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 = baseMapper.getInsuranceList(param);
		// 购买月数
		if (CollectionUtils.isNotEmpty(insuranceList)){
			insuranceList.forEach(e -> e.setBuyMonth(null==e.getPurchaseCycle()?String.valueOf(LocalDateUtil.betweenMonth(e.getPolicyStart().toString(),e.getPolicyEnd().toString())):(e.getPurchaseCycle().indexOf("个月")==-1?e.getPurchaseCycle():e.getPurchaseCycle().indexOf("个月")==-1?e.getPurchaseCycle():e.getPurchaseCycle().substring(0,e.getPurchaseCycle().indexOf("个月")))));
			TInsuranceOperate tInsuranceOperate;
			for (InsuranceListVO listVO : insuranceList) {
				if (CommonConstants.FOUR_INT == listVO.getBuyHandleStatus()) {
					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().forEach(e -> e.setBuyMonth(null==e.getPurchaseCycle()?String.valueOf(LocalDateUtil.betweenMonth(e.getPolicyStart().toString(),e.getPolicyEnd().toString())):(e.getPurchaseCycle().indexOf("个月")==-1?e.getPurchaseCycle():e.getPurchaseCycle().indexOf("个月")==-1?e.getPurchaseCycle():e.getPurchaseCycle().substring(0,e.getPurchaseCycle().indexOf("个月")))));
		}
		return insuranceList;
	}

	/**
	 * 商险新增
	 *
	 * @param paramList
	 * @param autoFlag true 自动化 false 非自动还
	 * @return {@link R <List<InsuranceAddParam>>}
	 * @author licancan
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R<List<InsuranceAddParam>> addInsurance(List<InsuranceAddParam> paramList,String orderNo,boolean autoFlag) {
		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();
		Map<String,TSettleDomainSelectVo> mapSelectVo = new HashMap<>();
		Map<String, List<InsuranceAddParam>> map = addInsuranceCheck(paramList,user,autoFlag,mapSelectVo);
		//返回给前端的结果
		List<InsuranceAddParam> listResult = map.get("listResult");
		//保存到数据库中的结果
		List<InsuranceAddParam> listSuccess = map.get("listSuccess");
		List<TInsuranceDetail> detailList = new ArrayList<>();
		boolean isAuto = false;
		List<TInsuranceOperate> operateList = new ArrayList<>();
		//先获取必要的数据避免过程异常不好处理
		Date preDispatchDate = DateUtil.formatDateByPatten(new Date(), DateUtil.ISO_EXPANDED_DATE_FORMAT);
		TEmployeeInsuranceWorkDayVo dayVo = null;
		LocalTime currentTime = LocalTime.now();
		R<TEmployeeInsuranceWorkDayVo> dataR;
		if (!currentTime.isBefore(LocalTime.of(15, 20)) && !currentTime.equals(LocalTime.of(15, 20))) {
			preDispatchDate = DateUtil.addDayByDate(preDispatchDate, 1);
		}
		//日期赋值
		dayVo = new TEmployeeInsuranceWorkDayVo();
		dayVo.setType(CommonConstants.TWO_STRING);
		dayVo.setRegistDate(preDispatchDate);
		try {
			dataR = socialDaprUtils.getBeforeOrAfterWorkDay(dayVo);
			if (Common.isNotNull(dataR)
					&& Common.isNotNull(dataR.getData())
					&& Common.isNotNull(dataR.getData().getRegistDate())) {
				preDispatchDate = dataR.getData().getPriDisDate();
			} else {
				return R.failed("获取最近工作日失败！");
			}
		}catch (Exception e){
			return R.failed("获取最近工作日异常："+e.getMessage());
		}
		if (CollectionUtils.isNotEmpty(listSuccess)){
			List<TInsuranceSettle> settleList = new ArrayList<>();
			List<String> sourceIdCardList = new ArrayList<>();
			List<TInsuranceDetail> pushList = new ArrayList<>();
			for (InsuranceAddParam success : listSuccess) {
				TInsuranceDetail detail = new TInsuranceDetail();
				BeanCopyUtils.copyProperties(success,detail);
				//购买类型，默认为「新增」
				detail.setOrderNo(orderNo);
				detail.setBuyType(CommonConstants.ONE_INT);
				if (Common.isNotNull(user)) {
					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(null == user ? "1" : user.getId());
				detail.setCreateName(null == user ? "自动化派单" + "-" + success.getCustomerUserName() : user.getNickname());
				detail.setId(RandomStringUtils.randomNumeric(19));
				//是否见费出单逻辑处理：预估保费结算、购买周期计算、保单结束日期结算、参保开始日期计算、预计办理日期计算
				initJfcdInfo(preDispatchDate, detail,settleList);
				detailList.add(detail);
				sourceIdCardList.add(detail.getEmpIdcardNo());
				baseMapper.insert(detail);
				if (CommonConstants.ZERO_STRING.equals(detail.getIsJfcd())){
					pushList.add(detail);
					updateEmployeeInsurancePre(success.getInsurancePreId(),detail,CommonConstants.SEVEN_STRING);
					updateEmployeeInsurancePreRenew(success.getInsurancePreRenewId(),detail,CommonConstants.SEVEN_STRING);
				}else {
					updateEmployeeInsurancePre(success.getInsurancePreId(),detail,CommonConstants.THREE_STRING);
					updateEmployeeInsurancePreRenew(success.getInsurancePreRenewId(),detail,CommonConstants.THREE_STRING);
				}


				if (isAuto || Common.isNotNull(success.getCustomerUserName())) {
					isAuto = true;
					operateList.add(addOperateNewUserName(detail.getId(), "自动化派单-" + success.getCustomerUserName()
							,InsurancesConstants.ADD,null,CommonConstants.ONE_INT));
				}
			}
			if (Common.isNotNull(pushList)){
				for (TInsuranceDetail detail : pushList){
					//生成收入数据
					createInsuranceInfo(detail,mapSelectVo.get(detail.getDeptNo()));
				}
				//异步任务推送
				doJointInsuranceTask.pushEstime(pushList);
			}
			List<String> replaceIdList = new ArrayList<>();
			for (TInsuranceDetail d : detailList) {
				replaceIdList.add(d.getId());
			}
			// 同步操作档案的 商险状态为：2正常（0无2正常3失效4处理中）
			this.doFailInfo(detailList, sourceIdCardList, replaceIdList, CommonConstants.FOUR_STRING);

			//插入结算数据
			/*if (!settleList.isEmpty()) {
				tInsuranceSettleService.saveBatch(settleList);
				settleList.clear();
			}*/
		}
		//操作记录
		if (!isAuto) {
			addOperate(detailList, user, InsurancesConstants.ADD, null, CommonConstants.ONE_INT);
		} else {
			if (operateList != null && !operateList.isEmpty()) {
				tInsuranceOperateService.saveBatch(operateList);
			}
		}
		//派单失败更新商险待购买数据
		if (CollectionUtils.isNotEmpty(listResult)){
			List<InsuranceAddParam> listUpdateResult = listResult.stream().filter(e -> e.getIsExit() == null)
					.collect(Collectors.toList());
			if (CollectionUtils.isNotEmpty(listUpdateResult)) {
				List<String> idList = new ArrayList<>();
				List<String> idRenewList = new ArrayList<>();
				for (InsuranceAddParam addParam : listResult) {
					if (Common.isNotNull(addParam.getInsurancePreId())) {
						idList.add(addParam.getInsurancePreId());
					}
					if (Common.isNotNull(addParam.getInsurancePreRenewId())) {
						idRenewList.add(addParam.getInsurancePreRenewId());
					}
				}
				if (!idList.isEmpty()) {
					updateEmployeeInsurancePre(idList);
				}
				if (!idRenewList.isEmpty()) {
					updateEmployeeInsurancePreRenew(idRenewList);
				}
			}
			return R.other(listResult,InsurancesConstants.ADD_SUCCESS,CommonConstants.TWO_INT);
		} else {
			return R.ok(null,InsurancesConstants.ADD_SUCCESS);
		}
	}

	private void initJfcdInfo(Date preDispatchDate, TInsuranceDetail detail,List<TInsuranceSettle> settleList) {
		//购买周期
		long purchaseCycle = 0;
		LocalDate buyStartDate;
		//计算预计办理日期：若派单当日为工作日3点20之前，则预计办理日期为派单日期,若为3点20之后或派单日为非工作日，则预计办理日期为派单日后最近的一个工作日
		detail.setPreHandleTime(LocalDateUtil.parseLocalDate(DateUtil.formatDate(preDispatchDate)));

		//计算参保开始日期：新增\批增\替换的参保开始日期=MAX("保单开始时间"、"预计办理日期+1日")；
		if (detail.getPolicyStart().isAfter(detail.getPreHandleTime().plusDays(1))){
			buyStartDate = detail.getPolicyStart();
		}else {
			buyStartDate = detail.getPreHandleTime().plusDays(1);
		}
		if (null != detail.getPolicyEnd() && null != buyStartDate){
			purchaseCycle = LocalDateUtil.betweenMonth(buyStartDate.toString(),detail.getPolicyEnd().toString());
		}
		//计算购买周期：购买周期=保单结束日期-参保开始日期+1（天数）；购买周期=保单结束日期-参保开始日期+1（天数）推算出月数；
		//按天计费方式
		long day = LocalDateUtil.betweenDay(buyStartDate.toString(),detail.getPolicyEnd().toString());
		if (null != detail.getBillingType() && CommonConstants.ZERO_INT == detail.getBillingType().intValue()){
			//计算预计保费：根据计费方式、购买标准、购买天数/月数等计算：
			//“计费方式”为“按天”的，预估保费=购买周期天数/365*购买标准+5元；
			//“计费方式”为“按月”的，预估保费=购买周期月数对应的费率*购买标准+5元
			//按天计费方式
			detail.setEstimatePremium(new BigDecimal(detail.getBuyStandard())
					.multiply(new BigDecimal(day))
					.divide(new BigDecimal("365"), 2, RoundingMode.HALF_UP)
					.add(new BigDecimal("5.00")));
		//按月计费方式
		}else if (null != detail.getBillingType() && CommonConstants.ONE_INT == detail.getBillingType().intValue()){
			TInsuranceTypeRate typeRate = tInsuranceTypeRateService.getOne(Wrappers.<TInsuranceTypeRate>query().lambda()
					.eq(TInsuranceTypeRate::getInsuranceTypeId, detail.getInsuranceTypeId())
					.eq(TInsuranceTypeRate::getMonth, purchaseCycle)
					.eq(TInsuranceTypeRate::getDeleteFlag, CommonConstants.ZERO_INT)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (null != typeRate){
				detail.setRate(new BigDecimal(typeRate.getRate()));
			}
			detail.setEstimatePremium(new BigDecimal(detail.getBuyStandard())
					.multiply(null== detail.getRate()?BigDecimal.ZERO: detail.getRate())
					.add(new BigDecimal("5.00")));
		}
		//v1.7.21 如果预估报废大于购买标准，则预估保费=购买标准
		if (detail.getEstimatePremium() != null && detail.getBuyStandard() != null) {
			try {
				String buyStandardStr = detail.getBuyStandard().trim();
				if (!buyStandardStr.isEmpty()) {
					BigDecimal buyStandard = new BigDecimal(buyStandardStr);
					if (detail.getEstimatePremium().compareTo(buyStandard) > 0) {
						detail.setEstimatePremium(buyStandard);
					}
				} else {
					log.warn("购买标准为空字符串，跳过设置预估保费");
				}
			} catch (NumberFormatException e) {
				log.error("设置预估保费时发生异常，购买标准格式无效：{}, 预估保费：{}",
						  detail.getBuyStandard(), detail.getEstimatePremium(), e);
			}
		}

		//购买周期
		detail.setPurchaseCycle(purchaseCycle+"个月/"+day+"天");
		if (CommonConstants.ZERO_STRING.equals(detail.getIsJfcd())){
			//预估缴费状态 0待缴费、1已缴费
			detail.setPaymentStatus(CommonConstants.ZERO_STRING);
			detail.setBuyHandleStatus(CommonConstants.SIX_INT);
			//保费存储
			TInsuranceSettle settle = new TInsuranceSettle();
			settle.setInsDetailId(detail.getId());
			settle.setSettleType(detail.getSettleType());
			settle.setSettleHandleStatus(CommonConstants.ONE_STRING);
			settle.setCreateTime(LocalDateTime.now());
			settle.setEstimatePushTime(LocalDateTime.now());
			settle.setEstimatePremium(detail.getEstimatePremium());
			//调完ekp接口才会是1
			settle.setIsEstimatePush(CommonConstants.ZERO_INT);
			settle.setId(RandomStringUtils.randomNumeric(19));
			tInsuranceSettleService.save(settle);
			detail.setDefaultSettleId(settle.getId());
		}else {
			detail.setEstimatePremium(BigDecimal.ZERO);
		}
	}

	/**
	 * 商险批增
	 *
	 * @param paramList
	 * @param autoFlag true 自动化 false 非自动还
	 * @return {@link R<List<InsuranceBatchParam>>}
	 * @author licancan
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R<List<InsuranceBatchParam>> batchInsurance(List<InsuranceBatchParam> paramList,String orderNo,boolean autoFlag) {
		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);
		}
		//先获取必要的数据避免过程异常不好处理
		Date preDispatchDate = DateUtil.formatDateByPatten(new Date(), DateUtil.ISO_EXPANDED_DATE_FORMAT);
		TEmployeeInsuranceWorkDayVo dayVo = null;
		LocalTime currentTime = LocalTime.now();
		R<TEmployeeInsuranceWorkDayVo> dataR;
		if (!currentTime.isBefore(LocalTime.of(15, 20)) && !currentTime.equals(LocalTime.of(15, 20))) {
			preDispatchDate = DateUtil.addDayByDate(preDispatchDate, 1);
		}
		//日期赋值
		dayVo = new TEmployeeInsuranceWorkDayVo();
		dayVo.setType(CommonConstants.TWO_STRING);
		dayVo.setRegistDate(preDispatchDate);
		try {
			dataR = socialDaprUtils.getBeforeOrAfterWorkDay(dayVo);
			if (Common.isNotNull(dataR)
					&& Common.isNotNull(dataR.getData())
					&& Common.isNotNull(dataR.getData().getRegistDate())) {
				preDispatchDate = dataR.getData().getPriDisDate();
			} else {
				return R.failed("获取最近工作日失败！");
			}
		}catch (Exception e){
			return R.failed("获取最近工作日异常："+e.getMessage());
		}
		YifuUser user = SecurityUtils.getUser();
		Map<String,TSettleDomainSelectVo> mapSelectVo = new HashMap<>();
		Map<String, List<InsuranceBatchParam>> map = batchInsuranceCheck(paramList,user,autoFlag,mapSelectVo);
		//返回给前端的结果
		List<InsuranceBatchParam> listResult = map.get("listResult");
		//保存到数据库中的结果
		List<InsuranceBatchParam> listSuccess = map.get("listSuccess");
		List<TInsuranceDetail> detailList = new ArrayList<>();
		boolean isAuto = false;
		List<TInsuranceOperate> operateList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(listSuccess)){
			TInsuranceDetail detail;
			List<String> sourceIdCardList = new ArrayList<>();
			List<String> replaceIdList = new ArrayList<>();
			List<TInsuranceSettle> settleList = new ArrayList<>();
			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);
				if (Common.isNotNull(user)) {
					detail.setCreateUserDeptId(user.getDeptId().toString());
					detail.setCreateUserDeptName(user.getDeptName());
				}
				detail.setActualPremium(new BigDecimal("0.00"));
				detail.setEstimatePremium(new BigDecimal("0.00"));
				detail.setCreateBy(null == user ? "1" : user.getId());
				detail.setCreateName(null == user ? "自动化派单" + "-" + success.getCustomerUserName()  : user.getNickname());
				detailList.add(detail);
				sourceIdCardList.add(detail.getEmpIdcardNo());
				replaceIdList.add(detail.getId());
				//是否见费出单逻辑处理：预估保费结算、购买周期计算、保单结束日期结算、参保开始日期计算、预计办理日期计算
				initJfcdInfo(preDispatchDate, detail,settleList);
				baseMapper.insert(detail);
				if (CommonConstants.ZERO_STRING.equals(detail.getIsJfcd())){
					//生成收入数据
					createInsuranceInfo(detail,mapSelectVo.get(detail.getDeptNo()));
					updateEmployeeInsurancePre(success.getInsurancePreId(),detail,CommonConstants.SEVEN_STRING);
					updateEmployeeInsurancePreRenew(success.getInsurancePreRenewId(),detail,CommonConstants.SEVEN_STRING);
					//异步任务推送
					List<TInsuranceDetail> successList = new ArrayList<>();
					successList.add(detail);
					doJointInsuranceTask.pushEstime(successList);
				}else {
					updateEmployeeInsurancePre(success.getInsurancePreId(),detail,CommonConstants.THREE_STRING);
					updateEmployeeInsurancePreRenew(success.getInsurancePreRenewId(),detail,CommonConstants.THREE_STRING);
				}


				if (isAuto || Common.isNotNull(success.getCustomerUserName())) {
					isAuto = true;
					operateList.add(addOperateNewUserName(detail.getId(), "自动化派单-" + success.getCustomerUserName()
							,InsurancesConstants.BATCH,null,CommonConstants.ONE_INT));
				}
			}
			// 同步操作档案的 商险状态为：2正常（0无2正常3失效4处理中）
			this.doFailInfo(detailList, sourceIdCardList, replaceIdList, CommonConstants.FOUR_STRING);
			//插入结算数据
			/*if (!settleList.isEmpty()) {
				tInsuranceSettleService.saveBatch(settleList);
				settleList.clear();
			}*/
		}
		//操作记录
		if (!isAuto) {
			addOperate(detailList, user, InsurancesConstants.BATCH, null, CommonConstants.ONE_INT);
		} else {
			if (operateList != null && !operateList.isEmpty()) {
				tInsuranceOperateService.saveBatch(operateList);
			}
		}
		//派单失败更新商险待购买数据
		if (CollectionUtils.isNotEmpty(listResult)){
			List<InsuranceBatchParam> listUpdateResult = listResult.stream().filter(e -> e.getIsExit() == null)
					.collect(Collectors.toList());
			if (CollectionUtils.isNotEmpty(listUpdateResult)) {
				List<String> idList = new ArrayList<>();
				List<String> idRenewList = new ArrayList<>();
				for (InsuranceBatchParam addParam : listResult) {
					if (Common.isNotNull(addParam.getInsurancePreId())) {
						idList.add(addParam.getInsurancePreId());
					}
					if (Common.isNotNull(addParam.getInsurancePreRenewId())) {
						idRenewList.add(addParam.getInsurancePreRenewId());
					}
				}
				if (!idList.isEmpty()) {
					updateEmployeeInsurancePre(idList);
				}
				if (!idRenewList.isEmpty()) {
					updateEmployeeInsurancePreRenew(idRenewList);
				}
			}
			return R.other(listResult,InsurancesConstants.BATCH_SUCCESS,CommonConstants.TWO_INT);
		} else {
			return R.ok(null,InsurancesConstants.BATCH_SUCCESS);
		}
	}

	/**
	 * 商险替换
	 *
	 * @param paramList
	 * @param autoFlag true 自动化 false 非自动还
	 * @return {@link R<List<InsuranceReplaceParam>>}
	 * @author licancan
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R<List<InsuranceReplaceParam>> replaceInsurance(List<InsuranceReplaceParam> paramList,String orderNo,boolean autoFlag) {
		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();
		Date preDispatchDate = DateUtil.formatDateByPatten(new Date(), DateUtil.ISO_EXPANDED_DATE_FORMAT);
		TEmployeeInsuranceWorkDayVo dayVo = null;
		LocalTime currentTime = LocalTime.now();
		R<TEmployeeInsuranceWorkDayVo> dataR;
		if (!currentTime.isBefore(LocalTime.of(15, 20)) && !currentTime.equals(LocalTime.of(15, 20))) {
			preDispatchDate = DateUtil.addDayByDate(preDispatchDate, 1);
		}
		//日期赋值
		dayVo = new TEmployeeInsuranceWorkDayVo();
		dayVo.setType(CommonConstants.TWO_STRING);
		dayVo.setRegistDate(preDispatchDate);
		try {
			dataR = socialDaprUtils.getBeforeOrAfterWorkDay(dayVo);
			if (Common.isNotNull(dataR)
					&& Common.isNotNull(dataR.getData())
					&& Common.isNotNull(dataR.getData().getRegistDate())) {
				preDispatchDate = dataR.getData().getPriDisDate();
			} else {
				return R.failed("获取最近工作日失败！");
			}
		}catch (Exception e){
			return R.failed("获取最近工作日异常："+e.getMessage());
		}
		Map<String, List<InsuranceReplaceParam>> map = replaceInsuranceCheck(paramList,user,autoFlag);
		//返回给前端的结果
		List<InsuranceReplaceParam> listResult = map.get("listResult");
		//保存到数据库中的结果
		List<InsuranceReplaceParam> listSuccess = map.get("listSuccess");
		List<TInsuranceDetail> detailList = new ArrayList<>();
		TInsuranceType insuranceType;
		TInsuranceCompany insuranceCompany;
		boolean isAuto = false;
		List<TInsuranceOperate> operateList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(listSuccess)){
			for (InsuranceReplaceParam success : listSuccess) {
				//替换
				TInsuranceDetail newDetail  = new TInsuranceDetail();
				//原数据置为无效：姓名 + 身份证号 + 项目编码 + 保险公司 + 险种名称 + 保单开始时间 + 保单结束时间 + 购买标准 + 有效
				TInsuranceDetail detail = success.getDetail();
				BeanCopyUtils.copyProperties(detail,newDetail);
				detail.setIsEffect(CommonConstants.ONE_INT);
				detail.setIsOverdue(null);
				detail.setUpdateTime(LocalDateTime.now());
				this.updateById(detail);
				// 保险公司-险种-购买标准 是否存在
				insuranceCompany = tInsuranceCompanyService.getOne(Wrappers.<TInsuranceCompany>query().lambda()
						.eq(TInsuranceCompany::getCompanyName, detail.getInsuranceCompanyName())
						.eq(TInsuranceCompany::getDeleteFlag, CommonConstants.ZERO_INT)
						.last(CommonConstants.LAST_ONE_SQL)
				);
				if (Optional.ofNullable(insuranceCompany).isPresent()) {
					insuranceType = tInsuranceTypeService.getOne(Wrappers.<TInsuranceType>query().lambda()
							.eq(TInsuranceType::getName, detail.getInsuranceTypeName())
							.eq(TInsuranceType::getInsuranceCompanyId, insuranceCompany.getId())
							.eq(TInsuranceType::getDeleteFlag, CommonConstants.ZERO_INT)
							.eq(TInsuranceType::getEnable, CommonConstants.ZERO_INT)
							.last(CommonConstants.LAST_ONE_SQL)
					);
					if (Optional.ofNullable(insuranceType).isPresent()) {
						newDetail.setIsAdress(insuranceType.getIsAdress());
					}
				}
				//新数据置为待办理
				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);
				if (Common.isNotNull(user)) {
					newDetail.setCreateUserDeptId(user.getDeptId().toString());
					newDetail.setCreateUserDeptName(user.getDeptName());
				}
				newDetail.setSignFlag(CommonConstants.ZERO_INT);
				//创建时间是新数据插入时间
				newDetail.setCreateTime(LocalDateTime.now());
				newDetail.setCreateBy(null == user ? "1" : user.getId());
				newDetail.setCreateName(null == user ? "自动化派单" + "-" + success.getCustomerUserName()  : user.getNickname());
				//替换不参与结算
				newDetail.setDefaultSettleId(null);
				//替换不继承备注  20250331 fxj  替换模板新增备注字段不用清空
				//newDetail.setRemark(null);
				//替换不继承保单生效日期
				newDetail.setPolicyEffect(null);
				//保费都默认是0
				newDetail.setActualPremium(new BigDecimal("0.00"));
				newDetail.setEstimatePremium(new BigDecimal("0.00"));
				newDetail.setPreHandleTime(LocalDateUtil.parseLocalDate(DateUtil.formatDate(preDispatchDate)));
				long purchaseCycle = 0;
				LocalDate buyStartDate;
				//计算参保开始日期：新增\批增\替换的参保开始日期=MAX("保单开始时间"、"预计办理日期+1日")；
				if (newDetail.getPolicyStart().isAfter(newDetail.getPreHandleTime().plusDays(1))){
					buyStartDate = newDetail.getPolicyStart();
				}else {
					buyStartDate = newDetail.getPreHandleTime().plusDays(1);
				}
				if (null != newDetail.getPolicyEnd() && null != buyStartDate){
					purchaseCycle = LocalDateUtil.betweenMonth(buyStartDate.toString(),newDetail.getPolicyEnd().toString());
				}
				//计算购买周期：购买周期=保单结束日期-参保开始日期+1（天数）；购买周期=保单结束日期-参保开始日期+1（天数）推算出月数；
				//按天计费方式
				long day = LocalDateUtil.betweenDay(buyStartDate.toString(),newDetail.getPolicyEnd().toString());
				//购买周期
				newDetail.setPurchaseCycle(purchaseCycle+"个月/"+day+"天");
				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(null == user ? "1" : user.getId());
					replace.setCreateName(null == user ? "自动化派单" + "-" + success.getCustomerUserName() : user.getNickname());
					replace.setCreateTime(LocalDateTime.now());
					tInsuranceReplaceService.save(replace);
					updateEmployeeInsurancePre(success.getInsurancePreId(),newDetail,CommonConstants.THREE_STRING);
					updateEmployeeInsurancePreRenew(success.getInsurancePreRenewId(),newDetail,CommonConstants.THREE_STRING);
				}
				detailList.add(newDetail);

				if (isAuto || Common.isNotNull(success.getCustomerUserName())) {
					isAuto = true;
					operateList.add(addOperateNewUserName(detail.getId(), "自动化派单-" + success.getCustomerUserName()
							,InsurancesConstants.REPLACE,null,CommonConstants.ONE_INT));
				}
			}
		}
		//操作记录
		if (!isAuto) {
			addOperate(detailList, user, InsurancesConstants.REPLACE, null, CommonConstants.ONE_INT);
		} else {
			if (operateList != null && !operateList.isEmpty()) {
				tInsuranceOperateService.saveBatch(operateList);
			}
		}
		//派单失败更新商险待购买数据
		if (CollectionUtils.isNotEmpty(listResult)){
			List<InsuranceReplaceParam> listUpdateResult = listResult.stream().filter(e -> e.getIsExit() == null)
					.collect(Collectors.toList());
			if (CollectionUtils.isNotEmpty(listUpdateResult)) {
				List<String> idList = new ArrayList<>();
				List<String> idRenewList = new ArrayList<>();
				for (InsuranceReplaceParam addParam : listResult) {
					if (Common.isNotNull(addParam.getInsurancePreId())) {
						idList.add(addParam.getInsurancePreId());
					}
					if (Common.isNotNull(addParam.getInsurancePreRenewId())) {
						idRenewList.add(addParam.getInsurancePreRenewId());
					}
				}
				if (!idList.isEmpty()) {
					updateEmployeeInsurancePre(idList);
				}
				if (!idRenewList.isEmpty()) {
					updateEmployeeInsurancePreRenew(idRenewList);
				}
			}
			return R.other(listResult,InsurancesConstants.REPLACE_SUCCESS,CommonConstants.TWO_INT);
		} else {
			return R.ok(null,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);
		}
		if (CommonConstants.ZERO_STRING.equals(byId.getIsJfcd())){
			return R.failed(InsurancesConstants.NOT_JFCD_ERROR);
		}
		//校验当前保单信息是否由当前登录人创建
		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()));
				//冗余办理地省、市
				param.setInsuranceHandleProvince(insuranceCompany.getInsuranceHandleProvince());
				param.setInsuranceHandleProvinceName(insuranceCompany.getInsuranceHandleProvinceName());
				param.setInsuranceHandleCity(insuranceCompany.getInsuranceHandleCity());
				param.setInsuranceHandleCityName(insuranceCompany.getInsuranceHandleCityName());

				TInsuranceType insuranceType = tInsuranceTypeService.getOne(Wrappers.<TInsuranceType>query().lambda()
						.eq(TInsuranceType::getName, param.getInsuranceTypeName())
						.eq(TInsuranceType::getInsuranceCompanyId, insuranceCompany.getId())
						.eq(TInsuranceType::getDeleteFlag, CommonConstants.ZERO_INT)
						.eq(TInsuranceType::getEnable, 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)
							.eq(TInsuranceTypeStandard::getEnable, 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())
					.eq(TInsuranceDetail::getBuyStandard, param.getBuyStandard())
					.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);
			}
			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);
			updateEmployeeInsurancePre(null,byId,CommonConstants.THREE_STRING);
			updateEmployeeInsurancePreRenew(null,byId,CommonConstants.THREE_STRING);
			// 同步档案
			List<TInsuranceDetail> detailList = new ArrayList<>();
			detailList.add(byId);
			List<String> sourceIdCardList = new ArrayList<>();
			List<String> replaceIdList = new ArrayList<>();
			sourceIdCardList.add(byId.getEmpIdcardNo());
			replaceIdList.add(byId.getId());
			// 同步操作档案的 商险状态为：2正常（0无2正常3失效4处理中）
			this.doFailInfo(detailList, sourceIdCardList, replaceIdList, CommonConstants.FOUR_STRING);
		}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);
					updateEmployeeInsurancePre(null,byId,CommonConstants.THREE_STRING);
					updateEmployeeInsurancePreRenew(null,byId,CommonConstants.THREE_STRING);

					// 同步档案
					List<TInsuranceDetail> detailList = new ArrayList<>();
					detailList.add(byId);
					List<String> sourceIdCardList = new ArrayList<>();
					List<String> replaceIdList = new ArrayList<>();
					sourceIdCardList.add(byId.getEmpIdcardNo());
					replaceIdList.add(byId.getId());
					// 同步操作档案的 商险状态为：2正常（0无2正常3失效4处理中）
					this.doFailInfo(detailList, sourceIdCardList, replaceIdList, CommonConstants.THREE_STRING);
				}
			}
		} 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){
			//见费出单 费用类型也是预估
			if (CommonConstants.ZERO_STRING.equals(insuranceDetailVO.getIsJfcd())){
				insuranceDetailVO.setPremiumType(CommonConstants.ZERO_INT);
			}
			//启用BPO结算模式的也是预估
			if (null != insuranceDetailVO.getDeptNo()){
				TSettleDomainSelectVo settleResult =archivesDaprUtils.selectDeptByNo(insuranceDetailVO.getDeptNo());
				if (settleResult != null && CommonConstants.IS_TRUE.equals(settleResult.getBpoEnable()) ) {
					insuranceDetailVO.setPremiumType(CommonConstants.ONE_INT);
				}
			}
			if (null != insuranceDetailVO.getPremiumType() && CommonConstants.ONE_INT == insuranceDetailVO.getPremiumType().intValue()){
				insuranceDetailVO.setEstimatePremium(BigDecimal.ZERO);
			}
			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());
				}
			}
			//购买周期
			//计费方式(0：按天，1：按月)
			if (null != insuranceDetailVO.getBillingType()){
				if (CommonConstants.ZERO_INT == insuranceDetailVO.getBillingType().intValue()){
					insuranceDetailVO.setBuyCycle(insuranceDetailVO.getPurchaseCycle());
				}else if (CommonConstants.ONE_INT == insuranceDetailVO.getBillingType().intValue()){
					insuranceDetailVO.setBuyCycle(insuranceDetailVO.getPurchaseCycle());
				}
			}


			//如果是批增需要重新处理购买周期，按生效日期和保单结束时间计算
			/*if (CommonConstants.THREE_INT == insuranceDetailVO.getBuyType()){
				if (Objects.isNull(insuranceDetailVO.getPolicyEffect())){
					insuranceDetailVO.setBuyCycle(null);
				}else {
					day = LocalDateUtil.betweenDay(insuranceDetailVO.getPolicyEffect().toString(),insuranceDetailVO.getPolicyEnd().toString());
					month = LocalDateUtil.betweenMonth(insuranceDetailVO.getPolicyEffect().toString(),insuranceDetailVO.getPolicyEnd().toString());
					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());
			//被替换人
			TInsuranceReplace one = tInsuranceReplaceService.getOne(Wrappers.<TInsuranceReplace>query().lambda()
					.eq(TInsuranceReplace::getToInsuranceDetailId, insuranceDetailVO.getId())
					//huyc-代码优化,取替换状态为成功的那一条数据
					.eq(TInsuranceReplace::getReplaceStatus, CommonConstants.ONE_INT)
					.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();
						if(Objects.nonNull(data)){
							ProjectSetInfoVo setInfoVo = data.get(byId.getDeptNo());
							if (null != setInfoVo){
								insuranceDetailVO.setCoverProjectName(Optional.ofNullable(setInfoVo.getDepartName()).orElse(""));
								insuranceDetailVO.setCoverInvoiceTitle(Optional.ofNullable(setInfoVo.getInvoiceTitleInsurance()).orElse(""));
							}
						}
					}
				}
			}

			//替换人
			TInsuranceReplace replace = tInsuranceReplaceService.getOne(Wrappers.<TInsuranceReplace>query().lambda()
					.eq(TInsuranceReplace::getFromInsuranceDetailId, insuranceDetailVO.getId())
					//huyc-代码优化,取替换状态为成功的那一条数据
					.eq(TInsuranceReplace::getReplaceStatus, CommonConstants.ONE_INT)
					.last(CommonConstants.LAST_ONE_SQL));
			if (Optional.ofNullable(replace).isPresent()) {
				TInsuranceDetail replaceById = this.getById(replace.getToInsuranceDetailId());
				if (Optional.ofNullable(replaceById).isPresent()) {
					insuranceDetailVO.setReplaceEmpName(replaceById.getEmpName());
					insuranceDetailVO.setReplaceEmpIdcardNo(replaceById.getEmpIdcardNo());
					R<SetInfoVo> infoByCodes = archivesDaprUtil.getSetInfoByCodes(Arrays.asList(replaceById.getDeptNo()));
					if (null != infoByCodes && infoByCodes.getCode() == CommonConstants.SUCCESS && Common.isNotNull(infoByCodes.getData())) {
						Map<String, ProjectSetInfoVo> data = infoByCodes.getData().getProjectSetInfoVoMap();
						if(Objects.nonNull(data)){
							ProjectSetInfoVo setInfoVo = data.get(replaceById.getDeptNo());
							if (null != setInfoVo){
								insuranceDetailVO.setReplaceProjectName(Optional.ofNullable(setInfoVo.getDepartName()).orElse(""));
								insuranceDetailVO.setReplaceInvoiceTitle(Optional.ofNullable(setInfoVo.getInvoiceTitleInsurance()).orElse(""));
							}
						}
					}
				}
			}


			//减员类型 处理创建人、创建时间、备注
			if(CommonConstants.FIVE_INT == insuranceDetailVO.getDistributeType()){
				TInsuranceRefund refund = tInsuranceRefundService.getOne(Wrappers.<TInsuranceRefund>query().lambda()
						.eq(TInsuranceRefund::getId, insuranceDetailVO.getRefundId())
						.orderByDesc(TInsuranceRefund::getUpdateTime)
						.last(CommonConstants.LAST_ONE_SQL)
				);
				if (Optional.ofNullable(refund).isPresent()){
					insuranceDetailVO.setSurrender(refund.getRefundMoney());
					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();
				if(Objects.nonNull(data)){
					ProjectSetInfoVo jsonObject = data.get(insuranceDetailVO.getDeptNo());
					if (null != jsonObject){
						insuranceDetailVO.setInvoiceTitle(Optional.ofNullable(jsonObject.getInvoiceTitleInsurance()).orElse(""));
					}
				}
			}

			List<TBusinessOperate> list = tBusinessOperateService.getOperateListByBusinessId(id);
			if (CollectionUtils.isNotEmpty(list)){
				insuranceDetailVO.setOperateList(list);
			}

		}
		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<InsuranceExportListOneVO>}
	 * @author huyc
	 */
	@Override
	public R<List<InsuranceExportListOneVO>> getInsuranceExportOneList(InsuranceExportListParam param, String mId) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isNotNull(mId)) {
			param.setMId(mId);
		}
		param.setCreateBy(user.getId());
		//设置updateBy字段是给导出使用的
		param.setUpdateBy(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<InsuranceExportListOneVO> insuranceExportList;
		//如果是待投保状态，sql中HANDLED_BY过滤条件不需要，这里强制变为null
		if(param.getBuyHandleStatus() == CommonConstants.ONE_INT){
			param.setUpdateBy(null);
		}
		//如勾选项不为空，则导出勾选记录；否则导出当前筛选条件下 && 「待投保」的结果集
		if (CollectionUtils.isNotEmpty(param.getIdList())){
			insuranceExportList =  baseMapper.getInsuranceExportOneListBySelect(param.getIdList());
		}else {
			insuranceExportList = baseMapper.getInsuranceExportOnetList(param);
		}
		if (CollectionUtils.isNotEmpty(insuranceExportList)){
			List<TInsuranceDetail> detailList = new ArrayList<>();
			//根据项目编码获取项目名称
			List<String> collect = insuranceExportList.stream().map(InsuranceExportListOneVO::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 (InsuranceExportListOneVO 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()));
					//购买天数
					if (Common.isNotNull(record.getPurchaseCycle())){
							if (record.getPurchaseCycle().indexOf("天") != -1 && record.getPurchaseCycle().indexOf("个月") != -1){
								try {
									record.setBuyDay(Long.valueOf(record.getPurchaseCycle().substring(record.getPurchaseCycle().indexOf("个月")+3,record.getPurchaseCycle().indexOf("天"))));
								}catch (Exception e){
									record.setBuyDay(LocalDateUtil.betweenDay(record.getPolicyStart().toString(),record.getPolicyEnd().toString()));
								}
							}
					}else {
						record.setBuyDay(LocalDateUtil.betweenDay(record.getPolicyStart().toString(),record.getPolicyEnd().toString()));
					}
					//如果是批增需要重新处理购买周期，按生效日期和保单结束时间计算
					if (CommonConstants.THREE_INT == record.getBuyType()){
						if (Objects.isNull(record.getPolicyEffect())){
							record.setBuyMonth(null);
							record.setBuyDay(null);
						}else {
							record.setBuyMonth(LocalDateUtil.betweenMonth(record.getPolicyEffect().toString(),record.getPolicyEnd().toString()));
							record.setBuyDay(LocalDateUtil.betweenDay(record.getPolicyEffect().toString(),record.getPolicyEnd().toString()));
						}
					}
					//如果是待投保，需要处理相关逻辑，投保中、投保成功只是单纯的导出
					if(param.getBuyHandleStatus() == CommonConstants.ONE_INT){
						TInsuranceDetail detail = new TInsuranceDetail();
						detail.setId(record.getId());
						//update状态由「待投保」置为「投保中」
						detail.setBuyHandleStatus(CommonConstants.TWO_INT);
						if (record.getBuyType() == CommonConstants.ONE_INT){
							//  “投保类型”为“新增”的  若保单开始日期等于导出办理日期+1日，则为导出办理日期+1日； 若小于导入办理日期+1日，则也按照导出办理日期+1日算    若大于导出办理日期+1日，则等于保单开始日期；
							if (null != record.getPolicyStart() && record.getPolicyStart().isAfter(LocalDate.now().plusDays(CommonConstants.ONE_INT))){
								detail.setPolicyEffect(record.getPolicyStart());
							}else {
								detail.setPolicyEffect(LocalDate.now().plusDays(CommonConstants.ONE_INT));
							}
						}else {
							//批增和替换的生效日期就等于导出办理日期+1日
							detail.setPolicyEffect(LocalDate.now().plusDays(CommonConstants.ONE_INT));
						}
						detail.setDefaultSettleId(record.getDefaultSettleId());
						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);
						updateEmployeeInsurancePreById(detail, Stream.of("3").collect(Collectors.toList()),CommonConstants.FOUR_STRING);
						updateEmployeeInsurancePreRenewById(detail, Stream.of("3").collect(Collectors.toList()),CommonConstants.FOUR_STRING, false);
					}
				}
			}
			//批量更新
			if (CollectionUtils.isNotEmpty(detailList)){
				this.saveOrUpdateBatch(detailList);
			}
			//操作记录
			addOperate(detailList,user,InsurancesConstants.EXPORT,null,CommonConstants.ONE_INT);

			//针对是替换类型的做处理,每一条替换数据对应一条被替换数据
			List<InsuranceExportListOneVO> listVOS = insuranceExportList.stream().filter(e -> e.getBuyType() == CommonConstants.FOUR_INT).collect(Collectors.toList());
			List<InsuranceExportListOneVO> list = new ArrayList<>();
			if(CollectionUtils.isNotEmpty(listVOS)){
				for (InsuranceExportListOneVO listVO : listVOS) {
					listVO.setRemarkDispatch(listVO.getRemark());
					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()){
							InsuranceExportListOneVO vo = new InsuranceExportListOneVO();
							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()));
							//如果是批增需要重新处理购买周期，按生效日期和保单结束时间计算
							if (CommonConstants.THREE_INT == vo.getBuyType()){
								if (Objects.isNull(vo.getPolicyEffect())){
									vo.setBuyMonth(null);
									vo.setBuyDay(null);
								}else {
									vo.setBuyMonth(LocalDateUtil.betweenMonth(vo.getPolicyEffect().toString(),vo.getPolicyEnd().toString()));
									vo.setBuyDay(LocalDateUtil.betweenDay(vo.getPolicyEffect().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(InsuranceExportListOneVO::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 (InsuranceExportListOneVO record : list) {
									ProjectSetInfoVo jsonObject = data.get(record.getDeptNo());
									if (null != jsonObject) {
										record.setInvoiceTitle(Optional.ofNullable(jsonObject.getInvoiceTitleInsurance()).orElse(""));
									}
								}
							}
						}
					}catch (Exception e){
						for (InsuranceExportListOneVO 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(crossMergerOne(list,listVOS));
				}
			}

		}
		return R.ok(insuranceExportList);
	}

	/**
	 * 导出办理
	 *
	 * @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());
		//设置updateBy字段是给导出使用的
		param.setUpdateBy(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;
		//如果是待投保状态，sql中HANDLED_BY过滤条件不需要，这里强制变为null
		if(param.getBuyHandleStatus() == CommonConstants.ONE_INT){
			param.setUpdateBy(null);
		}
		//如勾选项不为空，则导出勾选记录；否则导出当前筛选条件下 && 「待投保」的结果集
		if (CollectionUtils.isNotEmpty(param.getIdList())){
			insuranceExportList =  baseMapper.getInsuranceExportListBySelect(param.getIdList());
		}else {
			insuranceExportList = baseMapper.getInsuranceExportList(param);
		}
		if (CollectionUtils.isNotEmpty(insuranceExportList)){
			List<TInsuranceDetail> detailList = new ArrayList<>();
			//根据项目编码获取项目名称
			List<String> collect = insuranceExportList.stream().map(InsuranceExportListVO::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()));
					//如果是批增需要重新处理购买周期，按生效日期和保单结束时间计算
					if (CommonConstants.THREE_INT == record.getBuyType()){
						if (Objects.isNull(record.getPolicyEffect())){
							record.setBuyMonth(null);
							record.setBuyDay(null);
						}else {
							record.setBuyMonth(LocalDateUtil.betweenMonth(record.getPolicyEffect().toString(),record.getPolicyEnd().toString()));
							record.setBuyDay(LocalDateUtil.betweenDay(record.getPolicyEffect().toString(),record.getPolicyEnd().toString()));
						}
					}
					//如果是待投保，需要处理相关逻辑，投保中、投保成功只是单纯的导出
					if(param.getBuyHandleStatus() == CommonConstants.ONE_INT){
						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);
						updateEmployeeInsurancePreById(detail, Stream.of("3").collect(Collectors.toList()),CommonConstants.FOUR_STRING);
						updateEmployeeInsurancePreRenewById(detail, Stream.of("3").collect(Collectors.toList()),CommonConstants.FOUR_STRING, false);
					}
				}
			}
			//批量更新
			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.setRemarkDispatch(listVO.getRemark());
					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()));
							//如果是批增需要重新处理购买周期，按生效日期和保单结束时间计算
							if (CommonConstants.THREE_INT == vo.getBuyType()){
								if (Objects.isNull(vo.getPolicyEffect())){
									vo.setBuyMonth(null);
									vo.setBuyDay(null);
								}else {
									vo.setBuyMonth(LocalDateUtil.betweenMonth(vo.getPolicyEffect().toString(),vo.getPolicyEnd().toString()));
									vo.setBuyDay(LocalDateUtil.betweenDay(vo.getPolicyEffect().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(InsuranceExportListVO::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<>();

		//根据id获取所有的商险明细
		List<TInsuranceDetail> detailList = baseMapper.selectBatchIds(idList);
		//返回给前端的数据
		List<InsuranceListVO> errorList = new ArrayList<>();
		//后端处理的数据
		List<TInsuranceDetail> successList = new ArrayList<>();
		//被替换人的档案要处理状态
		List<String> sourceIdCardList = new ArrayList<>();
		// 被替换的id
		List<String> replaceIdList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(detailList)){
			TInsuranceReplace one;
			TInsuranceDetail byId;
			List<TInsuranceDetail> updList = new ArrayList<>();
			List<TInsuranceReplace> replaceList = new ArrayList<>();
			TInsuranceDetail newDetail;
			TInsuranceDetail oldDetail;
			for (TInsuranceDetail detail : detailList) {
				oldDetail = new TInsuranceDetail();
				newDetail = new TInsuranceDetail();
				BeanCopyUtils.copyProperties(detail,oldDetail);
				BeanCopyUtils.copyProperties(detail,newDetail);
				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{
					//判断是否已支出或支出中
					EkpSettleStatusVo vo = ekpSettleService.getSettleStatusFromEkpInsuranceDetail(detail.getId());
					if (vo != null && (vo.getPayStatus().equals("已结算")
							|| vo.getPayStatus().equals("结算中"))) {
						InsuranceListVO listVO = new InsuranceListVO();
						BeanCopyUtils.copyProperties(detail,listVO);
						listVO.setProjectName(detail.getDeptName());
						listVO.setErrorMessage(InsurancesConstants.REDUCE_ROLLBACK_PAY_IS_NOT_ALLOW);
						errorList.add(listVO);
						continue;
					}
					//判断是否是替换类型的退回，如果是，需要将被替换者激活，替换者有效状态为空
					if(detail.getBuyType() == CommonConstants.FOUR_INT){
						//替换者有效状态为空
						detail.setIsEffect(null);
						one = tInsuranceReplaceService.getOne(Wrappers.<TInsuranceReplace>query().lambda()
								.eq(TInsuranceReplace::getToInsuranceDetailId, detail.getId())
								//huyc-代码优化,取替换状态为成功的那一条数据
								.eq(TInsuranceReplace::getReplaceStatus, CommonConstants.ONE_INT)
								.last(CommonConstants.LAST_ONE_SQL));
						if (Optional.ofNullable(one).isPresent()){
							//替换记录变为失败
							one.setReplaceStatus(CommonConstants.ZERO_INT);
							replaceList.add(one);
							byId = this.getById(one.getFromInsuranceDetailId());
							if (Optional.ofNullable(byId).isPresent()){
								//被替换者激活
								byId.setIsEffect(CommonConstants.ZERO_INT);
								byId.setIsOverdue(CommonConstants.ZERO_INT);
								updList.add(byId);
							}
						}
					}
					// 记录状态置为「退回」
					detail.setBuyHandleStatus(CommonConstants.FOUR_INT);
					if (CommonConstants.ZERO_STRING.equals(detail.getIsJfcd())){
						detail.setPaymentTime(CommonConstants.EMPTY_STRING);
						detail.setPaymentStatus(CommonConstants.ZERO_STRING);
						//添加日志
						newDetail.setPaymentTime(CommonConstants.EMPTY_STRING);
						newDetail.setPaymentStatus(CommonConstants.ZERO_STRING);
						tBusinessOperateService.saveModificationRecord(detail.getId(),oldDetail,newDetail,"投保退回更新缴费状态、缴费时间",user.getNickname());
					}
					//投保成功后再次投保退回，需要将保单生效日期、是否有效、是否过期置为空
					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);
					sourceIdCardList.add(detail.getEmpIdcardNo());
					replaceIdList.add(detail.getId());
				}

			}
			//批量更新商险和替换表
			if (!updList.isEmpty()) {
				this.updateBatchById(updList);
				updList.clear();
			}
			if (!replaceList.isEmpty()) {
				tInsuranceReplaceService.updateBatchById(replaceList);
				replaceList.clear();
			}
		}
		if (CollectionUtils.isNotEmpty(successList)){
			TInsuranceSettle settle;
			SettleVo settleVo;
			R<TIncomeDetailReturnVo> incomeDetailList;
//			TInsuranceCompany insuranceCompany;
//			TInsuranceType insuranceType;
			for (TInsuranceDetail detail : successList) {
//				// 是否地市自购
//				insuranceCompany = tInsuranceCompanyService.getOne(Wrappers.<TInsuranceCompany>query().lambda()
//						.eq(TInsuranceCompany::getCompanyName, detail.getInsuranceCompanyName())
//						.eq(TInsuranceCompany::getDeleteFlag, CommonConstants.ZERO_INT)
//						.last(CommonConstants.LAST_ONE_SQL));
//				if (Optional.ofNullable(insuranceCompany).isPresent()) {
//					insuranceType = tInsuranceTypeService.getOne(Wrappers.<TInsuranceType>query().lambda()
//							.eq(TInsuranceType::getName, detail.getInsuranceTypeName())
//							.eq(TInsuranceType::getInsuranceCompanyId, insuranceCompany.getId())
//							.eq(TInsuranceType::getDeleteFlag, CommonConstants.ZERO_INT)
//							.last(CommonConstants.LAST_ONE_SQL)
//					);
//					detail.setIsAdress(insuranceType.getIsAdress());
//				}

				if (StringUtils.isNotBlank(detail.getDefaultSettleId())){
					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 = 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;
							//如果是见费出单，投保中，推送作废 2026-01-22 v1.7.19
							if (CommonConstants.ZERO_STRING.equals(detail.getIsJfcd())){
								//红冲预估推送
								detail.setDefaultSettleId(burden.getId());
								pushResult = pushEstimate(detail, CommonConstants.THREE_INT);
								//已投保 需要处理实缴和差额数据 (已支出或支出中禁止退保)
								//直接删除实缴及实缴与预估的差额
								ekpSettleService.deleteEkpInsuranceDetailAsso(detail.getId());
							} else {
								//预估已推送，实缴未推送
								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);
									}
									//预估已推送，实缴已推送
								} else 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);
									}
									//预估未推送，实缴已推送
								} else 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{
								TIncomeDetail incomeDetail = new TIncomeDetail();
								incomeDetail.setSourceId(detail.getId());
								incomeDetailList = socialDaprUtils.getTIncomeDetailList(incomeDetail);
								if (Common.isNotNull(incomeDetailList) && incomeDetailList.getCode() == CommonConstants.SUCCESS) {
									for (TIncomeDetail detailIncome : incomeDetailList.getData().getDetailList()) {
										TIncomeDetail detail1 = new TIncomeDetail();
										BeanCopyUtils.copyProperties(detailIncome, detail1);
										detail1.setId(CommonConstants.NULL);
										detail1.setRedData(CommonConstants.ONE_STRING);
										detail1.setMoney(detail1.getMoney().negate());
										socialDaprUtils.createTIncomeDetail(detail1);
									}
								}
							}catch (Exception e){
								log.error("收入数据同步处理失败："+e);
							}
						}
					}
				}
				//获取成功数据的remark
				paramList.forEach(e ->{
					if (detail.getId().equals(e.getId())){
						operateList.add(e);
					}
				});
				updateEmployeeInsurancePreById(detail,Stream.of("3","4","6").collect(Collectors.toList()),CommonConstants.FIVE_STRING);
				updateEmployeeInsurancePreRenewById(detail,Stream.of("3","4","6").collect(Collectors.toList()),CommonConstants.FIVE_STRING, true);

			}
			//更新状态
			this.updateBatchById(successList);

			// 处理档案状态
			if (CollectionUtils.isNotEmpty(successList)) {
				this.doFailInfo(successList, sourceIdCardList, replaceIdList, CommonConstants.ZERO_STRING);
			}
		}
		//操作记录
		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) {
		List<InsuranceHandleImportParam> operateList = insuranceChangeCheck(param,false);
		//检验成功的数据
		List<InsuranceHandleImportParam> successList = operateList.stream().filter(e-> e.getErrorMessage().equals(CommonConstants.RESULT_DATA_SUCESS)).collect(Collectors.toList());
		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());
			successList.clear();
			//投保成功
			if (CollectionUtils.isNotEmpty(collectSuccess)){
				List<InsuranceHandleParam> list = new ArrayList<>();
				collectSuccess.forEach(e ->{
					InsuranceHandleParam handleParam = new InsuranceHandleParam();
					handleParam.setId(e.getId());
					handleParam.setRemark(e.getRemark());
					list.add(handleParam);
				});
				collectSuccess.clear();
				// 关联档案1
				this.successfulInsurance(user,list);
			}

			//投保退回
			if (CollectionUtils.isNotEmpty(collectRollBack)){
				List<InsuranceHandleParam> list = new ArrayList<>();
				collectRollBack.forEach(e ->{
					InsuranceHandleParam handleParam = new InsuranceHandleParam();
					handleParam.setId(e.getId());
					handleParam.setRemark(e.getRemark());
					list.add(handleParam);
				});
				collectRollBack.clear();
				// 关联档案2
				this.rollBackInsurance(user,list);
			}
		}
		if (operateList.stream().allMatch(e->e.getErrorMessage().equals(CommonConstants.RESULT_DATA_SUCESS))) {
			operateList = null;
		}
		return R.ok(operateList,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) {
		//解析参数里的商险id
		List<String> idList = paramList.stream().map(InsuranceHandleParam::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<>();
		List<TInsuranceDetail> successOne = new ArrayList<>();
		List<TInsuranceDetail> successTwo = new ArrayList<>();
		//见费出单已经生成预估数据了不用推送了
		List<TInsuranceDetail> successThree = new ArrayList<>();
		List<TInsuranceDetail> successBanlance = new ArrayList<>();
		//被替换人标记被替换成功
		List<TInsuranceDetail> sourceList = new ArrayList<>();
		//被替换人的档案要处理状态
		List<String> sourceIdCardList = new ArrayList<>();
		// 被替换的id
		List<String> replaceIdList = new ArrayList<>();
		List<TInsuranceSettle> settleList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(detailList)){
			TInsuranceReplace one;
			//项目信息
			Map<String,TSettleDomainSelectVo> mapSelectVo = this.getSelectVoMap();
			TSettleDomain settleDomain;
			TInsuranceDetail byId;
			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));
						successOne.add(detail);
						//投保替换不生成预估需要排除掉
						successThree.add(detail);
						updateEmployeeInsurancePreById(detail, Stream.of("4").collect(Collectors.toList()),CommonConstants.SIX_STRING);
						updateEmployeeInsurancePreRenewById(detail, Stream.of("4").collect(Collectors.toList()),CommonConstants.SIX_STRING, false);

						//查找被替换人信息
						one = tInsuranceReplaceService.getOne(Wrappers.<TInsuranceReplace>query().lambda()
								.eq(TInsuranceReplace::getToInsuranceDetailId, detail.getId())
								//huyc-代码优化,取替换状态为成功的那一条数据
								.eq(TInsuranceReplace::getReplaceStatus, CommonConstants.ONE_INT)
								.last(CommonConstants.LAST_ONE_SQL));
						if (Optional.ofNullable(one).isPresent()) {
							byId = this.getById(one.getFromInsuranceDetailId());
							if (Optional.ofNullable(byId).isPresent()) {
								sourceList.add(byId);
								replaceIdList.add(byId.getId());
								sourceIdCardList.add(byId.getEmpIdcardNo());
							}
						}
					}else{
						//获取项目信息
						if (null != mapSelectVo) {
							settleDomain = mapSelectVo.get(detail.getDeptNo());
						} else {
							settleDomain = null;
						}
						//根据结算类型判断是否需要计算预估保费
						//预估 (是否见费出单为的不用生成预估，因为之前已经生成了)
						if (detail.getSettleType() == CommonConstants.ZERO_INT ){
							if (CommonConstants.ONE_STRING.equals(detail.getIsJfcd())){
								if (CommonConstants.ONE_INT == detail.getBillingType()){
									// 按月查费率
									// 预估保费 = 费率 * 购买标准 + 5元
									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());
									detail.setUpdateBy(user.getId());
									//保费存储
									TInsuranceSettle settle = new TInsuranceSettle();
									settle.setInsDetailId(detail.getId());
									settle.setSettleType(detail.getSettleType());
									settle.setSettleHandleStatus(CommonConstants.ONE_STRING);
									settle.setCreateTime(LocalDateTime.now());
									settle.setEstimatePushTime(LocalDateTime.now());
									settle.setEstimatePremium(estimatePremium);
									//调完ekp接口才会是1
									settle.setIsEstimatePush(CommonConstants.ZERO_INT);
									settle.setId(RandomStringUtils.randomNumeric(19));
									settleList.add(settle);
									detail.setDefaultSettleId(settle.getId());
									successTwo.add(detail);
									updateEmployeeInsurancePreById(detail, Stream.of("4").collect(Collectors.toList()),CommonConstants.SIX_STRING);
									updateEmployeeInsurancePreRenewById(detail, Stream.of("4").collect(Collectors.toList()),CommonConstants.SIX_STRING, false);
									//生成收入数据
									createInsuranceInfo(detail,settleDomain);
								}else {
									//按天
									//计算起止时间的天数
									long day = LocalDateUtil.betweenDay(detail.getPolicyStart().toString(), detail.getPolicyEnd().toString());
									if (detail.getBuyType() == CommonConstants.THREE_INT){
										detail.setPolicyEffect(LocalDate.now().plusDays(CommonConstants.ONE_INT));
										day = LocalDateUtil.betweenDay(detail.getPolicyEffect().toString(), detail.getPolicyEnd().toString());
									}
									//预估保费 = (购买标准 / 365) * 天数  + 5元
									BigDecimal estimatePremium = new BigDecimal(detail.getBuyStandard())
											.multiply(new BigDecimal(day))
											.divide(new BigDecimal("365"),CommonConstants.TWO_INT,BigDecimal.ROUND_HALF_UP);
									detail.setEstimatePremium(estimatePremium);
									//记录状态均置为「已投保」
									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());
									//保费存储
									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());
									settle.setId(RandomStringUtils.randomNumeric(19));
									settleList.add(settle);
									detail.setDefaultSettleId(settle.getId());
									successTwo.add(detail);
									updateEmployeeInsurancePreById(detail, Stream.of("4").collect(Collectors.toList()),CommonConstants.SIX_STRING);
									updateEmployeeInsurancePreRenewById(detail, Stream.of("4").collect(Collectors.toList()),CommonConstants.SIX_STRING, false);
									//生成收入数据
									createInsuranceInfo(detail,settleDomain);
								}
							}else if (CommonConstants.ZERO_STRING.equals(detail.getIsJfcd())){
								//记录状态均置为「已投保」
								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());
								successTwo.add(detail);
								successThree.add(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());
							detail.setUpdateBy(user.getId());
							successOne.add(detail);
							updateEmployeeInsurancePreById(detail, Stream.of("4").collect(Collectors.toList()),CommonConstants.SIX_STRING);
							updateEmployeeInsurancePreRenewById(detail, Stream.of("4").collect(Collectors.toList()),CommonConstants.SIX_STRING, false);
							//如果是见费出单,不重复生成预估，具体差额在登记保单保费处处理
							if (CommonConstants.ZERO_STRING.equals(detail.getIsJfcd())){
								successThree.add(detail);
							}
						}
					}
				}
			}
		}
		//分开操作保证批量更新
		updateBatchById(successOne);
		updateBatchById(successTwo);
		successList.addAll(successOne);
		successList.addAll(successTwo);
		//把差额也算进去
		if (!successBanlance.isEmpty()){
			successList.addAll(successBanlance);
		}
		successOne.clear();
		successTwo.clear();
		//插入结算数据
		if (!settleList.isEmpty()) {
			tInsuranceSettleService.saveBatch(settleList);
			settleList.clear();
		}
		// 被替换的老商险，要处理档案状态
		if (CollectionUtils.isNotEmpty(sourceIdCardList)) {
			this.doFailInfo(sourceList, sourceIdCardList, replaceIdList, CommonConstants.THREE_STRING);
		}
		if (CollectionUtils.isNotEmpty(successList)){
			for (TInsuranceDetail detail : successList) {
				//获取成功数据的remark
				paramList.forEach(e ->{
					if (detail.getId().equals(e.getId())){
						operateList.add(e);
					}
				});
			}
		}
		if (CollectionUtils.isNotEmpty(successList)) {
			// 异步任务操作档案的 商险状态为：2正常（0无2正常3失效4处理中）
			// 2026-03-12因为有空指针，查看发现下面对successList.removeAll(successThree)导致的：
			List<TInsuranceDetail> updateStatusList = new ArrayList<>(successList);
			doJointInsuranceTask.updateEmpInfp(updateStatusList, CommonConstants.TWO_STRING);
			//从successList中排查 successThree 的数据 这部分不用推送
			if (Common.isNotNull(successThree)){
				successList.removeAll(successThree);
			}
			//异步任务推送
			doJointInsuranceTask.pushEstime(successList);
		}
		addOperate(operateList,user,InsurancesConstants.SUCCESSFUL);
		addOperate(sourceList,user,InsurancesConstants.SOURCE_REPLACE,null,CommonConstants.ONE_INT);
		return R.ok(errorList, InsurancesConstants.OPERATE_SUCCESS);
	}

	/**
	 * @param sourceList 失效的商险list
	 * @param sourceIdCardList 失效的身份证list
	 * @param replaceIdList 失效的idlist
	 * @Description:
	 * @Author: hgw
	 * @Date: 2022/11/23 17:57
	 * @return: void
	 **/
	private void doFailInfo(List<TInsuranceDetail> sourceList, List<String> sourceIdCardList, List<String> replaceIdList, String toStatus) {
		List<TInsuranceDetail> sourceEmpList = null;
		if (sourceIdCardList != null && !sourceIdCardList.isEmpty()) {
			sourceEmpList = baseMapper.selectByIdCardList(sourceIdCardList, replaceIdList);
		}
		if (sourceEmpList != null && !sourceEmpList.isEmpty()) {
			// 项目档案状态
			Map<String , Integer> proStatusMap = new HashMap<>();
			// 人员档案状态
			Map<String , Integer> empStatusMap = new HashMap<>();
			for (TInsuranceDetail detail : sourceList) {
				proStatusMap.put(detail.getEmpIdcardNo() + CommonConstants.DOWN_LINE_STRING + detail.getDeptNo(), Integer.parseInt(toStatus));
				empStatusMap.put(detail.getEmpIdcardNo(), Integer.parseInt(toStatus));
			}
			Integer proStatus;
			Integer empStatus;
			int status;
			for (TInsuranceDetail detail : sourceEmpList) {
				proStatus = proStatusMap.get(detail.getEmpIdcardNo() + CommonConstants.DOWN_LINE_STRING + detail.getDeptNo());
				empStatus = empStatusMap.get(detail.getEmpIdcardNo());

				// 判断该项目的商险的状态 2正常＞4处理中＞3失效＞0无商险
				// 0无2正常3失效4处理中
				status = this.judgeStatus(detail);

				if (proStatus != null) {
					if (proStatus != CommonConstants.TWO_INT && (status == CommonConstants.TWO_INT
							|| status == CommonConstants.FOUR_INT
							|| (status == CommonConstants.THREE_INT && proStatus != CommonConstants.FOUR_INT))) {
						proStatus = status;
					}
				} else {
					proStatus = status;
				}
				if (empStatus != null) {
					if (empStatus != CommonConstants.TWO_INT && (status == CommonConstants.TWO_INT
							|| status == CommonConstants.FOUR_INT
							|| (status == CommonConstants.THREE_INT && empStatus != CommonConstants.FOUR_INT))) {
						empStatus = status;
					}
				} else {
					empStatus = status;
				}
				proStatusMap.put(detail.getEmpIdcardNo()+CommonConstants.DOWN_LINE_STRING+detail.getDeptNo(), proStatus);
				empStatusMap.put(detail.getEmpIdcardNo(), empStatus);
			}
			if (!proStatusMap.isEmpty()) {
				EmpStatusVo empStatusVo = this.getEmpStatusVo(proStatusMap, true);
				archivesDaprUtil.updateEmployeeInsuranceStatus(empStatusVo);
			}
			if (!empStatusMap.isEmpty()) {
				EmpStatusVo empStatusVo = this.getEmpStatusVo(empStatusMap, false);
				archivesDaprUtil.updateEmployeeInfoInsuranceStatus(empStatusVo);
			}
		} else {
			// 异步任务操作档案的 商险状态为：3失效（0无2正常3失效4处理中）
			doJointInsuranceTask.updateEmpInfp(sourceList, toStatus);
		}
	}

	/**
	 * @param isDept true :含项目，要分割字符串； false：不含项目，直接用身份证，仅更新人员档案
	 * @Description: 提取方法，塞值
	 * @Author: hgw
	 * @Date: 2022/11/23 16:48
	 * @return: com.yifu.cloud.plus.v1.yifu.archives.vo.EmpStatusVo
	 **/
	private EmpStatusVo getEmpStatusVo(Map<String, Integer> empStatusMap, boolean isDept) {
		EmpStatusVo empStatusVo = new EmpStatusVo();
		EmpIdCardAndDeptVo empIdCardAndDeptVo;
		List<EmpIdCardAndDeptVo> voList = new ArrayList<>();
		for (Map.Entry<String, Integer> entry : empStatusMap.entrySet()) {
			empIdCardAndDeptVo = new EmpIdCardAndDeptVo();
			if (isDept) {
				empIdCardAndDeptVo.setIdCard(entry.getKey().split(CommonConstants.DOWN_LINE_STRING)[0]);
				empIdCardAndDeptVo.setDeptNo(entry.getKey().split(CommonConstants.DOWN_LINE_STRING)[1]);
			} else {
				empIdCardAndDeptVo.setIdCard(entry.getKey());
			}
			empIdCardAndDeptVo.setStatus(String.valueOf(entry.getValue()));
			voList.add(empIdCardAndDeptVo);
		}
		empStatusVo.setEmpInfo(voList);
		return empStatusVo;
	}

	/**
	 * @param detail
	 * @Description: 判断商险状态
	 * @Author: hgw
	 * @Date: 2022/11/23 16:35
	 * @return: int
	 **/
	private int judgeStatus(TInsuranceDetail detail) {
		// （0无2正常3失效4处理中）
		if (detail.getBuyHandleStatus() == CommonConstants.FOUR_INT) {
			return CommonConstants.ZERO_INT;
		} else if ((Common.isEmpty(detail.getIsEffect()) || detail.getIsEffect() == CommonConstants.ZERO_INT)
				&& (Common.isEmpty(detail.getIsOverdue()) || detail.getIsOverdue() == CommonConstants.ZERO_INT)
				&& ((Common.isEmpty(detail.getBuyHandleStatus()) || detail.getBuyHandleStatus() == CommonConstants.THREE_INT)
				&& (Common.isEmpty(detail.getReduceHandleStatus()) || detail.getReduceHandleStatus() != CommonConstants.FOUR_INT))) {
			return CommonConstants.TWO_INT;
		} else if ((Common.isNotNull(detail.getIsOverdue()) && detail.getIsOverdue() == CommonConstants.ONE_INT)
				|| (Common.isNotNull(detail.getIsEffect()) && detail.getIsEffect() == CommonConstants.ONE_INT)
				|| (Common.isNotNull(detail.getReduceHandleStatus()) && detail.getReduceHandleStatus() == CommonConstants.FOUR_INT)
				|| (Common.isNotNull(detail.getBuyHandleStatus()) && detail.getBuyHandleStatus() == CommonConstants.FIVE_INT)) {
			return CommonConstants.THREE_INT;
		} else {
			return CommonConstants.FOUR_INT;
		}
	}
	/**
	 * @param sourceList
	 * @Description: // 同步操作档案的 商险状态为：3失效（0无2正常3失效4处理中）
	 * @Author: hgw
	 * @Date: 2022/11/23 15:46
	 * @return: void
	 **/
	private void updateEmpInfp(List<TInsuranceDetail> sourceList, String status) {
		EmpStatusVo empStatusVo = new EmpStatusVo();
		EmpIdCardAndDeptVo empIdCardAndDeptVo;
		List<EmpIdCardAndDeptVo> voList = new ArrayList<>();
		for (TInsuranceDetail d : sourceList) {
			empIdCardAndDeptVo = new EmpIdCardAndDeptVo();
			empIdCardAndDeptVo.setIdCard(d.getEmpIdcardNo());
			empIdCardAndDeptVo.setDeptNo(d.getDeptNo());
			empIdCardAndDeptVo.setStatus(status);
			voList.add(empIdCardAndDeptVo);
		}
		empStatusVo.setEmpInfo(voList);
		archivesDaprUtil.updateEmployeeInsuranceStatus(empStatusVo);
		archivesDaprUtil.updateEmployeeInfoInsuranceStatus(empStatusVo);
	}

	/**
	 * 登记保单保费
	 *
	 * @param paramList
	 * @return {@link R<List<InsuranceRegisterParam>>}
	 * @author licancan
	 */
	@Override
	public R<List<InsuranceRegisterParam>> registeredPolicyPremium(List<InsuranceRegisterParam> paramList) {
		if (CollectionUtils.isEmpty(paramList)){
			return R.failed(CommonConstants.DATA_CAN_NOT_EMPTY);
		}
		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);
		}
		//获取当前登录人的商险办理地权限
		LambdaQueryWrapper<TInsuranceAreaRes> areaQuery = new LambdaQueryWrapper<>();
		areaQuery.eq(TInsuranceAreaRes::getUserId,user.getId()).eq(TInsuranceAreaRes::getStatus,CommonConstants.ZERO_INT);
		List<TInsuranceAreaRes> insuranceAreaResList = tInsuranceAreaResService.list(areaQuery);
		if(CollectionUtils.isEmpty(insuranceAreaResList)) {
			return R.failed(InsurancesConstants.NO_PERMISSION);
		}
		List<InsuranceRegisterParam> operatList = registeredPolicyPremiumCheck(paramList,insuranceAreaResList);
		//保存到数据库中的结果
		List<InsuranceRegisterParam> listSuccess = operatList.stream().filter(e-> e.getErrorMessage().equals(CommonConstants.RESULT_DATA_SUCESS)).collect(Collectors.toList());

		if (CollectionUtils.isNotEmpty(listSuccess)){
			//商险明细更新list
			List<TInsuranceDetail> detailList = new ArrayList<>();
			//项目信息
			Map<String,TSettleDomainSelectVo> mapSelectVo = this.getSelectVoMap();
			//保单号list   MVP1.7.15 取消同步插入保单维护信息
			//List<TInsurancePolicy> policyList = new ArrayList<>();
			//业务操作记录表list
			List<TBusinessOperate> operateList = new ArrayList<>();
//			//结算信息list
//			List<TInsuranceSettle> settleList = new ArrayList<>();
			BigDecimal actualMoney;
			TSettleDomain settleDomain;
			TInsuranceDetail detail;
			List<TInsuranceReplace> list;
			List<TInsuranceReplace> replaceList;
			TInsuranceSettle settle;
			TInsurancePolicy one;
			BigDecimal bigDecimalAct;
			R<TIncomeDetailReturnVo> detailInfoList;
			for (InsuranceRegisterParam success : listSuccess) {
				long d1 = System.currentTimeMillis();
				//登记保单保费
				//查数据：姓名 + 身份证号 + 保险公司 + 险种名称 + 保单开始时间 + 保单结束时间 + 购买标准
				detail = success.getDetail();
				actualMoney = detail.getActualPremium();
				boolean booleanInvoiceNo = false;
				if (StringUtils.isNotBlank(success.getInvoiceNo())){
					if (Common.isEmpty(detail.getInvoiceNo()) || !success.getInvoiceNo().equals(detail.getInvoiceNo())) {
						booleanInvoiceNo = true;
					}
					detail.setInvoiceNo(success.getInvoiceNo());
					//如果发票号不为空，将替换类型的发票号也全部更新
					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<InsuranceUpdateVO> details = baseMapper.selectByIds(collect);
						if (CollectionUtils.isNotEmpty(details)){
							details.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){
					settle = tInsuranceSettleService.getById(detail.getDefaultSettleId());
					//如果未推送则推送预估新增
					if(null != settle && CommonConstants.ZERO_INT == settle.getIsEstimatePush()){
						doJointInsuranceTask.asynchronousEkpInfo(detail,settle,CommonConstants.ONE_INT);
					}
				}
				boolean booleanPolicyNo = false;
				if (StringUtils.isNotBlank(success.getPolicyNo())){
					if (Common.isEmpty(detail.getPolicyNo()) || !success.getPolicyNo().equals(detail.getPolicyNo())) {
						booleanPolicyNo = true;
					}
					detail.setPolicyNo(success.getPolicyNo());
					//保单号不为空，维护到保单表中 MVP1.7.15 取消同步插入保单维护信息

					//如果保单号不为空，将替换类型的保单号也全部更新
					replaceList = tInsuranceReplaceService.list(Wrappers.<TInsuranceReplace>query().lambda()
							.eq(TInsuranceReplace::getOriginInsuranceDetailId, detail.getId()));
					if (CollectionUtils.isNotEmpty(replaceList)){
						List<String> collect = replaceList.stream().map(TInsuranceReplace::getToInsuranceDetailId).distinct().collect(Collectors.toList());
						List<InsuranceUpdateVO> details = baseMapper.selectByIds(collect);
						if (CollectionUtils.isNotEmpty(details)){
							details.forEach(e -> e.setPolicyNo(success.getPolicyNo()));
							//这里自己写sql更新保单号，防止用mybatisPlus批量更新，把updateTime更新了（updateTime不能更新）
							baseMapper.updatePolicyNoBatch(details);
						}
					}
				}
				//如果保费不为空
				if (StringUtils.isNotBlank(success.getActualPremium())){
					bigDecimalAct = new BigDecimal(success.getActualPremium());
					//如果当前保单为合并结算
					if ((detail.getSettleType() == CommonConstants.ZERO_INT || CommonConstants.ZERO_STRING.equals(detail.getIsJfcd()) ) &&
							StringUtils.isNotBlank(detail.getDefaultSettleId())) {
						settle = tInsuranceSettleService.getById(detail.getDefaultSettleId());
						if (Optional.ofNullable(settle).isPresent()) {
							//如果当前实缴信息未推送，则新增实缴单推送
							if (CommonConstants.ZERO_INT == settle.getIsActualPush()) {
								//保费存储
								settle.setActualPremium(bigDecimalAct);
								settle.setIsActualPush(CommonConstants.ZERO_INT);
								settle.setUpdateTime(LocalDateTime.now());
//								settleList.add(settle);
								//调EKP新增实际保费
								detail.setActualPremium(bigDecimalAct);
								doJointInsuranceTask.asynchronousEkpInfo(detail,settle,CommonConstants.TWO_INT);

								//如果当前实缴信息已推送，且金额与本次不一致，则推送实缴更新
							} else if (detail.getActualPremium().compareTo(bigDecimalAct) != 0) {
								//推送保费更新
								settle.setActualPremium(bigDecimalAct);
								settle.setIsActualPush(CommonConstants.ZERO_INT);
								settle.setUpdateTime(LocalDateTime.now());
//								settleList.add(settle);
								//调EKP更新实际保费
								detail.setActualPremium(bigDecimalAct);
								doJointInsuranceTask.asynchronousEkpInfo(detail,settle,CommonConstants.FOUR_INT);
							}
						}
						//如果当前保单为单独结算
					} else if(detail.getSettleType() == CommonConstants.ONE_INT){
						//推送过实缴信息且金额与本次不一致，则推送更新
						if(StringUtils.isNotBlank(detail.getDefaultSettleId()) &&
								(!Common.isNotNull(detail.getActualPremium()) ||
								bigDecimalAct.compareTo(detail.getActualPremium()) != 0)){
							//推送保费更新
							settle = tInsuranceSettleService.getById(detail.getDefaultSettleId());
							settle.setActualPremium(bigDecimalAct);
							settle.setIsActualPush(CommonConstants.ZERO_INT);
							settle.setUpdateTime(LocalDateTime.now());
//							settleList.add(settle);
							//调EKP更新实际保费
							detail.setActualPremium(bigDecimalAct);
							doJointInsuranceTask.asynchronousEkpInfo(detail,settle,CommonConstants.FOUR_INT);
							//未推送过实缴信息，则推送新增
						} else if(StringUtils.isBlank(detail.getDefaultSettleId())){
							//保费存储
							TInsuranceSettle settleNew = new TInsuranceSettle();
							settleNew.setInsDetailId(detail.getId());
							settleNew.setSettleType(detail.getSettleType());
							settleNew.setSettleHandleStatus(CommonConstants.ONE_STRING);
							settleNew.setActualPremium(bigDecimalAct);
							settleNew.setIsActualPush(CommonConstants.ZERO_INT);
							//调完ekp接口才会是1
							settleNew.setCreateTime(LocalDateTime.now());
							tInsuranceSettleService.save(settleNew);
							detail.setDefaultSettleId(settleNew.getId());
							//调EKP新增实际保费
							detail.setActualPremium(bigDecimalAct);
							doJointInsuranceTask.asynchronousEkpInfo(detail,settleNew,CommonConstants.TWO_INT);
						}
					}
					//实缴导入时根据条件取生成差额数据，其他情况会在推送数据时去规整 对应的应收和应支
					if (CommonConstants.ZERO_STRING.equals(detail.getIsJfcd())) {
						//登记保单保费时为已投保，已投保无法退回，故直接删除差额重新生成即可
						ekpSettleService.callBackBalance(detail.getId());
						tInsuranceSettleService.remove(Wrappers.<TInsuranceSettle>query().lambda()
								.eq(TInsuranceSettle::getInsDetailId, detail.getId())
								.eq(TInsuranceSettle::getSettleType, CommonConstants.TWO_INT));
						TInsuranceSettle settleNew = new TInsuranceSettle();
						settleNew.setInsDetailId(detail.getId());
						settleNew.setSettleType(CommonConstants.TWO_INT);
						settleNew.setSettleHandleStatus(CommonConstants.ONE_STRING);
						settleNew.setActualPremium(bigDecimalAct);
						settleNew.setIsEstimatePush(CommonConstants.ZERO_INT);
						settleNew.setEstimatePremium(detail.getEstimatePremium());
						//调完ekp接口才会是1
						settleNew.setCreateTime(LocalDateTime.now());
						if (bigDecimalAct.compareTo(detail.getEstimatePremium()) != 0){
							tInsuranceSettleService.save(settleNew);
							detail.setBalanceId(settleNew.getId());
							doJointInsuranceTask.asynchronousEkpInfo(detail,settleNew,CommonConstants.SEVEN_INT);
						}
					}

				}
				//如果当前保费为空，且保单号或发票号不一样
				if ((Common.isEmpty(success.getActualPremium()) || (Common.isNotNull(detail.getActualPremium())
						&& Common.isNotNull(success.getActualPremium()) && new BigDecimal(success.getActualPremium()).compareTo(detail.getActualPremium()) == 0))
						&& (booleanInvoiceNo || booleanPolicyNo) && StringUtils.isNotBlank(detail.getDefaultSettleId())) {
					settle = tInsuranceSettleService.getById(detail.getDefaultSettleId());
					if (Optional.ofNullable(settle).isPresent()) {
						//如果当前实缴信息未推送，则新增实缴单推送
						doJointInsuranceTask.asynchronousEkpInfo(detail,settle,CommonConstants.FOUR_INT);
					}
				}
				detailList.add(detail);
				this.updateById(detail);
				try {
					//获取项目信息
					if (null != mapSelectVo) {
						settleDomain = mapSelectVo.get(detail.getDeptNo());
					} else {
						settleDomain = null;
					}
					if (detail.getBuyType() != CommonConstants.FOUR_INT &&
							CommonConstants.ONE_INT == detail.getSettleType() &&
							new BigDecimal(success.getActualPremium()).compareTo(actualMoney) != 0) {
						BigDecimal gMoney = BigDecimal.ZERO;
						boolean isBl = false;
						if (Common.isNotNull(settleDomain) && Common.isNotNull(settleDomain.getMrSettleType()) &&
								CommonConstants.TWO_STRING.equals(settleDomain.getMrSettleType())) {
							// 含有商险，则计算收入
							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, RoundingMode.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);
								//判断是否存在当月的商险收入数据
								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, RoundingMode.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);
								}
								//判断是否存在当月的商险收入数据
								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,settleDomain);
					}
				}catch (Exception e){
					log.error("收入数据同步处理失败："+e);
				}
				long d2 = System.currentTimeMillis();
				log.info("登记保单保费一条耗时：" + (d2 - d1));
			}
			//批量更新和插入数据
//			if (!settleList.isEmpty()) {
//				tInsuranceSettleService.updateBatchById(settleList);
//				settleList.clear();
//			}
			// MVP1.7.15 取消同步插入保单维护信息
			/*if (!policyList.isEmpty()) {
				tInsurancePolicyService.saveBatch(policyList);
				policyList.clear();
			}*/
			//操作记录
			addOperate(detailList,user,InsurancesConstants.REGISTERED,null,CommonConstants.ONE_INT);
			if (operatList.stream().allMatch(e->e.getErrorMessage().equals(CommonConstants.RESULT_DATA_SUCESS))) {
				operatList = null;
			}
		}
		return R.ok(operatList,InsurancesConstants.OPERATE_SUCCESS);
	}

	/**
	 * 登记发票号
	 *
	 * @param paramList
	 * @return {@link R< List<InsuranceRegisterInvoiceNoParam>>}
	 * @author licancan
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R<List<InsuranceRegisterInvoiceNoParam>> registeredInvoiceNo(List<InsuranceRegisterInvoiceNoParam> paramList) {
		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);
		}
		//获取当前登录人的商险办理地权限
		LambdaQueryWrapper<TInsuranceAreaRes> areaQuery = new LambdaQueryWrapper<>();
		areaQuery.eq(TInsuranceAreaRes::getUserId,user.getId()).eq(TInsuranceAreaRes::getStatus,CommonConstants.ZERO_INT);
		List<TInsuranceAreaRes> insuranceAreaResList = tInsuranceAreaResService.list(areaQuery);
		if(CollectionUtils.isEmpty(insuranceAreaResList)) {
			return R.failed(InsurancesConstants.NO_PERMISSION);
		}
		List<InsuranceRegisterInvoiceNoParam> operateList = registeredInvoiceNoCheck(paramList,insuranceAreaResList);
		//需要修改的结果
		List<InsuranceRegisterInvoiceNoParam> listSuccess = operateList.stream().filter(e-> e.getErrorMessage().equals(CommonConstants.RESULT_DATA_SUCESS)).collect(Collectors.toList());
		List<TInsuranceDetail> detailList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(listSuccess)){
			boolean invoiceNoFlag = false;
			boolean policeNoFlag = false;
			String invoiceNoInfo = "";
			String policeNoInfo = "";
			for (InsuranceRegisterInvoiceNoParam success : listSuccess) {
				TInsuranceDetail detail = success.getDetail();
				if (Optional.ofNullable(detail).isPresent()){
					//判断本地更新了保单号还是发票号还是两个都更新了
					//当两次发票号不一致时
					if (Common.isNotNull(success.getInvoiceNo()) && !success.getInvoiceNo().equals(detail.getInvoiceNo())){
						invoiceNoFlag = true;
						invoiceNoInfo = ";变更前发票号:" + (Common.isEmpty(detail.getInvoiceNo()) ? "":detail.getInvoiceNo())
								+ ";变更后发票号:" + success.getInvoiceNo();
						detail.setInvoiceNo(success.getInvoiceNo());
					}
					//当两次保单号不一致时
					if (Common.isNotNull(success.getPolicyNo()) && !success.getPolicyNo().equals(detail.getPolicyNo())){
						policeNoFlag = true;
						policeNoInfo = ";变更前保单号:" + (Common.isEmpty(detail.getPolicyNo()) ? "":detail.getPolicyNo())
								+ ";变更后保单号:" + success.getPolicyNo();
						detail.setPolicyNo(success.getPolicyNo());
					}
					detailList.add(detail);
					//当两次发票号或发票号不一致时才更新
					if ((policeNoFlag || invoiceNoFlag) && StringUtils.isNotBlank(detail.getDefaultSettleId())){
						try {
							//推送修改信息
							EkpUpdateParam ekpUpdateParam = new EkpUpdateParam();
							ekpUpdateParam.setFd_3b5bf02d3b8fc4(success.getPolicyStart());
							ekpUpdateParam.setFd_3b5bf02e1d47cc(success.getPolicyEnd());
							ekpUpdateParam.setFd_3b5bf02fa14596(getBuyType(detail.getBuyType()));
							if (invoiceNoFlag) {
								ekpUpdateParam.setFd_3b5bf030ab1a56(success.getInvoiceNo());
							}
							if (policeNoFlag) {
								ekpUpdateParam.setFd_3bb431933ee968(success.getPolicyNo());
							}
							ekpUpdateParam.setFd_3b5bf031b52314(detail.getBuyStandard());
							ekpUpdateParam.setFd_3b5bf032d7a822(detail.getId() + "_" + detail.getDefaultSettleId());
							ekpUpdateParam.setFd_3b5bf0b7b4c058("操作人:" + user.getNickname() + ";操作时间:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + invoiceNoInfo + policeNoInfo);
							doJointInsuranceTask.updateInsrancesDetailAllStatus(ekpUpdateParam);
						} catch (Exception e) {
							log.error("pushEkp error registeredInvoiceNo:", e.getMessage());
						}
					}
				}
			}
		}

		if (CollectionUtils.isNotEmpty(detailList)){
			this.updateBatchById(detailList);
		}

		//操作记录
		addOperate(detailList,user,InsurancesConstants.REGISTERED_INVOICE,null,CommonConstants.ONE_INT);
		if (operateList.stream().allMatch(e->e.getErrorMessage().equals(CommonConstants.RESULT_DATA_SUCESS))) {
			operateList = null;
		}
		return R.ok(operateList,InsurancesConstants.OPERATE_SUCCESS);
	}

	/**
	 * 购买类型转换
	 *
	 * @author licancan
	 * @param buyType
	 * @return {@link String}
	 */
	private String getBuyType(Integer buyType){
		String result = "";
		if (Common.isNotNull(buyType)) {
			switch (buyType) {
				case 1:
					result = "新增";
					break;
				case 3:
					result = "批增";
					break;
				case 4:
					result = "替换";
					break;
				default:
					result = "";
			}
		}
		return result;
	}

	/**
	 * 已投保信息修改
	 *
	 * @author licancan
	 * @param paramList
	 * @return {@link R<List<InsuranceInsuredParam>>}
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
		public R<List<InsuranceInsuredParam>> updateInsuranceInsured(List<InsuranceInsuredParam> paramList) {
		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);
		}
		//获取当前登录人的商险办理地权限
		LambdaQueryWrapper<TInsuranceAreaRes> areaQuery = new LambdaQueryWrapper<>();
		areaQuery.eq(TInsuranceAreaRes::getUserId,user.getId()).eq(TInsuranceAreaRes::getStatus,CommonConstants.ZERO_INT);
		List<TInsuranceAreaRes> insuranceAreaResList = tInsuranceAreaResService.list(areaQuery);
		if(CollectionUtils.isEmpty(insuranceAreaResList)) {
			return R.failed(InsurancesConstants.NO_PERMISSION);
		}
		List<InsuranceInsuredParam> operateList = updateInsuranceInsuredCheck(paramList,insuranceAreaResList);
		//需要修改的结果
		List<InsuranceInsuredParam> listSuccess = operateList.stream().filter(e-> e.getErrorMessage().equals(CommonConstants.RESULT_DATA_SUCESS)).collect(Collectors.toList());
		List<TInsuranceDetail> detailList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(listSuccess)){
			TInsuranceDetail detail;
			for (InsuranceInsuredParam success : listSuccess) {
				detail = success.getDetail();
				if (Optional.ofNullable(detail).isPresent()){
					TInsuranceDetail oldDetail = new TInsuranceDetail();
					BeanCopyUtils.copyProperties(detail,oldDetail);
					if (StringUtils.isNotBlank(success.getPolicyStartNew())){
						detail.setPolicyStart(LocalDateUtil.parseLocalDate(success.getPolicyStartNew()));
					}
					if (StringUtils.isNotBlank(success.getPolicyEndNew())){
						detail.setPolicyEnd(LocalDateUtil.parseLocalDate(success.getPolicyEndNew()));
					}
					if (Objects.nonNull(success.getBuyType())){
						detail.setBuyType(success.getBuyType());
					}
					if (Common.isNotNull(success.getBuyStandardNew())) {
						detail.setBuyStandard(success.getBuyStandardNew());
					}
					detailList.add(detail);
					//变更记录
					tBusinessOperateService.saveModificationRecord(detail.getId(),oldDetail,detail,success.getReason());

					//只有当结算id存在的时候修改数据才会推给ekp
					if (StringUtils.isNotBlank(detail.getDefaultSettleId())){
						String differenceKey = HrEquator.comparisonValue(oldDetail, detail);
						if(!Common.isEmpty(differenceKey)){
							try {
								//推送修改信息
								StringBuilder sb = new StringBuilder();
								sb.append("操作人:" + user.getNickname() + ";操作时间:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
								if (!oldDetail.getPolicyStart().toString().equals(detail.getPolicyStart().toString())) {
									sb.append(";变更前保单开始时间:" + oldDetail.getPolicyStart() + ";变更后保单开始时间:" + detail.getPolicyStart());
								}
								if (!oldDetail.getPolicyEnd().toString().equals(detail.getPolicyEnd().toString())) {
									sb.append(";变更前保单结束时间:" + oldDetail.getPolicyEnd() + ";变更后保单结束时间:" + detail.getPolicyEnd());
								}
								if (!oldDetail.getBuyType().equals(detail.getBuyType())) {
									sb.append(";变更前投保类型:" + getBuyType(oldDetail.getBuyType()) + ";变更后投保类型:" + getBuyType(detail.getBuyType()));
								}
								if (!oldDetail.getBuyStandard().equals(detail.getBuyStandard())) {
									sb.append(";变更前购买标准:" + oldDetail.getBuyStandard() + ";变更后购买标准:" + detail.getBuyStandard());
								}
								if (StringUtils.isNotBlank(success.getReason())){
									sb.append(";变更原因:" + success.getReason());
								}
								EkpUpdateParam ekpUpdateParam = new EkpUpdateParam();
								ekpUpdateParam.setFd_3b5bf02d3b8fc4(success.getPolicyStartNew());
								ekpUpdateParam.setFd_3b5bf02e1d47cc(success.getPolicyEndNew());
								ekpUpdateParam.setFd_3b5bf02fa14596(getBuyType(success.getBuyType()));
								ekpUpdateParam.setFd_3b5bf031b52314(detail.getBuyStandard());
								ekpUpdateParam.setFd_3b5bf032d7a822(detail.getId() + "_" + detail.getDefaultSettleId());
								ekpUpdateParam.setFd_3b5bf0b7b4c058(sb.toString());
								doJointInsuranceTask.updateInsrancesDetail(ekpUpdateParam);
							}catch (Exception e){
								log.error("pushEkp error updateInsuranceInsured:", e);
							}
						}
					}
				}
			}
		}

		if (CollectionUtils.isNotEmpty(detailList)){
			this.updateBatchById(detailList);
		}

		//操作记录
		if (operateList.stream().allMatch(e->e.getErrorMessage().equals(CommonConstants.RESULT_DATA_SUCESS))) {
			operateList = null;
		}
		return R.ok(operateList,InsurancesConstants.OPERATE_SUCCESS);
	}

	/**
	 * 已投保信息修改
	 *
	 * @param param
	 * @return {@link R<String>}
	 * @author licancan
	 */
	@Override
	public R<String> updateInsuranceInsuredById(InsuranceInsuredDetailParam param) {
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		if (StringUtils.isBlank(param.getId())){
			return R.failed(InsurancesConstants.ID_IS_EMPTY);
		}
		if (StringUtils.isBlank(param.getPolicyStart()) && StringUtils.isBlank(param.getPolicyEnd())
				&& Objects.isNull(param.getBuyType()) && StringUtils.isBlank(param.getBuyStandard())){
			return R.failed(InsurancesConstants.CHOOSE_ONE_OF_THREE);
		}
		if (StringUtils.isNotBlank(param.getPolicyStart())){
			if(!LocalDateUtil.isDate(param.getPolicyStart(),LocalDateUtil.NORM_DATE_PATTERN)){
				return R.failed(InsurancesConstants.POLICY_START_NEW_PARSE_ERROR);
			}
		}
		if (StringUtils.isNotBlank(param.getPolicyEnd())){
			if(!LocalDateUtil.isDate(param.getPolicyEnd(),LocalDateUtil.NORM_DATE_PATTERN)){
				return R.failed(InsurancesConstants.POLICY_END_NEW_PARSE_ERROR);
			}
		}
		if (StringUtils.isNotBlank(param.getPolicyStart()) && StringUtils.isNotBlank(param.getPolicyEnd())){
			if (!LocalDateUtil.compareDate(param.getPolicyStart(),param.getPolicyEnd())){
				return R.failed(InsurancesConstants.POLICY_START_NEW_SHOULD_LESS_THAN_POLICY_END_NEW);
			}
		}
		if (StringUtils.isBlank(param.getReason())){
			return R.failed(InsurancesConstants.REASON_EMPTY);
		}
		if (StringUtils.isNotBlank(param.getReason()) && !ValidityUtil.validate50(param.getReason())){
			return R.failed(InsurancesConstants.REASON_MORE_THAN_50);
		}
		TInsuranceDetail byId = this.getById(param.getId());
		if (!Optional.ofNullable(byId).isPresent()){
			return R.failed(InsurancesConstants.NOT_FOUND_INSURANCE_RECORD);
		}
		if (byId.getBuyType() == CommonConstants.FOUR_INT && param.getBuyType() != CommonConstants.FOUR_INT){
			return R.failed(InsurancesConstants.REPLACE_NOT_ALLOW);
		}
		if (byId.getBuyHandleStatus() != CommonConstants.THREE_INT && byId.getBuyHandleStatus() != CommonConstants.FIVE_INT){
			return R.failed(InsurancesConstants.CURRENT_STATUS_NOT_CHANGE_INSURANCE_RECORD);
		}
		TInsuranceDetail old = new TInsuranceDetail();
		BeanCopyUtils.copyProperties(byId,old);
		if (StringUtils.isNotBlank(param.getPolicyStart())){
			byId.setPolicyStart(LocalDateUtil.parseLocalDate(param.getPolicyStart()));
		}
		if (StringUtils.isNotBlank(param.getPolicyEnd())){
			byId.setPolicyEnd(LocalDateUtil.parseLocalDate(param.getPolicyEnd()));
		}
		if (Objects.nonNull(param.getBuyType())){
			byId.setBuyType(param.getBuyType());
		}
		if (Objects.nonNull(param.getBuyStandard())){
			//判断变更后购买标准是否存在
			//购买标准
			TInsuranceTypeStandard typeStandard = tInsuranceTypeStandardService.getOne(Wrappers.<TInsuranceTypeStandard>query().lambda()
					.eq(TInsuranceTypeStandard::getBuyStandard, param.getBuyStandard())
					.eq(TInsuranceTypeStandard::getInsuranceTypeId, byId.getInsuranceTypeId())
					.eq(TInsuranceTypeStandard::getDeleteFlag, CommonConstants.ZERO_INT)
					.eq(TInsuranceTypeStandard::getEnable, CommonConstants.ZERO_INT)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (!Optional.ofNullable(typeStandard).isPresent()) {
				return R.failed(InsurancesConstants.CHANGE_BUY_STANDARD_NOT_EXIST);
			}
			byId.setBuyStandard(param.getBuyStandard());
		}
		//变更记录
		tBusinessOperateService.saveModificationRecord(byId.getId(),old,byId,param.getReason());

		//只有当结算id存在的时候修改数据才会推给ekp
		if(StringUtils.isNotBlank(byId.getDefaultSettleId())){
			String differenceKey = HrEquator.comparisonValue(old, byId);
			if(!Common.isEmpty(differenceKey)){
				try {
					//推送修改信息
					StringBuilder sb = new StringBuilder();
					sb.append("操作人:" + user.getNickname() + ";操作时间:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
					if (!old.getPolicyStart().toString().equals(param.getPolicyStart())) {
						sb.append(";变更前保单开始时间:" + old.getPolicyStart() + ";变更后保单开始时间:" + param.getPolicyStart());
					}
					if (!old.getPolicyEnd().toString().equals(param.getPolicyEnd())) {
						sb.append(";变更前保单结束时间:" + old.getPolicyEnd() + ";变更后保单结束时间:" + param.getPolicyEnd());
					}
					if (!old.getBuyType().equals(param.getBuyType())) {
						sb.append(";变更前投保类型:" + getBuyType(old.getBuyType()) + ";变更后投保类型:" + getBuyType(param.getBuyType()));
					}
					if (!old.getBuyStandard().equals(param.getBuyStandard())) {
						sb.append(";变更前购买标准:" + old.getBuyStandard() + ";变更后购买标准:" + param.getBuyStandard());
					}
					if (StringUtils.isNotBlank(param.getReason())){
						sb.append(";变更原因:" + param.getReason());
					}
					EkpUpdateParam ekpUpdateParam = new EkpUpdateParam();
					ekpUpdateParam.setFd_3b5bf02d3b8fc4(param.getPolicyStart());
					ekpUpdateParam.setFd_3b5bf02e1d47cc(param.getPolicyEnd());
					ekpUpdateParam.setFd_3b5bf02fa14596(getBuyType(param.getBuyType()));
					ekpUpdateParam.setFd_3b5bf031b52314(byId.getBuyStandard());
					ekpUpdateParam.setFd_3b5bf032d7a822(byId.getId() + "_" + byId.getDefaultSettleId());
					ekpUpdateParam.setFd_3b5bf0b7b4c058(sb.toString());
					doJointInsuranceTask.updateInsrancesDetail(ekpUpdateParam);
				}catch (Exception e){
					log.error("pushEkp error updateInsuranceInsuredById:",e.getMessage());
				}
			}
		}
		this.updateById(byId);
		return R.ok(InsurancesConstants.OPERATE_SUCCESS);
	}

	/**
	 * 商险新增校验
	 *
	 * @author licancan
	 * @param paramList
	 * @return {@link Map<String, List<InsuranceAddParam>>}
	 */
	private Map<String,List<InsuranceAddParam>> addInsuranceCheck(List<InsuranceAddParam> paramList,
																  YifuUser user,boolean autoFlag,
																  Map<String,TSettleDomainSelectVo> mapSelectVo){
		//1.9.11超管无需校验项目权限
		List<String> deptNoList = new ArrayList<>();
		if (Common.isNotNull(user) && !CommonConstants.ZERO_STRING.equals(user.getSystemFlag())) {
			//deptNoList = getDeptNoList(user.getId());
			deptNoList = getDeptNoMapAndDeptNo(user.getId());
		}
		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());
		// 查询是否配置了自动化配置，如果有项目权限 有自动化配置就限制提交
		Map<String, String> insurAutoMap = getInsurAutoMap(paramList);
		//派单前系统已有在途/在保数据的人员明细
//		List<InsuredListVo> listInProgress = new ArrayList<>();
		TInsuranceType insuranceType = null;
		TSettleDomainSelectVo settleDomainSelectVo = null;
		TSettleDomainSelectVo settleResult = null;
		//定义外层循环标识，方便去重的时候跳出
		outer:
		for (int i = 0; i < distinctList.size(); i++) {
			InsuranceAddParam param = distinctList.get(i);
			if (!mapSelectVo.containsKey(param.getDeptNo())){
				// 1. 查询项目信息获取客户信息
				settleResult = archivesDaprUtil.selectDeptByNo(param.getDeptNo());
				if (settleResult == null) {
					param.setErrorMessage("项目编码[" + param.getDeptNo() + "]信息不存在");
					listResult.add(param);
					continue;
				}else {
					mapSelectVo.put(param.getDeptNo(),settleResult);
				}
			}

			param.setBuyType(CommonConstants.ONE_INT);
			// 必填校验
			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;
			}
			//根据项目编码查询项目是否存在
			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 {
							// MVP1.7.11：校验户是否在服务项里
							// 获取项目的服务项
							if (Common.isEmpty(projectSetInfoVo.getServerItem())) {
								param.setErrorMessage("项目未维护服务项目，请联系管理员");
								listResult.add(param);
								continue;
							}
							String[] serverItemArr = projectSetInfoVo.getServerItem().split("、");
							// 服务项校验
							if (!ArrayUtils.contains(serverItemArr, "商险")) {
								param.setErrorMessage("该项目未勾选 商险 服务项，请至EKP系统-项目查询与变更处勾选后，再次尝试");
								listResult.add(param);
								continue;
							}

							//对应的项目编码已停止合作
							if (CommonConstants.ONE_STRING.equals(projectSetInfoVo.getStopFlag()) ||
									CommonConstants.TWO_STRING.equals(projectSetInfoVo.getStopFlag())) {
								param.setErrorMessage(InsurancesConstants.EMP_DISPATCH_SETTLEDOMAIN_STOP);
								listResult.add(param);
								continue;
							}
							//结算类型，根据项目编码获取，并冗余到明细记录中
							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;
			}
			//校验当前项目是否在权限范围内
			//1.9.11超管无需校验项目权限
			if (Common.isNotNull(user) && !CommonConstants.ZERO_STRING.equals(user.getSystemFlag())) {
				if (CollectionUtils.isEmpty(deptNoList)) {
					param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_IN_USER_DEPT_LIST);
					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;
				}
				// 存在自动化配置且是启用的直接限制MVPV1.7.15 fxj 2025-09-17
				if (!autoFlag && null != insurAutoMap.get(param.getDeptNo())){
					param.setErrorMessage(InsurancesConstants.INSURANCE_AUTO_FLAG_IS_ENABLE);
					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.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;
			}

			// 保单开始日期 > 当前派单日期
			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 (DateUtil.getDateStr(DateUtil.stringToDate(param.getPolicyStart()), 1).compareTo(param.getPolicyEnd().replaceAll("-", "")) < CommonConstants.ZERO_INT) {
				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())
						//20221107 现在需求要求允许同一个人同时存在多个不同的在保信息
						//&& LocalDateUtil.hasOverlap(LocalDateUtil.parseLocalDate(param.getPolicyStart()),LocalDateUtil.parseLocalDate(param.getPolicyEnd()),LocalDateUtil.parseLocalDate(repeat.getPolicyStart()),LocalDateUtil.parseLocalDate(repeat.getPolicyEnd()))
						&& param.getPolicyStart().equals(repeat.getPolicyStart()) && param.getPolicyEnd().equals(repeat.getPolicyEnd())
						&& param.getBuyStandard().equals(repeat.getBuyStandard())
						&& 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;
				}
			}

			//省市区域校验是否正确并设置对应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));
			}

			// 保险公司-险种-购买标准 是否存在
			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()));
				//冗余办理地省、市
				param.setInsuranceHandleProvince(insuranceCompany.getInsuranceHandleProvince());
				param.setInsuranceHandleProvinceName(insuranceCompany.getInsuranceHandleProvinceName());
				param.setInsuranceHandleCity(insuranceCompany.getInsuranceHandleCity());
				param.setInsuranceHandleCityName(insuranceCompany.getInsuranceHandleCityName());

				insuranceType = tInsuranceTypeService.getOne(Wrappers.<TInsuranceType>query().lambda()
						.eq(TInsuranceType::getName, param.getInsuranceTypeName())
						.eq(TInsuranceType::getInsuranceCompanyId, insuranceCompany.getId())
						.eq(TInsuranceType::getDeleteFlag, CommonConstants.ZERO_INT)
						.eq(TInsuranceType::getEnable, 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 {
					//如果有年龄限制则判断年龄是否在16-70之间
					if (CommonConstants.ZERO_STRING.equals(insuranceType.getAgeLimit()) && (IdCardUtil.getFullAge(param.getEmpIdcardNo()) < CommonConstants.SIXTEEN_INT || IdCardUtil.getFullAge(param.getEmpIdcardNo()) > CommonConstants.SEVENTY)) {
						param.setErrorMessage(InsurancesConstants.EMP_AGE_NOT_LEGITIMATE);
						listResult.add(param);
						continue;
					}
					param.setIsAdress(insuranceType.getIsAdress());
					//购买标准
					TInsuranceTypeStandard typeStandard = tInsuranceTypeStandardService.getOne(Wrappers.<TInsuranceTypeStandard>query().lambda()
							.eq(TInsuranceTypeStandard::getBuyStandard, param.getBuyStandard())
							.eq(TInsuranceTypeStandard::getInsuranceTypeId, insuranceType.getId())
							.eq(TInsuranceTypeStandard::getDeleteFlag, CommonConstants.ZERO_INT)
							.eq(TInsuranceTypeStandard::getEnable, 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)
						);
						param.setPurchaseCycle(month+CommonConstants.EMPTY_STRING);
						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 (Common.isNotNull(param.getSettleMonth()) && !LocalDateUtil.isDate(param.getSettleMonth(), LocalDateUtil.NORM_MONTH_PATTERN)) {
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_PARSE_ERROR);
				listResult.add(param);
				continue;
			}
			if (Common.isNotNull(param.getSettleMonth()) && !LocalDateUtil.isCurrentOrFutureMonth(param.getSettleMonth())) {
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_SHOULD_IS_FUTURE);
				listResult.add(param);
				continue;
			}
			//兼容处理，结算月为空时赋值null huych
			if (Common.isEmpty(param.getSettleMonth())) {
				param.setSettleMonth(null);
			}

			//记录查重校验：姓名 + 身份证号 + 保险公司 + 险种 + 保单开始日期~保单结束日期 + 购买标准 是唯一（剔除退回、过期状态的记录）
			//待投保、投保中、已投保(有效、未过期)
			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())
					.eq(TInsuranceDetail::getBuyStandard, param.getBuyStandard())
					.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;
			}
			//本次派单人员系统已有参保明细  如果是二次派单则无需校验
			if (Common.isEmpty(param.getIsExit())) {
				List<TInsurancePreDetail> listInsured = baseMapper.getOnProcessInsuredList(param.getEmpIdcardNo());
				if (checkIsExit(listResult, param, listInsured)){
					continue;
				}
			}
			//获取项目信息
			if (null != mapSelectVo && mapSelectVo.size() > 0){
				settleDomainSelectVo = mapSelectVo.get(param.getDeptNo());
			}
			//初始化是否见费出单字段值
			initJfcd(insuranceType, settleDomainSelectVo, param);
			listSuccess.add(param);
		}
		map.put("listResult",listResult);
		map.put("listSuccess",listSuccess);
		return map;
	}

	private void initJfcd(TInsuranceType insuranceType, TSettleDomainSelectVo settleDomainSelectVo, InsuranceAddParam param) {
		// 默认设置为"1"，只有在满足特定条件时才设置为"0"
		param.setIsJfcd(CommonConstants.ONE_STRING);
		
		// 检查必要对象不为空，且满足见费出单条件
		if (Common.isNotNull(insuranceType) && 
		    Common.isNotNull(settleDomainSelectVo) &&
		    CommonConstants.ZERO_STRING.equals(insuranceType.getIsJfcd()) && 
		    CommonConstants.IS_FALSE.equals(settleDomainSelectVo.getBpoEnable())) {
				param.setIsJfcd(CommonConstants.ZERO_STRING);
		}
	}

	private void initJfcdBatch(TInsuranceType insuranceType, TSettleDomainSelectVo settleDomainSelectVo, InsuranceBatchParam param) {
		// 默认设置为"1"，只有在满足特定条件时才设置为"0"
		param.setIsJfcd(CommonConstants.ONE_STRING);

		// 检查必要对象不为空，且满足见费出单条件
		if (Common.isNotNull(insuranceType) &&
				Common.isNotNull(settleDomainSelectVo) &&
				CommonConstants.ZERO_STRING.equals(insuranceType.getIsJfcd()) &&
				CommonConstants.IS_FALSE.equals(settleDomainSelectVo.getBpoEnable())) {
			param.setIsJfcd(CommonConstants.ZERO_STRING);
		}
	}

	/**
	 * @Author fxj
	 * @Description 判断商险 待投保、投保中、已投保(有效，未过期)  如果保单生效时间为空直接提示存在在途或在保数据
	 * 如果保单生效时间不为空 判断新增保单生效时间及保单结束时间重叠判断，重叠给提示，不重叠允许新增
	 * @Date 15:40 2025/11/20
	 * @Param
	 * @return
	**/
	private boolean checkIsExit(List<InsuranceAddParam> listResult, InsuranceAddParam param, List<TInsurancePreDetail> listInsured) {
		if (Common.isNotNull(listInsured) && !listInsured.isEmpty()) {
			boolean flag = false;
			for (TInsurancePreDetail detail: listInsured){
				//如果保单生效日期为空就不需校验，按原逻辑处理 提示存在在途或在保数据
				if (Common.isEmpty(detail.getPolicyEffect())) {
					flag = true;
					break;
				}
				//保单生效日期及保单结束时间与新增数据的保单开始时间及保单结束时间重叠判断，重叠给提示，不重叠允许新增不走原逻辑
				if (LocalDateUtil.hasOverlap(detail.getPolicyEffect(), detail.getPolicyEnd(),
						DateUtil.stringToDate(param.getPolicyStart(), LocalDateUtil.NORM_DATE_PATTERN),
						DateUtil.stringToDate(param.getPolicyEnd(), LocalDateUtil.NORM_DATE_PATTERN))) {
					flag = true;
					break;
				}
			}
			if (flag){
				if (!listInsured.isEmpty()) {
					param.setIsExit(CommonConstants.ONE_STRING);
					param.setErrorMessage(InsurancesConstants.DIS_PERSON_DATA_IS_EXIST);
					param.setInProgressList(listInsured);
					listResult.add(param);
					return true;
				}
			}
		}
		return false;
	}
	private boolean checkReplaceIsExit(List<InsuranceReplaceParam> listResult,
									   InsuranceReplaceParam param,
									   List<TInsurancePreDetail> listInsured) {
		if (Common.isNotNull(listInsured) && !listInsured.isEmpty()) {
			boolean flag = false;
			for (TInsurancePreDetail detail: listInsured){
				//如果保单生效日期为空就不需校验，按原逻辑处理 提示存在在途或在保数据
				if (Common.isEmpty(detail.getPolicyEffect())) {
					flag = true;
					break;
				}
				//保单生效日期及保单结束时间与新增数据的保单开始时间及保单结束时间重叠判断，重叠给提示，不重叠允许新增不走原逻辑
				if (LocalDateUtil.hasOverlap(detail.getPolicyEffect(), detail.getPolicyEnd(),
						DateUtil.getDateByDayNum(1),
						DateUtil.stringToDate(param.getPolicyEnd(), LocalDateUtil.NORM_DATE_PATTERN))) {
					flag = true;
					break;
				}
			}
			if (flag){
				if (!listInsured.isEmpty()) {
					param.setIsExit(CommonConstants.ONE_STRING);
					param.setErrorMessage(InsurancesConstants.DIS_PERSON_DATA_IS_EXIST);
					param.setInProgressList(listInsured);
					listResult.add(param);
					return true;
				}
			}
		}
		return false;
	}
	private boolean checkBatchIsExit(List<InsuranceBatchParam> listResult, InsuranceBatchParam param, List<TInsurancePreDetail> listInsured) {
		if (Common.isNotNull(listInsured) && !listInsured.isEmpty()) {
			boolean flag = false;
			for (TInsurancePreDetail detail: listInsured){
				//如果保单生效日期为空就不需校验，按原逻辑处理 提示存在在途或在保数据
				if (Common.isEmpty(detail.getPolicyEffect())) {
					flag = true;
					break;
				}
				//保单生效日期及保单结束时间与新增数据的保单开始时间及保单结束时间重叠判断，重叠给提示，不重叠允许新增不走原逻辑
				if (LocalDateUtil.hasOverlap(detail.getPolicyEffect(), detail.getPolicyEnd(),
						DateUtil.getDateByDayNum(1),
						DateUtil.convertToDateByLocalDate(param.getPolicyEnd()))) {
					flag = true;
					break;
				}
			}
			if (flag){
				if (!listInsured.isEmpty()) {
					param.setIsExit(CommonConstants.ONE_STRING);
					param.setErrorMessage(InsurancesConstants.DIS_PERSON_DATA_IS_EXIST);
					param.setInProgressList(listInsured);
					listResult.add(param);
					return true;
				}
			}
		}
		return false;
	}

	private Map<String, String> getInsurAutoMap(List<InsuranceAddParam> paramList) {
		Map<String, String> insurAutoMap = null;
		List<String> departNos = null;
		if (Common.isNotNull(paramList)){
			departNos = paramList.stream().map(InsuranceAddParam::getDeptNo).collect(Collectors.toList());
		}
		if (Common.isNotNull(departNos)){
			R<Map<String, String>> resR = archivesDaprUtil.getProjectAutoSetMap(departNos);
			if (Common.isNotNull(resR) && Common.isNotNull(resR.getData())){
				insurAutoMap = resR.getData();
			}else {
				throw new RuntimeException("获取商险自动化配置失败");
			}
		}
		return null==insurAutoMap?new HashMap<>():insurAutoMap;
	}

	private Map<String, String> getBatchInsurAutoMap(List<InsuranceBatchParam> paramList) {
		Map<String, String> insurAutoMap = null;
		List<String> departNos = null;
		if (Common.isNotNull(paramList)){
			departNos = paramList.stream().map(InsuranceBatchParam::getDeptNo).collect(Collectors.toList());
		}
		if (Common.isNotNull(departNos)){
			R<Map<String, String>> resR = archivesDaprUtil.getProjectAutoSetMap(departNos);
			if (Common.isNotNull(resR) && Common.isNotNull(resR.getData())){
				insurAutoMap = resR.getData();
			}else {
				throw new RuntimeException("获取商险自动化配置失败");
			}
		}
		return null==insurAutoMap?new HashMap<>():insurAutoMap;
	}
	private Map<String, String> getReplaceInsurAutoMap(List<InsuranceReplaceParam> paramList) {
		Map<String, String> insurAutoMap = null;
		List<String> departNos = null;
		if (Common.isNotNull(paramList)){
			departNos = paramList.stream().map(InsuranceReplaceParam::getReplaceDeptNo).collect(Collectors.toList());
		}
		if (Common.isNotNull(departNos)){
			R<Map<String, String>> resR = archivesDaprUtil.getProjectAutoSetMap(departNos);
			if (Common.isNotNull(resR) && Common.isNotNull(resR.getData())){
				insurAutoMap = resR.getData();
			}else {
				throw new RuntimeException("获取商险自动化配置失败");
			}
		}
		return null==insurAutoMap?new HashMap<>():insurAutoMap;
	}
	/**
	 * 商险批增校验
	 *
	 * @author licancan
	 * @param paramList
	 * @return {@link Map< String, List< InsuranceBatchParam>>}
	 */
	private Map<String,List<InsuranceBatchParam>> batchInsuranceCheck(List<InsuranceBatchParam> paramList,YifuUser user,boolean autoFlag,
																	  Map<String,TSettleDomainSelectVo> mapSelectVo){
		//1.9.11超管无需校验项目权限
		List<String> deptNoList = new ArrayList<>();
		if (Common.isNotNull(user) && !CommonConstants.ZERO_STRING.equals(user.getSystemFlag())) {
			deptNoList = getDeptNoMapAndDeptNo(user.getId());
		}
		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());
		// 查询是否配置了自动化配置，如果有项目权限 有自动化配置就限制提交
		Map<String, String> insurAutoMap = getBatchInsurAutoMap(paramList);
		TInsuranceType insuranceType = null;
		TSettleDomainSelectVo settleDomainSelectVo = null;
		TSettleDomainSelectVo settleResult = null;
		//定义外层循环标识，方便去重的时候跳出
		outer:
		for (int i = 0; i < distinctList.size(); i++) {
			InsuranceBatchParam param = distinctList.get(i);
			if (!mapSelectVo.containsKey(param.getDeptNo())){
				// 1. 查询项目信息获取客户信息
				settleResult = archivesDaprUtil.selectDeptByNo(param.getDeptNo());
				if (settleResult == null) {
					param.setErrorMessage("项目编码[" + param.getDeptNo() + "]信息不存在");
					listResult.add(param);
					continue;
				}else {
					mapSelectVo.put(param.getDeptNo(),settleResult);
				}
			}

			param.setBuyType(CommonConstants.THREE_INT);
			// 必填校验
			if (StringUtils.isBlank(param.getDeptNo())){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_EMPTY);
				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 {
							// MVP1.7.11：校验户是否在服务项里
							// 获取项目的服务项
							if (Common.isEmpty(projectSetInfoVo.getServerItem())){
								param.setErrorMessage("项目未维护服务项目，请联系管理员");
								listResult.add(param);
								continue;
							}
							String[] serverItemArr = projectSetInfoVo.getServerItem().split("、");
							// 服务项校验
							if (!ArrayUtils.contains(serverItemArr, "商险")) {
								param.setErrorMessage("该项目未勾选 商险 服务项，请至EKP系统-项目查询与变更处勾选后，再次尝试");
								listResult.add(param);
								continue;
							}
							//对应的项目编码已停止合作
							if (CommonConstants.ONE_STRING.equals(projectSetInfoVo.getStopFlag()) ||
									CommonConstants.TWO_STRING.equals(projectSetInfoVo.getStopFlag())){
								param.setErrorMessage(InsurancesConstants.EMP_DISPATCH_SETTLEDOMAIN_STOP);
								listResult.add(param);
								continue;
							}
							//结算类型，根据项目编码获取，并冗余到明细记录中
							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;
			}
			//校验当前项目是否在权限范围内
			//1.9.11超管无需校验项目权限
			if (Common.isNotNull(user) && !CommonConstants.ZERO_STRING.equals(user.getSystemFlag())) {
				if (CollectionUtils.isEmpty(deptNoList)) {
					param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_IN_USER_DEPT_LIST);
					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;
				}
				// 存在自动化配置且是启用的直接限制MVPV1.7.15 fxj 2025-09-17
				if (!autoFlag && null != insurAutoMap.get(param.getDeptNo())){
					param.setErrorMessage(InsurancesConstants.INSURANCE_AUTO_FLAG_IS_ENABLE);
					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.isNotBlank(param.getRemark())){
				if (!ValidityUtil.validate50(param.getRemark())){
					param.setErrorMessage(InsurancesConstants.REMARK_NOT_MORE_THAN_50);
					listResult.add(param);
					continue;
				}
			}
			//非自动化派单才需要进行这些校验
			if (Common.isEmpty(param.getPolicyStart()) && Common.isEmpty(param.getPolicyEnd())) {
				//保单开始日期、结束日期，根据保单号到t_insurance_policy表查询的 1128需求调整改造
				TInsurancePolicy limitOne = tInsurancePolicyService.getOne(Wrappers.<TInsurancePolicy>query().lambda()
						.eq(TInsurancePolicy::getPolicyNo, param.getPolicyNo())
						.eq(TInsurancePolicy::getDeleteFlag, CommonConstants.ZERO_INT)
						.last(CommonConstants.LAST_ONE_SQL));
				if (!Optional.ofNullable(limitOne).isPresent()) {
					param.setErrorMessage(InsurancesConstants.POLICY_NO_EXIST);
					listResult.add(param);
					continue;
				} else {
					//自动化派单的取自动化派单的起止日期
					if (Common.isEmpty(param.getPolicyStart()) && Common.isEmpty(param.getPolicyEnd())) {
						param.setPolicyStart(limitOne.getPolicyStart());
						param.setPolicyEnd(limitOne.getPolicyEnd());
					}
					if (limitOne.getEnableFlag() == CommonConstants.ONE_INT) {
						param.setErrorMessage(InsurancesConstants.POLICY_NO_FORBIDDEN);
						listResult.add(param);
						continue;
					}
					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.isFutureDate(limitOne.getPolicyEnd().toString())) {
						param.setErrorMessage(InsurancesConstants.POLICY_END_SHOULD_IS_FUTURE);
						listResult.add(param);
						continue;
					}
					if (!LocalDateUtil.compareDate(limitOne.getPolicyStart().toString(), limitOne.getPolicyEnd().toString())) {
						param.setErrorMessage(InsurancesConstants.POLICY_START_SHOULD_LESS_THAN_POLICY_END);
						listResult.add(param);
						continue;
					}
				}
			}
			// 身份证号位数校验（18 位合法）
			if (!ValidityUtil.validateIDCard(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_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.getPolicyNo().equals(repeat.getPolicyNo())
						&& param.getInsuranceCompanyName().equals(repeat.getInsuranceCompanyName())
						&& param.getInsuranceTypeName().equals(repeat.getInsuranceTypeName())
						&& param.getBuyStandard().equals(repeat.getBuyStandard())
						&& 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;
				}
			}
			//省市区域校验是否正确并设置对应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));
			}

			// 保险公司-险种-购买标准 是否存在
			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()));
				//冗余办理地省、市
				param.setInsuranceHandleProvince(insuranceCompany.getInsuranceHandleProvince());
				param.setInsuranceHandleProvinceName(insuranceCompany.getInsuranceHandleProvinceName());
				param.setInsuranceHandleCity(insuranceCompany.getInsuranceHandleCity());
				param.setInsuranceHandleCityName(insuranceCompany.getInsuranceHandleCityName());

				insuranceType = tInsuranceTypeService.getOne(Wrappers.<TInsuranceType>query().lambda()
						.eq(TInsuranceType::getName, param.getInsuranceTypeName())
						.eq(TInsuranceType::getInsuranceCompanyId, insuranceCompany.getId())
						.eq(TInsuranceType::getDeleteFlag, CommonConstants.ZERO_INT)
						.eq(TInsuranceType::getEnable, 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 {
					//如果有年龄限制则判断年龄是否在16-70之间
					if (CommonConstants.ZERO_STRING.equals(insuranceType.getAgeLimit()) && (IdCardUtil.getFullAge(param.getEmpIdcardNo()) < CommonConstants.SIXTEEN_INT || IdCardUtil.getFullAge(param.getEmpIdcardNo()) > CommonConstants.SEVENTY)){
						param.setErrorMessage(InsurancesConstants.EMP_AGE_NOT_LEGITIMATE);
						listResult.add(param);
						continue;
					}
					param.setIsAdress(insuranceType.getIsAdress());
					//购买标准
					TInsuranceTypeStandard typeStandard = tInsuranceTypeStandardService.getOne(Wrappers.<TInsuranceTypeStandard>query().lambda()
							.eq(TInsuranceTypeStandard::getBuyStandard, param.getBuyStandard())
							.eq(TInsuranceTypeStandard::getInsuranceTypeId, insuranceType.getId())
							.eq(TInsuranceTypeStandard::getDeleteFlag, CommonConstants.ZERO_INT)
							.eq(TInsuranceTypeStandard::getEnable, 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)
						);
						param.setPurchaseCycle(month+CommonConstants.EMPTY_STRING);
						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(Common.isNotNull(param.getSettleMonth()) && !LocalDateUtil.isDate(param.getSettleMonth(),LocalDateUtil.NORM_MONTH_PATTERN)){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_PARSE_ERROR);
				listResult.add(param);
				continue;
			}
			if(Common.isNotNull(param.getSettleMonth()) && !LocalDateUtil.isCurrentOrFutureMonth(param.getSettleMonth())){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_SHOULD_IS_FUTURE);
				listResult.add(param);
				continue;
			}
			//兼容处理，结算月为空时赋值null huych
			if(Common.isEmpty(param.getSettleMonth())){
				param.setSettleMonth(null);
			}

			//记录查重校验：姓名 + 身份证号 + 保单号 + 保险公司 + 险种 + 购买标准
			//待投保、投保中、已投保(有效、未过期)
			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::getPolicyNo,param.getPolicyNo())
					.eq(TInsuranceDetail::getInsuranceCompanyName, param.getInsuranceCompanyName())
					.eq(TInsuranceDetail::getInsuranceTypeName, param.getInsuranceTypeName())
					.eq(TInsuranceDetail::getBuyStandard, param.getBuyStandard())
					.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;
			}
			//本次派单人员系统已有参保明细  如果是二次派单则无需校验
			if (Common.isEmpty(param.getIsExit())) {
				List<TInsurancePreDetail> listInsured = baseMapper.getOnProcessInsuredList(param.getEmpIdcardNo());
				if (checkBatchIsExit(listResult, param, listInsured)){
					continue;
				}
			}
			if (null != mapSelectVo && mapSelectVo.size() > 0){
				settleDomainSelectVo = mapSelectVo.get(param.getDeptNo());
			}
			//初始化是否见费出单字段值
			initJfcdBatch(insuranceType, settleDomainSelectVo, param);
			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,boolean autoFlag){
		//1.9.11超管无需校验项目权限
		List<String> deptNoList = new ArrayList<>();
		if (Common.isNotNull(user) && !CommonConstants.ZERO_STRING.equals(user.getSystemFlag())) {
			deptNoList = getDeptNoList(user.getId());
		}
		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());
		TInsuranceType insuranceType;
		TInsuranceCompany insuranceCompany;
		// 查询是否配置了自动化配置，如果有项目权限 有自动化配置就限制提交
		Map<String, String> insurAutoMap = getReplaceInsurAutoMap(paramList);
		//定义外层循环标识，方便去重的时候跳出
		outer:
		for (int i = 0; i < distinctList.size(); i++) {
			InsuranceReplaceParam param = distinctList.get(i);
			param.setBuyType(CommonConstants.FOUR_INT);
			// 必填校验
			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;
			}
			//根据项目编码查询项目是否存在
			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 {
							// MVP1.7.11：校验户是否在服务项里
							// 获取项目的服务项
							if (Common.isEmpty(projectSetInfoVo.getServerItem())){
								param.setErrorMessage("项目未维护服务项目，请联系管理员");
								listResult.add(param);
								continue;
							}
							String[] serverItemArr = projectSetInfoVo.getServerItem().split("、");
							// 服务项校验
							if (!ArrayUtils.contains(serverItemArr, "商险")) {
								param.setErrorMessage("该项目未勾选 商险 服务项，请至EKP系统-项目查询与变更处勾选后，再次尝试");
								listResult.add(param);
								continue;
							}

							//对应的替换员工项目编码已停止合作
							if (CommonConstants.ONE_STRING.equals(projectSetInfoVo.getStopFlag()) ||
									CommonConstants.TWO_STRING.equals(projectSetInfoVo.getStopFlag())){
								param.setErrorMessage(InsurancesConstants.EMP_DISPATCH_REPALCE_SETTLEDOMAIN_STOP);
								listResult.add(param);
								continue;
							}
							//结算类型，根据项目编码获取，并冗余到明细记录中
							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;
			}
			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.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;
			}
			// 保险公司-险种-购买标准 是否存在
			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()) {
				insuranceType = tInsuranceTypeService.getOne(Wrappers.<TInsuranceType>query().lambda()
						.eq(TInsuranceType::getName, param.getInsuranceTypeName())
						.eq(TInsuranceType::getInsuranceCompanyId, insuranceCompany.getId())
						.eq(TInsuranceType::getDeleteFlag, CommonConstants.ZERO_INT)
						.eq(TInsuranceType::getEnable, CommonConstants.ZERO_INT)
						.last(CommonConstants.LAST_ONE_SQL)
				);
				if (Optional.ofNullable(insuranceType).isPresent()) {
//					param.setIsAdress(insuranceType.getIsAdress());
					if (CommonConstants.ZERO_STRING.equals(
							insuranceType.getAgeLimit()) && (IdCardUtil.getFullAge(param.getEmpIdcardNo())
							< CommonConstants.SIXTEEN_INT || IdCardUtil.getFullAge(param.getEmpIdcardNo())
							> 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 (DateUtil.getDateStr(DateUtil.stringToDate(param.getPolicyStart()),1).compareTo(param.getPolicyEnd().replaceAll("-","")) < CommonConstants.ZERO_INT){
				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())
						//20221107 现在需求要求允许同一个人同时存在多个不同的在保信息
						//&& LocalDateUtil.hasOverlap(LocalDateUtil.parseLocalDate(param.getPolicyStart()),LocalDateUtil.parseLocalDate(param.getPolicyEnd()),LocalDateUtil.parseLocalDate(repeat.getPolicyStart()),LocalDateUtil.parseLocalDate(repeat.getPolicyEnd()))
						&& param.getPolicyStart().equals(repeat.getPolicyStart()) && param.getPolicyEnd().equals(repeat.getPolicyEnd())
						&& param.getBuyStandard().equals(repeat.getBuyStandard())
						&& 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;
			}
			//原数据查重校验：姓名 + 身份证号 + 项目编码 + 保险公司 + 险种名称 + 保单开始时间 + 保单结束时间 + 购买标准 + 有效
			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::getBuyStandard, param.getBuyStandard())
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
					//有效
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsEffect,CommonConstants.ZERO_INT)
									.or().isNull(TInsuranceDetail::getIsEffect)
					)
					.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 {
				//校验当前项目是否在权限范围内
				//1.9.11超管无需校验项目权限
				if (Common.isNotNull(user) && !CommonConstants.ZERO_STRING.equals(user.getSystemFlag())) {
					if (CollectionUtils.isEmpty(deptNoList)) {
						param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_IN_USER_DEPT_LIST);
						listResult.add(param);
						continue;
					}
					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;
					}
					// 存在自动化配置且是启用的直接限制MVPV1.7.15 fxj 2025-09-17
					if (!autoFlag && null != insurAutoMap.get(param.getReplaceDeptNo())){
						param.setErrorMessage(InsurancesConstants.INSURANCE_AUTO_FLAG_IS_ENABLE);
						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())
					.eq(TInsuranceDetail::getBuyStandard, param.getBuyStandard())
					.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;
			}
			//本次派单人员系统已有参保明细  如果是二次派单则无需校验
			if (Common.isEmpty(param.getIsExit())) {
				List<TInsurancePreDetail> listInsured = baseMapper.getOnProcessInsuredList(param.getReplaceEmpIdcardNo());
				if (checkReplaceIsExit(listResult, param, listInsured)){
					continue;
				}
			}
			//所有校验通过后设置查到的结果
			//直接用excel里面的备注覆盖既有备注
			detail.setRemark(param.getRemark());
			param.setDetail(detail);
			listSuccess.add(param);
		}
		map.put("listResult",listResult);
		map.put("listSuccess",listSuccess);
		return map;
	}

	/**
	 * 登记保单保费校验
	 *
	 * @author licancan
	 * @param paramList
	 * @return {@link Map<String, List<InsuranceRegisterParam>>}
	 */
	private List<InsuranceRegisterParam> registeredPolicyPremiumCheck(List<InsuranceRegisterParam> paramList,List<TInsuranceAreaRes> insuranceAreaResList){
		List<InsuranceRegisterParam> distinctList = paramList.stream().distinct().collect(Collectors.toList());
		TInsuranceDetail detail;
		TInsurancePolicy addPolicyNo;
		TInsurancePolicy batchPolicyNo;
		TInsuranceSettle settle;
		Map<String,String> map = new HashMap<>();
		InsuranceRegisterParam param;
		SettleVo settleVo;
		List<TInsuranceEkp> ekpList;
		// EKP 结算状态、支出状态
		EkpSettleStatusVo settleStatus;
		for (int i = 0; i < distinctList.size(); i++) {
			param = distinctList.get(i);
			param.setFlag(CommonConstants.ONE_STRING);
			// 必填校验
			if (StringUtils.isBlank(param.getEmpName())){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceCompanyName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceTypeName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_TYPE_NAME_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getPolicyStart())){
				param.setErrorMessage(InsurancesConstants.POLICY_START_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getPolicyEnd())){
				param.setErrorMessage(InsurancesConstants.POLICY_END_NOT_EMPTY);
				continue;
			}
			if(!LocalDateUtil.isDate(param.getPolicyStart(),LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_START_PARSE_ERROR);
				continue;
			}
			if(!LocalDateUtil.isDate(param.getPolicyEnd(),LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_END_PARSE_ERROR);
				continue;
			}
			if (StringUtils.isBlank(param.getBuyStandard())){
				param.setErrorMessage(InsurancesConstants.BUY_STANDARD_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isNotBlank(param.getPolicyNo()) && !ValidityUtil.validate50(param.getPolicyNo())){
				param.setErrorMessage(InsurancesConstants.POLICY_NO_MORE_THAN_50);
				continue;
			}
			if (StringUtils.isNotBlank(param.getActualPremium()) && !ValidityUtil.validateMoney(param.getActualPremium())) {
				param.setErrorMessage(InsurancesConstants.ACTUAL_PREMIUM_PARSE_ERROR);
				continue;
			}
			if (StringUtils.isNotBlank(param.getInvoiceNo()) && !ValidityUtil.validate50(param.getInvoiceNo())){
				param.setErrorMessage(InsurancesConstants.INVOICE_NO_MORE_THAN_50);
				continue;
			}

			//表内数据重复 员工姓名、员工身份证号码、保险公司、险种、起止时间、购买标准
			StringBuilder errorTemp = new StringBuilder();
			errorTemp.append(param.getEmpName());
			errorTemp.append("_");
			errorTemp.append(param.getEmpIdcardNo());
			errorTemp.append("_");
			errorTemp.append(param.getInsuranceCompanyName());
			errorTemp.append("_");
			errorTemp.append(param.getInsuranceTypeName());
			errorTemp.append("_");
			errorTemp.append(param.getPolicyStart());
			errorTemp.append("_");
			errorTemp.append(param.getPolicyEnd());
			errorTemp.append("_");
			errorTemp.append(param.getBuyStandard());
			if (null == map.get(errorTemp.toString())) {
				map.put(errorTemp.toString(),"1");
			} else {
				param.setErrorMessage(InsurancesConstants.DUPLICATE_DATA_ERROR);
				continue;
			}

			//查数据是否存在：姓名 + 身份证号 + 保险公司 + 险种名称 + 保单开始时间 + 保单结束时间 + 购买标准
			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::getBuyStandard,param.getBuyStandard())
					//排除替换类型，解决保单保费挂靠问题
					.ne(TInsuranceDetail::getBuyType,CommonConstants.FOUR_INT)
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (!Optional.ofNullable(detail).isPresent()){
				param.setErrorMessage(InsurancesConstants.NOT_FOUND_INSERT_OR_BATCH_RECORD);
				continue;
			}else {
				if(null == detail.getInsuranceHandleProvince() || null == detail.getInsuranceHandleCity()){
					param.setErrorMessage(InsurancesConstants.HANDLE_PROVINCE_IS_NULL);
					continue;
				}
				//商险办理地权限校验
				String c = detail.getInsuranceHandleCity().toString();
				if(insuranceAreaResList.stream().noneMatch(s -> c.equals(s.getCity()))){
					param.setErrorMessage(InsurancesConstants.NO_DETAIL_JURISDICTION);
					continue;
				}

				LambdaQueryWrapper<TInsuranceEkp> ekpLambdaQueryWrapper = new LambdaQueryWrapper<>();
				ekpLambdaQueryWrapper.eq(TInsuranceEkp :: getDetailId,detail.getId()).eq(TInsuranceEkp ::getResendFlag,CommonConstants.ZERO_INT);
				ekpList = tInsuranceEkpService.list(ekpLambdaQueryWrapper);
				if(CollectionUtils.isNotEmpty(ekpList)){
					param.setErrorMessage(InsurancesConstants.EKP_SEND_ERROR);
					continue;
				}
				// 如果保费不存在，保单号、保费必填
				if (null == detail.getActualPremium()){
					if (StringUtils.isBlank(param.getPolicyNo())){
						param.setErrorMessage(InsurancesConstants.POLICY_NO_EMPTY);
						continue;
					}
					if (StringUtils.isBlank(param.getActualPremium())){
						param.setErrorMessage(InsurancesConstants.ACTUAL_PREMIUM_EMPTY);
						continue;
					}
				} else if (BigDecimal.ZERO.compareTo(detail.getActualPremium()) == 0
						&& Common.isEmpty(param.getActualPremium())) {
					param.setErrorMessage(InsurancesConstants.ACTUAL_PREMIUM_EMPTY);
					continue;
				}

				//批增类型，保单号存在
				if (detail.getBuyType() == CommonConstants.THREE_INT && StringUtils.isNotBlank(param.getPolicyNo())) {
					batchPolicyNo = tInsurancePolicyService.getOne(Wrappers.<TInsurancePolicy>query().lambda()
							.eq(TInsurancePolicy::getPolicyNo, param.getPolicyNo())
							.eq(TInsurancePolicy::getDeleteFlag, CommonConstants.ZERO_INT)
							.last(CommonConstants.LAST_ONE_SQL)
					);
					if (!Optional.ofNullable(batchPolicyNo).isPresent()) {
						param.setErrorMessage(InsurancesConstants.POLICY_NO_NOT_EXIST);
						continue;
					} else {
						//保单表中存在保单号，判断保险公司和险种是否一致
						if (!batchPolicyNo.getInsuranceCompanyName().equals(param.getInsuranceCompanyName())) {
							param.setErrorMessage(InsurancesConstants.POLICY_NO_COMPANY_NAME_NOT_SAME);
							continue;
						}
						if (!batchPolicyNo.getInsuranceTypeName().equals(param.getInsuranceTypeName())) {
							param.setErrorMessage(InsurancesConstants.POLICY_NO_TYPE_NAME_NOT_SAME);
							continue;
						}
					}
				}else if (detail.getBuyType() == CommonConstants.ONE_INT && StringUtils.isNotBlank(param.getPolicyNo())) {
					//新增类型，保单号已存在但是和填写的保险公司不一致
					addPolicyNo = tInsurancePolicyService.getOne(Wrappers.<TInsurancePolicy>query().lambda()
							.eq(TInsurancePolicy::getPolicyNo, param.getPolicyNo())
							.eq(TInsurancePolicy::getDeleteFlag, CommonConstants.ZERO_INT)
							.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);
							continue;
						}
						if (!addPolicyNo.getInsuranceTypeName().equals(param.getInsuranceTypeName())) {
							param.setErrorMessage(InsurancesConstants.POLICY_NO_TYPE_NAME_NOT_SAME);
							continue;
						}
					}

				}

				if (detail.getBuyType() == CommonConstants.FOUR_INT){
					param.setErrorMessage(InsurancesConstants.BUY_TYPE_FOUR_NOT_REGISTERED);
					continue;
				}
				if (detail.getBuyHandleStatus() == CommonConstants.ONE_INT){
					param.setErrorMessage(InsurancesConstants.BUY_HANDLE_ONE_NOT_REGISTERED);
					continue;
				}
				if (detail.getBuyHandleStatus() == CommonConstants.SIX_INT){
					param.setErrorMessage(InsurancesConstants.BUY_HANDLE_SIX_NOT_REGISTERED);
					continue;
				}
				if (detail.getBuyHandleStatus() == CommonConstants.TWO_INT){
					param.setErrorMessage(InsurancesConstants.BUY_HANDLE_TWO_NOT_REGISTERED);
					continue;
				}
				if (detail.getBuyHandleStatus() == CommonConstants.FOUR_INT){
					param.setErrorMessage(InsurancesConstants.BUY_HANDLE_FOUR_NOT_REGISTERED);
					continue;
				}
				if (StringUtils.isNotBlank(detail.getDefaultSettleId())){
					settle = tInsuranceSettleService.getById(detail.getDefaultSettleId());
					if (Optional.ofNullable(settle).isPresent()){
						settleStatus = getSettleStatusFromEkpInsuranceDetail(detail.getId(), detail.getDefaultSettleId());
						if(null != settleStatus){
							if(Common.isNotNull(settleStatus.getSettleStatus())) {
								//保费更新或者保单号发票号更新
								if (InsurancesConstants.SETTLE_TWO.equals(settleStatus.getSettleStatus())) {
									param.setErrorMessage(InsurancesConstants.SETTLE_HANDLE_THREE_NOT_REGISTERED);
									continue;
								}
								if (InsurancesConstants.SETTLE_ONE.equals(settleStatus.getSettleStatus())) {
									param.setErrorMessage(InsurancesConstants.SETTLE_HANDLE_TWO_NOT_REGISTERED);
									continue;
								}
							}
							// 商险已支出，无法登记保单保费
							if(Common.isNotNull(settleStatus.getPayStatus())) {
								//保费更新或者保单号发票号更新
								if (InsurancesConstants.SETTLE_TWO.equals(settleStatus.getPayStatus())) {
									param.setErrorMessage(InsurancesConstants.PAY_SETTLE_TWO_NOT_REGISTERED);
									continue;
								}
								if (InsurancesConstants.SETTLE_ONE.equals(settleStatus.getPayStatus())) {
									param.setErrorMessage(InsurancesConstants.PAY_SETTLE_ONE_NOT_REGISTERED);
									continue;
								}
							}
						}
					}
				}
			}
			param.setErrorMessage(CommonConstants.RESULT_DATA_SUCESS);
			param.setFlag(CommonConstants.ZERO_STRING);
			//所有校验通过后设置查到的结果
			param.setDetail(detail);
		}
		map.clear();
		return distinctList;
	}

	/**
	 * 登记发票号校验
	 *
	 * @author licancan
	 * @param paramList
	 * @param insuranceAreaResList 办理地权限
	 * @return {@link List<InsuranceRegisterInvoiceNoParam>}
	 */
	private List<InsuranceRegisterInvoiceNoParam> registeredInvoiceNoCheck(List<InsuranceRegisterInvoiceNoParam> paramList, List<TInsuranceAreaRes> insuranceAreaResList){
		List<InsuranceRegisterInvoiceNoParam> collect = paramList.stream().distinct().collect(Collectors.toList());
		for (InsuranceRegisterInvoiceNoParam param : collect) {
			param.setFlag(CommonConstants.ONE_STRING);
			// 必填校验
			if (StringUtils.isBlank(param.getEmpName())){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceCompanyName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceTypeName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_TYPE_NAME_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getPolicyStart())){
				param.setErrorMessage(InsurancesConstants.POLICY_START_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getPolicyEnd())){
				param.setErrorMessage(InsurancesConstants.POLICY_END_NOT_EMPTY);
				continue;
			}
			if(!LocalDateUtil.isDate(param.getPolicyStart(),LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_START_PARSE_ERROR);
				continue;
			}
			if(!LocalDateUtil.isDate(param.getPolicyEnd(),LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_END_PARSE_ERROR);
				continue;
			}
			if (StringUtils.isBlank(param.getBuyStandard())){
				param.setErrorMessage(InsurancesConstants.BUY_STANDARD_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getInvoiceNo()) && StringUtils.isBlank(param.getPolicyNo())){
				param.setErrorMessage(InsurancesConstants.INVOICE_NO_EMPTY);
				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::getBuyStandard,param.getBuyStandard())
					//排除替换类型
					.ne(TInsuranceDetail::getBuyType,CommonConstants.FOUR_INT)
					//只查询已投保和已减员的
					.in(TInsuranceDetail::getBuyHandleStatus,CommonConstants.THREE_INT,CommonConstants.FIVE_INT)
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (!Optional.ofNullable(detail).isPresent()){
				param.setErrorMessage(InsurancesConstants.NOT_FOUND_INSERT_OR_BATCH_RECORD);
				continue;
			}else {
				if(null == detail.getInsuranceHandleProvince() || null == detail.getInsuranceHandleCity()){
					param.setErrorMessage(InsurancesConstants.HANDLE_PROVINCE_IS_NULL);
					continue;
				}
				String c = detail.getInsuranceHandleCity().toString();
				//商险办理地权限校验
				if(insuranceAreaResList.stream().noneMatch(s -> c.equals(s.getCity()))){
					param.setErrorMessage(InsurancesConstants.NO_DETAIL_JURISDICTION);
					continue;
				}
				if (detail.getBuyHandleStatus() != CommonConstants.THREE_INT && detail.getBuyHandleStatus() != CommonConstants.FIVE_INT){
					param.setErrorMessage(InsurancesConstants.CURRENT_STATUS_NOT_REGISTER_INVOICE_NO);
					continue;
				}
			}
			param.setErrorMessage(CommonConstants.RESULT_DATA_SUCESS);
			param.setFlag(CommonConstants.ZERO_STRING);
			//所有校验通过后设置查到的结果
			param.setDetail(detail);
		}
		return collect;
	}

	public static final List<String> BUY_TYPE = Arrays.asList(InsurancesConstants.INSERT,InsurancesConstants.BATCH_INSERT);

	/**
	 * 已投保信息修改校验
	 *
	 * @author licancan
	 * @param paramList
	 * @param insuranceAreaResList 办理地权限
	 * @return {@link List<InsuranceInsuredParam>}
	 */
	private List<InsuranceInsuredParam> updateInsuranceInsuredCheck(List<InsuranceInsuredParam> paramList, List<TInsuranceAreaRes> insuranceAreaResList){
		List<InsuranceInsuredParam> collect = paramList.stream().distinct().collect(Collectors.toList());
		TInsuranceDetail detail;
		TInsuranceTypeStandard typeStandard;
		for (InsuranceInsuredParam param : collect) {
			param.setFlag(CommonConstants.ONE_STRING);
			// 必填校验
			if (StringUtils.isBlank(param.getEmpName())){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceCompanyName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getInsuranceTypeName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_TYPE_NAME_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getPolicyStart())){
				param.setErrorMessage(InsurancesConstants.POLICY_START_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getPolicyEnd())){
				param.setErrorMessage(InsurancesConstants.POLICY_END_NOT_EMPTY);
				continue;
			}
			if(!LocalDateUtil.isDate(param.getPolicyStart(),LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_START_PARSE_ERROR);
				continue;
			}
			if(!LocalDateUtil.isDate(param.getPolicyEnd(),LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_END_PARSE_ERROR);
				continue;
			}
			if (StringUtils.isBlank(param.getBuyStandard())){
				param.setErrorMessage(InsurancesConstants.BUY_STANDARD_NOT_EMPTY);
				continue;
			}
			if (StringUtils.isBlank(param.getPolicyStartNew()) && StringUtils.isBlank(param.getPolicyEndNew())
					&& StringUtils.isBlank(param.getBuyTypeStr()) && StringUtils.isBlank(param.getBuyStandardNew())){
				param.setErrorMessage(InsurancesConstants.CHOOSE_ONE_OF_THREE);
				continue;
			}
			if (StringUtils.isNotBlank(param.getPolicyStartNew())){
				if(!LocalDateUtil.isDate(param.getPolicyStartNew(),LocalDateUtil.NORM_DATE_PATTERN)){
					param.setErrorMessage(InsurancesConstants.POLICY_START_NEW_PARSE_ERROR);
					continue;
				}
			}
			if (StringUtils.isNotBlank(param.getPolicyEndNew())){
				if(!LocalDateUtil.isDate(param.getPolicyEndNew(),LocalDateUtil.NORM_DATE_PATTERN)){
					param.setErrorMessage(InsurancesConstants.POLICY_END_NEW_PARSE_ERROR);
					continue;
				}
			}
			if (StringUtils.isNotBlank(param.getPolicyStartNew()) && StringUtils.isNotBlank(param.getPolicyEndNew())){
				if (!LocalDateUtil.compareDate(param.getPolicyStartNew(),param.getPolicyEndNew())){
					param.setErrorMessage(InsurancesConstants.POLICY_START_NEW_SHOULD_LESS_THAN_POLICY_END_NEW);
					continue;
				}
			}
			if (StringUtils.isNotBlank(param.getBuyTypeStr())){
				if (!BUY_TYPE.contains(param.getBuyTypeStr())){
					param.setErrorMessage(InsurancesConstants.BUY_TYPE_ERROR_NEW);
					continue;
				}else {
					if (InsurancesConstants.INSERT.equals(param.getBuyTypeStr())){
						param.setBuyType(CommonConstants.ONE_INT);
					}
					if (InsurancesConstants.BATCH_INSERT.equals(param.getBuyTypeStr())){
						param.setBuyType(CommonConstants.THREE_INT);
					}
				}
			}
			if (StringUtils.isBlank(param.getReason())){
				param.setErrorMessage(InsurancesConstants.REASON_EMPTY);
				continue;
			}
			if (StringUtils.isNotBlank(param.getReason()) && !ValidityUtil.validate50(param.getReason())){
				param.setErrorMessage(InsurancesConstants.REASON_MORE_THAN_50);
				continue;
			}
			//查数据是否存在：姓名 + 身份证号 + 保险公司 + 险种名称 + 保单开始时间 + 保单结束时间 + 购买标准
			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::getBuyStandard,param.getBuyStandard())
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
					//只查询已投保和已减员的
					.in(TInsuranceDetail::getBuyHandleStatus,CommonConstants.THREE_INT,CommonConstants.FIVE_INT)
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.last(CommonConstants.LAST_ONE_SQL)
			);
			if (!Optional.ofNullable(detail).isPresent()){
				param.setErrorMessage(InsurancesConstants.NOT_FOUND_INSURANCE_RECORD);
				continue;
			}else {
				if(null == detail.getInsuranceHandleProvince() || null == detail.getInsuranceHandleCity()){
					param.setErrorMessage(InsurancesConstants.HANDLE_PROVINCE_IS_NULL);
					continue;
				}
				//商险办理地权限校验
				String insuranceHandleCity = detail.getInsuranceHandleCity().toString();
				String insuranceHandleProvince = detail.getInsuranceHandleProvince().toString();
				if(insuranceAreaResList.stream().noneMatch(s -> insuranceHandleCity.equals(s.getCity()) && insuranceHandleProvince.equals(s.getProvince()))){
					param.setErrorMessage(InsurancesConstants.NO_DETAIL_JURISDICTION);
					continue;
				}
				//判断是否是已投保状态或已减员
				if (detail.getBuyHandleStatus() != CommonConstants.THREE_INT && detail.getBuyHandleStatus() != CommonConstants.FIVE_INT){
					param.setErrorMessage(InsurancesConstants.CURRENT_STATUS_NOT_CHANGE_INSURANCE_RECORD);
					continue;
				}
				if (detail.getBuyType() == CommonConstants.FOUR_INT && Objects.nonNull(param.getBuyType()) && param.getBuyType() != CommonConstants.FOUR_INT){
					param.setErrorMessage(InsurancesConstants.REPLACE_NOT_ALLOW);
					continue;
				}
				//判断变更后购买标准是否存在
				if (Common.isNotNull(param.getBuyStandardNew())) {
					//购买标准
					typeStandard = tInsuranceTypeStandardService.getOne(Wrappers.<TInsuranceTypeStandard>query().lambda()
							.eq(TInsuranceTypeStandard::getBuyStandard, param.getBuyStandardNew())
							.eq(TInsuranceTypeStandard::getInsuranceTypeId, detail.getInsuranceTypeId())
							.eq(TInsuranceTypeStandard::getDeleteFlag, CommonConstants.ZERO_INT)
							.eq(TInsuranceTypeStandard::getEnable, CommonConstants.ZERO_INT)
							.last(CommonConstants.LAST_ONE_SQL)
					);
					if (!Optional.ofNullable(typeStandard).isPresent()) {
						param.setErrorMessage(InsurancesConstants.CHANGE_BUY_STANDARD_NOT_EXIST);
						continue;
					}
				}
			}
			param.setErrorMessage(CommonConstants.RESULT_DATA_SUCESS);
			param.setFlag(CommonConstants.ZERO_STRING);
			//所有校验通过后设置查到的结果
			param.setDetail(detail);
		}
		return collect;
	}

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

	private TInsuranceOperate addOperateNewUserName(String detailId, String userName, String operateDesc, String remark, Integer displayFlag){
		TInsuranceOperate operate = new TInsuranceOperate();
		operate.setRemark(remark);
		operate.setDisplayFlag(displayFlag);
		operate.setInsuranceDetailId(detailId);
		operate.setOperateDesc(operateDesc);
		operate.setCreateBy(CommonConstants.ONE_STRING);
		operate.setCreateName(userName);
		operate.setCreateTime(LocalDateTime.now());
		return operate;
	}

	/**
	 * 操作记录(无审批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);
				if (Common.isNotNull(user)) {
					operate.setCreateBy(user.getId());
					operate.setCreateName(user.getNickname());
				}else {
					operate.setCreateBy(detail.getCreateBy());
					operate.setCreateName(detail.getCreateName());
				}
				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;
	}

	/**
	 * 将集合交叉合并，list1 是第一个顺序 list2 是第二个顺序
	 *
	 * @author huyc
	 * @param list1
	 * @param list2
	 * @return {@link List<InsuranceExportListOneVO>}
	 */
	private List<InsuranceExportListOneVO> crossMergerOne (List<InsuranceExportListOneVO> list1, List<InsuranceExportListOneVO> list2){
		//将list放入到链表队列
		LinkedList<InsuranceExportListOneVO> st1 = new LinkedList<>(list1);
		LinkedList<InsuranceExportListOneVO> st2 = new LinkedList<>(list2);
		//计算较大的数组长度
		int max = list1.size() > list2.size() ? list1.size() : list2.size();
		//新建一个最终结果的list
		List<InsuranceExportListOneVO> 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;
	}

	private YifuUser getNewYifuUser(String userId, String userName) {
		Set<String> dbAuthsSet = new HashSet<>();
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		return new YifuUser(userId, 1L, "", userName,
				userName, "0", SecurityConstants.BCRYPT + "123456",
				"12345678911", true, true, true,
				true,
				"1", authorities, "1",
				null, null,
				null, null);
	}

	// 离职导致的减员
	@Override
	public BaseSearchListVO leaveToReduceInsurance(BaseSearchListVO paramVo) {
		List<String> insuranceList = paramVo.getListStringParam();
		YifuUser newUser = getNewYifuUser(paramVo.getUserId(), paramVo.getUserName());
		List<InsuranceExportListVO> oldList = baseMapper.getInsuranceExportListBySelect(insuranceList);
		List<InsuranceRefundCheck> insuranceRefundCheckList = new ArrayList<>();
		InsuranceRefundCheck refund;
		if (oldList != null && !oldList.isEmpty()) {
			for (InsuranceExportListVO vo : oldList) {
				refund = new InsuranceRefundCheck();
				refund.setId(vo.getId());
				refund.setEmpName(vo.getEmpName());
				// 员工姓名	员工身份证号码	保险公司名称	险种名称	购买标准（元）	保单开始日期	保单结束日期
				refund.setEmpIdcardNo(vo.getEmpIdcardNo());
				refund.setInsuranceCompanyName(vo.getInsuranceCompanyName());
				refund.setInsuranceTypeName(vo.getInsuranceTypeName());
				refund.setBuyStandard(vo.getBuyStandard());
				if (Common.isNotNull(vo.getPolicyStart())) {
					refund.setPolicyStart(vo.getPolicyStart().toString());
				}
				if (Common.isNotNull(vo.getPolicyEnd())) {
					refund.setPolicyEnd(vo.getPolicyEnd().toString());
				}
				insuranceRefundCheckList.add(refund);
			}
		}
		R<List<InsuranceRefundCheck>> a = saveInsuranceRefund(insuranceRefundCheckList, null, newUser);
		BaseSearchListVO vo = new BaseSearchListVO();
		if (a != null && a.getData() != null) {
			List<ErrorMessage> errorMessageList = new ArrayList<>();
			ErrorMessage errorMessage;
			for (InsuranceRefundCheck check : a.getData()) {
				errorMessage = new ErrorMessage(CommonConstants.ONE_INT, check.getErrorMessage(), CommonConstants.GREEN, check.getId());
				errorMessageList.add(errorMessage);
			}
			vo.setErrorMessageList(errorMessageList);
		}
		return vo;
	}
	/***********************减员办理********************************/

	/**
	 * 减员导入
	 *
	 * @author zhaji
	 * @param insuranceRefundCheckList 减员表
	 * @return {@link R}
	 */
	@Override
	public R saveInsuranceRefund(List<InsuranceRefundCheck> insuranceRefundCheckList,String orderNo, YifuUser user) {
		if (user == null) {
			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 查询参数
	 * @param response 相应参数
	 * @return void
	 */
	@Override
	public void getInsuredList(InsuredParam param, HttpServletResponse response) {
		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> list = new ArrayList<>();
		//处理导出
		String fileName = "商险已投保人员名册" + DateUtil.getThisTime() + CommonConstants.XLSX;
		long count = this.baseMapper.getInsuredListCount(param);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName  , "UTF-8"));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, InsuredListVo.class).build();
			int index = 0;
			if (count >  CommonConstants.ZERO_INT){
				Field[] allFields = InsuredListVo.class.getDeclaredFields();
				WriteSheet writeSheet;
				ExcelUtil<InsuredListVo> util;
				//处理封面抬头
				//获取所有项目信息
				Map<String, ProjectSetInfoVo> data = null;
				try {
					R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(new ArrayList<>());
					if (null != setInfoByCodes && setInfoByCodes.getCode() == CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
						data = setInfoByCodes.getData().getProjectSetInfoVoMap();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					param.setLimitStart(i);
					param.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = this.baseMapper.getInsuredList(param);
					if (Common.isNotNull(list)){
						util = new ExcelUtil<>(InsuredListVo.class);
						TInsuranceReplace one;
						TInsuranceReplace fromOne;
						TInsuranceDetail byId;
						ProjectSetInfoVo coverObject;
						for (InsuredListVo vo:list){
							//被替换人
							one = tInsuranceReplaceService.getOne(Wrappers.<TInsuranceReplace>query().lambda()
									.eq(TInsuranceReplace::getToInsuranceDetailId, vo.getId())
									//huyc-代码优化,取替换状态为成功的那一条数据
									.eq(TInsuranceReplace::getReplaceStatus, CommonConstants.ONE_INT)
									.last(CommonConstants.LAST_ONE_SQL));
							if (Optional.ofNullable(one).isPresent()) {
								byId = this.getById(one.getFromInsuranceDetailId());
								if (Optional.ofNullable(byId).isPresent()) {
									vo.setCoverEmpName(byId.getEmpName());
									vo.setCoverEmpIdcardNo(byId.getEmpIdcardNo());
									vo.setCoverProjectName(byId.getDeptName());
									if (Common.isNotNull(data) && Common.isNotNull(data.get(byId.getDeptNo()))){
										coverObject = data.get(byId.getDeptNo());
										vo.setCoverInvoiceTitle(Optional.ofNullable(coverObject.getInvoiceTitleInsurance()).orElse(""));
									}else {
										vo.setCoverInvoiceTitle("未获取到对应项目信息");
									}
								}
							}

							//替换人
							fromOne = tInsuranceReplaceService.getOne(Wrappers.<TInsuranceReplace>query().lambda()
									.eq(TInsuranceReplace::getFromInsuranceDetailId, vo.getId())
									//huyc-代码优化,取替换状态为成功的那一条数据
									.eq(TInsuranceReplace::getReplaceStatus, CommonConstants.ONE_INT)
									.last(CommonConstants.LAST_ONE_SQL));
							if (Optional.ofNullable(fromOne).isPresent()) {
								byId = this.getById(fromOne.getToInsuranceDetailId());
								if (Optional.ofNullable(byId).isPresent()) {
									vo.setReplaceEmpName(byId.getEmpName());
									vo.setReplaceEmpIdcardNo(byId.getEmpIdcardNo());
									vo.setReplaceProjectName(byId.getDeptName());
									if (Common.isNotNull(data) && Common.isNotNull(data.get(byId.getDeptNo()))){
										coverObject = data.get(byId.getDeptNo());
										vo.setReplaceInvoiceTitle(Optional.ofNullable(coverObject.getInvoiceTitleInsurance()).orElse(""));
									}else {
										vo.setReplaceInvoiceTitle("未获取到对应项目信息");
									}
								}
							}
							//购买月数
							vo.setBuyMonth(LocalDateUtil.betweenMonth(vo.getPolicyStart().toString(), vo.getPolicyEnd().toString()));

							if (Common.isNotNull(data) && Common.isNotNull(data.get(vo.getDeptNo()))) {
								coverObject = data.get(vo.getDeptNo());
								vo.setInvoiceTitle(Optional.ofNullable(coverObject.getInvoiceTitleInsurance()).orElse(""));
							}
							util.convertEntityAsso(vo,null,null,null,allFields);
						}
					}
					if (Common.isNotNull(list)){
						writeSheet = EasyExcel.writerSheet("sheet"+index).build();
						excelWriter.write(list,writeSheet);
						index++;
					}
					i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
					if (Common.isNotNull(list)){
						list.clear();
					}
				}
			}else {
				WriteSheet writeSheet = EasyExcel.writerSheet("sheet"+index).build();
				excelWriter.write(list,writeSheet);
			}
			if (Common.isNotNull(list)){
				list.clear();
			}
			out.flush();
			excelWriter.finish();
		}catch (Exception e){
			log.error("执行异常" ,e);
		}finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

	/**
	 * 导出商险明细项目变更日志
	 *
	 * @author yifu
	 * @param param 查询参数
	 * @param response 响应参数
	 * @return void
	 */
	@Override
	public void exportInsuranceChangeLog(InsuredParam param, HttpServletResponse response) {
		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<InsuranceChangeLogExportVo> list = new ArrayList<>();
		//处理导出
		String fileName = "商险明细项目变更日志" + DateUtil.getThisTime() + CommonConstants.XLSX;
		long count = this.baseMapper.getInsuranceChangeLogExportCount(param);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, "UTF-8"));

			if (count > 10000) {
				out.write("不可导出超过一万行数据，请修改筛选条件后重新导出".getBytes("GBK"));
				out.close();
				return;
			}
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, InsuranceChangeLogExportVo.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					param.setLimitStart(i);
					param.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = this.baseMapper.getInsuranceChangeLogExportList(param);
					if (Common.isNotNull(list)) {
						WriteSheet writeSheet = EasyExcel.writerSheet("sheet" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcel.writerSheet("sheet" + index).build();
				excelWriter.write(list, writeSheet);
			}
			if (Common.isNotNull(list)) {
				list.clear();
			}
			out.flush();
			excelWriter.finish();
		} catch (Exception e) {
			log.error("导出商险明细项目变更日志执行异常", e);
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("关闭输出流异常", e);
			}
		}
	}

	/**
	 * 已减员列表分页查询
	 *
	 * @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)){

			//根据项目编码获取项目名称
			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);
	}

	/**
	 * 减员退费分页列表
	 *
	 * @param page  分页信息
	 * @param param 筛选条件
	 * @param mId   菜单Id
	 * @return {@link R}
	 * @author zhangyun
	 */
	@Override
	public R getInsuranceRefundMoneyPageList(Page<RefundListVo> page, InsuranceRefundHandlingParam 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<RefundListVo> insuranceRefundMoneyPageList = this.baseMapper.getInsuranceRefundMoneyPageList(page, param);

		return R.ok(insuranceRefundMoneyPageList);
	}

	/**
	 * 减员退费不分页列表
	 *
	 * @param param 筛选条件
	 * @return {@link R}
	 * @author zhangyun
	 */
	@Override
	public R getInsuranceRefundMoneyList(InsuranceRefundHandlingParam 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<RefundListVo> insuranceRefundMoneyList = this.baseMapper.getInsuranceRefundMoneyList(param);

		return  R.ok(insuranceRefundMoneyList);
	}

	/**
	 * 减员办理列表分页查询
	 *
	 * @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());
		//设置updateBy字段是给导出使用的
		param.setUpdateBy(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;
		//如果是待减员状态，sql中UPDATE_BY过滤条件不需要，这里强制变为null
		if(param.getReduceHandleStatus() == CommonConstants.ONE_INT){
			param.setUpdateBy(null);
		}
		//如勾选项不为空，则导出勾选记录；否则导出当前筛选条件下 && 「待减员」的结果集
		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 (CommonConstants.THREE_INT == record.getBuyType()){
						if (Objects.isNull(record.getPolicyEffect())){
							record.setBuyMonth(null);
							record.setBuyDay(null);
						}else {
							record.setBuyMonth(LocalDateUtil.betweenMonth(record.getPolicyEffect().toString(),record.getPolicyEnd().toString()));
							record.setBuyDay(LocalDateUtil.betweenDay(record.getPolicyEffect().toString(),record.getPolicyEnd().toString()));
						}
					}
					if (data != null) {
						ProjectSetInfoVo jsonObject = data.get(record.getDeptNo());
						if (null != jsonObject) {
							record.setInvoiceTitle(Optional.ofNullable(jsonObject.getInvoiceTitleInsurance()).orElse(""));
						}
					}
					//如果是待减员，需要处理相关逻辑，减员中、减员成功只是单纯的导出
					if(param.getReduceHandleStatus() == CommonConstants.ONE_INT){
						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)){
				List<String> idList = new ArrayList<>();
				for (TInsuranceDetail s : detailList) {
					LambdaUpdateWrapper<TInsuranceDetail> updateWrapper = new LambdaUpdateWrapper<>();
					updateWrapper.eq(TInsuranceDetail :: getId,s.getId()).set(TInsuranceDetail :: getReduceHandleStatus,CommonConstants.TWO_INT);
					update(updateWrapper);
					idList.add(s.getId());
				}
				// 商险办理，更新离职待办
				this.sendLeave(idList, CommonConstants.SIX_STRING, CommonConstants.ONE_STRING, null, user);
			}
			//批量更新
			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<>();
		//被替换人的档案要处理状态
		List<String> sourceIdCardList = new ArrayList<>();
		// 被替换的id
		List<String> replaceIdList = 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);

						// 已减员
						this.sendLeaveById(tInsuranceDetail.getId(), CommonConstants.EIGHT_STRING, CommonConstants.ONE_STRING, remark, user);
					}else {
						tInsuranceDetail.setBuyHandleStatus(CommonConstants.THREE_INT);

						// 9减员退回
						this.sendLeaveById(tInsuranceDetail.getId(), CommonConstants.NINE_STRING, CommonConstants.ZERO_STRING, remark, user);
					}
					tInsuranceDetail.setUpdateBy(user.getId());
					tInsuranceDetail.setUpdateTime(LocalDateTime.now());
					successList.add(tInsuranceDetail);
					sourceIdCardList.add(tInsuranceDetail.getEmpIdcardNo());
					replaceIdList.add(tInsuranceDetail.getId());
					//更新减员记录
					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);
		// 减员失效
		this.doFailInfo(successList, sourceIdCardList, replaceIdList, CommonConstants.THREE_STRING);
		//操作记录
		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);
		}
		List<InsuranceHandleImportParam> list = insuranceChangeCheck(insuranceRefundImportList,true);
		//检验成功的数据
		List<InsuranceHandleImportParam> successList = list.stream().filter(e-> e.getErrorMessage().equals(CommonConstants.RESULT_DATA_SUCESS)).collect(Collectors.toList());
		//减员退回
		List<TInsuranceOperate> operateList =new ArrayList<>(16);
		List<TInsuranceDetail> sourceList = new ArrayList<>();
		//被替换人的档案要处理状态
		List<String> sourceIdCardList = new ArrayList<>();
		// 被替换的id
		List<String> replaceIdList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(successList)) {
			TInsuranceOperate operate;
			TInsuranceDetail detail;
			for (InsuranceHandleImportParam param : successList) {
				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());
				detail = this.getById(param.getId());
				detail.setUpdateBy(user.getId());
				detail.setUpdateTime(LocalDateTime.now());
				if(InsurancesConstants.SUCCESS.equals(param.getHandType())){
					detail.setReduceHandleStatus(CommonConstants.FOUR_INT);
					detail.setBuyHandleStatus(CommonConstants.FIVE_INT);
					refund.set(TInsuranceRefund :: getReduceHandleStatus,CommonConstants.FOUR_INT);
				}else{
					detail.setReduceHandleStatus(CommonConstants.THREE_INT);
					refund.set(TInsuranceRefund :: getReduceHandleStatus,CommonConstants.THREE_INT);
				}
				this.updateById(detail);
				sourceList.add(detail);
				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);

					// 商险办理，更新离职待办
					this.sendLeaveById(param.getId(), CommonConstants.EIGHT_STRING, CommonConstants.ONE_STRING, param.getRemark(), user);
				}else{
					operate.setOperateDesc(InsurancesConstants.INSURANCE_REFUND_FAILED);

					// 商险办理，更新离职待办
					this.sendLeaveById(param.getId(), CommonConstants.NINE_STRING, CommonConstants.ONE_STRING, param.getRemark(), user);
				}
				operateList.add(operate);
				sourceIdCardList.add(detail.getEmpIdcardNo());
				replaceIdList.add(detail.getId());


			}

		}
		tInsuranceOperateService.saveBatch(operateList);
		// 减员失效
		this.doFailInfo(sourceList, sourceIdCardList, replaceIdList, CommonConstants.THREE_STRING);
		if (list.stream().allMatch(e->e.getErrorMessage().equals(CommonConstants.RESULT_DATA_SUCESS))) {
			list = null;
		}
		return R.ok(list, 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 = doJointInsuranceTask.insertInsrancesDetail(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) {
					//取出预估和实缴的是否需要推送的状态
					boolean sjFlag = true;
					boolean ygFlag = true;
					if ((Common.isNotNull(success.getSettleStatus()) &&
							(InsurancesConstants.SETTLE_ONE.equals(success.getSettleStatus()) ||
									InsurancesConstants.SETTLE_TWO.equals(success.getSettleStatus())))
							|| (Common.isNotNull(success.getPaySettleStatus()) &&
							(InsurancesConstants.SETTLE_ONE.equals(success.getPaySettleStatus()) ||
									InsurancesConstants.SETTLE_TWO.equals(success.getPaySettleStatus())))){
						sjFlag = false;
					}
					if ((Common.isNotNull(success.getYgSettleStatus()) &&
							(InsurancesConstants.SETTLE_ONE.equals(success.getYgSettleStatus()) ||
							InsurancesConstants.SETTLE_TWO.equals(success.getYgSettleStatus())))
							|| (Common.isNotNull(success.getYgPaySettleStatus()) &&
							(InsurancesConstants.SETTLE_ONE.equals(success.getYgPaySettleStatus()) ||
							InsurancesConstants.SETTLE_TWO.equals(success.getYgPaySettleStatus())))){
						ygFlag = false;
					}
					//新的结算信息
					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 :: getDeptName,success.getNewDeptName())
							.set(TInsuranceDetail :: getUnitNo,success.getNewCustomerCode())
							.set(TInsuranceDetail :: getUnitName,success.getNewCustomerName())
							.set(TInsuranceDetail :: getDeptId,success.getNewDeptId())
							.set(TInsuranceDetail :: getUnitId,success.getNewCustomerId())
							.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) && 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().isEmpty()) {
							//原项目生成红冲数据
							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, null);
						}
					}
					//商险id
					String insuranceDetailId = success.getId();
					//旧结算信息id
					String oldDefaultSettleId = success.getDefaultSettleId();
					//如果变更前为单独结算
					if(CommonConstants.ONE_INT == oldSettleType){
						//登记了保单保费
						if (!BigDecimalUtils.isNullOrZero(actualPremium) && sjFlag) {
							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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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)){
							//如果预估和实缴都推送了
							if(byId.getIsActualPush() == CommonConstants.ONE_INT &&
									byId.getIsEstimatePush() == CommonConstants.ONE_INT && ygFlag && sjFlag){
								//新增新的结算信息
								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);
								//推送作废结算信息至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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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 && ygFlag){
								//新增新的结算信息
								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);
								//推送作废结算信息至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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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){
								//新增新的结算信息
								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);
								//先推送预估，再推送实际
								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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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 ){
								if (ygFlag) {
									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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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 = doJointInsuranceTask.insertInsrancesDetail(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);
								}
							}
						}
					}
					//新增项目变更的操作信息
					TInsurancesChangeLog insuranceOperate = new TInsurancesChangeLog();
					insuranceOperate.setPreId(success.getId());
					insuranceOperate.setCreateBy(user.getId());
					insuranceOperate.setCreateName(user.getNickname());
					insuranceOperate.setCreateTime(LocalDateTime.now());
					insuranceOperate.setReason("项目变更");
					insuranceOperate.setDifferenceInfo("deptName,deptNo");
					Map<String, String> oldMap = new HashMap<>();
					oldMap.put("deptName", success.getOldDeptName());
					oldMap.put("deptNo", success.getOldDeptNo());
					insuranceOperate.setOldInfo(JSON.toJSONString(oldMap, features));
					Map<String, String> newMap = new HashMap<>();
					newMap.put("deptName", success.getNewDeptName());
					newMap.put("deptNo", success.getNewDeptNo());
					insuranceOperate.setNewInfo(JSON.toJSONString(newMap, features));
					insurancesChangeLogService.save(insuranceOperate);
//					operateList.add(insuranceOperate);
				}
			});
		}
		//改变原来写法，原来逻辑在执行这段代码前前面的线程任务还在执行operateList并没值，所以日志没保存上
//		tInsuranceOperateService.saveBatch(operateList);
		List<DeptChangeCheckParam> errorList = stringListMap.get(InsurancesConstants.ERROR_LIST);
		return R.ok(errorList,InsurancesConstants.IMPORT_SUCCESS);
	}

	private static final SerializerFeature[] features = new SerializerFeature[]{
			WriteMapNullValue, WriteNullNumberAsZero, WriteNullListAsEmpty,
			WriteNullStringAsEmpty, WriteDateUseDateFormat
	};

	/**
	 * 根据保险公司名称查询保单明细
	 *
	 * @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 zhangyun
	 * @param paramList 导入参数
	 * @return {@link R}
	 */
	@Override
	public R updateRefundMoney(List<RefundMoneyUpdateParam> paramList) {
		YifuUser user = SecurityUtils.getUser();
		//获取当前登录人的商险办理地权限
		LambdaQueryWrapper<TInsuranceAreaRes> areaQuery = new LambdaQueryWrapper<>();
		areaQuery.eq(TInsuranceAreaRes::getUserId,user.getId()).eq(TInsuranceAreaRes::getStatus,CommonConstants.ZERO_INT);
		List<TInsuranceAreaRes> insuranceAreaResList = tInsuranceAreaResService.list(areaQuery);
		if(CollectionUtils.isEmpty(insuranceAreaResList)) {
			return R.failed(InsurancesConstants.NO_PERMISSION);
		}
		Map<String, List<RefundMoneyUpdateParam>> map = refundMoneyCheck(paramList,insuranceAreaResList);

		List<RefundMoneyUpdateParam> successList = map.get(InsurancesConstants.SUCCESS_LIST);
		List<TInsuranceOperate> insuranceOperateList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(successList)){
			for (RefundMoneyUpdateParam param : successList) {
				TInsuranceRefund insuranceRefund = new TInsuranceRefund();
				insuranceRefund.setId(param.getId());
				insuranceRefund.setRefundMoney(new BigDecimal(param.getRefundMoney()));
				insuranceRefund.setReduceHandleStatus(CommonConstants.FOUR_INT);
				insuranceRefund.setUpdateBy(user.getId());
				insuranceRefund.setUpdateTime(LocalDateTime.now());
				tInsuranceRefundService.updateRefundMoney(insuranceRefund);
				//新增操作记录
				TInsuranceOperate insuranceOperate = new TInsuranceOperate();
				insuranceOperate.setInsuranceDetailId(param.getInsDetailId());
				insuranceOperate.setCreateBy(user.getId());
				insuranceOperate.setCreateName(user.getNickname());
				insuranceOperate.setCreateTime(LocalDateTime.now());
				insuranceOperate.setDisplayFlag(CommonConstants.ONE_INT);
				insuranceOperate.setOperateDesc(InsurancesConstants.REGISTERED_SURRENDER_EXPENSE);
				insuranceOperateList.add(insuranceOperate);

				// 推送EKP
				if (param.getEkpInsurancesInfo() != null) {
					if (Common.isEmpty(param.getEkpInsurancesInfo().getFd_id())) {
						ekpInsurancesInfoMapper.insert(param.getEkpInsurancesInfo());
					} else {
						ekpInsurancesInfoMapper.updateById(param.getEkpInsurancesInfo());
					}
				}
			}
		}
		tInsuranceOperateService.saveBatch(insuranceOperateList);
		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(null == user ? "1" : user.getId());
		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;
			}
			//购买标准
			String buyStandard = param.getBuyStandard();
			if (StringUtils.isBlank(buyStandard)){
				param.setErrorMessage(InsurancesConstants.BUY_STANDARD_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			// 身份证号位数校验（18 位合法）
			if (!ValidityUtil.validateIDCard(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_LEGITIMATE);
				errorList.add(param);
				continue;
			}
			// 保单开始日期格式校验
			if(!LocalDateUtil.isDate(policyStart,LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_START_PARSE_ERROR);
				errorList.add(param);
				continue;
			}
			// 保单结束日期格式校验
			if(!LocalDateUtil.isDate(policyEnd,LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_END_PARSE_ERROR);
				errorList.add(param);
				continue;
			}
			//备注格式校验
			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))
					.eq(TInsuranceDetail::getBuyStandard,buyStandard)
					.orderByDesc(TInsuranceDetail::getUpdateTime)
					.eq(TInsuranceDetail::getIsEffect,CommonConstants.ZERO_STRING)
					.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(CollectionUtils.isEmpty(deptNoList)){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_IN_USER_DEPT_LIST);
				errorList.add(param);
				continue;
			}
			//非系统管理员，项目权限校验
			if(Common.isNotNull(user) && !CommonConstants.ZERO_STRING.equals(user.getSystemFlag())
					&& 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<RefundMoneyUpdateParam>> refundMoneyCheck(List<RefundMoneyUpdateParam> paramList,List<TInsuranceAreaRes> insuranceAreaResList){

		Map<String,List<RefundMoneyUpdateParam>> map = new HashMap<>(16);
		List<RefundMoneyUpdateParam> errorList = new ArrayList<>();
		List<RefundMoneyUpdateParam> successList = new ArrayList<>();
		// 查询或组装新的退费使用
		EkpInsurancesInfo ekpInsurancesInfo;
		// 查询商险，组装EKP的退费明细使用
		TInsuranceDetail insuranceDetail;

		// 获取身份证，获取项目信息（主要是bpo信息）
		List<String> idCardList = new ArrayList<>();
		for (RefundMoneyUpdateParam param : paramList) {
			//身份证号
			if(Common.isNotNull(param.getEmpIdcardNo())){
				idCardList.add(param.getEmpIdcardNo());
			}
		}
		// 存项目BPO信息
		Map<String, EkpInsuranceDeptInfoVo> deptMap = new HashMap<>();
		if (idCardList != null && !idCardList.isEmpty()) {
			List<String> deptNoList = this.baseMapper.selectDeptNoListByIdCard(idCardList);
			if (deptNoList != null && !deptNoList.isEmpty()) {
				// 查找EKP项目信息
				deptMap = ekpSettleService.getEkpDeptInfoByDeptNo(deptNoList);
			}
		}

		EkpInsuranceDeptInfoVo deptInfo;
		double yingShou;
		double yingZhi;
		for (RefundMoneyUpdateParam param : paramList) {

			//姓名
			if(StringUtils.isBlank(param.getEmpName())){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//身份证号
			if(StringUtils.isBlank(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			//保险公司
			if(StringUtils.isBlank(param.getInsuranceCompanyName())){
				param.setErrorMessage(InsurancesConstants.REFUND_INSURANCE_COMPANY_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

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

			//保单开始时间为空
			if(StringUtils.isBlank(param.getPolicyStart())){
				param.setErrorMessage(InsurancesConstants.REFUND_INSURANCE_START_DATE_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//保单开始时间格式不正确
			if(!LocalDateUtil.isDate(param.getPolicyStart(),LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_START_PARSE_ERROR);
				errorList.add(param);
				continue;
			}
			//保单结束时间
			if(StringUtils.isBlank(param.getPolicyEnd())){
				param.setErrorMessage(InsurancesConstants.REFUND_INSURANCE_END_DATE_NOT_EMPTY);
				errorList.add(param);
				continue;
			}
			//保单结束时间格式不正确
			if(!LocalDateUtil.isDate(param.getPolicyEnd(),LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_END_PARSE_ERROR);
				errorList.add(param);
				continue;
			}
			//购买标准
			if(StringUtils.isBlank(param.getBuyStandard())){
				param.setErrorMessage(InsurancesConstants.REFUND_BUY_STANDARD_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			//退费金额
			if(StringUtils.isBlank(param.getRefundMoney())){
				param.setErrorMessage(InsurancesConstants.REFUND_MONEY_NOT_EMPTY);
				errorList.add(param);
				continue;
			}

			if(!ValidityUtil.validateMoney(param.getRefundMoney())){
				param.setErrorMessage(InsurancesConstants.REFUND_MONEY_PARSE_ERROR);
				errorList.add(param);
				continue;
			}

			//必填格式校通过后查询对应的保单信息
			InsuranceRefundVo insuranceRefund = this.baseMapper.selectRefundDetailId(param);
			if(Common.isEmpty(insuranceRefund)){
				param.setErrorMessage(InsurancesConstants.REFUND_IS_NULL);
				errorList.add(param);
				continue;
			}else{
				if(null == insuranceRefund.getInsuranceHandleProvince() || null == insuranceRefund.getInsuranceHandleCity()){
					param.setErrorMessage(InsurancesConstants.HANDLE_PROVINCE_IS_NULL);
					errorList.add(param);
					continue;
				}
				//商险办理地权限校验
				if(insuranceAreaResList.stream().noneMatch(s -> insuranceRefund.getInsuranceHandleCity().toString().equals(s.getCity())
						&& insuranceRefund.getInsuranceHandleProvince().toString().equals(s.getProvince()))){
					param.setErrorMessage(InsurancesConstants.NO_DETAIL_JURISDICTION);
					errorList.add(param);
					continue;
				}else{
					String refundMoney = param.getRefundMoney();
					if(!BigDecimalUtils.isNullOrZero(insuranceRefund.getRefundMoney()) && insuranceRefund.getRefundMoney().compareTo(new BigDecimal(refundMoney)) == CommonConstants.ZERO_INT){
						continue;
					}
				}
				if (Common.isEmpty(insuranceRefund.getInsDetailId())) {
					param.setErrorMessage(InsurancesConstants.REFUND_NO_INS_DETAIL_ID);
					errorList.add(param);
					continue;
				}
				// 检测EKP的商险明细的支出状态是否已结算或结算中：
				ekpInsurancesInfo = ekpInsurancesInfoMapper.getEkpInsurancesInfoByRefund(insuranceRefund.getInsDetailId());
				if (ekpInsurancesInfo != null) {
					if (InsurancesConstants.SETTLE_ONE.equals(ekpInsurancesInfo.getFd_3adfe6eda67236())) {
						param.setErrorMessage(InsurancesConstants.REFUND_ZH_SETTLE);
						errorList.add(param);
						continue;
					}
					if (InsurancesConstants.SETTLE_TWO.equals(ekpInsurancesInfo.getFd_3adfe6eda67236())) {
						param.setErrorMessage(InsurancesConstants.REFUND_YI_SETTLE);
						errorList.add(param);
						continue;
					}

				} else {
					ekpInsurancesInfo = new EkpInsurancesInfo();
					insuranceDetail = this.getById(insuranceRefund.getInsDetailId());
					if (insuranceDetail == null) {
						param.setErrorMessage(InsurancesConstants.REFUND_YI_SETTLE);
						errorList.add(param);
						continue;
					}
					try {
						this.initValues(ekpInsurancesInfo, insuranceDetail, param, CommonConstants.FOUR_STRING);
					} catch (Exception e) {
						param.setErrorMessage(InsurancesConstants.ACTUAL_PREMIUM_PARSE_ERROR);
						errorList.add(param);
						continue;
					}
				}
				//实际保费
				if (Common.isNotNull(param.getRefundMoney())) {
					ekpInsurancesInfo.setFd_3adfe6610c0d2c(-Double.parseDouble(param.getRefundMoney()));
				}
				//发生日期（更新时会变动——倩倩与郭彤已知）
				ekpInsurancesInfo.setFd_3adfe67c24dace(DateUtil.getCurrentDateTime());
				if (Common.isNotNull(ekpInsurancesInfo.getFd_3adfe658c6229e())) {
					deptInfo = deptMap.get(ekpInsurancesInfo.getFd_3adfe658c6229e());
					if (deptInfo == null) {
						param.setErrorMessage(InsurancesConstants.GET_DEPT_DETAIL_ERROR);
						errorList.add(param);
						continue;
					}
					// 是否为BPO业务
					ekpInsurancesInfo.setFd_3b178fab62d196(deptInfo.getIsBpo());
					// 是否启用BPO结算模式
					ekpInsurancesInfo.setFd_usebpo_settle(deptInfo.getBpoSettle());
					//商险封面抬头
					ekpInsurancesInfo.setFd_3b941cbcea3e1a(deptInfo.getInsurancesTitle());

					// HRO登记的退费为正数，推送到EKP后，为负数，具体为应收还是应支如下：
					//商险退费不退款，生成的EKP明细，有没有应收，逻辑如下：
					//【是】BPO项目，没有应收，有应支。（收款过程和结束，改明细的收款状态）
					//【非】BPO项目，有应收，有应支。

					yingZhi = ekpInsurancesInfo.getFd_3adfe6610c0d2c();
					if ("是".equals(deptInfo.getIsBpo())) {
						yingShou = 0.0;
					} else {
						yingShou = ekpInsurancesInfo.getFd_3adfe6610c0d2c();
					}
					//应收
					ekpInsurancesInfo.setFd_3adfe6e30f2a3c(yingShou);
					//应支
					ekpInsurancesInfo.setFd_3adfe6e3911ffe(yingZhi);
				} else {
					param.setErrorMessage(InsurancesConstants.GET_DEPT_DETAIL_ERROR);
					errorList.add(param);
					continue;
				}
				param.setEkpInsurancesInfo(ekpInsurancesInfo);
			}
			param.setId(insuranceRefund.getId());
			param.setInsDetailId(insuranceRefund.getInsDetailId());
			successList.add(param);
		}

		map.put(InsurancesConstants.ERROR_LIST,errorList);
		map.put(InsurancesConstants.SUCCESS_LIST,successList);
		return map;
	}

	// 初始化EKP商险明细，用来退保不退费
	public void initValues(EkpInsurancesInfo pushParam, TInsuranceDetail insuranceDetail, RefundMoneyUpdateParam param, String code) throws Exception {
		//单据类型：退费
		pushParam.setFd_3adfe6af71a1cc(InsurancesConstants.REFUND_TYPE);
		// 实际结算月份默认为空
		pushParam.setFd_3af9d11088facc(null);
		//有无预估
		pushParam.setFd_3af9d1441ef7b6(CommonConstants.EMPTY_STRING);

		//预估金额
		pushParam.setFd_3af9d15f7018fa(null);
		//预估金额已收
		pushParam.setFd_3af9d1662141a4(null);
		//是否全部结算
		pushParam.setFd_3b13b2ecc164aa("是");

		//项目编码
		pushParam.setFd_3adfe658c6229e(null != insuranceDetail.getDeptNo() ? insuranceDetail.getDeptNo() : CommonConstants.EMPTY_STRING);
		//项目名称
		pushParam.setFd_3adfe6592b4158(null != insuranceDetail.getDeptName() ? insuranceDetail.getDeptName() : CommonConstants.EMPTY_STRING);
		//单号,sxdd + 商险id + 标识
		pushParam.setFd_3adfe67a9f6364("SXDD" + LocalDateTimeUtils.formatTime(LocalDateTime.now(), DateUtil.ISO_DATE_FORMAT)
				+ insuranceDetail.getId() + code );
		//项目id 项目编码
		pushParam.setFd_3b16dfb32778f2(insuranceDetail.getDeptId());
		pushParam.setFd_3b16dfb32778f2_text(insuranceDetail.getDeptNo());

		//客户编码
		pushParam.setFd_3adfe6598281e8(insuranceDetail.getUnitNo());
		//客户名称
		pushParam.setFd_3adfe7a2688902(insuranceDetail.getUnitName());
		//发生日期（更新时会变动——倩倩与郭彤已知）
		pushParam.setFd_3adfe67c24dace(DateUtil.getCurrentDateTime());

		//姓名
		pushParam.setFd_3adfe65d759650(null != param.getEmpName() ? param.getEmpName() : CommonConstants.EMPTY_STRING);
		//身份证号
		pushParam.setFd_3adfe65dbd9f68(null != param.getEmpIdcardNo() ? param.getEmpIdcardNo() : CommonConstants.EMPTY_STRING);
		//发票号
		pushParam.setFd_3adfe65e0cd094(CommonConstants.EMPTY_STRING);

		//险种
		pushParam.setFd_3adfe65f6599e4(null != param.getInsuranceTypeName() ? param.getInsuranceTypeName() : CommonConstants.EMPTY_STRING);
		//保险公司
		pushParam.setFd_3adfe65ea04728(null != param.getInsuranceCompanyName() ? param.getInsuranceCompanyName() : CommonConstants.EMPTY_STRING);
		//保单号
		pushParam.setFd_3adfe65e60e110(CommonConstants.EMPTY_STRING);

		//保险开始日期
		pushParam.setFd_3adfe6b7e0ede8(null != param.getPolicyStart() ? DateUtil.stringToDate(param.getPolicyStart()) : null);
		//保险结束日期
		pushParam.setFd_3adfe6b847bfe6(null != param.getPolicyEnd() ? DateUtil.stringToDate(param.getPolicyEnd()) : null);
		//购买标准
		pushParam.setFd_3adfe6d55384c6(Common.isNotNull(param.getBuyStandard()) ? Double.parseDouble(param.getBuyStandard()) : null);

		//医保
		pushParam.setFd_3adfe66041a996(null);
		//事故或残疾
		pushParam.setFd_3adfe6609aa810(CommonConstants.EMPTY_STRING);

		// 状态
		pushParam.setFd_3af9197b31071c(CommonConstants.EMPTY_STRING);
		// 商险ID
		pushParam.setFd_3b0a5743acab7e(insuranceDetail.getId());
		//hro结算月
		pushParam.setFd_3b13b3076af5a0(null);

		//是否为BPO业务
		pushParam.setFd_3b178fab62d196("否");

		//结算状态
		pushParam.setFd_3adfe6ec6a8cbe("未结算");
		//收款状态
		pushParam.setFd_3adfe6ef5dfaac("未收");
		//支出结算状态
		pushParam.setFd_3adfe6eda67236("未结算");
		//付款状态
		pushParam.setFd_3adfe6f05531ec("未付");
		//创建时间
		pushParam.setCreateTime(DateUtil.getCurrentDateTime());
	}


	/**
	 * 结算月份校验
	 *
	 * @author zhaji
	 * @param settleMonthCheckList 变更列表
	 * @return {@link R}
	 */
	private Map<String,List<SettleMonthChangeCheckParam>> settleMonthChangeCheck(List<SettleMonthChangeCheckParam> settleMonthCheckList,YifuUser user) {
		List<String> deptNoList = getDeptNoList(null == user ? "1" : user.getId());
		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(CollectionUtils.isEmpty(deptNoList)){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_IN_USER_DEPT_LIST);
				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(Common.isNotNull(param.getSettleMonth()) && !LocalDateUtil.isDate(param.getSettleMonth(),LocalDateUtil.NORM_MONTH_PATTERN)){
				param.setErrorMessage(InsurancesConstants.SETTLE_MONTH_PARSE_ERROR);
				errorList.add(param);
				continue;
			}
			if(Common.isNotNull(param.getSettleMonth()) && !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);
			//如果保单信息为空
			if (Common.isEmpty(insuranceDetail)){
				param.setErrorMessage(InsurancesConstants.USER_DATA_IS_NOT_EXIST);
				errorList.add(param);
				continue;
			}
			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;
			}
			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 flag true 减员 false 投保成功/退回
	 * @return {@link Map<String, List<InsuranceHandleImportParam>}
	 */
	private List<InsuranceHandleImportParam> insuranceChangeCheck(List<InsuranceHandleImportParam> checkList, boolean flag) {
		List<InsuranceHandleImportParam> distinctList = checkList.stream().distinct().collect(Collectors.toList());
		//定义外层循环标识，方便去重的时候跳出
		Map<String,String> map = new HashMap<>();
		InsuranceHandleImportParam param;
		String handType;
		String remark;
		TInsuranceDetail insuranceDetail;
		for (int i = 0; i < distinctList.size(); i++) {
			param = distinctList.get(i);
			//办理结果
			param.setFlag(CommonConstants.ONE_STRING);
			handType = param.getHandType();
			if(StringUtils.isBlank(handType)){
				param.setErrorMessage(InsurancesConstants.HAND_RESULT_IS_EMPTY);
				continue;
			}
			if(!InsurancesConstants.SUCCESS.equals(handType) && !InsurancesConstants.FAILED.equals(handType)){
				param.setErrorMessage(InsurancesConstants.HAND_RESULT_ERROR);
				continue;
			}
			//办理意见
			remark = param.getRemark();
			if(InsurancesConstants.FAILED.equals(handType) && StringUtils.isBlank(remark)){
				param.setErrorMessage(InsurancesConstants.ROLLBACK_MESSAGE_IS_EMPTY);
				continue;
			}
			if(StringUtils.isNotBlank(remark) && !ValidityUtil.validate50(remark)){
				param.setErrorMessage(InsurancesConstants.HAND_REMARK_NOT_MORE_THAN_50);
				continue;
			}
			//员工姓名
			if(StringUtils.isBlank(param.getEmpName())){
				param.setErrorMessage(InsurancesConstants.EMP_NAME_NOT_EMPTY);
				continue;
			}
			//员工身份证
			if(StringUtils.isBlank(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_EMPTY);
				continue;
			}
			//保险公司名称
			if(StringUtils.isBlank(param.getInsuranceCompanyName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EMPTY);
				continue;
			}
			//险种名称
			if(StringUtils.isBlank(param.getInsuranceTypeName())){
				param.setErrorMessage(InsurancesConstants.INSURANCE_TYPE_NAME_NOT_EMPTY);
				continue;
			}
			//购买标准
			if(StringUtils.isBlank(param.getBuyStandard())){
				param.setErrorMessage(InsurancesConstants.BUY_STANDARD_NOT_EMPTY);
				continue;
			}
			//保单开始日期
			if(StringUtils.isBlank(param.getPolicyStart())){
				param.setErrorMessage(InsurancesConstants.POLICY_START_NOT_EMPTY);
				continue;
			}
			//保单结束日期
			if(StringUtils.isBlank(param.getPolicyEnd())){
				param.setErrorMessage(InsurancesConstants.POLICY_END_NOT_EMPTY);
				continue;
			}
			// 身份证号位数校验（18 位合法）
			if (!ValidityUtil.validateIDCard(param.getEmpIdcardNo())){
				param.setErrorMessage(InsurancesConstants.EMP_IDCARD_NO_NOT_LEGITIMATE);
				continue;
			}
			// 保单开始日期格式校验
			if(!LocalDateUtil.isDate(param.getPolicyStart(),LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_START_PARSE_ERROR);
				continue;
			}
			// 保单结束日期格式校验
			if(!LocalDateUtil.isDate(param.getPolicyEnd(),LocalDateUtil.NORM_DATE_PATTERN)){
				param.setErrorMessage(InsurancesConstants.POLICY_END_PARSE_ERROR);
				continue;
			}

			//表内数据重复 员工姓名、员工身份证号码、保险公司名称、险种名称、保单开始日期、保单结束日期、购买标准 去重
			StringBuilder errorTemp = new StringBuilder();
			errorTemp.append(param.getEmpName());
			errorTemp.append("_");
			errorTemp.append(param.getEmpIdcardNo());
			errorTemp.append("_");
			errorTemp.append(param.getInsuranceCompanyName());
			errorTemp.append("_");
			errorTemp.append(param.getInsuranceTypeName());
			errorTemp.append("_");
			errorTemp.append(param.getPolicyStart());
			errorTemp.append("_");
			errorTemp.append(param.getPolicyEnd());
			errorTemp.append("_");
			errorTemp.append(param.getBuyStandard());
			if (null == map.get(errorTemp.toString())) {
				map.put(errorTemp.toString(),"1");
			} else {
				param.setErrorMessage(InsurancesConstants.DUPLICATE_DATA_ERROR);
				continue;
			}

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

	/**
	 * 获取投保状态的值
	 *
	 * @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(null == user ? "1" : user.getId());
		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)){
				errorList.add(param);
				param.setErrorMessage(InsurancesConstants.POLICY_START_NOT_EMPTY);
				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());
					param.setNewDeptId(jsonObject.getId());
					param.setNewCustomerId(jsonObject.getCustomerId());
					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);
			//如果保单信息为空
			if (Common.isEmpty(insuranceDetail)){
				param.setErrorMessage(InsurancesConstants.USER_DATA_IS_NOT_EXIST);
				errorList.add(param);
				continue;
			}
			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(CollectionUtils.isEmpty(deptNoList)){
				param.setErrorMessage(InsurancesConstants.DEPT_NO_NOT_IN_USER_DEPT_LIST);
				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;
						}
					}
					DeptSettleVo deptSettleVo = deptUpdGetSettleStatusFromEkpInsuranceDetail(insuranceDetail.getId(), defaultSettleId);
					if(Common.isNotNull(deptSettleVo)){
						param.setSettleStatus(deptSettleVo.getSettleStatus());
						param.setPaySettleStatus(deptSettleVo.getPaySettleStatus());
					}
					DeptSettleVo deptYgSettleVo = deptYgGetSettleStatusFromEkpInsuranceDetail(insuranceDetail.getId(), defaultSettleId);
					if(Common.isNotNull(deptYgSettleVo)){
						param.setYgSettleStatus(deptYgSettleVo.getSettleStatus());
						param.setYgPaySettleStatus(deptYgSettleVo.getPaySettleStatus());
					}
				}
			}

			//预估
			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(null == user ? "1" : user.getId());
		List<Dept> deptList = new ArrayList<>(16);
		if (CollectionUtils.isNotEmpty(deptNoList)){
			R<SetInfoVo> setInfoByCodes = archivesDaprUtil.getSetInfoByCodes(deptNoList);
			if (null != setInfoByCodes && setInfoByCodes.getCode() == CommonConstants.SUCCESS && Common.isNotNull(setInfoByCodes.getData())) {
				SetInfoVo data = setInfoByCodes.getData();
				if (Optional.ofNullable(data).isPresent()){
					Map<String, ProjectSetInfoVo> projectSetInfoVoMap = data.getProjectSetInfoVoMap();
					if (MapUtils.isNotEmpty(projectSetInfoVoMap)){
						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<>();
		for (TInsuranceDetail tInsuranceDetail : list) {
			LambdaUpdateWrapper<TInsuranceDetail>  updateWrapper = new LambdaUpdateWrapper<>();
			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紧急出险成功");

	}

	/**
	 * 紧急出险
	 *
	 * @param paramList 商险明细id集合
	 * @return {@link R}
	 * @author licancan
	 */
	@Override
	@Transactional(value = "insurancesTransactionManager" ,rollbackFor = {Exception.class})
	public R urgentUpdateIsUseByIds(List<String> paramList) {
		List<TInsuranceOperate> operateList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(paramList)){
			paramList.stream().forEach(e ->{
				TInsuranceDetail byId = this.getById(e);
				if (Optional.ofNullable(byId).isPresent()){
					if (byId.getIsUse() != CommonConstants.ONE_INT){
						TInsuranceOperate operate = new TInsuranceOperate();
						byId.setIsUse(CommonConstants.ONE_INT);
						byId.setUpdateTime(LocalDateTime.now());
						updateById(byId);
						operate.setOperateDesc(InsurancesConstants.URGENT_UPDATE_IS_USE);
						operate.setCreateName(InsurancesConstants.SYSTEM_TRIGGER);
						operate.setInsuranceDetailId(byId.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(),false);
	}

	@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(),false);
	}

	@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(),false);
	}

	@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(), SecurityUtils.getUser());
	}

	/**
	 * 订单商险列表查询
	 *
	 * @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 userId mapSelectVo
	 * @return {@link List< String>}
	 */
	public List<String> getDeptNoList(String userId){
		List<String> deptList = new ArrayList<>(16);
		try{
			R<TSettleDomainListVo> settleDomainList = archivesDaprUtil.getSettleDomainIdsByUserId(userId);
			if(Common.isNotNull(settleDomainList) && settleDomainList.getCode() == CommonConstants.SUCCESS){
				TSettleDomainListVo data = settleDomainList.getData();
				if (Optional.ofNullable(data).isPresent()){
					deptList = data.getDeptNos();
				}
			}
		}catch (Exception e){
			log.error("查询项目信息出错："+e);
		}
		return deptList;
	}
	/**
	 * 获取项目权限
	 *
	 * @author zhaji
	 * @param userId
	 * @return {@link List< String>}
	 */
	public List<String> getDeptNoMapAndDeptNo(String userId){
		List<String> deptList = new ArrayList<>(16);
		try{
			R<TSettleDomainListVo> settleDomainList = archivesDaprUtil.getSettleDomainIdsByUserId(userId);
			if(Common.isNotNull(settleDomainList) && settleDomainList.getCode() == CommonConstants.SUCCESS){
				TSettleDomainListVo data = settleDomainList.getData();
				if (Optional.ofNullable(data).isPresent()){
					deptList = data.getDeptNos();
				}
			}
		}catch (Exception e){
			log.error("查询项目信息出错："+e);
		}
		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();
		TInsuranceSettleCancel cancel = new TInsuranceSettleCancel();
		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);
		}
		//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 = doJointInsuranceTask.insertInsrancesDetail(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 huyc
	 * @param
	 * @return {@link String}
	 */
	@Override
	public DeptSettleVo deptUpdGetSettleStatusFromEkpInsuranceDetail(String detailId,String settleId){
		String id = detailId+CommonConstants.DOWN_LINE_STRING+settleId;
		//获取ekp结算信息
		return ekpSettleService.getDeptSettle(id);
	}

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

	/**
	 * 从商险订单明细中获取当前保单的结算状态
	 *
	 * @author huyc
	 * @param
	 * @return {@link String}
	 */
	@Override
	public EkpSettleStatusVo getSettleStatusFromEkpInsuranceDetail(String detailId, String settleId){
		String id = detailId+CommonConstants.DOWN_LINE_STRING+settleId;
		//获取ekp结算信息
		return ekpSettleService.getSettleStatusFromEkpInsuranceDetail(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) {
		if (Common.isEmpty(settleDomain)) {
			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 = CommonConstants.ONE_INT == insuranceDetail.getSettleType() ? insuranceDetail.getActualPremium() : insuranceDetail.getEstimatePremium();

		//判断是否为按人次收费
		int isSum = 0;
		if (Common.isNotNull(settleDomain)) {
			// 含有商险，则计算收入
			if (Common.isNotNull(settleDomain.getManageServerItem()) && settleDomain.getManageServerItem()
					.contains(CommonConstants.THREE_STRING) && CommonConstants.ZERO_STRING.equals(settleDomain.getManagementTag())) {
				//预估模式
				if (CommonConstants.ONE_STRING.equals(settleDomain.getMrSettleType())) {
					//预估模式只有按人次和人数收费
					if (CommonConstants.THREE_STRING.equals(settleDomain.getManagementType()) &&
							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, RoundingMode.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) && CommonConstants.ZERO_STRING.equals(settleDomain.getRiskFundTag())) {
				//预估模式
				if (CommonConstants.ONE_STRING.equals(settleDomain.getMrSettleType())) {
					if (CommonConstants.THREE_STRING.equals(settleDomain.getRiskFundType()) &&
							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, RoundingMode.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);
	}

	@Override
	public void ekpUpdateInsuranceDept(ChangeDeptVo changeDeptVo) {
		Set<String> detailIdSet = new HashSet<>();
		for (ChangeDeptDetailVo vo : changeDeptVo.getShangxian()) {
			if (Common.isNotNull(vo.getId())) {
				detailIdSet.add(vo.getId().split(CommonConstants.DOWN_LINE_STRING)[0]);
			}
		}
		if (!detailIdSet.isEmpty()) {
			baseMapper.ekpUpdateInsuranceDept(detailIdSet, changeDeptVo.getDept());
		}
	}

	@Override
	public R updateInsuranceSettleStatus(EkpStatusParamVo vo) {
		if (Common.isEmpty(vo)) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		try {
			log.info("商险状态更新报文"+JSON.toJSONString(vo));
			doJointInsuranceTask.updateInsuranceSettleStatus(vo);
		}catch (Exception e) {
			log.error("商险结算状态更新异常", e);
			return R.failed("商险结算状态更新异常");
		}
		return R.ok();	}

	@Override
	public R updateSocialSettleStatus(EkpStatusParamVo vo) {
		if (Common.isEmpty(vo)) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		doJointInsuranceTask.updateSocialSettleStatus(vo);
		return R.ok();	}

	@Override
	public R updateIncomeSettleStatus(EkpStatusParamVo vo) {
		if (Common.isEmpty(vo)) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		doJointInsuranceTask.updateIncomeSettleStatus(vo);
		return R.ok();	}


	@Override
	public R updateSalarySettleStatus(EkpStatusParamVo vo) {
		if (Common.isEmpty(vo)) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		try {
			doJointInsuranceTask.updateSalarySettleStatus(vo);
		}catch (Exception e) {
			log.error("薪资结算状态更新异常", e);
			return R.failed("薪资结算状态更新异常");
		}
		return R.ok();	}

	@Override
	public void updateSettleStatus() {
		//获取所有结算状态同步失败的数据
		long count = updateStatusErrorMapper.selectCount(Wrappers.<TUpdateStatusError>query().lambda()
				.eq(TUpdateStatusError::getStatus,CommonConstants.ZERO_INT));
		if (count > 0) {
			List<TUpdateStatusError> list;
			int i = (int) Math.ceil((double) count / CommonConstants.TEN_THOUSAND_INT);
			for (int j = 0; j < i; j++) {
				//判断缴费库中社保合计和本次导入合计相加是否为0，为0则不生成收入
				list = updateStatusErrorMapper.selectList(Wrappers.<TUpdateStatusError>query().lambda()
						.eq(TUpdateStatusError::getStatus,CommonConstants.ZERO_INT).last(" limit 0,10000"));
				synchronized (this) {
					if (Common.isNotNull(list)) {
						for (TUpdateStatusError t: list) {
							//更新商险结算状态
							if (CommonConstants.FOUR_STRING.equals(t.getTypeFlag())) {
								doJointInsuranceTask.aUpdateInsuranceSettleStatus(t);
							}
							//更新社保结算状态
							if (CommonConstants.ONE_STRING.equals(t.getTypeFlag()) ||
									CommonConstants.ZERO_STRING.equals(t.getTypeFlag())) {
								doJointInsuranceTask.aUpdateSocialSettleStatus(t);
							}
							//更新收入结算状态
							if (CommonConstants.TWO_STRING.equals(t.getTypeFlag()) ||
									CommonConstants.THREE_STRING.equals(t.getTypeFlag())) {
								doJointInsuranceTask.aUpdateIncomeSettleStatus(t);
							}
							//更新薪资结算状态
							if (CommonConstants.FIVE_STRING.equals(t.getTypeFlag())) {
								doJointInsuranceTask.aUpdateSalarySettleStatus(t);
							}
						}
					}
				}
			}
		}
	}

	private Map<String, TSettleDomainSelectVo> getSelectVoMap() {
		R<TSettleDomainListVo> settleDomainR = archivesDaprUtil.selectAllSettleDomainSelectVos();
		Map<String,TSettleDomainSelectVo> mapSelectVo = null;
		if (Common.isNotNull(settleDomainR) && Common.isNotNull(settleDomainR.getData())){
			mapSelectVo = settleDomainR.getData().getMapSelectVo();
		}
		if (Common.isEmpty(mapSelectVo)){
			throw new CheckedException(CommonConstants.SETTLE_DOMAIN_GET_ERROR);
		}
		return mapSelectVo;
	}
	/**
	 * @Author fxj
	 * @Description 商险到期提醒分页查询
	 * @Date 16:51 2023/2/16
	 **/
	@Override
	public IPage<TBusinessInsuranceVo> getInsuranceExpireWarnVoPage(Page<TBusinessInsuranceVo> page, InsuranceSearchVo condition) {
		YifuUser user = SecurityUtils.getUser();
		long roleId = 1851541100126863362L;
		long roleId2 = 1536909784224051202L;
		boolean isSsc =	this.haveRole(user, roleId);
		boolean isProjectManager = this.haveRole(user, roleId2);
		if (isSsc) {
			condition.setAlertId(null);
		} else {
			if (isProjectManager){
				condition.setAlertId(null);
			}else{
				condition.setAlertId(user.getId());
			}
		}
		if (isProjectManager && !isSsc){
			R<TSettleDomainListVo> sdRes = archivesDaprUtil.getSettleDomainIdsByUserId(user.getId());
			if (Common.isNotNull(sdRes)){
				condition.setSettleDomainIds(sdRes.getData().getDeptNos());
				if (Common.isEmpty(sdRes.getData().getDeptNos())){
					List<String> nos = new ArrayList<>();
					nos.add("11");
					condition.setSettleDomainIds(nos);
				}
			}else{
				List<String> nos = new ArrayList<>();
				nos.add("11");
				condition.setSettleDomainIds(nos);
			}
		}
//		List<TInsuranceAreaRes> areaRes = insuranceAreaResMapper.selectList(Wrappers.<TInsuranceAreaRes>query().lambda()
//				.eq(TInsuranceAreaRes::getUserId, user.getId()).eq(TInsuranceAreaRes::getStatus, CommonConstants.ZERO_STRING));
//		if (Common.isNotNull(areaRes)) {
//			List<String> provinces = new ArrayList<>();
//			List<String> citys = new ArrayList<>();
//			for (TInsuranceAreaRes res : areaRes) {
//				if (Common.isEmpty(res.getCity())) {
//					provinces.add(res.getProvince());
//				} else {
//					citys.add(res.getCity());
//				}
//			}
//			condition.setInsuranceProvinces(provinces);
//			condition.setInsuranceCitys(citys);
//		}
		IPage<TBusinessInsuranceVo> recordsPage = new Page<>();
		int limitStart = (int)(page.getCurrent()-1)*(int)page.getSize();
		int limitEnd = (int)page.getSize();
		condition.setLimitStart(limitStart);
		condition.setLimitEnd(limitEnd);

		recordsPage.setPages(page.getPages());
		recordsPage.setSize(page.getSize());
		recordsPage.setCurrent(page.getCurrent());
		recordsPage.setTotal(baseMapper.noPageCountDiy(condition));
		recordsPage.setRecords(baseMapper.pageDiy(condition));
		return recordsPage;
	}

	@Override
	public R<Object> batchexpireIgnore(List<String> ids,String remark) {
		if (Common.isEmpty(ids) || Common.isEmpty(remark)){
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		baseMapper.batchexpireIgnore(ids,remark);
		//更新商险到期提醒表
		baseMapper.batchexpireAlertIgnore(ids,remark);
		return R.ok();
	}

	@Override
	public R<Object> batchIgnoreInsuranceAlert(List<String> ids,String remark) {
		if (Common.isEmpty(ids) || Common.isEmpty(remark)){
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		// 先查再更新
		List<TInsuranceAlert> alertList = tInsuranceWarnMapper.selectInsuranceAlertList(ids);
		if (alertList != null && !alertList.isEmpty()) {
			List<String> successList = new ArrayList<>();
			Map<String, TInsuranceAlert> alertMap = new HashMap<>();
			for (TInsuranceAlert alert : alertList) {
				alertMap.put(alert.getId(), alert);
			}
			TInsuranceAlert alert;
			int successNum = 0;
			for (String id : ids) {
				alert = alertMap.get(id);
				if (alert != null && InsurancesConstants.ALERT_IGNORE_STATUS.contains(alert.getProcessStatus())) {
					successList.add( id);
					successNum++;
				}
			}
			if (!successList.isEmpty()) {
				baseMapper.batchexpireIgnore(successList, remark);
				//更新商险到期提醒表
				baseMapper.batchexpireAlertIgnore(successList, remark);
			}
			if (successNum == ids.size()) {
				return R.ok();
			} else if (successNum == CommonConstants.ZERO_INT) {
				return R.failed();
			} else {
				int failNum = ids.size() - successNum;
				return new R<>(CommonConstants.TWO_INT, "成功"+successNum+"条；"+"失败"+failNum+"条", null);
			}
		} else {
			return R.failed("无数据可操作");
		}
	}

	/**
	 * @Author fxj
	 * @Description 商险到期提醒 批量备注更新
	 * @Date 16:26 2023/2/21
	 **/
	@Override
	public R<List<ErrorMessage>> remarkBatchAdd(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<InsurancesWarnUpdateVo> util1 = new ExcelUtil<>(InsurancesWarnUpdateVo.class);
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {

			EasyExcelFactory.read(inputStream, InsurancesWarnUpdateVo.class, new ReadListener<InsurancesWarnUpdateVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<InsurancesWarnUpdateVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(InsurancesWarnUpdateVo data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex + 1);
					ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)) {
						errorMessageList.add(errorMessage);
					} else {
						cachedDataList.add(data);
					}
					if (cachedDataList.size() >= BATCH_COUNT) {
						saveData();
						// 存储完成清理 list
						cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
					}
				}

				@Override
				public void doAfterAllAnalysed(AnalysisContext context) {
					saveData();
				}
				/**
				 * 加上存储数据库
				 */
				private void saveData() {
					log.info("{}条数据，开始存储数据库！", cachedDataList.size());
					if (!cachedDataList.isEmpty()) {
						remarkBatchAdd(cachedDataList, errorMessageList);
					}
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR_TWO, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR_TWO);
		}
		boolean isTrue = true;
		for (ErrorMessage message : errorMessageList) {
			if (!CommonConstants.UPDATE_SUCCESS.equals(message.getMessage())) {
				isTrue = false;
				break;
			}
		}
		if (isTrue) {
			return R.ok();
		} else {
			return R.ok(errorMessageList);
		}
	}
	@Override
	public R<Object> expireIgnore(TBusinessInsuranceVo vo) {
		if (Common.isEmpty(vo.getId()) || Common.isEmpty(vo.getExpireRemark())) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		TInsuranceDetail entity = baseMapper.selectById(vo.getId());
		if (entity == null) {
			return R.failed("未查询到相关商险订单");
		}
		entity.setExpireIgnoreFlag(CommonConstants.ZERO_STRING);
		entity.setExpireRemark(vo.getExpireRemark());
		baseMapper.updateById(entity);
		baseMapper.updateExpireAlert(entity.getId(),CommonConstants.ZERO_STRING,null);
		return R.ok();
	}
	private void remarkBatchAdd(List<InsurancesWarnUpdateVo> businessInsuranceVoList,List<ErrorMessage> errorMessages) {
		InsurancesWarnUpdateVo vo;
		TInsuranceDetail detail;
		for (int i = 0; i < businessInsuranceVoList.size(); i++) {
			try {
				int line = i;
				vo = businessInsuranceVoList.get(i);
				if (Common.isEmpty(vo.getEmpName())) {
					errorMessages.add(new ErrorMessage(i + 2, InsurancesConstants.EMP_NAME_NOT_EMPTY));
					continue;
				}
				if (Common.isEmpty(vo.getEmpIdcardNo())) {
					errorMessages.add(new ErrorMessage(i + 2, InsurancesConstants.EMP_IDCARD_NO_NOT_EMPTY));
					continue;
				}
				if (vo.getPolicyStart() == null) {
					errorMessages.add(new ErrorMessage(i + 2, InsurancesConstants.POLICY_START_NOT_EMPTY));
					continue;
				}
				if (vo.getPolicyEnd() == null) {
					errorMessages.add(new ErrorMessage(i + 2, InsurancesConstants.POLICY_END_NOT_EMPTY));
					continue;
				}
				if (Common.isEmpty(vo.getBuyStandard())) {
					errorMessages.add(new ErrorMessage(i + 2, InsurancesConstants.BUY_STANDARD_NOT_EMPTY));
					continue;
				}
				if (Common.isEmpty(vo.getInsuranceCompanyName())) {
					errorMessages.add(new ErrorMessage(i + 2, InsurancesConstants.INSURANCE_COMPANY_NAME_NOT_EMPTY));
					continue;
				}
				if (Common.isEmpty(vo.getInsuranceTypeName())) {
					errorMessages.add(new ErrorMessage(i + 2, InsurancesConstants.INSURANCE_TYPE_NAME_NOT_EMPTY));
					continue;
				}
				if (Common.isEmpty(vo.getDeptNo())) {
					errorMessages.add(new ErrorMessage(i + 2, InsurancesConstants.PROJECT_NO_IS_NOT_EMPTY));
					continue;
				}
				if (Common.isEmpty(vo.getDeptName())) {
					errorMessages.add(new ErrorMessage(i + 2, InsurancesConstants.PROJECT_NAME_IS_NOT_EMPTY));
					continue;
				}
				// 必填校验
				ErrorMessage errorMessage = null;
				boolean matchRemark = false;
				String expireIgnoreFlag = null;
				for (String remark : InsurancesConstants.INSURANCE_IGNORE_REMARK) {
					if (StringUtils.equals(remark, vo.getRenewal())) { //是否续保
						matchRemark = true;
						if (StringUtils.equals(remark, InsurancesConstants.INSURANCE_IGNORE_REMARK[5])) {
							expireIgnoreFlag = CommonConstants.ONE_STRING; //不忽略
							if (StringUtils.isEmpty(vo.getExpireRemark())) {
								errorMessage = new ErrorMessage(line + 2, "备注不能为空");
								continue;
							}
						} else {
							expireIgnoreFlag = CommonConstants.ZERO_STRING; //忽略
							if (StringUtils.isEmpty(vo.getExpireRemark())) {
								vo.setExpireRemark(remark);
							}
						}
					}
				}
				if (errorMessage != null) {
					errorMessages.add(errorMessage);
					continue;
				}
				if (!matchRemark) {
					errorMessages.add(new ErrorMessage(line + 2, "是否续保未定义"));
					continue;
				}
				//查数据是否存在：姓名 + 身份证号 + 保险公司 + 险种名称 + 保单开始时间 + 保单结束时间 + 购买标准
				detail = this.baseMapper.selectOne(Wrappers.<TInsuranceDetail>query().lambda()
						.eq(TInsuranceDetail::getEmpName, vo.getEmpName())
						.eq(TInsuranceDetail::getEmpIdcardNo, vo.getEmpIdcardNo())
						.eq(TInsuranceDetail::getInsuranceCompanyName, vo.getInsuranceCompanyName())
						.eq(TInsuranceDetail::getInsuranceTypeName, vo.getInsuranceTypeName())
						.eq(TInsuranceDetail::getPolicyStart, vo.getPolicyStart())
						.eq(TInsuranceDetail::getPolicyEnd, vo.getPolicyEnd())
						.eq(TInsuranceDetail::getBuyStandard,vo.getBuyStandard())
						.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
						.orderByDesc(TInsuranceDetail::getUpdateTime)
						.last(CommonConstants.LAST_ONE_SQL)
				);
				if (!Optional.ofNullable(detail).isPresent()) {
					errorMessages.add(new ErrorMessage(line + 2, InsurancesConstants.NOT_FOUND_INSURANCE_RECORD));
					continue;
				}
				detail.setExpireIgnoreFlag(expireIgnoreFlag);
				detail.setExpireRemark(vo.getExpireRemark());
				this.updateById(detail);
				baseMapper.updateExpireAlert(detail.getId(),expireIgnoreFlag,vo.getExpireRemark());
				errorMessages.add(new ErrorMessage(line + 2, CommonConstants.UPDATE_SUCCESS));
			} catch (Exception e) {
				log.error("商险批量备注执行异常", e);
				errorMessages.add(new ErrorMessage(i + 2, CommonConstants.UPDATE_DATA_FAIL));
				continue;
			}
		}
	}
	/**
	 * @Author fxj
	 * @Description 商险到期提醒导出
	 * @Date 16:25 2023/2/21
	**/
	@Override
	public void exportInsurancesWarn(InsuranceSearchVo searchVo, HttpServletResponse response, List<String> exportFields, String idstr) {
		String fileName = InsurancesConstants.INSURANCE_ALERT_EXPORT + DateUtil.getThisTime() + CommonConstants.XLSX;
		//获取要导出的列表
		List<InsuranceWarnExportVo> list = new ArrayList<>();
		if (Common.isNotNull(idstr)){
			searchVo.setIdList(Common.getList(idstr));
		}
		YifuUser user = SecurityUtils.getUser();
		long roleId = 1851541100126863362L;
		long roleId2 = 1536909784224051202L;
		boolean isSsc =	this.haveRole(user, roleId);
		boolean isProjectManager = this.haveRole(user, roleId2);
		if ("许瑞玲".equals(user.getNickname()) || "1".equals(user.getId()) || isSsc) {
			//searchVo.setCreateBy(null);
			searchVo.setAlertId(null);
		} else {
			if (isProjectManager){
				searchVo.setAlertId(null);
			}else{
				searchVo.setAlertId(user.getId());
			}
			//searchVo.setCreateBy(user.getId());
		}
		if (isProjectManager && !isSsc){
			R<TSettleDomainListVo> sdRes = archivesDaprUtil.getSettleDomainIdsByUserId(user.getId());
			if (Common.isNotNull(sdRes)){
				searchVo.setSettleDomainIds(sdRes.getData().getDeptNos());
				if (Common.isEmpty(sdRes.getData().getDeptNos())){
					List<String> nos = new ArrayList<>();
					nos.add("11");
					searchVo.setSettleDomainIds(nos);
				}
			}else{
				List<String> nos = new ArrayList<>();
				nos.add("11");
				searchVo.setSettleDomainIds(nos);
			}
		}
		long count = noPageCountDiy(searchVo);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding(CommonConstants.UTF8);
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName  , CommonConstants.UTF8));
			ExcelUtil<InsuranceWarnExportVo> util = new ExcelUtil<>(InsuranceWarnExportVo.class);
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, InsuranceWarnExportVo.class)
					.includeColumnFieldNames(exportFields).build();
			int index = 0;
			if (count >  CommonConstants.ZERO_INT){
				WriteSheet writeSheet;
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT_1) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT_1);
					list = noPageDiy(searchVo);
					if (Common.isNotNull(list)){
						writeSheet = EasyExcel.writerSheet(InsurancesConstants.INSURANCE_ALERT_EXPORT+index).build();
						excelWriter.write(list,writeSheet);
						index++;
					}
					if (Common.isNotNull(list)){
						list.clear();
					}
				}
			}else {
				WriteSheet writeSheet = EasyExcel.writerSheet(InsurancesConstants.INSURANCE_ALERT_EXPORT+index).build();
				excelWriter.write(list,writeSheet);
			}
			if (Common.isNotNull(list)){
				list.clear();
			}
			excelWriter.finish();
		}catch (Exception e){
			log.error(InsurancesConstants.INSURANCE_ALERT_EXPORT+"执行异常" ,e);
		}finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error(InsurancesConstants.INSURANCE_ALERT_EXPORT+"执行异常", e);
			}
		}
	}

	@Override
	public R<Object> expireRemark(TBusinessInsuranceVo vo) {
		if (Common.isEmpty(vo.getId()) || Common.isEmpty(vo.getExpireRemark())) {
			return R.failed(InsurancesConstants.UPLOAD_PARAM_CHECK_FAIL);
		}
		TInsuranceDetail entity = baseMapper.selectById(vo.getId());
		if (entity == null) {
			return R.failed("未查询到相关商险订单");
		}
		entity.setExpireRemark(vo.getExpireRemark());
		baseMapper.updateById(entity);
		baseMapper.updateExpireAlert(vo.getId(),null,vo.getExpireRemark());
		return R.ok();
	}

	private List<InsuranceWarnExportVo> noPageDiy(InsuranceSearchVo searchVo) {
//		List<String> domainIds = getExportCondition(searchVo);
		return baseMapper.noPageDiy(searchVo);
	}

	private int noPageCountDiy(InsuranceSearchVo searchVo) {
//		List<String> domainIds = getExportCondition(searchVo);
		return baseMapper.noPageCountDiy(searchVo);
	}

	private List<String> getExportCondition(InsuranceSearchVo searchVo) {
		YifuUser user = SecurityUtils.getUser();
		R<TSettleDomainListVo >  sdRes = archivesDaprUtil.getPermissionByUserId(user.getId());
		List<TInsuranceAreaRes> areaRes = insuranceAreaResMapper.selectList(Wrappers.<TInsuranceAreaRes>query().lambda()
				.eq(TInsuranceAreaRes::getUserId,user.getId()).eq(TInsuranceAreaRes::getStatus,CommonConstants.ZERO_STRING));
		if (Common.isNotNull(areaRes)) {
			List<String> provinces = new ArrayList<>();
			List<String> citys = new ArrayList<>();
			for (TInsuranceAreaRes res:areaRes){
				if (Common.isEmpty(res.getCity())){
					provinces.add(res.getProvince());
				}else {
					citys.add(res.getCity());
				}
			}
			searchVo.setInsuranceProvinces(provinces);
			searchVo.setInsuranceCitys(citys);
		}
		searchVo.setCreateBy(SecurityUtils.getUser().getId());
		if (Common.isNotNull(sdRes) && Common.isNotNull(sdRes.getData())){
			return  sdRes.getData().getDeptIds();
		}
		return null;
	}
	@Override
	public R<Integer> getExpireInsuranceWarn() {
		InsuranceSearchVo searchVo = new InsuranceSearchVo();
//		List<String> domainIds =  getExportCondition(searchVo);
		return R.ok(baseMapper.noPageCountDiy(searchVo));
	}

	@Override
	public R<Integer> getUserInsuranceMessageWarnCount(String userName) {
		InsuranceSearchVo searchVo = new InsuranceSearchVo();
		searchVo.setAlertId(SecurityUtils.getUser().getId());
		searchVo.setExpireIgnoreFlag(CommonConstants.ONE_STRING);
		return R.ok(baseMapper.noPageCountDiy(searchVo));
	}

	private boolean haveRole(YifuUser user, long roleId) {
		List<Long> roleList = user.getClientRoleMap().get(ClientNameConstants.CLIENT_MVP);
		for (Long role : roleList) {
			if (role == roleId) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @param idCardList 身份证
	 * @Description: 获取商险是否在保
	 * @Author: hgw
	 * @Date: 2025/1/15 9:25
	 * @return: com.yifu.cloud.plus.v1.yifu.salary.vo.SalaryRiskListVo
	 **/
	@Override
	public SalaryRiskListVo getRiskByIdCard(List<TSalaryAccount> idCardList) {
		SalaryRiskListVo returnVo = new SalaryRiskListVo();
		if (idCardList != null && !idCardList.isEmpty()) {
			List<String> cardList = new ArrayList<>();
			for (TSalaryAccount a : idCardList) {
				cardList.add(a.getEmpIdcard());
			}
			List<TInsuranceDetail> detailList = baseMapper.selectInUseByIdCardList(cardList);
			List<SalaryRiskVo> list = new ArrayList<>();
			SalaryRiskVo riskVo;
			Map<String, String> idMap = new HashMap<>();
			if (detailList != null && !detailList.isEmpty()) {
				for (TInsuranceDetail d : detailList) {
					idMap.put(d.getEmpIdcardNo(), d.getEmpName());
				}
			}
			for (TSalaryAccount s : idCardList) {
				if (idMap.get(s.getEmpIdcard()) == null) {
					riskVo = new SalaryRiskVo();
					riskVo.setEmpIdCard(s.getEmpIdcard());
					riskVo.setEmpName(s.getEmpName());
					riskVo.setMsg("不存在商险");
					list.add(riskVo);
				}
			}
			returnVo.setList(list);
		}
		return returnVo;
	}

	@Override
	public TEmployeeInsuranceSelectVo selectInsuranceInfo(TEmployeeInsurancePreVo preVo) {
		TEmployeeInsuranceSelectVo selectVo = new TEmployeeInsuranceSelectVo();
		TInsuranceDetail insuranceDetail = baseMapper.selectOne(Wrappers.<TInsuranceDetail>query().lambda()
				.eq(TInsuranceDetail::getEmpIdcardNo, preVo.getEmpIdcard())
				.eq(TInsuranceDetail::getBuyStandard, preVo.getBuyStandard())
				.eq(TInsuranceDetail::getInsuranceTypeName, preVo.getInsuranceTypeName())
				.eq(TInsuranceDetail::getInsuranceCompanyName, preVo.getInsuranceCompanyName())
				.eq(TInsuranceDetail::getPolicyStart, LocalDateUtil.parseLocalDate(DateUtil.dateToString(preVo.getPolicyStart(),DateUtil.ISO_EXPANDED_DATE_FORMAT)))
				.eq(TInsuranceDetail::getPolicyEnd, LocalDateUtil.parseLocalDate(DateUtil.dateToString(preVo.getPolicyEnd(),DateUtil.ISO_EXPANDED_DATE_FORMAT)))
				.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)
				)
//				//在用
//				.and(wrapper -> wrapper.eq(TInsuranceDetail::getIsUse, CommonConstants.ZERO_INT)
//						.or().isNull(TInsuranceDetail::getIsUse)
//				)
				.orderByDesc(TInsuranceDetail::getCreateTime)
				.last(CommonConstants.LAST_ONE_SQL)
		);
		selectVo.setInsuranceDetail(insuranceDetail);
		return selectVo;
	}


	/**
	 * 商险自动化-被替换人的分页接口
	 *
	 * @author chenyuxi
	 * @param page
	 * @param param
	 * @return {@link R<IPage<InsuranceListVO>>}
	 */
	@Override
	public IPage<InsuredListVo> replacePageToAutoSelect(Page<InsuredListVo> page, InsuredParam param, String mId) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isNotNull(mId)) {
			param.setMId(mId);
		}
		if(Common.isEmpty(user)){
			return null;
		}
		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"));
		}
		return baseMapper.replacePageToAutoSelect(page,param);
	}

	/**
	 * 商险自动化-针对批增的查询保单号的分页接口
	 *
	 * @author chenyuxi
	 * @param page
	 * @param param
	 * @return {@link R<IPage<InsuranceListVO>>}
	 */
	@Override
	public IPage<InsuredListVo> policyPageToAutoSelect(Page<InsuredListVo> page, InsuredParam param, String mId) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isNotNull(mId)) {
			param.setMId(mId);
		}
		if(Common.isEmpty(user)){
			return null;
		}
		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 today = LocalDateUtil.getDateSrt(LocalDate.now());
		param.setPolicyEnd(today);
		return baseMapper.policyPageToAutoSelect(page,param);
	}

	@Override
	public List<TInsurancePreDetail> getOnProcessInsurancesInfo(String empIdCard) {
		return baseMapper.getOnProcessInsuredList(empIdCard);
	}

	@Override
	public List<TInsurancePreDetail> getUnAutoProcessInsuredList(String empIdCard) {
		return baseMapper.getUnAutoProcessInsuredList(empIdCard);
	}

	//商险各个入口更新待购买列表状态更新
	private void updateEmployeeInsurancePre(String insurancePreId,TInsuranceDetail insuranceDetail,String status) {
		TEmployeeInsurancePre pre;
		if (null != insurancePreId) {
			pre = employeeInsurancePreMapper.selectOne(Wrappers.<TEmployeeInsurancePre>query().lambda()
					.eq(TEmployeeInsurancePre::getId,insurancePreId)
					.in(TEmployeeInsurancePre::getProcessStatus,Stream.of("0","1","2","5","7").collect(Collectors.toList()))
					.last(CommonConstants.LAST_ONE_SQL));
		} else {
			pre = employeeInsurancePreMapper.selectOne(Wrappers.<TEmployeeInsurancePre>query().lambda()
					.eq(TEmployeeInsurancePre::getEmpIdcard, insuranceDetail.getEmpIdcardNo())
					.eq(TEmployeeInsurancePre::getDeptNo, insuranceDetail.getDeptNo())
					.eq(TEmployeeInsurancePre::getBuyStandard, insuranceDetail.getBuyStandard())
					.eq(TEmployeeInsurancePre::getInsuranceTypeName, insuranceDetail.getInsuranceTypeName())
					.eq(TEmployeeInsurancePre::getInsuranceCompanyName, insuranceDetail.getInsuranceCompanyName())
					.eq(TEmployeeInsurancePre::getPolicyStart, insuranceDetail.getPolicyStart())
					.eq(TEmployeeInsurancePre::getPolicyEnd, insuranceDetail.getPolicyEnd())
					.in(TEmployeeInsurancePre::getProcessStatus, Stream.of("0","1","2","5","7").collect(Collectors.toList()))
					.last(CommonConstants.LAST_ONE_SQL));
		}
		if (Common.isNotNull(pre)) {
			pre.setProcessStatus(status);
			if (Common.isNotNull(insuranceDetail.getId())) {
				pre.setInsurancesId(insuranceDetail.getId());
				pre.setIsAddress(insuranceDetail.getIsAdress());
			}
			employeeInsurancePreMapper.updateById(pre);
		}
	}

	//更新商险待购买派单失败
	private void updateEmployeeInsurancePre(List<String> insurancePreIdList) {
		if (!insurancePreIdList.isEmpty()) {
			employeeInsurancePreMapper.updateBatchById(insurancePreIdList);
		}
	}

	//商险各个入口更新待购买列表状态更新
	private void updateEmployeeInsurancePreById(TInsuranceDetail insuranceDetail,List<String> preStatusList,String status) {
		TEmployeeInsurancePre pre = employeeInsurancePreMapper.selectOne(Wrappers.<TEmployeeInsurancePre>query().lambda()
				.eq(TEmployeeInsurancePre::getInsurancesId,insuranceDetail.getId())
				.in(TEmployeeInsurancePre::getProcessStatus,preStatusList)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(pre)) {
			pre.setProcessStatus(status);
			employeeInsurancePreMapper.updateById(pre);
		}
	}

	// hgw-1商险待续签-商险各个入口更新待续签列表状态更新
	private void updateEmployeeInsurancePreRenew(String insurancePreId,TInsuranceDetail insuranceDetail,String status) {
		TInsurancePreRenewDetail pre;
		if (null != insurancePreId) {
			pre = tInsurancePreRenewDetailMapper.selectOne(Wrappers.<TInsurancePreRenewDetail>query().lambda()
					.eq(TInsurancePreRenewDetail::getId,insurancePreId)
					.in(TInsurancePreRenewDetail::getProcessStatus,Stream.of("0","1","2","5","7").collect(Collectors.toList()))
					.last(CommonConstants.LAST_ONE_SQL));
		} else {
			pre = tInsurancePreRenewDetailMapper.selectOne(Wrappers.<TInsurancePreRenewDetail>query().lambda()
					.eq(TInsurancePreRenewDetail::getEmpIdcardNo, insuranceDetail.getEmpIdcardNo())
					.eq(TInsurancePreRenewDetail::getDeptNo, insuranceDetail.getDeptNo())
					.eq(TInsurancePreRenewDetail::getBuyStandard, insuranceDetail.getBuyStandard())
					.eq(TInsurancePreRenewDetail::getInsuranceTypeName, insuranceDetail.getInsuranceTypeName())
					.eq(TInsurancePreRenewDetail::getInsuranceCompanyName, insuranceDetail.getInsuranceCompanyName())
					.eq(TInsurancePreRenewDetail::getPolicyStart, insuranceDetail.getPolicyStart())
					.eq(TInsurancePreRenewDetail::getPolicyEnd, insuranceDetail.getPolicyEnd())
					.in(TInsurancePreRenewDetail::getProcessStatus, Stream.of("0","1","2","5","7").collect(Collectors.toList()))
					.last(CommonConstants.LAST_ONE_SQL));
		}
		if (Common.isNotNull(pre)) {
			pre.setProcessStatus(status);
			if (Common.isNotNull(insuranceDetail.getId())) {
				pre.setInsurancesIdNew(insuranceDetail.getId());
				pre.setIsAddress(insuranceDetail.getIsAdress());
			}
			tInsurancePreRenewDetailMapper.updateById(pre);
		}
	}

	// hgw-2商险待续签-更新商险待购买派单失败
	private void updateEmployeeInsurancePreRenew(List<String> insurancePreIdList) {
		if (!insurancePreIdList.isEmpty()) {
			tInsurancePreRenewDetailMapper.updateRenewBatchById(insurancePreIdList);
		}
	}

	// hgw-3商险待续签-商险各个入口更新待购买列表状态更新
	// handleFailToSendQwFlag - 办理失败发送企微
	private void updateEmployeeInsurancePreRenewById(TInsuranceDetail insuranceDetail, List<String> preStatusList
			, String status, boolean handleFailToSendQwFlag) {
		TInsurancePreRenewDetail pre = tInsurancePreRenewDetailMapper.selectOne(Wrappers.<TInsurancePreRenewDetail>query().lambda()
				.eq(TInsurancePreRenewDetail::getInsurancesIdNew,insuranceDetail.getId())
				.in(TInsurancePreRenewDetail::getProcessStatus,preStatusList)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(pre)) {
			pre.setProcessStatus(status);
			tInsurancePreRenewDetailMapper.updateById(pre);
			if (handleFailToSendQwFlag) {
				handleFailToSendQw(pre.getCustomerUserLoginname(), pre.getCustomerUsername(), pre.getId(), pre.getEmpName()
						, pre.getEmpIdcardNo(), insuranceDetail.getBackRemark());
			}
		}
	}

	/**
	 * @Description: 自动化续签的商险办理失败，发送企微
	 * @Author: hgw
	 * @Date: 2025/11/19 18:02
	 * @return: void
	 **/
	private void handleFailToSendQw(String customerUserLoginname, String customerUsername, String preRenewId, String empName
			, String empIdCard, String errorrMessage) {
			TInsurancePreRenewDetailQw qw = new TInsurancePreRenewDetailQw();
			String qwUuId = String.valueOf(UUID.randomUUID()).replace("-", "");
			qw.setId(qwUuId);
			qw.setCreateTime(LocalDateTime.now());
			qw.setCustomerUserLoginname(customerUserLoginname);
			qw.setCustomerUsername(customerUsername);
			qw.setDescription(empName + CommonConstants.CENTER_SPLIT_LINE_STRING + empIdCard + "，商险续保办理失败 <br>请及时处理，以免产生用工风险！");
			// 派单失败，组装需要推送企微的明细
			TInsurancePreRenewDetailQwDetail qwDetail = new TInsurancePreRenewDetailQwDetail();
			qwDetail.setPreId(preRenewId);
			qwDetail.setMainId(qwUuId);
			qwDetail.setEmpName(empName);
			qwDetail.setEmpIdcard(empIdCard);
			qwDetail.setErrorInfo(errorrMessage);
			qwDetail.setErrorTime(LocalDateTime.now());

			tInsurancePreRenewDetailQwService.save(qw);
			tInsurancePreRenewDetailQwDetailService.save(qwDetail);

			if (Common.isNotNull(customerUserLoginname)) {
				Map<String, String> sysUserMap = getUserQiWeiInfo(customerUserLoginname);
				String qwInfo;
				if (!sysUserMap.isEmpty()) {
					qwInfo = sysUserMap.get(customerUserLoginname);
					if (Common.isNotNull(qwInfo)) {
						sendMessageToWx(qwInfo, qw.getDescription(), qw.getId());
					}
				}
			}
	}

	/**
	 * @param userLoginNames 登录名，逗号拼接
	 * @Description: 获取客服的企微信息
	 * @Author: hgw
	 * @Date: 2025/8/8 17:59
	 * @return: java.util.Map<java.lang.String, java.lang.String>
	 **/
	private Map<String, String> getUserQiWeiInfo(String userLoginNames) {
		Map<String, String> sysUserMap = new HashMap<>();
		// 获取项目对应的前端客服用户信息--客服账号需要正常
		if (Common.isNotKong(userLoginNames)) {
			R<SysUserListVo> res = upmsDaprUtils.getUserIdsByUserNames(userLoginNames);
			List<SysUser> users = null;
			if (Common.isNotNull(res) && Common.isNotNull(res.getData()) && Common.isNotNull(res.getData().getUserList())) {
				users = res.getData().getUserList();
			}
			if (Common.isNotKong(users)) {
				for (SysUser user : users) {
					if (Common.isNotNull(user.getWxMessage())) {
						sysUserMap.put(user.getUsername(), user.getWxMessage());
					}
				}
			}
		}
		return sysUserMap;
	}

	//发送企业微信待办
	private void sendMessageToWx(String useruserWx, String content, String mainId) {
		if (Common.isEmpty(useruserWx) || Common.isEmpty(content)) {
			return;
		}
		StringBuilder sendUser = null;
		if (Common.isNotKong(useruserWx)) {
			sendUser = new StringBuilder(useruserWx);
		}
		if (sendUser != null) {
			RestTemplate restTemplate = new RestTemplate();
			Map<String, Object> requestMap = new HashMap<>();
			Map<String, Object> textcard = new HashMap<>();
			textcard.put("title", "【作业自动化——商险续保办理失败提醒】");
			textcard.put("url", String.format(SecurityConstants.WX_GET_MESSAGE_AUTH_URL, wxConfig.getCorpid(), wxConfig.getDomainName() + "/auth/oauth/wxLogin", "78" + mainId));
			textcard.put("description", content);
			requestMap.put("touser", sendUser);
			requestMap.put("agentid", wxConfig.getAgentid());
			requestMap.put("msgtype", "textcard");
			requestMap.put("textcard", textcard);
			// 必须加上header说明
			if (!wxConfig.sendTextCard(restTemplate, requestMap)) {
				wxConfig.sendTextCard(restTemplate, requestMap);
			}
		}
	}

	@Override
	public BaseSearchVO getInsurancesStatus(BaseSearchVO paramVo) {
		BaseSearchVO returnVo = new BaseSearchVO();
		if (Common.isNotNull(paramVo) && Common.isNotNull(paramVo.getEmpIdCard()) && Common.isNotNull(paramVo.getDeptNo())) {
			List<String> idList = baseMapper.getInsuranceDetailList(paramVo.getEmpIdCard(), paramVo.getDeptNo());
			if (idList != null && !idList.isEmpty()) {
				String idString = String.join(CommonConstants.COMMA_STRING, idList);
				if (idString.length()>1000) {
					idString = idString.substring(0, 1000);
				}
				returnVo.setResultIdOne(idString);
				returnVo.setResultIdOneStatus("已投保");
			}
		}
		return returnVo;
	}
	@Override
	public BaseSearchVO getInsurancesStatusByClose(BaseSearchVO paramVo) {
		BaseSearchVO returnVo = new BaseSearchVO();
		if (Common.isNotNull(paramVo) && Common.isNotNull(paramVo.getEmpIdCard()) && Common.isNotNull(paramVo.getDeptNo())) {
			// 如果存在不等于3减员退回的，表示未减完成
			List<String> idListReduce = baseMapper.getInsuranceDetailListByClose(paramVo.getEmpIdCard(), paramVo.getDeptNo());
			if (idListReduce != null && !idListReduce.isEmpty()) {
				returnVo.setResultIdOne(CommonConstants.ONE_STRING);
			}
		}
		return returnVo;
	}

	// 审核或办理，更新离职待办
	// isSuccess 0：失败；1：成功
	private void sendLeave(List<String> idList, String doStatus, String isSuccess, String failRemark, YifuUser user) {

		BaseServiceParamListVO updateVo = new BaseServiceParamListVO();
		updateVo.setListParam(idList);
		updateVo.setDoType(CommonConstants.THREE_STRING);
		updateVo.setDoStatus(doStatus);
		updateVo.setIsSuccess(isSuccess);
		if (Common.isNotNull(isSuccess) && CommonConstants.ZERO_STRING.equals(isSuccess)) {
			updateVo.setRemark(failRemark);
			if (user != null && Common.isNotNull(user.getNickname())) {
				updateVo.setUserName(user.getNickname());
			}
		}
		cspDaprUtil.reduceHandleToLeave(updateVo);
	}

	// 审核或办理，更新离职待办
	// isSuccess 0：失败；1：成功
	private void sendLeaveById(String id, String doStatus, String isSuccess, String failRemark, YifuUser user) {

		BaseServiceParamListVO updateVo = new BaseServiceParamListVO();
		List<String> idList = new ArrayList<>();
		idList.add(id);
		updateVo.setListParam(idList);
		updateVo.setDoType(CommonConstants.THREE_STRING);
		updateVo.setDoStatus(doStatus);
		updateVo.setIsSuccess(isSuccess);
		if (Common.isNotNull(isSuccess) && CommonConstants.ZERO_STRING.equals(isSuccess)) {
			updateVo.setRemark(failRemark);
			if (user != null && Common.isNotNull(user.getNickname())) {
				updateVo.setUserName(user.getNickname());
			}
		}
		cspDaprUtil.reduceHandleToLeave(updateVo);
	}
	/**
	 * @Author fxj
	 * @Description 获取见费出单的结算及支出状态
	 * @Date 10:26 2026/1/21
	 * @Param
	 * @return
	**/
	@Override
	public R getSettleStatusFromEkpInsuranceDetailAsso(String detailId,String settleId) {
		String id = detailId+CommonConstants.DOWN_LINE_STRING+settleId;
		EkpSettleStatusVo vo = ekpSettleService.getSettleStatusFromEkpInsuranceDetailAsso(id);
		if (null == vo){
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		return R.ok(vo);
	}

	/**
	 * @Author fxj
	 * @Description  撤回  --待缴费状态的投保记录 可撤回
	 * @Date 10:34 2026/1/21
	 * @Param
	 * @return
	**/
	@Override
	public R callBack(TInsuranceDetail detail) {
		String id = detail.getId()+CommonConstants.DOWN_LINE_STRING+detail.getDefaultSettleId();
		EkpSettleStatusVo vo = ekpSettleService.getSettleStatusFromEkpInsuranceDetailAsso(id);
		if (null != vo && ("已结算".equals(vo.getSettleStatus()) || "结算中".equals(vo.getSettleStatus()))){
			return R.failed("已结算或结算中的投保记录不可撤回");
		}
		try {
			//未结算删除 EKP 的预估数据
			ekpSettleService.deleteEkpInsuranceDetail(id);
			//未结算删除 HRO的投保数据
			baseMapper.deleteById(detail.getId());
			//未结算删除 HRO的预估结算数据
			tInsuranceSettleService.removeById(detail.getDefaultSettleId());
			//查询并删除收入信息
			TIncomeDetail incomeDetail = new TIncomeDetail();
			incomeDetail.setSourceId(detail.getId());
			R<TIncomeDetailReturnVo> detailList = socialDaprUtils.getTIncomeDetailList(incomeDetail);
			if(Common.isNotNull(detailList) && detailList.getCode() == CommonConstants.SUCCESS
					&& !detailList.getData().getDetailList().isEmpty()){
				List<TIncomeDetail> incomeDetailList = detailList.getData().getDetailList();
				for (TIncomeDetail income : incomeDetailList) {
					socialDaprUtils.deleteById(income);
					socialDaprUtils.deleteIncomeById(income);
					//删除管理费
					ekpSettleService.deleteEkpManagerInfo(income.getId());
					//删除风险金
					ekpSettleService.deleteEkpEkpRiskInfo(income.getId());
				}
			}
			//未结算更新自动化测的状态为待派单 temployeeinsurancepre
			LambdaUpdateWrapper<TEmployeeInsurancePre> updateWrapper = new LambdaUpdateWrapper<>();
			updateWrapper.eq(TEmployeeInsurancePre::getInsurancesId,detail.getId());
			updateWrapper.set(TEmployeeInsurancePre::getProcessStatus,CommonConstants.ONE_STRING);
			employeeInsurancePreMapper.update(null,updateWrapper);

			LambdaUpdateWrapper<TInsurancePreRenewDetail> updateNewWrapper = new LambdaUpdateWrapper<>();
			updateNewWrapper.eq(TInsurancePreRenewDetail::getInsurancesIdNew,detail.getId());
			updateNewWrapper.set(TInsurancePreRenewDetail::getProcessStatus,CommonConstants.ONE_STRING);
			tInsurancePreRenewDetailMapper.update(null,updateNewWrapper);
		} catch (Exception e) {
			return R.failed("撤回异常："+e.getMessage());
		}
		return R.ok();
	}
	/**
	 * @Author fxj
	 * @Description 手动拉取缴费状态
	 * @Date 10:52 2026/1/21
	 * @Param
	 * @return
	 **/
	@Override
	public R pullPaymentStatus(String idStr,YifuUser user ) {
		List<TInsuranceDetail> list = null;
		if (Common.isNotNull(idStr)){
			list = baseMapper.selectBatchIds(Arrays.asList(idStr.split(CommonConstants.COMMA_STRING)));
		}else {
			list = baseMapper.selectList(Wrappers.<TInsuranceDetail>query().lambda()
					.eq(TInsuranceDetail::getBuyHandleStatus,CommonConstants.SIX_INT)
					.eq(BaseEntity::getCreateBy, user.getId())
					.eq(TInsuranceDetail::getIsJfcd,CommonConstants.ZERO_STRING));
		}

		if (Common.isNotNull(list)){
			List<String> idStrs = new ArrayList<>();
			for (TInsuranceDetail detail:list){
				idStrs.add(detail.getId()+CommonConstants.DOWN_LINE_STRING+detail.getDefaultSettleId());
			}
			//list转为MAP  id 为 key
			Map<String,TInsuranceDetail> map = list.stream().collect(Collectors.toMap(TInsuranceDetail::getId, v -> v));
			List<EkpSettleStatusVo> voList = ekpSettleService.getSettleStatusFromEkpAssoByIds(idStrs);
			if (Common.isNotNull(voList)){
				//如果EKP对应提前缴费的预估数据已结算或已垫付则HRO商险派单状态同步为待投保
				List<TInsuranceDetail> updateList = new ArrayList<>();
				// 自动化测需要同步更新为待投保
				List<String>  ids = new ArrayList<>();
				TInsuranceDetail detail = null;
				TInsuranceDetail detailOld = null;
				String detailId = null;
				for (EkpSettleStatusVo vo : voList){
					if (null != vo.getDetailId() && vo.getDetailId().length() > 19){
						detailId = vo.getDetailId().substring(0,19);
						if (("已收".equals(vo.getPaymentStatus())
								|| "垫付".equals(vo.getPaymentStatus()))
								&& map.containsKey(detailId)){
							detail = map.get(detailId);
							detail.setPaymentStatus(CommonConstants.ONE_STRING);
							if (null != detail){
								detailOld = new TInsuranceDetail();
								BeanCopyUtils.copyProperties(detail,detailOld);
								detail.setPaymentTime(vo.getStatusUpdateTime());
								detail.setBuyHandleStatus(CommonConstants.ONE_INT);
								detail.setUpdateTime(LocalDateTime.now());
								detail.setPaymentStatus(CommonConstants.ONE_STRING);
								detail.setUpdateBy("05501879fed711eca3540242ac110010");
								tBusinessOperateService.saveModificationRecord(detail.getId(),detailOld,detail,"手动拉取缴费：收款结算单已收或垫付同步更新投保状态为待投保","EKP系统");
								updateList.add(detail);
								ids.add(detailId);
							}
						}
					}
				}
				if (Common.isNotNull(updateList)){
					this.updateBatchById(updateList);
				}
				if (Common.isNotNull(ids)){
					//通过ids 更新自动化测状态processStatus为待投保
					LambdaUpdateWrapper<TEmployeeInsurancePre> updateDiyInfoWrapper = new LambdaUpdateWrapper<>();
					updateDiyInfoWrapper.in(TEmployeeInsurancePre::getInsurancesId, ids)
							.set(TEmployeeInsurancePre::getProcessStatus,CommonConstants.THREE_STRING);
					employeeInsurancePreMapper.update(null, updateDiyInfoWrapper);
				}
			}
		}
		return R.ok();
	}

	@Override
	public R callBackInsuranceBuyHandleStatus(EkpStatusParamVo vo) {
		try {
			callBackInsuranceBuyHandleStatusSub(vo);
		}catch (Exception e) {
			log.error("商险结算状态更新异常", e);
			return R.failed("商险结算状态更新异常");
		}
		return R.ok();
	}
	@Async
	public void callBackInsuranceBuyHandleStatusSub(EkpStatusParamVo vo) {
		try {
			//根据结算单号获取明细id和结算状态
			List<String> detailIds = null;
			if (null != vo  && Common.isNotNull(vo.getDetailIds())){
				detailIds = Arrays.asList(vo.getDetailIds().split(CommonConstants.COMMA_STRING));
			}
			if (detailIds != null && !detailIds.isEmpty()) {
				List<String> insuranceIds = new ArrayList<>();
				TInsuranceDetail detailOld = null;
				TInsuranceDetail detail = null;
				for (String id : detailIds) {
					//获取所有的明细id
					if (Common.isNotNull(id)) {
						detail = baseMapper.selectById(id);
						detailOld = new TInsuranceDetail();
						BeanCopyUtils.copyProperties(detail,detailOld);
						//见费出单且是待投保状态 直接回退到 待缴费 并清空缴费时间和缴费状态
						if (Common.isNotNull(detail)
								&& CommonConstants.ONE_INT == detail.getBuyHandleStatus().intValue()
								&& CommonConstants.ZERO_STRING.equals(detail.getIsJfcd())) {
							detail.setPaymentTime(CommonConstants.EMPTY_STRING);
							detail.setPaymentStatus(CommonConstants.ZERO_STRING);
							detail.setBuyHandleStatus(CommonConstants.SIX_INT);
							detail.setUpdateBy("05501879fed711eca3540242ac110010");
							detail.setUpdateTime(LocalDateTime.now());
							baseMapper.updateById(detail);
							tBusinessOperateService.saveModificationRecord(detail.getId(),detailOld,detail,"收款结算单退单或撤销匹配同步更新投保状态为待缴费","EKP系统");
							insuranceIds.add(id);
						}
					}
				}
				if (!insuranceIds.isEmpty()){
					//通过ids 更新自动化测状态processStatus为待投保
					LambdaUpdateWrapper<TEmployeeInsurancePre> updateDiyInfoWrapper = new LambdaUpdateWrapper<>();
					updateDiyInfoWrapper.in(TEmployeeInsurancePre::getInsurancesId, insuranceIds)
							.set(TEmployeeInsurancePre::getProcessStatus,CommonConstants.SEVEN_STRING);
					employeeInsurancePreMapper.update(null, updateDiyInfoWrapper);

					LambdaUpdateWrapper<TInsurancePreRenewDetail> updateReNewInfoWrapper = new LambdaUpdateWrapper<>();
					updateReNewInfoWrapper.in(TInsurancePreRenewDetail::getInsurancesId, insuranceIds)
							.set(TInsurancePreRenewDetail::getProcessStatus,CommonConstants.SEVEN_STRING);
					tInsurancePreRenewDetailMapper.update(null, updateReNewInfoWrapper);
				}
			}
		} catch (Exception e) {
			TUpdateStatusError error = new TUpdateStatusError();
			error.setSettleNo(vo.getSettleNo());
			error.setStatus(CommonConstants.ZERO_INT);
			error.setTitle(e.getMessage());
			error.setTypeFlag(CommonConstants.FOUR_STRING);
			error.setCreateTime(DateUtil.getCurrentDateTime());
			error.setSettleType(vo.getPayFlag());
			updateStatusErrorMapper.insert(error);
			log.error("收款结算单退单或撤销匹配更新是否见费出单的商险状态为待缴费", e);
		}
	}

	@Override
	public Double getInsuranceListPagePaymentMoney(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"));
		}
		return baseMapper.getInsuranceListPagePaymentMoney(param);
	}
}
