/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yifu4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.vo.IdNameNoVo;
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.R;
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.dapr.util.SocialDaprUtils;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.UpmsDaprUtils;
import com.yifu.cloud.plus.v1.yifu.insurances.config.WxConfig;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.TInsuranceAlert;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.TInsurancePreRenewDetail;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.TInsurancePreRenewDetailQw;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.TInsurancePreRenewDetailQwDetail;
import com.yifu.cloud.plus.v1.yifu.insurances.mapper.insurances.TInsurancePreRenewDetailMapper;
import com.yifu.cloud.plus.v1.yifu.insurances.mapper.insurances.TInsuranceWarnMapper;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.TInsuranceDetailService;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.TInsurancePreRenewDetailQwDetailService;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.TInsurancePreRenewDetailQwService;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.TInsurancePreRenewDetailService;
import com.yifu.cloud.plus.v1.yifu.insurances.util.LocalDateUtil;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.*;
import com.yifu.cloud.plus.v1.yifu.social.vo.TEmployeeInsuranceWorkDayVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 商险续签待办
 *
 * @author hgw
 * @date 2025-11-11 16:33:49
 */
@Log4j2
@Service
public class TInsurancePreRenewDetailServiceImpl extends ServiceImpl<TInsurancePreRenewDetailMapper, TInsurancePreRenewDetail> implements TInsurancePreRenewDetailService {

	@Autowired
	@Lazy
	private TInsuranceDetailService detailService;

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

	@Autowired
	private WxConfig wxConfig;

	@Autowired
	private UpmsDaprUtils upmsDaprUtils;

	@Autowired
	private SocialDaprUtils socialDaprUtils;

	/**
	 * 商险续签待办简单分页查询
	 *
	 * @param tInsurancePreRenewDetail 商险续签待办
	 * @return
	 */
	@Override
	public IPage<TInsurancePreRenewDetail> getTInsurancePreRenewDetailPage(Page<TInsurancePreRenewDetail> page, TInsurancePreRenewDetail tInsurancePreRenewDetail) {
		return baseMapper.getTInsurancePreRenewDetailPage(page, tInsurancePreRenewDetail);
	}

	@Override
	public R<String> doEdit(TInsurancePreRenewDetail tInsurancePreRenewDetail) {
		if (tInsurancePreRenewDetail != null && Common.isNotNull(tInsurancePreRenewDetail.getId())) {
			TInsuranceAlert alert = tInsuranceWarnMapper.selectInsuranceAlertOne(tInsurancePreRenewDetail.getId());
			if (alert != null && Common.isNotNull(alert.getId()) && Common.isNotNull(alert.getProcessStatus())) {
				if (!(CommonConstants.ONE_STRING.equals(alert.getProcessStatus())
						|| CommonConstants.TWO_STRING.equals(alert.getProcessStatus())
						|| CommonConstants.FIVE_STRING.equals(alert.getProcessStatus()))) {
					return R.failed("该状态不可编辑，请刷新后重试");
				}
				this.updateById(tInsurancePreRenewDetail);
				return R.ok();
			} else {
				return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
			}
		} else {
			return R.failed("请传参ID");
		}
	}

	@Override
	public R<String> doSure(TInsurancePreRenewDetail tInsurancePreRenewDetail) {
		if (tInsurancePreRenewDetail != null && Common.isNotNull(tInsurancePreRenewDetail.getId())) {
			TInsuranceAlert alert = tInsuranceWarnMapper.selectInsuranceAlertOne(tInsurancePreRenewDetail.getId());
			if (alert != null && Common.isNotNull(alert.getId())) {
				if (CommonConstants.ZERO_STRING.equals(alert.getProcessStatus())) {
					tInsurancePreRenewDetail.setProcessStatus(CommonConstants.ONE_STRING);
					this.updateById(tInsurancePreRenewDetail);
					return R.ok();
				} else {
					return R.failed("状态不是待确认");
				}
			} else {
				return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
			}
		} else {
			return R.failed("请传参ID");
		}
	}

	@Override
	public R<String> doSureBatch(BatchIgnoreVo vo) {
		List<String> ids = vo.getIds();
		if (Common.isEmpty(ids)) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		// 先查再更新
		List<TInsuranceAlert> alertList = tInsuranceWarnMapper.selectInsuranceAlertListBySure(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 && CommonConstants.ZERO_STRING.equals(alert.getProcessStatus())) {
					successList.add(id);
					successNum++;
				}
			}
			if (successNum == CommonConstants.ZERO_INT) {
				return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
			} else {
				baseMapper.doBatchSure(successList);
				return R.ok();
			}
		} else {
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
	}

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

	//发送企业微信待办
	private void sendWxSureMessage(IdNameNoVo messageVo) {
		//获取前端客服
		SysUser user;
		if (Common.isEmpty(messageVo.getName())) {
			return;
		}
		R<SysUser> res = upmsDaprUtils.getSimpleUserByLoginName(messageVo.getName());
		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", "06" + messageVo.getName());
			StringBuilder description = new StringBuilder();
			String title = "作业自动化——商险临期续保提醒";
			description.append("商险剩余天数不足5个工作日的人数："+messageVo.getId()+"人").append("<br>")
					.append("请及时续保，以免脱保，产生用工风险！");
			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);
			}
		}
	}

	@Override
	public boolean isWorkDayTest() {
		return isWorkDay();
	}
	/**
	 * 判断指定日期是否为工作日
	 * @return true-工作日，false-非工作日
	 */
	private boolean isWorkDay() {
		TEmployeeInsuranceWorkDayVo workDayVo = new TEmployeeInsuranceWorkDayVo();
		LocalDate localDate = LocalDate.now();
		// 转换为java.util.Date（如果需要）
		Date today = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
		workDayVo.setRegistDate(today);

		// 使用THolidayInfoService的checkIsWorkDay方法判断是否为假期
		// 如果是假期则不是工作日，否则是工作日
		R<Boolean> res = socialDaprUtils.checkIsWorkDay(workDayVo);
		return !res.getData();
	}

	@Override
	public void autoDoInsurancePreRenew() {
		//获取所有待派单的数据
		// 工作日逻辑
		if (isWorkDay()) {

			List<String> unConfirmList = baseMapper.getAllNeedDispatchData();
			if (null != unConfirmList && !unConfirmList.isEmpty()) {
				//更新成已确认
				LambdaUpdateWrapper<TInsurancePreRenewDetail> updateWrapper = new LambdaUpdateWrapper<>();
				updateWrapper.in(TInsurancePreRenewDetail::getId, unConfirmList)
						.eq(TInsurancePreRenewDetail::getProcessStatus, CommonConstants.ZERO_STRING)
						.set(TInsurancePreRenewDetail::getProcessStatus, CommonConstants.ONE_STRING);
				this.update(updateWrapper);
				try {
					this.batchDoInsurancePreRenew(unConfirmList, CommonConstants.ONE_STRING, true);
				} catch (Exception e) {
					log.error("执行异常", e);
				}
			}
		}
	}

	@Override
	public R<List<InsuranceAutoParam>> batchDoInsurancePreRenew(List<String> idList, String sameFlag, boolean pushQiWeiFlag) {

		List<TInsurancePreRenewDetail> insurancePreList = baseMapper.selectPreRenewDetailListByDispatch(idList);
		if (Common.isEmpty(insurancePreList)) {
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		List<String> pushIdList = insurancePreList.stream().map(TInsurancePreRenewDetail::getId).collect(Collectors.toList());
		List<InsuranceAddParam> addParamList = new ArrayList<>();
		List<InsuranceBatchParam> batchAddParamList = new ArrayList<>();
		List<InsuranceReplaceParam> replaceAddParamList = new ArrayList<>();
		for (TInsurancePreRenewDetail insurancePre : insurancePreList) {
			//新增、批增、替换
			if (CommonConstants.ONE_INT == insurancePre.getBuyType()) {
				InsuranceAddParam addParam = new InsuranceAddParam();
				addParam.setEmpName(insurancePre.getEmpName());
				addParam.setEmpIdcardNo(insurancePre.getEmpIdcardNo());
				addParam.setDeptNo(insurancePre.getDeptNo());
				addParam.setInsuranceCompanyName(insurancePre.getInsuranceCompanyName());
				addParam.setInsuranceTypeName(insurancePre.getInsuranceTypeName());
				addParam.setPolicyStart(LocalDateUtil.getDateSrt(insurancePre.getPolicyStart(), LocalDateUtil.NORM_DATE_PATTERN));
				addParam.setPolicyEnd(LocalDateUtil.getDateSrt(insurancePre.getPolicyEnd(), LocalDateUtil.NORM_DATE_PATTERN));
				addParam.setBuyStandard(insurancePre.getBuyStandard());
				addParam.setInsuranceProvinceName(insurancePre.getInsuranceProvinceName());
				addParam.setInsuranceCityName(insurancePre.getInsuranceCityName());
				addParam.setSettleMonth(CommonConstants.EMPTY_STRING);
				addParam.setPost(insurancePre.getPost());
				addParam.setRemark(CommonConstants.EMPTY_STRING);
				addParam.setInsurancePreRenewId(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.getEmpName());
				addParam.setEmpIdcardNo(insurancePre.getEmpIdcardNo());
				addParam.setDeptNo(insurancePre.getDeptNo());
				addParam.setInsuranceCompanyName(insurancePre.getInsuranceCompanyName());
				addParam.setInsuranceTypeName(insurancePre.getInsuranceTypeName());
				addParam.setPolicyNo(insurancePre.getPolicyNo());
				addParam.setBuyStandard(insurancePre.getBuyStandard());
				addParam.setInsuranceProvinceName(insurancePre.getInsuranceProvinceName());
				addParam.setInsuranceCityName(insurancePre.getInsuranceCityName());
				addParam.setSettleMonth(CommonConstants.EMPTY_STRING);
				addParam.setPost(insurancePre.getPost());
				addParam.setRemark(CommonConstants.EMPTY_STRING);
				addParam.setInsurancePreRenewId(insurancePre.getId());
				addParam.setCustomerUserName(insurancePre.getCustomerUsername());
				addParam.setPolicyStart(insurancePre.getPolicyStart());
				addParam.setPolicyEnd(insurancePre.getPolicyEnd());
				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(LocalDateUtil.getDateSrt(insurancePre.getPolicyStart(), LocalDateUtil.NORM_DATE_PATTERN));
				addParam.setPolicyEnd(LocalDateUtil.getDateSrt(insurancePre.getPolicyEnd(), LocalDateUtil.NORM_DATE_PATTERN));
				addParam.setPost(insurancePre.getPost());
				addParam.setReplaceEmpName(insurancePre.getEmpName());
				addParam.setReplaceDeptNo(insurancePre.getDeptNo());
				addParam.setReplaceEmpIdcardNo(insurancePre.getEmpIdcardNo());
				addParam.setRemark(CommonConstants.EMPTY_STRING);
				addParam.setInsurancePreRenewId(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 = this.getInsuranceAutoParamList(paramList, batchParamList, replaceParamList);

		if (autoAddParamList.isEmpty()) {
			/*LambdaUpdateWrapper<TInsurancePreRenewDetail> updateWrapper = new LambdaUpdateWrapper<>();
			updateWrapper.in(TInsurancePreRenewDetail::getId, pushIdList)
					.set(TInsurancePreRenewDetail::getProcessStatus, CommonConstants.THREE_STRING);
			this.update(updateWrapper);*/
		} else {
			// 将 autoAddParamList 中的id等信息提取出来，放入一个 Set 中
			Set<String> autoAddParamSet = new HashSet<>();

			Map<String, String> errorMessageMap = new HashMap<>();
			for (InsuranceAutoParam info : autoAddParamList) {
				autoAddParamSet.add(info.getInsurancePreRenewId());
				errorMessageMap.put(info.getInsurancePreRenewId(), info.getErrorMessage());
			}

			Map<String, Integer> allNumMap = new HashMap<>();
			Map<String, Integer> failNumMap = new HashMap<>();
			Map<String, TInsurancePreRenewDetailQw> preQwMap = new HashMap<>();

			List<TInsurancePreRenewDetail> updateList = new ArrayList<>();
			TInsurancePreRenewDetail updatePre;
			LocalDateTime now = LocalDateTime.now();
			String errorrMessage;
			Integer nums;
			String customerUserLoginname;

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

			for (TInsurancePreRenewDetail pre : insurancePreList) {
				customerUserLoginname = pre.getCustomerUserLoginname();
				updatePre = new TInsurancePreRenewDetail();
				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 TInsurancePreRenewDetailQw();
							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);
						// 派单失败，组装需要推送企微的明细
						qwDetail = new TInsurancePreRenewDetailQwDetail();
						qwDetail.setPreId(pre.getId());
						qwDetail.setMainId(qwUuId);
						qwDetail.setEmpName(pre.getEmpName());
						qwDetail.setEmpIdcard(pre.getEmpIdcardNo());
						qwDetail.setErrorInfo(errorrMessage);
						qwDetail.setErrorTime(now);
						qwDetalList.add(qwDetail);
					}
					updatePre.setProcessStatus(CommonConstants.TWO_STRING);
					updatePre.setErrorTime(now);

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

				} else {
					// 派单成功的
					/*updatePre.setProcessStatus(CommonConstants.THREE_STRING);
					updateList.add(updatePre);*/
				}
			}
			if (!updateList.isEmpty()) {
				this.updateBatchById(updateList);
			}
			// pushQiWeiFlag 推送企微的flag，true表示推送企微
			if (pushQiWeiFlag && !preQwMap.isEmpty()) {
				List<TInsurancePreRenewDetailQw> qwList = new ArrayList<>();
				int allNum;
				int failNum;
				StringBuilder description;
				String userLoginNames = null;
				for (Map.Entry<String, TInsurancePreRenewDetailQw> entry : preQwMap.entrySet()) {
					customerUserLoginname = entry.getKey();
					if (Common.isNotNull(userLoginNames)) {
						userLoginNames += "," + customerUserLoginname;
					} else {
						userLoginNames = customerUserLoginname;
					}
					qw = entry.getValue();
					allNum = allNumMap.get(customerUserLoginname);
					if (Common.isEmpty(allNum)) {
						allNum = 0;
					}
					failNum = failNumMap.get(customerUserLoginname);
					if (Common.isEmpty(failNum)) {
						failNum = 0;
					}
					description = new StringBuilder("商险派单数：").append(allNum).append("份，【失败份数：").append(failNum)
							.append("份】<br>点击查看详情！<br>请及时至HRO系统处理，以免耽误购买进度！");
					qw.setDescription(description.toString());
					qwList.add(qw);
				}
				if (!qwDetalList.isEmpty() && !qwList.isEmpty()) {
					tInsurancePreRenewDetailQwDetailService.saveBatch(qwDetalList);
					tInsurancePreRenewDetailQwService.saveBatch(qwList);
					if (Common.isNotNull(userLoginNames)) {
						Map<String, String> sysUserMap = getUserQiWeiInfo(userLoginNames);
						String qwInfo;
						if (!sysUserMap.isEmpty()) {
							for (TInsurancePreRenewDetailQw sendQw : qwList) {
								qwInfo = sysUserMap.get(sendQw.getCustomerUserLoginname());
								if (Common.isNotNull(qwInfo)) {
									sendMessageToWx(qwInfo, sendQw.getDescription(), sendQw.getId());
								}
							}
						}
					}
				}
			}
		}
		return R.ok(autoAddParamList);
	}

	private 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.setInsurancePreRenewId(addParam.getInsurancePreRenewId());
		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.setInsurancePreRenewId(batchParam.getInsurancePreRenewId());
		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.setInsurancePreRenewId(replaceParam.getInsurancePreRenewId());
		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(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", "76" + 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
	public void updateInsurancePreRenewToIsLeave(BaseSearchVO paramVo) {
		baseMapper.updateInsurancePreRenewToIsLeave(paramVo.getEmpIdCard(), paramVo.getDeptNo());
	}

	// 离职待办确认后，更新为商险续签待办为已离职
	@Override
	public void updateInsurancePreRenewToIsLeaveList(BaseSearchListVO paramVoList) {
		if (paramVoList != null && !paramVoList.getListParam().isEmpty()) {
			for (BaseSearchVO paramVo : paramVoList.getListParam()) {
				baseMapper.updateInsurancePreRenewToIsLeave(paramVo.getEmpIdCard(), paramVo.getDeptNo());
			}
		}
	}

}
