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

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
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.yifu.cloud.plus.v1.csp.vo.EmployeeRegistrationCustomerUserUpdateVo;
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.EmployeeRegistrationPre;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EmployeeRegistrationPreVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainRegistListVo;
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.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.DateUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.LocalDateTimeUtils;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.BaseSearchVO;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.ArchivesDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.UpmsDaprUtils;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.insurances.config.WxConfig;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.*;
import com.yifu.cloud.plus.v1.yifu.insurances.mapper.insurances.TEmployeeInsurancePreMapper;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.*;
import com.yifu.cloud.plus.v1.yifu.insurances.util.LocalDateUtil;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 商险待办任务表
 *
 * @author huych
 * @date 2025-03-31 12:25:13
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class TEmployeeInsurancePreServiceImpl extends ServiceImpl<TEmployeeInsurancePreMapper, TEmployeeInsurancePre> implements TEmployeeInsurancePreService {

	@Autowired
	private ArchivesDaprUtil archivesDaprUtil;

	@Autowired
	@Lazy
	private TInsuranceDetailService detailService;
//
//	@Autowired
//	@Lazy
//	private ScheduleService scheduleService;

	@Autowired
	private WxConfig wxConfig;

	@Autowired
	private UpmsDaprUtils upmsDaprUtils;

	@Autowired
	private TInsurancePreDetailService preDetailService;

	@Autowired
	private TEmployeeInsurancePreQwService tEmployeeInsurancePreQwService;
	@Autowired
	private TEmployeeInsurancePreQwDetailService tEmployeeInsurancePreQwDetailService;

	@Autowired
	private TInsurancePreRenewDetailService tInsurancePreRenewDetailService;

	/**
	 * 商险待办任务表简单分页查询
	 *
	 * @param tEmployeeInsurancePre 商险待办任务表
	 * @return
	 */
	@Override
	public IPage<TEmployeeInsurancePre> getTEmployeeInsurancePrePage(Page<TEmployeeInsurancePre> page, TEmployeeInsurancePreSearchVo tEmployeeInsurancePre) {
		if (null == tEmployeeInsurancePre.getStatusList()) {
			tEmployeeInsurancePre.setStatusList(CommonConstants.processListPreArchivesStatus);
		}
		//权限赋值
		initSearchVo(tEmployeeInsurancePre);
		return baseMapper.getTEmployeeInsurancePrePage(page, tEmployeeInsurancePre);
	}

	@Override
	public List<TEmployeeInsurancePre> getTEmployeeInsurancePreNoPage(TEmployeeInsurancePreSearchVo tEmployeeInsurancePre) {
		//权限赋值
		tEmployeeInsurancePre.setType(CommonConstants.ONE_STRING);
		if (Common.isEmpty(tEmployeeInsurancePre.getStatusList())) {
			tEmployeeInsurancePre.setProcessStatus(CommonConstants.ZERO_STRING);
		}
		initSearchVo(tEmployeeInsurancePre);
		return baseMapper.getTEmployeeInsurancePreNoPage(tEmployeeInsurancePre);

	}

	@Override
	public long getTEmployeeInsuranceCount(TEmployeeInsurancePreSearchVo tEmployeeInsurancePre) {
		tEmployeeInsurancePre.setStatusList(CommonConstants.processListPreArchivesStatus);
		initSearchVo(tEmployeeInsurancePre);
		return baseMapper.selectExportCount(tEmployeeInsurancePre);
	}

	/**
	 * 商险待办任务表批量导出
	 *
	 * @param searchVo 商险待办任务表
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TEmployeeInsurancePreSearchVo searchVo) {
		String fileName = "商险待办任务表批量导出" + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<TEmployeeInsurancePreExportVo> list = new ArrayList<>();
		if (null == searchVo.getStatusList()) {
			searchVo.setStatusList(CommonConstants.processListPreArchivesStatus);
		}
		//权限赋值
		initSearchVo(searchVo);
		long count = baseMapper.selectExportCount(searchVo);
		try (ServletOutputStream out= response.getOutputStream();){
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, CommonConstants.UTF8));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, TEmployeeInsurancePreExportVo.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = baseMapper.selectExportList(searchVo);
					if (Common.isNotNull(list)) {
						WriteSheet writeSheet = EasyExcel.writerSheet("商险待办任务表" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcel.writerSheet("商险待办任务表" + index).build();
				excelWriter.write(list, writeSheet);
			}
			if (Common.isNotNull(list)) {
				list.clear();
			}
			excelWriter.finish();
		} catch (Exception e) {
			log.error("执行异常", e);
		}
	}

	@Override
	public R confirm(List<String> idList) {
		List<TEmployeeInsurancePre> insurancePreList = baseMapper.selectList(Wrappers.<TEmployeeInsurancePre>query()
				.lambda().in(TEmployeeInsurancePre::getId, idList)
				.eq(TEmployeeInsurancePre::getProcessStatus, CommonConstants.ZERO_STRING));
		if (Common.isEmpty(insurancePreList)) {
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		LambdaUpdateWrapper<TEmployeeInsurancePre> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.in(TEmployeeInsurancePre::getId,idList)
				.eq(TEmployeeInsurancePre::getProcessStatus, CommonConstants.ZERO_STRING)
				.set(TEmployeeInsurancePre::getProcessStatus, CommonConstants.ONE_STRING);
		this.update(updateWrapper);
		return R.ok();
	}

	// pushQiWeiFlag : 是否推送企微 true:推送（当前仅下午3点与3点20的定时任务，需要推送企微），false：不推送
	@Override
	public R batchDispatcherInsurance(List<String> idList, String sameFlag, boolean pushQiWeiFlag) {
		List<TEmployeeInsurancePre> insurancePreList = baseMapper.selectList(Wrappers.<TEmployeeInsurancePre>query()
				.lambda().in(TEmployeeInsurancePre::getId, idList)
				.in(TEmployeeInsurancePre::getProcessStatus, CommonConstants.processInsurancesStatus));
		if (Common.isEmpty(insurancePreList)) {
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		List<String> pushIdList = insurancePreList.stream().map(TEmployeeInsurancePre::getId).collect(Collectors.toList());
		List<InsuranceAddParam> addParamList = new ArrayList<>();
		List<InsuranceBatchParam> batchAddParamList = new ArrayList<>();
		List<InsuranceReplaceParam> replaceAddParamList = new ArrayList<>();
		for (TEmployeeInsurancePre insurancePre : insurancePreList) {
			//新增、批增、替换
			if (CommonConstants.ONE_INT == insurancePre.getBuyType()) {
				InsuranceAddParam addParam = new InsuranceAddParam();
				addParam.setEmpName(insurancePre.getEmployeeName());
				addParam.setEmpIdcardNo(insurancePre.getEmpIdcard());
				addParam.setDeptNo(insurancePre.getDeptNo());
				addParam.setInsuranceCompanyName(insurancePre.getInsuranceCompanyName());
				addParam.setInsuranceTypeName(insurancePre.getInsuranceTypeName());
				addParam.setPolicyStart(DateUtil.dateToString(insurancePre.getPolicyStart(),DateUtil.ISO_EXPANDED_DATE_FORMAT));
				addParam.setPolicyEnd(DateUtil.dateToString(insurancePre.getPolicyEnd(),DateUtil.ISO_EXPANDED_DATE_FORMAT));
				addParam.setBuyStandard(insurancePre.getBuyStandard());
				addParam.setInsuranceProvinceName(insurancePre.getFileProvince());
				addParam.setInsuranceCityName(insurancePre.getFileCity());
				addParam.setSettleMonth(CommonConstants.EMPTY_STRING);
				addParam.setPost(insurancePre.getPosition());
				addParam.setRemark(CommonConstants.EMPTY_STRING);
				addParam.setInsurancePreId(insurancePre.getId());
				addParam.setCustomerUserName(insurancePre.getCustomerUsername());
				addParam.setIsExit(sameFlag);
				addParamList.add(addParam);
			}
			if (CommonConstants.THREE_INT == insurancePre.getBuyType()) {
				InsuranceBatchParam addParam = new InsuranceBatchParam();
				addParam.setEmpName(insurancePre.getEmployeeName());
				addParam.setEmpIdcardNo(insurancePre.getEmpIdcard());
				addParam.setDeptNo(insurancePre.getDeptNo());
				addParam.setInsuranceCompanyName(insurancePre.getInsuranceCompanyName());
				addParam.setInsuranceTypeName(insurancePre.getInsuranceTypeName());
				addParam.setPolicyNo(insurancePre.getPolicyNo());
				addParam.setBuyStandard(insurancePre.getBuyStandard());
				addParam.setInsuranceProvinceName(insurancePre.getFileProvince());
				addParam.setInsuranceCityName(insurancePre.getFileCity());
				addParam.setSettleMonth(CommonConstants.EMPTY_STRING);
				addParam.setPost(insurancePre.getPosition());
				addParam.setRemark(CommonConstants.EMPTY_STRING);
				addParam.setInsurancePreId(insurancePre.getId());
				addParam.setCustomerUserName(insurancePre.getCustomerUsername());
				addParam.setPolicyStart(LocalDateUtil.parseLocalDate(DateUtil.dateToString(insurancePre.getPolicyStart(),DateUtil.ISO_EXPANDED_DATE_FORMAT)));
				addParam.setPolicyEnd(LocalDateUtil.parseLocalDate(DateUtil.dateToString(insurancePre.getPolicyEnd(),DateUtil.ISO_EXPANDED_DATE_FORMAT)));
				addParam.setIsExit(sameFlag);
				batchAddParamList.add(addParam);
			}
			if (CommonConstants.FOUR_INT == insurancePre.getBuyType()) {
				InsuranceReplaceParam addParam = new InsuranceReplaceParam();
				addParam.setEmpName(insurancePre.getReplaceEmployeeName());
				addParam.setEmpIdcardNo(insurancePre.getReplaceEmpIdcard());
				addParam.setDeptNo(insurancePre.getReplaceDeptNo());
				addParam.setInsuranceCompanyName(insurancePre.getInsuranceCompanyName());
				addParam.setInsuranceTypeName(insurancePre.getInsuranceTypeName());
				addParam.setBuyStandard(insurancePre.getBuyStandard());
				addParam.setPolicyStart(DateUtil.dateToString(insurancePre.getPolicyStart(),DateUtil.ISO_EXPANDED_DATE_FORMAT));
				addParam.setPolicyEnd(DateUtil.dateToString(insurancePre.getPolicyEnd(),DateUtil.ISO_EXPANDED_DATE_FORMAT));
				addParam.setPost(insurancePre.getPosition());
				addParam.setReplaceEmpName(insurancePre.getEmployeeName());
				addParam.setReplaceDeptNo(insurancePre.getDeptNo());
				addParam.setReplaceEmpIdcardNo(insurancePre.getEmpIdcard());
				addParam.setRemark(CommonConstants.EMPTY_STRING);
				addParam.setInsurancePreId(insurancePre.getId());
				addParam.setCustomerUserName(insurancePre.getCustomerUsername());
				addParam.setIsExit(sameFlag);
				replaceAddParamList.add(addParam);
			}
		}
		//组装返回给前端
		List<InsuranceAddParam> paramList = new ArrayList<>();
		List<InsuranceBatchParam> batchParamList = new ArrayList<>();
		List<InsuranceReplaceParam> replaceParamList = new ArrayList<>();
		if (!addParamList.isEmpty()) {
			R<List<InsuranceAddParam>> listR = detailService.addInsurance(addParamList,null,true);
			if (Common.isNotNull(listR) && Common.isNotNull(listR.getData()) && !listR.getData().isEmpty()) {
				paramList = listR.getData();
			}
		}
		if (!batchAddParamList.isEmpty()) {
			R<List<InsuranceBatchParam>> listR = detailService.batchInsurance(batchAddParamList,null,true);
			if (Common.isNotNull(listR) && Common.isNotNull(listR.getData()) && !listR.getData().isEmpty()) {
				batchParamList = listR.getData();
			}
		}
		if (!replaceAddParamList.isEmpty()) {
			R<List<InsuranceReplaceParam>> listR = detailService.replaceInsurance(replaceAddParamList,null,true);
			if (Common.isNotNull(listR) && Common.isNotNull(listR.getData()) && !listR.getData().isEmpty()) {
				replaceParamList = listR.getData();
			}
		}
		// 使用Stream合并三个列表
		List<InsuranceAutoParam> autoAddParamList = Stream.concat(
				paramList.stream().map(this::convertAddParam),
				Stream.concat(
						batchParamList.stream().map(this::convertBatchParam),
						replaceParamList.stream().map(this::convertReplaceParam)
				)
		).collect(Collectors.toList());

		if (autoAddParamList.isEmpty()) {
			/*LambdaUpdateWrapper<TEmployeeInsurancePre> updateWrapper = new LambdaUpdateWrapper<>();
			updateWrapper.in(TEmployeeInsurancePre::getId,pushIdList)
					.set(TEmployeeInsurancePre::getProcessStatus, CommonConstants.THREE_STRING);
			this.update(updateWrapper);*/
		} else {
			// 将 autoAddParamList 中的id等信息提取出来，放入一个 Set 中
			Set<String> autoAddParamSet = new HashSet<>();
			/*= autoAddParamList.stream()
					.map(InsuranceAutoParam::getInsurancePreId)
					.collect(Collectors.toSet());*/
			Map<String, String> errorMessageMap = new HashMap<>();
			for (InsuranceAutoParam info : autoAddParamList) {
				autoAddParamSet.add(info.getInsurancePreId());
				errorMessageMap.put(info.getInsurancePreId(), info.getErrorMessage());
			}

			Map<String, Set<String>> deptNumMap = new HashMap<>();
			Map<String, Integer> allNumMap = new HashMap<>();
			Map<String, Integer> failNumMap = new HashMap<>();
			//Map<String, List<TEmployeeInsurancePreQwDetail>> preDetailQwMap = new HashMap<>();
			Map<String, TEmployeeInsurancePreQw> preQwMap = new HashMap<>();
			// 派单失败的
			//List<TEmployeeInsurancePre> existingList = new ArrayList<>();
			// 派单成功的
			//List<TEmployeeInsurancePre> nonExistingList = new ArrayList<>();
			List<TEmployeeInsurancePre> updateList = new ArrayList<>();
			TEmployeeInsurancePre updatePre;
			LocalDateTime now = LocalDateTime.now();
			String errorrMessage;
			Set<String> tempSet;
			Integer nums;
			String customerUserLoginname;

			// 项目、人数、失败人数
			TEmployeeInsurancePreQw qw;
			TEmployeeInsurancePreQwDetail qwDetail;
			List<TEmployeeInsurancePreQwDetail> qwDetalList = new ArrayList<>();

			for (TEmployeeInsurancePre pre : insurancePreList) {
				customerUserLoginname = pre.getCustomerUserLoginname();
				if (Common.isNotNull(customerUserLoginname)) {
					tempSet = deptNumMap.get(customerUserLoginname);
					if (tempSet == null) {
						tempSet = new HashSet<>();
					}
					tempSet.add(pre.getDeptNo());
					deptNumMap.put(customerUserLoginname, tempSet);
				}
				updatePre = new TEmployeeInsurancePre();
				updatePre.setId(pre.getId());
				String qwUuId;

				if (Common.isNotNull(customerUserLoginname)) {
					nums = allNumMap.get(customerUserLoginname);
					if (Common.isEmpty(nums)) {
						nums = CommonConstants.ZERO_INT;
					}
					nums++;
					allNumMap.put(customerUserLoginname, nums);
				}
				// 派单失败的
				if (autoAddParamSet.contains(pre.getId())) {
					errorrMessage = errorMessageMap.get(pre.getId());
					if (Common.isNotNull(customerUserLoginname)) {
						nums = failNumMap.get(customerUserLoginname);
						if (Common.isEmpty(nums)) {
							nums = CommonConstants.ZERO_INT;
						}
						nums++;
						failNumMap.put(customerUserLoginname, nums);

						// 派单失败，组装需要推送企微的明细
						qw = preQwMap.get(customerUserLoginname);
						if (qw == null) {
							qw = new TEmployeeInsurancePreQw();
							qwUuId = String.valueOf(UUID.randomUUID()).replace("-", "");
							qw.setId(qwUuId);
							qw.setCreateTime(now);
							qw.setCustomerUserLoginname(customerUserLoginname);
							qw.setCustomerUsername(pre.getCustomerUsername());
						} else {
							qwUuId = qw.getId();
						}
						preQwMap.put(customerUserLoginname, qw);
						// 派单失败，组装需要推送企微的明细
						//qwDetalList = preDetailQwMap.get(customerUserLoginname);
						/*if (qwDetalList == null) {
							qwDetalList = new ArrayList<>();
						}*/
						qwDetail = new TEmployeeInsurancePreQwDetail();
						qwDetail.setPreId(pre.getId());
						qwDetail.setMainId(qwUuId);
						qwDetail.setEmpName(pre.getEmployeeName());
						qwDetail.setEmpIdcard(pre.getEmpIdcard());
						qwDetail.setErrorInfo(errorrMessage);
						qwDetail.setErrorTime(now);
						qwDetalList.add(qwDetail);
						//preDetailQwMap.put(customerUserLoginname, qwDetalList);
					}
					//existingList.add( pre)
					updatePre.setProcessStatus(CommonConstants.TWO_STRING);
					updatePre.setErrorTime(now);

					updatePre.setErrorInfo(errorrMessage);
					updateList.add(updatePre);

				} else {
					// 派单成功的 在各个口禅

					//nonExistingList.add(pre)
					/*updatePre.setProcessStatus(CommonConstants.THREE_STRING);
					updateList.add(updatePre)*/;
				}
			}
			if (!updateList.isEmpty()) {
				this.updateBatchById(updateList);
			}
			// pushQiWeiFlag 推送企微的flag，true表示推送企微
			if (pushQiWeiFlag && !preQwMap.isEmpty()) {
				List<TEmployeeInsurancePreQw> qwList = new ArrayList<>();
				int deptNum;
				int allNum;
				int failNum;
				StringBuilder description;
				String userLoginNames = null;
				for (Map.Entry<String, TEmployeeInsurancePreQw> entry : preQwMap.entrySet()) {
					customerUserLoginname = entry.getKey();
					if (Common.isNotNull(userLoginNames)) {
						userLoginNames += "," + customerUserLoginname;
					} else {
						userLoginNames = customerUserLoginname;
					}
					qw = entry.getValue();
					tempSet = deptNumMap.get(customerUserLoginname);
					if (Common.isNotNull(tempSet)) {
						deptNum = tempSet.size();
					} else {
						deptNum = 0;
					}
					allNum = allNumMap.get(customerUserLoginname);
					if (Common.isEmpty(allNum)) {
						allNum = 0;
					}
					failNum = failNumMap.get(customerUserLoginname);
					if (Common.isEmpty(failNum)) {
						failNum = 0;
					}
					description = new StringBuilder("项目数：").append(deptNum).append("个；自动化派单人数：")
							.append(allNum).append("个，【失败人数：").append(failNum).append("个】<br>请及时至HRO系统处理，以免人员漏保！");
					qw.setDescription(description.toString());
					qwList.add(qw);
				}
				if(!qwDetalList.isEmpty() && !qwList.isEmpty()) {
					tEmployeeInsurancePreQwDetailService.saveBatch(qwDetalList);
					tEmployeeInsurancePreQwService.saveBatch(qwList);
					if (Common.isNotNull(userLoginNames)) {
						Map<String, String> sysUserMap = getUserQiWeiInfo(userLoginNames);
						String qwInfo;
						if (!sysUserMap.isEmpty()) {
							for (TEmployeeInsurancePreQw sendQw : qwList) {
								qwInfo = sysUserMap.get(sendQw.getCustomerUserLoginname());
								if (Common.isNotNull(qwInfo)) {
									sendMessageToWx(qwInfo, sendQw.getDescription(), sendQw.getId());
								}
							}
						}
					}
				}

			}


			// 找出 insurancePreList 中在 autoAddParamList 中存在的数据
			/*List<TEmployeeInsurancePre> existingList = insurancePreList.stream()
					.filter(pre -> autoAddParamSet.contains(pre.getId()))
					.collect(Collectors.toList());

			// 找出 insurancePreList 中在 autoAddParamList 中不存在的数据
			List<TEmployeeInsurancePre> nonExistingList = insurancePreList.stream()
					.filter(pre -> !autoAddParamSet.contains(pre.getId()))
					.collect(Collectors.toList());
			//派单成功的更新状态为代投保，派单失败更新成派单失败
			if (!existingList.isEmpty()){
				List<String> onIdList = existingList.stream().map(TEmployeeInsurancePre::getId).collect(Collectors.toList())
				LambdaUpdateWrapper<TEmployeeInsurancePre> updateWrapper = new LambdaUpdateWrapper<>()
				updateWrapper.in(TEmployeeInsurancePre::getId,onIdList)
						.set(TEmployeeInsurancePre::getProcessStatus, CommonConstants.TWO_STRING)
				this.update(updateWrapper)
			}
			if (!nonExistingList.isEmpty()){
				List<String> unIdList = nonExistingList.stream().map(TEmployeeInsurancePre::getId).collect(Collectors.toList());
				LambdaUpdateWrapper<TEmployeeInsurancePre> updateWrapper = new LambdaUpdateWrapper<>();
				updateWrapper.in(TEmployeeInsurancePre::getId,unIdList)
						.set(TEmployeeInsurancePre::getProcessStatus, CommonConstants.THREE_STRING);
				this.update(updateWrapper);
			}*/
		}
		return R.ok(autoAddParamList);
	}

	//发送企业微信待办
	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", "65"+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);
			}
		}
	}

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

	@Override
	@Transactional
	public Boolean saveInsurancePreInfo(EmployeeRegistrationPreVo registrationPreVo) {
		if (Common.isNotNull(registrationPreVo.getInsuranceIsBuy())
				&& registrationPreVo.getInsuranceIsBuy().equals(CommonConstants.ZERO_STRING)
				&& !registrationPreVo.getExitInsuranceInfoList().isEmpty()) {
			//删除已存在的入职确认信息对应的商险明细
			preDetailService.remove(Wrappers.<TInsurancePreDetail>lambdaQuery()
					.eq(TInsurancePreDetail::getRegisterId, registrationPreVo.getExitInsuranceInfoList()
							.get(0).getRegisterId()));
			//批量新增
			preDetailService.saveBatch(registrationPreVo.getExitInsuranceInfoList());
			//批量删除商险待购买列表中的待确认、待派单、派单失败、投保退回的数据
			baseMapper.delete(Wrappers.<TEmployeeInsurancePre>query().lambda().in(
					TEmployeeInsurancePre::getProcessStatus,CommonConstants.insuranceAutoProcessStatus)
					.eq(TEmployeeInsurancePre::getRegisterId,registrationPreVo.getExitInsuranceInfoList()
							.get(0).getRegisterId()));
		} else {
			List<TEmployeeInsurancePreVo> employeeInsurancePreVos = registrationPreVo.getEmployeeInsurancePreVos();
			TEmployeeInsurancePre preExit;
			if (null != employeeInsurancePreVos && !employeeInsurancePreVos.isEmpty()) {
				try {
					//删除已存在的入职确认信息对应的商险明细
					preDetailService.remove(Wrappers.<TInsurancePreDetail>lambdaQuery()
							.eq(TInsurancePreDetail::getRegisterId, employeeInsurancePreVos.get(0).getRegisterId()));
					for (TEmployeeInsurancePreVo preVo : employeeInsurancePreVos) {
						//判断是否存在商险待购买信息
						preExit = baseMapper.selectOne(Wrappers.<TEmployeeInsurancePre>query().lambda()
								.eq(TEmployeeInsurancePre::getRegisterId, preVo.getRegisterId())
								.eq(TEmployeeInsurancePre::getEmpIdcard, preVo.getEmpIdcard())
								.eq(TEmployeeInsurancePre::getBuyStandard, preVo.getBuyStandard())
								.eq(TEmployeeInsurancePre::getInsuranceTypeName, preVo.getInsuranceTypeName())
								.eq(TEmployeeInsurancePre::getInsuranceCompanyName, preVo.getInsuranceCompanyName())
								.eq(TEmployeeInsurancePre::getPolicyStart, DateUtil.parseDate(DateUtil.dateToString(preVo.getPolicyStart()), DateUtil.ISO_EXPANDED_DATE_FORMAT))
								.eq(TEmployeeInsurancePre::getPolicyEnd, DateUtil.parseDate(DateUtil.dateToString(preVo.getPolicyEnd()), DateUtil.ISO_EXPANDED_DATE_FORMAT))
								.last(CommonConstants.LAST_ONE_SQL));
						TEmployeeInsurancePre pre = new TEmployeeInsurancePre();
						BeanUtils.copyProperties(preVo, pre);
						if (Common.isNotNull(preVo.getExpectedCollectionTime())) {
							pre.setExpectedCollectionTime(LocalDateTimeUtils.dateToLocalDateTime(preVo.getExpectedCollectionTime()));
						}
						if (Common.isNotNull(preExit)) {
							pre.setId(preExit.getId());
							baseMapper.deleteById(preExit);
							baseMapper.insert(pre);
						} else {
							baseMapper.insert(pre);
							//暂时不需要，先注释，后续可能会需要
//					if (Common.isNotNull(pre.getExpectedCollectionTime())) {
//						// 事务提交后触发调度
//						TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
//							@Override
//							public void afterCommit() {
//								LocalDateTime now = LocalDateTime.now();
//								if (pre.getExpectedCollectionTime().isEqual(now)) {
//									scheduleService.executeTask(pre.getId());
//								} else if (preVo.getExpectedCollectionTime().compareTo(LocalDateTimeUtils.convertLDTToDate(now)) > 0){
//									scheduleService.scheduleTask(pre);
//								}
//							}
//						});
//					}
						}
					}
				} catch (Exception e) {
					log.error("执行异常", e);
					return null;
				}
			}
		}
		return true;
	}

	@Override
	public Boolean updateInfoSaveInsurancePreInfo(EmployeeRegistrationPre registrationPre) {
		if (Common.isNotNull(registrationPre.getInsuranceIsBuy())
				&& registrationPre.getInsuranceIsBuy().equals(CommonConstants.ZERO_STRING)
				&& !registrationPre.getExitInsuranceInfoList().isEmpty()) {
			//删除已存在的入职确认信息对应的商险明细
			preDetailService.remove(Wrappers.<TInsurancePreDetail>lambdaQuery()
					.eq(TInsurancePreDetail::getRegisterId, registrationPre.getId()));
			//批量新增
			preDetailService.saveBatch(registrationPre.getExitInsuranceInfoList());
		}
		//如果商险是否已购买为否，删除商险已购买明细
		if (Common.isNotNull(registrationPre.getInsuranceIsBuy())
				&& registrationPre.getInsuranceIsBuy().equals(CommonConstants.ONE_STRING)) {
			//删除已存在的入职确认信息对应的商险明细
			preDetailService.remove(Wrappers.<TInsurancePreDetail>lambdaQuery()
					.eq(TInsurancePreDetail::getRegisterId, registrationPre.getId()));
		}
		return true;
	}

	@Override
	public Boolean deleteInsurancePreInfo(EmployeeRegistrationPre registrationPre) {
		//删除已存在的入职确认信息对应的商险明细
		preDetailService.remove(Wrappers.<TInsurancePreDetail>lambdaQuery()
				.eq(TInsurancePreDetail::getRegisterId, registrationPre.getId()));
		return true;
	}

	@Override
	public Boolean checkExitInsuanceIsProcess(EmployeeRegistrationPreVo preVo) {
		//如果状态有变动就会拦截
		if (Common.isNotNull(preVo) && Common.isNotNull(preVo.getExitInsuranceInfoList())
				&& !preVo.getExitInsuranceInfoList().isEmpty()) {
			for (TInsurancePreDetail preDetail: preVo.getExitInsuranceInfoList()) {
				TInsuranceDetail insuranceDetail = detailService.getById(preDetail.getId());
				if (Common.isEmpty(insuranceDetail) || !insuranceDetail.getBuyHandleStatus().equals(preDetail.getBuyHandleStatus())) {
					return false;
				}
			}
			//如果有数据新增也要拦截
			long count = detailService.count(Wrappers.<TInsuranceDetail>query().lambda()
					.eq(TInsuranceDetail::getEmpIdcardNo, preVo.getEmpIdcard())
					.eq(TInsuranceDetail::getDeleteFlag, CommonConstants.ZERO_INT)
					//流程中或者已完结
					.and(
							wrapper -> wrapper.eq(TInsuranceDetail::getIsEffect, CommonConstants.ZERO_INT)
									.eq(TInsuranceDetail::getIsOverdue, CommonConstants.ZERO_INT)
									.eq(TInsuranceDetail::getBuyHandleStatus, CommonConstants.THREE_INT)
									.or().eq(TInsuranceDetail::getBuyHandleStatus, CommonConstants.TWO_INT)
									.or().eq(TInsuranceDetail::getBuyHandleStatus, CommonConstants.SIX_INT)
									.or().eq(TInsuranceDetail::getBuyHandleStatus, CommonConstants.ONE_INT)));
			return count == preVo.getExitInsuranceInfoList().size();
		}
		return true;
	}

	@Override
	public TEmployeeInsuranceSelectVo selectInsurancePreInfoList(TEmployeeInsurancePreVo preVo) {
		TEmployeeInsuranceSelectVo selectVo = new TEmployeeInsuranceSelectVo();
		List<TEmployeeInsurancePre> list = new ArrayList<>();
		try {
			list = baseMapper.selectList(Wrappers.<TEmployeeInsurancePre>query().lambda()
					.eq(TEmployeeInsurancePre::getEmpIdcard, preVo.getEmpIdcard())
					.eq(TEmployeeInsurancePre::getBuyStandard, preVo.getBuyStandard())
					.eq(TEmployeeInsurancePre::getInsuranceTypeName, preVo.getInsuranceTypeName())
					.eq(TEmployeeInsurancePre::getInsuranceCompanyName, preVo.getInsuranceCompanyName())
					.eq(TEmployeeInsurancePre::getPolicyStart, DateUtil.parseDate(DateUtil.dateToString(preVo.getPolicyStart()), DateUtil.ISO_EXPANDED_DATE_FORMAT))
					.eq(TEmployeeInsurancePre::getPolicyEnd, DateUtil.parseDate(DateUtil.dateToString(preVo.getPolicyEnd()), DateUtil.ISO_EXPANDED_DATE_FORMAT))
			);
		}catch (Exception e){
			log.error("执行异常" ,e);
		}
		selectVo.setInsurancePreList(list);
		return selectVo;
	}

	@Override
	public void updateInsurancePreCustomerName(EmployeeRegistrationCustomerUserUpdateVo updateVo) {
		if (Common.isNotNull(updateVo)) {
			LambdaUpdateWrapper<TEmployeeInsurancePre> updateWrapper = new LambdaUpdateWrapper<>();
			updateWrapper.eq(TEmployeeInsurancePre::getDeptNo, updateVo.getDeptNo())
					.set(TEmployeeInsurancePre::getCustomerUsername, updateVo.getCustomerUserName())
					.set(TEmployeeInsurancePre::getCustomerUserLoginname, updateVo.getCustomerUserLoginName());
			this.update(updateWrapper);

			// 更新商险续签待办的前端客服
			LambdaUpdateWrapper<TInsurancePreRenewDetail> updateWrapper2 = new LambdaUpdateWrapper<>();
			updateWrapper2.eq(TInsurancePreRenewDetail::getDeptNo, updateVo.getDeptNo())
					.set(TInsurancePreRenewDetail::getCustomerUsername, updateVo.getCustomerUserName())
					.set(TInsurancePreRenewDetail::getCustomerUserLoginname, updateVo.getCustomerUserLoginName());
			tInsurancePreRenewDetailService.update(updateWrapper2);
		}
	}

	@Override
	public void pushWxConfrimMessage() {
		//获取所有预计派单时间为当天而且状态是待确认的商险待购买数据
		List<TEmployeeInsurancePre> unConfirmList = baseMapper.getAllUnconfimData();
		if (Common.isNotNull(unConfirmList) && !unConfirmList.isEmpty()) {
			for (TEmployeeInsurancePre pre : unConfirmList) {
				try {
					sendMessageToWx(pre);
				} catch (Exception e) {
					log.error("执行异常", e);
				}
			}
		}
	}

	@Override
	public void pushDisConfrimInsurances() {
		//获取所有待派单的数据
		List<String> unConfirmList = baseMapper.getAllUnDisData();
		if (null != unConfirmList && !unConfirmList.isEmpty()) {
			//更新成已确认
			LambdaUpdateWrapper<TEmployeeInsurancePre> updateWrapper = new LambdaUpdateWrapper<>();
			updateWrapper.in(TEmployeeInsurancePre::getId, unConfirmList)
					.eq(TEmployeeInsurancePre::getProcessStatus, CommonConstants.ZERO_STRING)
					.set(TEmployeeInsurancePre::getProcessStatus, CommonConstants.ONE_STRING);
			this.update(updateWrapper);
			try {
				this.batchDispatcherInsurance(unConfirmList,CommonConstants.ONE_STRING, true);
			} catch (Exception e) {
				log.error("执行异常", e);
			}
		}
	}

	/**
	 * @Description: 获取前端客服的所有项目权限
	 * @Author: huych
	 * @Date: 2025/3/13 17:02
	 * @return:
	 **/
	public void initSearchVo(TEmployeeInsurancePreSearchVo searchVo) {
		YifuUser user = SecurityUtils.getUser();
		long roleId = 1839501715787390978L;
		boolean isSsc = this.haveRole(user, roleId);
		if (isSsc || CommonConstants.ZERO_STRING.equals(user.getSystemFlag())) {
			searchVo.setAuthSql(null);
			return;
		}
		if (Common.isNotNull(searchVo.getType()) && CommonConstants.ONE_STRING.equals(searchVo.getType())) {
			searchVo.setAuthSql(null);
			//获取项目信息
			R<TSettleDomainRegistListVo> domainR = archivesDaprUtil.getAllDeptByCustomerLoginName(user.getUsername());
			if (null != domainR && null != domainR.getData() && null != domainR.getData().getDeptNos() && !domainR.getData().getDeptNos().isEmpty()) {
				searchVo.setDeptNoList(domainR.getData().getDeptNos());
			} else {
				searchVo.setId(CommonConstants.ONE_STRING_NEGATE);
			}
		}
	}

	public 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;
	}

	@Override
	public List<InsuranceAutoParam> getInsuranceAutoParamList(List<InsuranceAddParam> addParamList, List<InsuranceBatchParam> batchParamList
			, List<InsuranceReplaceParam> replaceParamList) {
		if (addParamList != null) {
			addParamList = new ArrayList<>();
		}
		if (batchParamList != null) {
			batchParamList = new ArrayList<>();
		}
		if (replaceParamList != null) {
			replaceParamList = new ArrayList<>();
		}
			// 使用Stream合并三个列表
		return Stream.concat(
				addParamList.stream().map(this::convertAddParam),
				Stream.concat(
						batchParamList.stream().map(this::convertBatchParam),
						replaceParamList.stream().map(this::convertReplaceParam)
				)
		).collect(Collectors.toList());
	}


	private InsuranceAutoParam convertAddParam(InsuranceAddParam addParam) {
		InsuranceAutoParam autoParam = new InsuranceAutoParam();
		// 复制InsuranceAddParam的字段
		autoParam.setEmpName(addParam.getEmpName());
		autoParam.setEmpIdcardNo(addParam.getEmpIdcardNo());
		autoParam.setDeptNo(addParam.getDeptNo());
		autoParam.setInsuranceCompanyName(addParam.getInsuranceCompanyName());
		autoParam.setInsuranceTypeName(addParam.getInsuranceTypeName());
		autoParam.setPolicyStart(addParam.getPolicyStart());
		autoParam.setPolicyEnd(addParam.getPolicyEnd());
		autoParam.setBuyStandard(addParam.getBuyStandard());
		autoParam.setInsuranceProvinceName(addParam.getInsuranceProvinceName());
		autoParam.setInsuranceCityName(addParam.getInsuranceCityName());
		autoParam.setSettleMonth(addParam.getSettleMonth());
		autoParam.setPost(addParam.getPost());
		autoParam.setRemark(addParam.getRemark());
		autoParam.setErrorMessage(addParam.getErrorMessage());
		autoParam.setInsurancePreId(addParam.getInsurancePreId());
		autoParam.setCustomerUserName(addParam.getCustomerUserName());
		autoParam.setIsExit(addParam.getIsExit());
		autoParam.setDeptName(addParam.getDeptName());
		autoParam.setBuyType(addParam.getBuyType());
		autoParam.setInProgressList(addParam.getInProgressList());
		return autoParam;
	}

	private InsuranceAutoParam convertBatchParam(InsuranceBatchParam batchParam) {
		InsuranceAutoParam autoParam = new InsuranceAutoParam();
		// 复制InsuranceBatchParam的字段
		autoParam.setEmpName(batchParam.getEmpName());
		autoParam.setEmpIdcardNo(batchParam.getEmpIdcardNo());
		autoParam.setDeptNo(batchParam.getDeptNo());
		autoParam.setInsuranceCompanyName(batchParam.getInsuranceCompanyName());
		autoParam.setInsuranceTypeName(batchParam.getInsuranceTypeName());
		autoParam.setPolicyNo(batchParam.getPolicyNo());
		autoParam.setBuyStandard(batchParam.getBuyStandard());
		autoParam.setInsuranceProvinceName(batchParam.getInsuranceProvinceName());
		autoParam.setInsuranceCityName(batchParam.getInsuranceCityName());
		autoParam.setSettleMonth(batchParam.getSettleMonth());
		autoParam.setPost(batchParam.getPost());
		autoParam.setRemark(batchParam.getRemark());
		autoParam.setErrorMessage(batchParam.getErrorMessage());
		autoParam.setInsurancePreId(batchParam.getInsurancePreId());
		autoParam.setCustomerUserName(batchParam.getCustomerUserName());
		autoParam.setIsExit(batchParam.getIsExit());
		autoParam.setDeptName(batchParam.getDeptName());
		autoParam.setBuyType(batchParam.getBuyType());
		autoParam.setInProgressList(batchParam.getInProgressList());
		autoParam.setPolicyEnd(LocalDateUtil.getDateSrt(batchParam.getPolicyEnd()));
		autoParam.setPolicyStart(LocalDateUtil.getDateSrt(batchParam.getPolicyStart()));
		return autoParam;
	}

	private InsuranceAutoParam convertReplaceParam(InsuranceReplaceParam replaceParam) {
		InsuranceAutoParam autoParam = new InsuranceAutoParam();
		// 复制InsuranceReplaceParam的字段
		autoParam.setEmpName(replaceParam.getEmpName());
		autoParam.setEmpIdcardNo(replaceParam.getEmpIdcardNo());
		autoParam.setDeptNo(replaceParam.getDeptNo());
		autoParam.setInsuranceCompanyName(replaceParam.getInsuranceCompanyName());
		autoParam.setInsuranceTypeName(replaceParam.getInsuranceTypeName());
		autoParam.setBuyStandard(replaceParam.getBuyStandard());
		autoParam.setPolicyEnd(replaceParam.getPolicyEnd());
		autoParam.setPolicyStart(replaceParam.getPolicyStart());
		autoParam.setPost(replaceParam.getPost());
		autoParam.setReplaceEmpName(replaceParam.getReplaceEmpName());
		autoParam.setReplaceDeptNo(replaceParam.getReplaceDeptNo());
		autoParam.setReplaceEmpIdcardNo(replaceParam.getReplaceEmpIdcardNo());
		autoParam.setErrorMessage(replaceParam.getErrorMessage());
		autoParam.setInsurancePreId(replaceParam.getInsurancePreId());
		autoParam.setCustomerUserName(replaceParam.getCustomerUserName());
		autoParam.setIsExit(replaceParam.getIsExit());
		autoParam.setDeptName(replaceParam.getDeptName());
		autoParam.setBuyType(replaceParam.getBuyType());
		autoParam.setInProgressList(replaceParam.getInProgressList());
		return autoParam;
	}

	//发送企业微信待办
	private void sendMessageToWx(TEmployeeInsurancePre insurancePre) {
		//获取前端客服
		SysUser user;
		if (Common.isEmpty(insurancePre.getCustomerUserLoginname())) {
			return;
		}
		R<SysUser> res = upmsDaprUtils.getSimpleUserByLoginName(insurancePre.getCustomerUserLoginname());
		if (Common.isNotNull(res) && Common.isNotNull(res.getData())) {
			user = res.getData();
		} else {
			return;
		}
		StringBuilder sendUser = null;
		if (Common.isNotKong(user.getWxMessage())) {
			sendUser = new StringBuilder(user.getWxMessage());
		}
		if (sendUser != null) {
			RestTemplate restTemplate = new RestTemplate();
			Map<String, Object> requestMap = new HashMap<>();
			Map<String, Object> textcard = new HashMap<>();
			String authUrl = String.format(SecurityConstants.WX_GET_MESSAGE_AUTH_URL, wxConfig.getCorpid(), wxConfig.getDomainName() + "/auth/oauth/wxLogin", "02" + insurancePre.getCustomerUserLoginname());
			StringBuilder description = new StringBuilder();
			String title = "商险投保确认";
			description.append("您有新的商险购买待确认数据，请及时确认").append("<br>");
			textcard.put("title", title);
			textcard.put("url", authUrl);
			textcard.put("description", description.toString());
			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);
			}
		}
	}
	/**
	 * @param empPreId 入职确认ID
	 * @Description: 根据
	 * @Author: hgw
	 * @Date: 2025/4/7 18:29
	 * @return: java.util.List<com.yifu.cloud.plus.v1.yifu.insurances.entity.TEmployeeInsurancePre>
	 **/
	@Override
	public EmployeePreLogListVo getListByEmpPreId(String empPreId) {
		EmployeePreLogListVo vo = new EmployeePreLogListVo();
		List<TEmployeeInsurancePre> preList = baseMapper.getListByEmpPreId(empPreId);
		if (Common.isNotNull(preList) && !preList.isEmpty()) {
			preList.forEach(e->e.setErrorTime(null));
		}
		vo.setPreList(preList);
		return vo;
	}

	/**
	 * @Description: 先删后增
	 * @Author: hgw
	 * @Date: 2025/4/8 11:30
	 * @return: boolean
	 **/
	@Override
	public boolean saveOrUpdateInsuranceList(List<TEmployeeInsurancePre> preList) {
		baseMapper.deleteByEmpPreId(preList.get(0).getRegisterId());
		this.saveOrUpdateBatch(preList);
		return true;
	}

	/**
	 * @Description: 删除
	 * @Author: hgw
	 * @Date: 2025/4/10 14:49
	 * @return: boolean
	 **/
	@Override
	public boolean deleteInsuranceByPreId(String preId) {
		baseMapper.deleteByEmpPreId(preId);
		return true;
	}

	@Override
	public EmployeePreInsuranceListVo getExitInsuranceListByEmpPreId(String empPreId) {
		EmployeePreInsuranceListVo vo = new EmployeePreInsuranceListVo();
		List<TInsurancePreDetail> preList = preDetailService.list(Wrappers.<TInsurancePreDetail>query().lambda()
						.eq(TInsurancePreDetail::getRegisterId, empPreId));
		if (Common.isNotNull(preList) && !preList.isEmpty()) {
			preList.forEach(e -> {
				e.setDisTime(DateUtil.convertToDateByLocalDateTime(e.getCreateTime()));
				e.setCreateTime(null);
				e.setUpdateTime(null);
			});
		}
		vo.setPreList(preList);
		return vo;
	}
	/**
	 * @Author fxj
	 * @Description 通过如入职ID删除商险待办数据
	 * @Date 20:31 2026/1/22
	 * @Param
	 * @return
	**/
	@Override
	public Boolean delInsurancePreByRegisterId(BaseSearchVO preVo) {
		return this.remove(Wrappers.<TEmployeeInsurancePre>query().lambda()
				.eq(TEmployeeInsurancePre::getRegisterId, preVo.getRegisterId()));
	}
	@Override
	public Boolean refuseInsurancePreByRegisterId(BaseSearchVO preVo) {
		LambdaUpdateWrapper<TEmployeeInsurancePre> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(TEmployeeInsurancePre::getRegisterId, preVo.getRegisterId());
		updateWrapper.set(TEmployeeInsurancePre::getIsRefuse, CommonConstants.ZERO_STRING);
		return this.update(updateWrapper);
	}
	@Override
	public R<TEmployeeInsurancePre> getInfoByRegistId(String registId) {
		if (Common.isEmpty(registId)){
			return R.failed(CommonConstants.PARAM_INFO_ERROR);
		}
		return R.ok(baseMapper.selectOne(Wrappers.<TEmployeeInsurancePre>query().lambda()
				.notIn(TEmployeeInsurancePre::getProcessStatus, Arrays.asList("0","1","2","5"))
				.eq(TEmployeeInsurancePre::getRegisterId, registId).last(CommonConstants.LAST_ONE_SQL)));
	}
}
