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

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
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.check.entity.TCheckMobile;
import com.yifu.cloud.plus.v1.csp.vo.EmployeeRegistrationUpdateVo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.*;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.*;
import com.yifu.cloud.plus.v1.yifu.archives.service.*;
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.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.util.alisms.AliSmsResult;
import com.yifu.cloud.plus.v1.yifu.common.core.util.alisms.RegistParamVo;
import com.yifu.cloud.plus.v1.yifu.common.core.util.alisms.YiFuSmsUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprCheckProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprInsurancesProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.*;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.TEmployeeInsurancePre;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.TInsuranceDetail;
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.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
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-12 17:14:19
 */
@Log4j2
@Service
@RequiredArgsConstructor
@EnableConfigurationProperties({DaprInsurancesProperties.class, DaprCheckProperties.class})
public class EmployeeRegistrationPreServiceImpl extends ServiceImpl<EmployeeRegistrationPreMapper, EmployeeRegistrationPre> implements EmployeeRegistrationPreService {

	private final DaprInsurancesProperties daprInsurancesProperties;

	@Autowired
	private InsuranceDaprUtil insuranceDaprUtil;

	@Autowired
	private CspDaprUtils cspDaprUtils;

	@Autowired
	private SocialDaprUtils socialDaprUtils;

	@Autowired
	private OSSUtil ossUtil;

	@Autowired
	private DaprCheckProperties daprCheckProperties;

	private final TEmployeePreLogService tEmployeePreLogService;

	private final TCompleteMonitorMapper completeMonitorMapper;

	private final TSettleDomainService tSettleDomainService;

	private final TPreEmpMainMapper empMainMapper;

	private final TRegisteWarningEmployeeService employeeService;

	private final TEmployeeInfoMapper employeeInfoMapper;

	private final MenuUtil menuUtil;

	private final TAttaInfoService attaInfoService;

	private final TEmployeeContractInfoMapper contractInfoMapper;

	private final TEmployeeContractPreMapper contractPreMapper;

	private final TGzOfferInfoMapper gzOfferInfoMapper;

	@Autowired
	@Lazy
	private ScheduleService scheduleService;

	@Autowired
	SysConfigMapper sysConfigMapper;

    /**
     * 入职待建档表简单分页查询
     * @param employeeRegistrationPre 入职待建档表
     * @return
     */
    @Override
    public IPage<EmployeeRegistrationPre> getEmployeeRegistrationPrePage(Page<EmployeeRegistrationPre> page, EmployeeRegistrationPreSearchVo employeeRegistrationPre){
		//权限赋值
		initSearchVo(employeeRegistrationPre);
		if (Common.isEmpty(employeeRegistrationPre.getStatusList())
				&& !CommonConstants.THREE_STRING.equals(employeeRegistrationPre.getType())) {
			employeeRegistrationPre.setStatusList(CommonConstants.processPreArchivesStatus);
		}
		return baseMapper.getEmployeeRegistrationPrePage(page, employeeRegistrationPre);
	}

	/**
	 * 入职待建档表批量导出
	 *
	 * @param searchVo 入职待建档表
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, EmployeeRegistrationPreSearchVo searchVo) {
		String fileName = "入职待建档表批量导出" + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<EmployeeRegistrationPreExportVo> list = new ArrayList<>();
		//权限赋值
		initSearchVo(searchVo);
		if (Common.isEmpty(searchVo.getStatusList())
				&& !CommonConstants.THREE_STRING.equals(searchVo.getType())) {
			searchVo.setStatusList(CommonConstants.processPreArchivesStatus);
		}
		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，然后文件流会自动关闭
			ExcelUtil<EmployeeRegistrationPreExportVo> util = new ExcelUtil<>(EmployeeRegistrationPreExportVo.class);
			// 获取所有字典type
			Map<String, String> nameAndDicTypeMap = util.getConverterDicType();
			// 获取所有字典对应的值
			Map<String, String> redisLabelMap = (Map<String, String>) RedisUtil.redis.opsForValue().get(CacheConstants.REDIS_DICT_LABLE);
			Set<String> exportFields = new HashSet<>(Arrays.asList("deptName", "deptNo", "employeeName", "empIdcard",
					"empPhone", "joinLeaveDate", "empNature", "contractType", "dataSource", "customerUsernameNew", "expectedCollectionTime", "processStatus"));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, EmployeeRegistrationPreExportVo.class)
					.registerConverter(new DictConverter(nameAndDicTypeMap, redisLabelMap))
					.includeColumnFieldNames(exportFields).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);
		}
	}

	/**
	 * 入职确认信息批量导出
	 *
	 * @param searchVo 入职待建档表
	 * @return
	 */
	@Override
	public void confirmExport(HttpServletResponse response, EmployeeRegistrationPreSearchVo searchVo) {
		String fileName = "入职确认信息批量导出" + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<EmployeeRegistrationPreInfoExportVo> list = new ArrayList<>();
		//权限赋值
		initSearchVo(searchVo);
		if (Common.isEmpty(searchVo.getStatusList())
				&& !CommonConstants.THREE_STRING.equals(searchVo.getType())) {
			searchVo.setStatusList(CommonConstants.processPreArchivesStatus);
		}
		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，然后文件流会自动关闭
			ExcelUtil<EmployeeRegistrationPreInfoExportVo> util = new ExcelUtil<>(EmployeeRegistrationPreInfoExportVo.class);
			// 获取所有字典type
			Map<String, String> nameAndDicTypeMap = util.getConverterDicType();
			// 获取所有字典对应的值
			Map<String, String> redisLabelMap = (Map<String, String>) RedisUtil.redis.opsForValue().get(CacheConstants.REDIS_DICT_LABLE);
			Set<String> exportFields = new HashSet<>(Arrays.asList("deptName", "deptNo", "employeeName", "empIdcard",
					"empPhone", "position", "joinLeaveDate", "confirmUser", "confirmTime", "serverItem", "empNature",
					"contractType", "fileAdress"));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, EmployeeRegistrationPreInfoExportVo.class)
					.registerConverter(new DictConverter(nameAndDicTypeMap, redisLabelMap))
					.includeColumnFieldNames(exportFields).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.selectConfirmExportList(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 updateRegistById(EmployeeRegistrationPre employeeRegistrationPre) {
		EmployeeRegistrationPre updatePre = baseMapper.selectById(employeeRegistrationPre.getId());
		if (Common.isEmpty(updatePre) || (updatePre.getProcessStatus().equals(CommonConstants.THREE_STRING)
				|| updatePre.getProcessStatus().equals(CommonConstants.FOUR_STRING))) {
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		YifuUser user = SecurityUtils.getUser();
		employeeRegistrationPre.setProcessStatus(CommonConstants.THREE_STRING);
		baseMapper.updateById(employeeRegistrationPre);
		//新增操作记录
		EmployeeRegistrationUpdateVo receiveVo = new EmployeeRegistrationUpdateVo();
		receiveVo.setEmployeeName(user.getNickname());
		receiveVo.setDeptNo(updatePre.getDeptNo());
		receiveVo.setEmpIdcard(updatePre.getEmpIdcard());
		receiveVo.setReason(employeeRegistrationPre.getReason());
		receiveVo.setEmployeeId(user.getId());
		try {
			//调用csp服务更新状态和新增操作记录
			cspDaprUtils.updateRegistByPreInfo(receiveVo);
		} catch (Exception e) {
			log.error("调用csp服务更新数据异常", e);
		}
		return R.ok();
	}

	@Override
	@Transactional
	public String saveRegistPreInfo(EmployeeRegistrationPreVo preVo) {
		//判断是否存在入职确认信息
		EmployeeRegistrationPre preExit = baseMapper.selectOne(Wrappers.<EmployeeRegistrationPre>query().lambda()
				.eq(EmployeeRegistrationPre::getEmpIdcard, preVo.getEmpIdcard())
				.eq(EmployeeRegistrationPre::getDeptNo, preVo.getDeptNo())
				.last(CommonConstants.LAST_ONE_SQL));
		EmployeeRegistrationPre pre = new EmployeeRegistrationPre();
		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);
			// 创建更新条件构造器
			LambdaUpdateWrapper<TAttaInfo> updateWrapper = new LambdaUpdateWrapper<>();
			// 设置更新条件和新值
			updateWrapper.eq(TAttaInfo::getDomainId, pre.getId())
					.set(TAttaInfo::getDomainId, CommonConstants.EMPTY_STRING);
			// 执行更新操作，清空附件的关联ID
			attaInfoService.update(updateWrapper);
			//清空合同待签订数据
			if (preVo.getServerItem().contains("合同") && null != preVo.getEmployeeContractPreVos() &&
					Common.isNotNull(preVo.getEmployeeContractPreVos().getContractFlag()) &&
					CommonConstants.ZERO_STRING.equals(preVo.getEmployeeContractPreVos().getContractFlag())) {
				//查询老的合同明细
				TEmployeeContractPre contractOld = contractPreMapper.selectOne(Wrappers.<TEmployeeContractPre>query().lambda()
						.eq(TEmployeeContractPre::getRegisterId, pre.getId())
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isNotNull(contractOld)) {
					// 创建更新条件构造器
					LambdaUpdateWrapper<TAttaInfo> updateWrapperContract = new LambdaUpdateWrapper<>();
					// 设置更新条件和新值
					updateWrapperContract.eq(TAttaInfo::getDomainId, contractOld.getId())
							.set(TAttaInfo::getDomainId, CommonConstants.EMPTY_STRING);
					// 执行更新操作，清空附件的关联ID
					attaInfoService.update(updateWrapperContract);
					contractPreMapper.deleteById(contractOld);
				}
			}
		}
		baseMapper.insert(pre);
		//附件赋值
		if (Common.isNotNull(preVo.getAttaList())) {
			for (TAttaInfoSaveVo attaInfoVo : preVo.getAttaList()) {
				TAttaInfo attaInfo = new TAttaInfo();
				BeanUtils.copyProperties(attaInfoVo, attaInfo);
				attaInfo.setDomainId(pre.getId());
				attaInfo.setCreateName("确认接收同步");
				attaInfoService.save(attaInfo);
			}
		}

		Map<String, TEmployeeInsurancePre> oldMap = new HashMap<>();
		if (Common.isNotNull(preExit)) {
			if (Common.isNotNull(preVo.getServerItem()) && preVo.getServerItem().contains("商险")) {
				// 查原商险，来对比
				R<EmployeePreLogListVo> sdr = HttpDaprUtil.invokeMethodPost(daprInsurancesProperties.getAppUrl(), daprInsurancesProperties.getAppId()
						, "/temployeeinsurancepre/inner/getListByEmpPreId", preExit.getId(), EmployeePreLogListVo.class, SecurityConstants.FROM_IN);
				List<TEmployeeInsurancePre> oldList = null;
				if (sdr != null && sdr.getData() != null && sdr.getData().getPreList() != null && !sdr.getData().getPreList().isEmpty()) {
					oldList = sdr.getData().getPreList();
				}

				//商险是否购买为否时增加校验
				if (Common.isNotNull(preVo.getInsuranceIsBuy())
						&& preVo.getInsuranceIsBuy().equals(CommonConstants.ZERO_STRING)
						&& !preVo.getExitInsuranceInfoList().isEmpty()) {
					List<TEmployeeInsurancePre> newList = new ArrayList<>();
					if (oldList != null && !oldList.isEmpty()) {
						//如果状态为0待确认,1待派单,2派单失败,5投保退回则清空数据，记录日志
						for (TEmployeeInsurancePre insurancePre : oldList) {
							if (CommonConstants.insuranceAutoProcessStatus.contains(insurancePre.getProcessStatus())) {
								insurancePre.setModelType(CommonConstants.THREE_STRING);
								newList.add(insurancePre);
							}
						}
						pre.setInsurancePreList(newList);
					}
				} else {
					List<TEmployeeInsurancePreVo> newList = preVo.getEmployeeInsurancePreVos();
					String newKey;
					Map<String, String> map = new HashMap<>();
					if (null != newList && !newList.isEmpty()) {
						for (TEmployeeInsurancePreVo preVo1 : newList) {
							newKey = this.getPreFiveKey(preVo1);
							map.put(newKey, "1");
						}
					}
					if (null != oldList && !oldList.isEmpty()) {
						for (TEmployeeInsurancePre oldInsurance : oldList) {
							// 1：判断是否变更 商险待办 的项目
							if (null != map.get(this.getPreOldFiveKey(oldInsurance))) {
								oldInsurance.setModelType(CommonConstants.ONE_STRING);
								oldMap.put(oldInsurance.getId(), oldInsurance);
							}
						}
					}
				}
			}
			String natureItemBefore = null;
			String natureItemAfter = null;
			String contractItemBefore = null;
			String contractItemAfter = null;
			String contractXfBefore = null;
			String contractXfAfter = null;

			if (!preExit.getContractType().equals(pre.getContractType())) {
				Map<String, String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(
						CacheConstants.DICT_DETAILS + CommonConstants.COLON_STRING + "personnel_type");
				for (Map.Entry<String, String> entry : dicObj.entrySet()) {
					if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(preExit.getContractType())) {
						contractItemBefore = entry.getValue();
					}
					if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(pre.getContractType())) {
						contractItemAfter = entry.getValue();
					}
					if (null != contractItemBefore && null != contractItemAfter) {
						break;
					}
				}
			}
			if (!preExit.getEmpNature().equals(pre.getEmpNature())) {
				Map<String, String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(
						CacheConstants.DICT_DETAILS + CommonConstants.COLON_STRING + "emp_natrue");
				for (Map.Entry<String, String> entry : dicObj.entrySet()) {
					if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(preExit.getEmpNature())) {
						natureItemBefore = entry.getValue();
					}
					if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(pre.getEmpNature())) {
						natureItemAfter = entry.getValue();
					}
					if (null != natureItemAfter && null != natureItemBefore) {
						break;
					}
				}
			}
			if (null != preExit.getContractSubName() && null == pre.getContractSubName()) {
				Map<String, String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(
						CacheConstants.DICT_DETAILS + CommonConstants.COLON_STRING + "contract_business_type");
				for (Map.Entry<String, String> entry : dicObj.entrySet()) {
					if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(preExit.getContractSubName())) {
						contractXfBefore = entry.getValue();
						break;
					}
				}
			}
			if (null == preExit.getContractSubName() && null != pre.getContractSubName()) {
				Map<String, String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(
						CacheConstants.DICT_DETAILS + CommonConstants.COLON_STRING + "contract_business_type");
				for (Map.Entry<String, String> entry : dicObj.entrySet()) {
					if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(pre.getContractSubName())) {
						contractXfAfter = entry.getValue();
						break;
					}
				}
			}
			if (null != preExit.getContractSubName() && null != pre.getContractSubName()
					&& !preExit.getContractSubName().equals(pre.getContractSubName())) {
				Map<String, String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(
						CacheConstants.DICT_DETAILS + CommonConstants.COLON_STRING + "contract_business_type");
				for (Map.Entry<String, String> entry : dicObj.entrySet()) {
					if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(preExit.getContractSubName())) {
						contractXfBefore = entry.getValue();
					}
					if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(pre.getContractSubName())) {
						contractXfAfter = entry.getValue();
					}
					if (null != contractXfBefore && null != contractXfAfter) {
						break;
					}
				}
			}
			if (!preExit.getProcessStatus().equals(pre.getProcessStatus())) {
				preExit.setProcessStatus(CommonConstants.THREE_STRING.equals(preExit.getProcessStatus()) ? "拒绝入职" : "已完成");
				pre.setProcessStatus("短信待发放");
			}
			if (null != natureItemBefore) {
				preExit.setEmpNature(natureItemBefore);
			}
			if (null != natureItemAfter) {
				pre.setEmpNature(natureItemAfter);
			}
			if (null != contractItemBefore) {
				preExit.setContractType(contractItemBefore);
			}
			if (null != contractItemAfter) {
				pre.setContractType(contractItemAfter);
			}
			if (null != contractXfBefore) {
				preExit.setContractSubName(contractXfBefore);
			}
			if (null != contractXfAfter) {
				pre.setContractSubName(contractXfAfter);
			}
			//查询老的合同明细
			TEmployeeContractPre contractOld = contractPreMapper.selectOne(Wrappers.<TEmployeeContractPre>query().lambda()
					.eq(TEmployeeContractPre::getRegisterId, pre.getId())
					.last(CommonConstants.LAST_ONE_SQL));
			// 添加日志并修改商险list
			tEmployeePreLogService.saveUpdateInsurance(preExit.getId(), preExit
					, pre, preVo.getCreateBy(), preVo.getCreateName(), oldMap, contractOld);
		}
		if (Common.isNotNull(preVo.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);
					}
				}
			});
		}
		return pre.getId();
	}

	/**
	 * @param employeeRegistrationPre
	 * @Description: 修改入职确认信息
	 * @Author: hgw + hyc
	 * @Date: 2025/4/9 14:45
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R
	 **/
	@Override
	public R updateCommonInfo(EmployeeRegistrationPre employeeRegistrationPre) {
		String id = employeeRegistrationPre.getId();
		if (Common.isEmpty(id)) {
			return R.failed("请传ID");
		}
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user) || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		//旧的对象，用来对比变更参数
		EmployeeRegistrationPre comparePre = baseMapper.selectById(id);
		if (Common.isEmpty(comparePre)) {
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		//1.9.11 huyc 信息修改手机号真实性校验
		if (Common.isNotNull(employeeRegistrationPre.getEmpPhone()) &&
				!employeeRegistrationPre.getEmpPhone().equals(comparePre.getEmpPhone())) {
			//手机号真实性校验
			TCheckMobile checkMobile = new TCheckMobile();
			checkMobile.setMobile(employeeRegistrationPre.getEmpPhone());
			R<TCheckMobile> res = HttpDaprUtil.invokeMethodPost(daprCheckProperties.getAppUrl(), daprCheckProperties.getAppId(), "/tcheckmobile/inner/checkOneMobile", JSON.toJSONString(checkMobile), TCheckMobile.class, SecurityConstants.FROM_IN);
			if (Common.isEmpty(res) || Common.isEmpty(res.getData())) {
				return R.failed("校验手机号码信息失败！");
			}
			TCheckMobile cm = res.getData();
			if (Common.isEmpty(cm.getStatus()) || !CommonConstants.ONE_STRING.equals(cm.getStatus())) {
				return R.failed(cm.getMessage());
			}
		}

		// 创建更新条件构造器
		LambdaUpdateWrapper<TAttaInfo> updateWrapper = new LambdaUpdateWrapper<>();
		// 设置更新条件和新值
		updateWrapper.eq(TAttaInfo::getDomainId, employeeRegistrationPre.getId())
				.set(TAttaInfo::getDomainId, CommonConstants.EMPTY_STRING);
		// 执行更新操作，清空附件的域名ID
		attaInfoService.update(updateWrapper);
		// 检查附件ID列表是否不为空、更新附件
		if (Common.isNotNull(employeeRegistrationPre.getAttaIdList())) {
			// 遍历员工注册记录中的附件ID列表
			TAttaInfo atta;
			for (String attaId : employeeRegistrationPre.getAttaIdList()) {
				// 根据ID获取附件信息
				atta = attaInfoService.getById(attaId);
				// 更新附件的域名ID为当前员工的注册ID
				atta.setDomainId(employeeRegistrationPre.getId());
				// 保存更新后的附件信息
				attaInfoService.updateById(atta);
			}
		}

		Map<String, TEmployeeInsurancePre> oldMap = new HashMap<>();
		// 查原商险，来对比
		R<EmployeePreLogListVo> sdr = HttpDaprUtil.invokeMethodPost(daprInsurancesProperties.getAppUrl(), daprInsurancesProperties.getAppId()
				, "/temployeeinsurancepre/inner/getListByEmpPreId", id, EmployeePreLogListVo.class, SecurityConstants.FROM_IN);
		List<TEmployeeInsurancePre> oldList = null;
		if (sdr != null && sdr.getData() != null && sdr.getData().getPreList() != null && !sdr.getData().getPreList().isEmpty()) {
			oldList = sdr.getData().getPreList();
		}

		// 1：存在商险，判断合规性+日期+五个不同等：
		if (Common.isNotNull(employeeRegistrationPre.getServerItem()) && employeeRegistrationPre.getServerItem().contains("商险")) {
			//商险是否购买为是时增加校验
			if (Common.isNotNull(employeeRegistrationPre.getInsuranceIsBuy())
					&& employeeRegistrationPre.getInsuranceIsBuy().equals(CommonConstants.ZERO_STRING)
					&& !employeeRegistrationPre.getExitInsuranceInfoList().isEmpty()) {
				//判断带出的流程中或者已完结的商险数据是否准确
				//商险是否存在判断
				employeeRegistrationPre.getExitInsuranceInfoList().forEach(e -> e.setCreateTime(null));
				boolean isTrue = checkInsuranceIsProcess(employeeRegistrationPre);
				if (isTrue) {
					return R.failed("带出的商险已购买数据状态或条数发生变更，请重新确认！");
				}
				List<TEmployeeInsurancePre> newList = new ArrayList<>();
				if (oldList != null && !oldList.isEmpty()) {
					//如果状态为0待确认,1待派单,2派单失败,5投保退回则清空数据，记录日志
					for (TEmployeeInsurancePre insurancePre : oldList) {
						if (CommonConstants.insuranceAutoProcessStatus.contains(insurancePre.getProcessStatus())) {
							insurancePre.setModelType(CommonConstants.THREE_STRING);
							newList.add(insurancePre);
						}
					}
					employeeRegistrationPre.setInsurancePreList(newList);
				}
			} else if (employeeRegistrationPre.getInsuranceIsBuy().equals(CommonConstants.ONE_STRING)) {
				if (employeeRegistrationPre.getInsurancePreList() == null
						|| employeeRegistrationPre.getInsurancePreList().isEmpty()) {
					return R.failed("含商险服务，商险配置不可为空");
				}
				List<TEmployeeInsurancePre> newList = employeeRegistrationPre.getInsurancePreList();
				// 1：合规性：查找信息是否允许：
				List<TEmployeeInsuranceExitCheckVo> errorList = new ArrayList<>();
				TEmployeeInsuranceExitCheckVo checkVo;
				Map<String, TEmployeeInsurancePre> newMap = new HashMap<>();
				// 新的KeyMap，存项目
				Map<String, String> newKeyDeptNoMap = new HashMap<>();
				// 判断重复性MAP
				Map<String, Integer> keyMap = new HashMap<>();
				String key;
				String newDeptNo;
				TEmployeeInsurancePreVo preVo;
				for (TEmployeeInsurancePre insurancePreVo : newList) {
					if (Common.isNotNull(insurancePreVo.getId())) {
						newMap.put(insurancePreVo.getId(), insurancePreVo);
					}
					// 初始化信息
					initInsurancePreInfo(employeeRegistrationPre, insurancePreVo, user, id);
					// 1：重复性判断
					key = this.getFiveKey(insurancePreVo);
					newDeptNo = insurancePreVo.getDeptNo();
					if (Common.isEmpty(newDeptNo)) {
						return R.failed("请传项目编码");
					}
					newKeyDeptNoMap.put(key, insurancePreVo.getDeptNo());
					if (keyMap.get(key) == null) {
						if (Common.isEmpty(insurancePreVo.getModelType()) || !insurancePreVo.getModelType().equals(CommonConstants.THREE_STRING)) {
							keyMap.put(key, CommonConstants.ONE_INT);
						}
					} else if (Common.isEmpty(insurancePreVo.getModelType()) || !insurancePreVo.getModelType().equals(CommonConstants.THREE_STRING)) {
						return R.failed("保险公司、险种、购买标准、保单起、止日期不可同时重复！");
					}

					insurancePreVo.setEmpIdcard(employeeRegistrationPre.getEmpIdcard());
					insurancePreVo.setDeptNo(employeeRegistrationPre.getDeptNo());
					//商险是否存在判断
					preVo = new TEmployeeInsurancePreVo();
					preVo.setEmployeeName(employeeRegistrationPre.getEmployeeName());
					preVo.setEmpIdcard(employeeRegistrationPre.getEmpIdcard());
					preVo.setBuyStandard(insurancePreVo.getBuyStandard());
					preVo.setBuyType(insurancePreVo.getBuyType());
					preVo.setDeptNo(insurancePreVo.getDeptNo());
					preVo.setInsuranceTypeName(insurancePreVo.getInsuranceTypeName());
					preVo.setInsuranceCompanyName(insurancePreVo.getInsuranceCompanyName());
					preVo.setPolicyStart(insurancePreVo.getPolicyStart());
					preVo.setPolicyEnd(insurancePreVo.getPolicyEnd());
					if (Common.isEmpty(insurancePreVo.getModelType())
							|| !CommonConstants.FOUR_STRING.equals(insurancePreVo.getModelType())) {
						checkVo = checkInsuranceExit(preVo);
						if (null != checkVo) {
							errorList.add(checkVo);
						} else {
							if (Common.isNotNull(preVo.getProcessStatus())) {
								insurancePreVo.setProcessStatus(preVo.getProcessStatus());
							} else {
								insurancePreVo.setProcessStatus(CommonConstants.ZERO_STRING);
							}
							if (Common.isNotNull(preVo.getIsAddress())) {
								insurancePreVo.setIsAddress(preVo.getIsAddress());
							}
							if (Common.isNotNull(preVo.getInsurancesId())) {
								insurancePreVo.setInsurancesId(preVo.getInsurancesId());
							}
						}
					}
				}
				if (!errorList.isEmpty()) {
					return R.other(CommonConstants.TWO_INT, null, errorList);
				}

				// 2：商险待办 的判断：
				if (oldList != null && !oldList.isEmpty()) {
					TEmployeeInsurancePre newPre;
					String oldKey;
					for (TEmployeeInsurancePre oldInsurance : oldList) {
						// 1：判断是否变更 商险待办 的项目
						oldKey = this.getFiveKey(oldInsurance);
						newDeptNo = newKeyDeptNoMap.get(oldKey);
						// 不同项目，在途（待确认、待派单、派单失败），要拦截
						if (Common.isNotNull(newDeptNo) && !newDeptNo.equals(oldInsurance.getDeptNo())
								&& !Common.isNotNull(oldInsurance.getProcessStatus())
								&& (CommonConstants.ZERO_STRING.equals(oldInsurance.getProcessStatus())
								|| CommonConstants.ONE_STRING.equals(oldInsurance.getProcessStatus())
								|| CommonConstants.TWO_STRING.equals(oldInsurance.getProcessStatus()))) {
							return R.failed("不可变更项目，请检查商险配置！");
						}
						oldMap.put(oldInsurance.getId(), oldInsurance);
						newPre = newMap.get(oldInsurance.getId());
						// 是否为不可修改的状态
						if (Common.isNotNull(oldInsurance.getProcessStatus())
								&& (CommonConstants.THREE_STRING.equals(oldInsurance.getProcessStatus())
								|| CommonConstants.FOUR_STRING.equals(oldInsurance.getProcessStatus())
								|| CommonConstants.SIX_STRING.equals(oldInsurance.getProcessStatus()))) {
							if (newPre == null) {
								return R.failed("含有不可删除的商险，请刷新后再修改！");
							} else if (Common.isNotNull(newPre.getModelType()) && !CommonConstants.FOUR_STRING.equals(newPre.getModelType())) {
								return R.failed("含有不可更改的商险，请刷新后再修改！");
							}
						} else {
							if (newPre == null) {
								oldInsurance.setModelType(CommonConstants.THREE_STRING);
								newList.add(oldInsurance);
							}
						}
					}
					employeeRegistrationPre.setInsurancePreList(newList);
				}
			}
		} else {
			employeeRegistrationPre.setInsuranceIsBuy("");
			// 2:保存时不存在商险类型，判断是否有不可删除的数据，有则拒绝：
			if (oldList != null && !oldList.isEmpty()) {
				for (TEmployeeInsurancePre oldInsurance : oldList) {
					if (Common.isNotNull(oldInsurance.getProcessStatus())
							&& (CommonConstants.THREE_STRING.equals(oldInsurance.getProcessStatus())
							|| CommonConstants.FOUR_STRING.equals(oldInsurance.getProcessStatus())
							|| CommonConstants.SIX_STRING.equals(oldInsurance.getProcessStatus()))) {
						return R.failed("含有不可删除的商险，请刷新后再修改！");
					}
				}
			}
		}

		//查询老的合同明细
		TEmployeeContractPre contractOld = contractPreMapper.selectOne(Wrappers.<TEmployeeContractPre>query().lambda()
				.eq(TEmployeeContractPre::getRegisterId, employeeRegistrationPre.getId())
				.last(CommonConstants.LAST_ONE_SQL));
		//1.9.12合同自动化校验逻辑
		//根据身份证号码和项目编号查询合同
		boolean flag = contractInfoMapper.selectCount(Wrappers.<TEmployeeContractInfo>query().lambda()
				.eq(TEmployeeContractInfo::getEmpIdcard, employeeRegistrationPre.getEmpIdcard())
				.eq(TEmployeeContractInfo::getDeptNo, employeeRegistrationPre.getDeptNo())
				.and(obj -> obj.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.ONE_INT)
						.or()
						.eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.TWO_INT)
						.eq(TEmployeeContractInfo::getInUse, CommonConstants.ZERO_STRING)
				)
				.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_INT)
				.last(CommonConstants.LAST_ONE_SQL)) > 0;
		if (employeeRegistrationPre.getServerItem().contains("合同") && Common.isEmpty(employeeRegistrationPre.getEmployeeContractPre()) && !flag) {
			return R.failed("未找到流程中或者在用的合同！");
		}
		if (employeeRegistrationPre.getServerItem().contains("合同") && null != employeeRegistrationPre.getEmployeeContractPre()) {
			TEmployeeContractPre employeeContractPreVo = employeeRegistrationPre.getEmployeeContractPre();
			if (Common.isNotNull(employeeContractPreVo.getId())) {
				TEmployeeContractPre contractStatus = contractPreMapper.selectById(employeeContractPreVo.getId());
				//待确认/待发起/发起失败/线下签待审核/线下签审核不通过/线下签待归档 不能编辑
				if (Common.isNotNull(contractStatus) && (CommonConstants.NINE_STRING.equals(contractStatus.getProcessStatus())
						|| CommonConstants.TWO_STRING.equals(contractStatus.getProcessStatus())
						|| CommonConstants.SIX_STRING.equals(contractStatus.getProcessStatus())
						|| CommonConstants.FOUR_STRING.equals(contractStatus.getProcessStatus())
						|| CommonConstants.EIGHT_STRING.equals(contractStatus.getProcessStatus()))
				) {
					return R.failed("流程中的合同待签订数据不可修改！");
				}
			}
			//是否已签署为否需要判断是否在用或者流程中的合同
			if ((CommonConstants.ONE_STRING.equals(employeeContractPreVo.getContractFlag()) || Common.isEmpty(employeeContractPreVo.getContractFlag())) && flag) {
				return R.failed("该人员已存在审核中或已签署的合同，请勿重复发起签署！");
			}
			if (CommonConstants.ONE_STRING.equals(employeeContractPreVo.getContractFlag()) || Common.isEmpty(employeeContractPreVo.getContractFlag())) {
				initContractPreInfo(employeeRegistrationPre, employeeContractPreVo, user, id);
				employeeRegistrationPre.setEmployeeContractPre(employeeContractPreVo);
			} else {
				employeeRegistrationPre.setEmployeeContractPre(null);
			}
		}

		//1.9.16社保自动化校验逻辑
		if (employeeRegistrationPre.getServerItem().contains("社保")) {
			//根据身份证号码和项目编号查询合同
			TEmployeeAutoRegistCheckVo cardVo = new TEmployeeAutoRegistCheckVo();
			cardVo.setEmpIdcard(employeeRegistrationPre.getEmpIdcard());
			R<Boolean> socialFlag = socialDaprUtils.selectExitEmpSocial(cardVo);
			//是否已签署为是需要判断合同是否在用或者流程中
			if (CommonConstants.ZERO_STRING.equals(employeeRegistrationPre.getSocialIsBuy()) &&
					(Common.isEmpty(socialFlag) || Boolean.TRUE.equals(!socialFlag.getData()))) {
				return R.other(CommonConstants.TWO_INT, null, "未找到流程中或者在用的社保信息！");
			}
			//是否已签署为否需要判断是否在用或者流程中的合同
			if (CommonConstants.ONE_STRING.equals(employeeRegistrationPre.getSocialIsBuy()) &&
					Common.isNotNull(socialFlag) && Boolean.TRUE.equals(socialFlag.getData()) &&
					null != employeeRegistrationPre.getDispatchInfoPreVo() &&
					Common.isEmpty(employeeRegistrationPre.getDispatchInfoPreVo().getId())) {
				return R.other(CommonConstants.TWO_INT, null, "该人员存在在途/有效的社保数据，请将“是否已参保”调整为“是”");
			}
			//流程中的社保数据不能修改
			//查已购买社保明细
			if (null != employeeRegistrationPre.getDispatchInfoPreVo() &&
					Common.isEmpty(employeeRegistrationPre.getDispatchInfoPreVo().getId())) {
				R<EmployeePreSocialListVo> socialSdr = socialDaprUtils.getSocialPreInfoStatus(id);
				if (socialSdr != null && socialSdr.getData() != null
						&& null != socialSdr.getData().getDispatchInfoPreVo()
						&& (socialSdr.getData().getDispatchInfoPreVo().getProcessStatus().equals(CommonConstants.THREE_STRING) ||
						socialSdr.getData().getDispatchInfoPreVo().getProcessStatus().equals(CommonConstants.FIVE_STRING) ||
						socialSdr.getData().getDispatchInfoPreVo().getProcessStatus().equals(CommonConstants.SIX_STRING) ||
						socialSdr.getData().getDispatchInfoPreVo().getProcessStatus().equals(CommonConstants.SEVEN_STRING) ||
						socialSdr.getData().getDispatchInfoPreVo().getProcessStatus().equals(CommonConstants.NINE_STRING))) {
					return R.failed("流程中的社保待购买数据不可修改！");
				}
			}
			//更新合同签署状态
			if (null != employeeRegistrationPre.getDispatchInfoPreVo()) {
				employeeRegistrationPre.getDispatchInfoPreVo().setContractStatus(flag ? CommonConstants.ZERO_STRING : CommonConstants.ONE_STRING);
			}
		}

		//操作记录中字典值的转化
		String natureItemBefore = null;
		String natureItemAfter = null;
		String contractItemBefore = null;
		String contractItemAfter = null;
		String contractXfBefore = null;
		String contractXfAfter = null;
		if (!comparePre.getContractType().equals(employeeRegistrationPre.getContractType())) {
			Map<String, String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(
					CacheConstants.DICT_DETAILS + CommonConstants.COLON_STRING + "personnel_type");
			for (Map.Entry<String, String> entry : dicObj.entrySet()) {
				if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(comparePre.getContractType())) {
					contractItemBefore = entry.getValue();
				}
				if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(employeeRegistrationPre.getContractType())) {
					contractItemAfter = entry.getValue();
				}
				if (null != contractItemBefore && null != contractItemAfter) {
					break;
				}
			}
		}
		if (!comparePre.getEmpNature().equals(employeeRegistrationPre.getEmpNature())) {
			Map<String, String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(
					CacheConstants.DICT_DETAILS + CommonConstants.COLON_STRING + "emp_natrue");
			for (Map.Entry<String, String> entry : dicObj.entrySet()) {
				if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(comparePre.getEmpNature())) {
					natureItemBefore = entry.getValue();
				}
				if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(employeeRegistrationPre.getEmpNature())) {
					natureItemAfter = entry.getValue();
				}
				if (null != natureItemAfter && null != natureItemBefore) {
					break;
				}
			}
		}
		if (null != comparePre.getContractSubName() && null == employeeRegistrationPre.getContractSubName()) {
			Map<String, String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(
					CacheConstants.DICT_DETAILS + CommonConstants.COLON_STRING + "contract_business_type");
			for (Map.Entry<String, String> entry : dicObj.entrySet()) {
				if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(comparePre.getContractSubName())) {
					contractXfBefore = entry.getValue();
					break;
				}
			}
		}
		if (null == comparePre.getContractSubName() && null != employeeRegistrationPre.getContractSubName()) {
			Map<String, String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(
					CacheConstants.DICT_DETAILS + CommonConstants.COLON_STRING + "contract_business_type");
			for (Map.Entry<String, String> entry : dicObj.entrySet()) {
				if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(employeeRegistrationPre.getContractSubName())) {
					contractXfAfter = entry.getValue();
					break;
				}
			}
		}
		if (null != comparePre.getContractSubName() && null != employeeRegistrationPre.getContractSubName()
				&& !comparePre.getContractSubName().equals(employeeRegistrationPre.getContractSubName())) {
			Map<String, String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(
					CacheConstants.DICT_DETAILS + CommonConstants.COLON_STRING + "contract_business_type");
			for (Map.Entry<String, String> entry : dicObj.entrySet()) {
				if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(comparePre.getContractSubName())) {
					contractXfBefore = entry.getValue();
				}
				if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(employeeRegistrationPre.getContractSubName())) {
					contractXfAfter = entry.getValue();
				}
				if (null != contractXfBefore && null != contractXfAfter) {
					break;
				}
			}
		}
		try {
			baseMapper.updateById(employeeRegistrationPre);
			if (null != natureItemBefore) {
				comparePre.setEmpNature(natureItemBefore);
			}
			if (null != natureItemAfter) {
				employeeRegistrationPre.setEmpNature(natureItemAfter);
			}
			if (null != contractItemBefore) {
				comparePre.setContractType(contractItemBefore);
			}
			if (null != contractItemAfter) {
				employeeRegistrationPre.setContractType(contractItemAfter);
			}
			if (null != contractXfBefore) {
				comparePre.setContractSubName(contractXfBefore);
			}
			if (null != contractXfAfter) {
				employeeRegistrationPre.setContractSubName(contractXfAfter);
			}
			// 添加日志并修改商险list
			tEmployeePreLogService.saveModifyAndUpdateInsurance(employeeRegistrationPre.getId(), comparePre
					, employeeRegistrationPre, user, oldMap, contractOld);

		} catch (Exception e) {
			log.error("生成入职待确认信息修改操作日志异常", e);
		}
		return R.ok();
	}

	//商险状态是否正常判断
	private boolean checkInsuranceIsProcess(EmployeeRegistrationPre pre) {
		EmployeeRegistrationPreVo preVo = new EmployeeRegistrationPreVo();
		BeanUtils.copyProperties(pre, preVo);
		R<Boolean> flag = insuranceDaprUtil.checkExitInsuanceIsProcess(preVo);
		//是否已签署为是需要判断合同是否在用或者流程中
		return Common.isEmpty(flag) || Boolean.TRUE.equals(!flag.getData());
	}

	private void initInsurancePreInfo(EmployeeRegistrationPre registration, TEmployeeInsurancePre preVo,
									  YifuUser user, String id) {
		preVo.setRegisterId(id);
		preVo.setCustomerUsername(registration.getCustomerUsernameNew());
		preVo.setCustomerUserLoginname(registration.getCustomerUserLoginname());
		preVo.setDeptName(registration.getDeptName());
		preVo.setDeptId(registration.getDeptId());
		preVo.setDataSource(registration.getDataSource());
		preVo.setPosition(registration.getPosition());
		preVo.setJoinLeaveDate(registration.getJoinLeaveDate());
		preVo.setDeptNo(registration.getDeptNo());
		preVo.setEmpPhone(registration.getEmpPhone());
		preVo.setEmployeeName(registration.getEmployeeName());
		preVo.setEmpIdcard(registration.getEmpIdcard());
		preVo.setCreateBy(user.getId());
		preVo.setCreateName(user.getNickname());
		preVo.setUpdateBy(user.getId());
		// 初始化preVo.setExpectedCollectionTime为15:20
		if (preVo.getExpectedCollectionTime() != null) {
			preVo.setExpectedCollectionTime(preVo.getExpectedCollectionTime().withHour(15).withMinute(20));
		}
	}

	/**
	 * 初始化合同
	 */
	private void initContractPreInfo(EmployeeRegistrationPre registration, TEmployeeContractPre employeeContractPreVo,
									 YifuUser user, String id) {
		employeeContractPreVo.setProcessStatus(CommonConstants.ZERO_STRING);
		employeeContractPreVo.setSituation("正常签订");
		// 设置员工注册ID
		employeeContractPreVo.setRegisterId(id);
		// 设置客户用户名
		employeeContractPreVo.setCustomerUsername(registration.getCustomerUsernameNew());
		// 设置客户用户登录名
		employeeContractPreVo.setCustomerUserLoginname(registration.getCustomerUserLoginname());
		// 设置部门名称
		employeeContractPreVo.setDeptName(registration.getDeptName());
		// 设置部门ID
		employeeContractPreVo.setDeptId(registration.getDeptId());
		// 设置数据源
		employeeContractPreVo.setDataSource(registration.getDataSource());
		// 设置职位
		employeeContractPreVo.setPosition(registration.getPosition());
		// 设置入职或离职日期
		employeeContractPreVo.setJoinLeaveDate(registration.getJoinLeaveDate());
		// 设置部门编号
		employeeContractPreVo.setDeptNo(registration.getDeptNo());
		// 设置员工联系电话
		employeeContractPreVo.setEmpPhone(registration.getEmpPhone());
		// 设置员工姓名
		employeeContractPreVo.setEmployeeName(registration.getEmployeeName());
		// 设置员工身份证号
		employeeContractPreVo.setEmpIdcard(registration.getEmpIdcard());
		// 设置创建者ID
		employeeContractPreVo.setCreateBy(user.getId());
		// 设置创建者
		employeeContractPreVo.setCreateName(user.getNickname());
		// 设置更新者ID
		employeeContractPreVo.setUpdateBy(user.getId());
		//是否撤销签署
		employeeContractPreVo.setSignFlag(CommonConstants.ONE_STRING);
		employeeContractPreVo.setRevokeReason(CommonConstants.EMPTY_STRING);
		//实习开始日期、实习结束日期赋值合同开始、截止日期
		if (Common.isNotNull(employeeContractPreVo.getInternshipPeriodStart())) {
			employeeContractPreVo.setContractStart(employeeContractPreVo.getInternshipPeriodStart());
		}
		if (Common.isNotNull(employeeContractPreVo.getInternshipPeriodEnd())) {
			employeeContractPreVo.setContractEnd(employeeContractPreVo.getInternshipPeriodEnd());
		}
		//合同岗位名称
		if (CommonConstants.ONE_STRING.equals(employeeContractPreVo.getPostType())
				&& Common.isEmpty(employeeContractPreVo.getPost())) {
			employeeContractPreVo.setPost(registration.getPosition());
		}
	}

	/**
	 * @param insurancePreVo
	 * @Description: 获取5个字段构成的关键字
	 * @Author: hgw
	 * @Date: 2025/4/9 11:23
	 * @return: java.lang.String
	 **/
	private String getFiveKey(TEmployeeInsurancePre insurancePreVo) {
		// 1：重复性判断
		return isNullToEmpty(insurancePreVo.getBuyStandard()) + CommonConstants.DOWN_LINE_STRING
				+ isNullToEmpty(insurancePreVo.getInsuranceTypeName()) + CommonConstants.DOWN_LINE_STRING
				+ isNullToEmpty(insurancePreVo.getInsuranceCompanyName()) + CommonConstants.DOWN_LINE_STRING
				+ isNullToEmpty(insurancePreVo.getPolicyStart()) + CommonConstants.DOWN_LINE_STRING + isNullToEmpty(insurancePreVo.getPolicyEnd());
	}

	/**
	 * @param insurancePreVo
	 * @Description: 获取5个字段构成的关键字
	 * @Author: hgw
	 * @Date: 2025/4/9 11:23
	 * @return: java.lang.String
	 **/
	private String getPreFiveKey(TEmployeeInsurancePreVo insurancePreVo) {
		// 1：重复性判断
		return isNullToEmpty(insurancePreVo.getBuyStandard()) + CommonConstants.DOWN_LINE_STRING
				+ isNullToEmpty(insurancePreVo.getInsuranceTypeName()) + CommonConstants.DOWN_LINE_STRING
				+ isNullToEmpty(insurancePreVo.getInsuranceCompanyName()) + CommonConstants.DOWN_LINE_STRING
				+ isNullToEmpty(DateUtil.dateToString(insurancePreVo.getPolicyStart(), DateUtil.ISO_EXPANDED_DATE_FORMAT))
				+ DateUtil.dateToString(insurancePreVo.getPolicyEnd(), DateUtil.ISO_EXPANDED_DATE_FORMAT);
	}

	private String getPreOldFiveKey(TEmployeeInsurancePre insurancePreVo) {
		// 1：重复性判断
		return isNullToEmpty(insurancePreVo.getBuyStandard()) + CommonConstants.DOWN_LINE_STRING
				+ isNullToEmpty(insurancePreVo.getInsuranceTypeName()) + CommonConstants.DOWN_LINE_STRING
				+ isNullToEmpty(insurancePreVo.getInsuranceCompanyName()) + CommonConstants.DOWN_LINE_STRING
				+ isNullToEmpty(DateUtil.dateToString(insurancePreVo.getPolicyStart(), DateUtil.ISO_EXPANDED_DATE_FORMAT))
				+ DateUtil.dateToString(insurancePreVo.getPolicyEnd(), DateUtil.ISO_EXPANDED_DATE_FORMAT);
	}

	/**
	 * @param str
	 * @Description: 空转化为空字符
	 * @Author: hgw
	 * @Date: 2025/4/9 11:29
	 * @return: java.lang.String
	 **/
	private String isNullToEmpty(Object str) {
		return null == str ? "" : str.toString();
	}

	@Override
	public R getListCount(EmployeeRegistrationPreSearchVo searchVo) {
		try {
			YifuUser user = SecurityUtils.getUser();
			//入职待建档数量
			menuUtil.setAuthSql(user, searchVo);
			initSearchVo(searchVo);
			searchVo.setStatusList(CommonConstants.processPreArchivesStatus);
			long countTwo = baseMapper.selectExportCount(searchVo);
			//档案待完整数量
			long countThree = completeMonitorMapper.getAllLackArchivesExportCount(searchVo);
			EmployeeRegistrationCountVo countVo = new EmployeeRegistrationCountVo();
			countVo.setTypeTwoCount(countTwo);
			countVo.setTypeThreeCount(countThree);
			return R.ok(countVo);
		} catch (Exception e) {
			log.error("查询数量异常", e);
			return R.failed(CommonConstants.RESULT_DATA_FAIL);
		}
	}

	// 商险是否存在判断 type 1 单个接收 2 批量接收
	private TEmployeeInsuranceExitCheckVo checkInsuranceExit(TEmployeeInsurancePreVo preVo) {
		//查询入职确认信息数据
		TEmployeeInsuranceExitCheckVo exitCheckVo = new TEmployeeInsuranceExitCheckVo();
		boolean erorFlag = false;
		R<TEmployeeInsuranceSelectVo> dataR = insuranceDaprUtil.selectInsurancePreInfoList(preVo);
		//查询商险数据
		TInsuranceDetail insuranceDetail = null;
		R<TEmployeeInsuranceSelectVo> dataInsurR = insuranceDaprUtil.selectInsuranceInfo(preVo);
		if (Common.isNotNull(dataInsurR) && Common.isNotNull(dataInsurR.getData()) && Common.isNotNull(dataInsurR.getData().getInsuranceDetail())) {
			insuranceDetail = dataInsurR.getData().getInsuranceDetail();
		}
		//二次确认接收场景
		if (Common.isNotNull(dataR) && Common.isNotNull(dataR.getData().getInsurancePreList())
				&& !dataR.getData().getInsurancePreList().isEmpty()) {
			//已存在该身份证的商险入职确认信息
			List<TEmployeeInsurancePre> list = dataR.getData().getInsurancePreList();
			for (TEmployeeInsurancePre pre : list) {
				//项目不同
				if (!preVo.getDeptNo().equals(pre.getDeptNo()) && (pre.getProcessStatus().equals(CommonConstants.ZERO_STRING) ||
						pre.getProcessStatus().equals(CommonConstants.ONE_STRING) ||
						pre.getProcessStatus().equals(CommonConstants.TWO_STRING))) {
					erorFlag = true;
					break;
				}
				//项目相同
				if (null != insuranceDetail && preVo.getDeptNo().equals(insuranceDetail.getDeptNo()) &&
						insuranceDetail.getBuyHandleStatus() != CommonConstants.FIVE_INT &&
						insuranceDetail.getBuyHandleStatus() != CommonConstants.FOUR_INT) {
					erorFlag = true;
					break;
				}
				if (null != insuranceDetail && !preVo.getDeptNo().equals(insuranceDetail.getDeptNo())
						&& insuranceDetail.getBuyHandleStatus() != CommonConstants.FIVE_INT) {
					erorFlag = true;
					break;
				}
			}
		} else {
			//第一次确认接收场景
			if (Common.isNotNull(insuranceDetail)) {
				//项目不同
				if (!preVo.getDeptNo().equals(insuranceDetail.getDeptNo()) && (insuranceDetail.getBuyHandleStatus() == CommonConstants.ONE_INT ||
						insuranceDetail.getBuyHandleStatus() == CommonConstants.TWO_INT ||
						insuranceDetail.getBuyHandleStatus() == CommonConstants.THREE_INT)) {
					erorFlag = true;
				}
				//项目相同带回状态
				if (preVo.getDeptNo().equals(insuranceDetail.getDeptNo()) && insuranceDetail.getBuyHandleStatus() != CommonConstants.FIVE_INT) {
					if (insuranceDetail.getBuyHandleStatus() == CommonConstants.ONE_INT) {
						preVo.setProcessStatus(CommonConstants.THREE_STRING);
					} else if (insuranceDetail.getBuyHandleStatus() == CommonConstants.TWO_INT) {
						preVo.setProcessStatus(CommonConstants.FOUR_STRING);
					} else if (insuranceDetail.getBuyHandleStatus() == CommonConstants.THREE_INT) {
						preVo.setProcessStatus(CommonConstants.SIX_STRING);
					} else if (insuranceDetail.getBuyHandleStatus() == CommonConstants.FOUR_INT) {
						preVo.setProcessStatus(CommonConstants.FIVE_STRING);
					}
					//是否地市自购
					preVo.setIsAddress(insuranceDetail.getIsAdress());
					preVo.setInsurancesId(insuranceDetail.getId());
				}
			}
		}
		//组装错误信息
		if (erorFlag) {
			exitCheckVo.setBuyType(preVo.getBuyType());
			exitCheckVo.setEmployeeName(preVo.getEmployeeName());
			exitCheckVo.setEmpIdcard(preVo.getEmpIdcard());
			exitCheckVo.setPolicyStart(preVo.getPolicyStart());
			exitCheckVo.setPolicyEnd(preVo.getPolicyEnd());
			exitCheckVo.setBuyStandard(preVo.getBuyStandard());
			exitCheckVo.setInsuranceCompanyName(preVo.getInsuranceCompanyName());
			exitCheckVo.setInsuranceTypeName(preVo.getInsuranceTypeName());
			exitCheckVo.setErrorMsg("存在流程中/已完结的商险数据");
		} else {
			return null;
		}
		return exitCheckVo;
	}

	@Override
	public R registrationPreAudit(EmployeeRegistrationPre pre) {
		TPreEmpMain empMain = empMainMapper.selectOne(Wrappers.<TPreEmpMain>query().lambda()
				.eq(TPreEmpMain::getEmpIdcard, pre.getEmpIdcard())
				.eq(TPreEmpMain::getDeptId, pre.getDeptId())
				.eq(TPreEmpMain::getStatus, CommonConstants.TWO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isEmpty(empMain)) {
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		return R.ok(empMain.getId());
	}

	@Override
	public R batchSendMessage(List<SendMessageUpdateVo> voList, String type) {
		if (Common.isNotNull(voList) && voList.size() > 200) {
			return R.failed("短信批量发送单次最多两百条");
		}
		//获取联系电话
		String contactTel ="0551-63468931";
		//获取模板
		String modelCode = "";
		SysConfig sysConfig = sysConfigMapper.getSysConfigLimitByKey("EMPLOYMENT_SMS_RLY");
		if (null != sysConfig){
			contactTel = sysConfig.getConfigValue();
			modelCode = sysConfig.getConfigValue1();
		}
		MessageTempleteVo templeteVo = baseMapper.selectTempleteVo(modelCode);
		String[] paramsDetail;
		String[] phonesArr;
		RlySmsUtil rlySmsUtil = new RlySmsUtil();
		HashMap<String, Object> sendResult;
		HashMap<String, Object> data;
		HashMap<String, Object> detail;
		String[][] t;
		//获取短信待发放和信息待填写的数据
		List<String> errorList = new ArrayList<>();
		if (CommonConstants.ONE_STRING.equals(type)) {
			for (SendMessageUpdateVo updateVo : voList) {
				paramsDetail = new String[3];
				phonesArr = new String[1];
				EmployeeRegistrationPre updatePre;
				updatePre = baseMapper.selectOne(Wrappers.<EmployeeRegistrationPre>query()
						.lambda().eq(EmployeeRegistrationPre::getId, updateVo.getId())
						.in(EmployeeRegistrationPre::getProcessStatus, CommonConstants.processStatus)
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isNotNull(updatePre)) {
					if (CommonConstants.ZERO_STRING.equals(updatePre.getProcessStatus())) {
						updatePre.setProcessStatus(CommonConstants.ONE_STRING);
					}
					//生成短信发送的记录
					TRegisteWarningEmployee smsEmployee = new TRegisteWarningEmployee();
					smsEmployee.setEmpName(updatePre.getEmployeeName());
					smsEmployee.setEmpPhone(updatePre.getEmpPhone());
					smsEmployee.setEmpIdcard(updatePre.getEmpIdcard());
					smsEmployee.setSendDate(DateUtil.getCurrentDateTime());
					smsEmployee.setSendMethod(CommonConstants.ONE_INT);
					smsEmployee.setWarningId(updatePre.getId());
					smsEmployee.setType(CommonConstants.ONE_STRING);
					smsEmployee.setDeptId(updatePre.getDeptId());
					employeeService.save(smsEmployee);
					paramsDetail[0] = smsEmployee.getEmpName()!=null?smsEmployee.getEmpName():"";
					paramsDetail[1] = smsEmployee.getId()!=null?smsEmployee.getId().toString():"";
					paramsDetail[2] = contactTel;
					if (smsEmployee.getEmpPhone() == null){
						smsEmployee.setMessage("短信发送失败: 电话不可为空！");
						employeeService.updateById(smsEmployee);
						continue;
					}
					if (null == templeteVo ||  null == templeteVo.getTempleteCode()){
						smsEmployee.setMessage("短信发送失败: 模板不可为空！");
						employeeService.updateById(smsEmployee);
						continue;
					}
					phonesArr[0]= smsEmployee.getEmpPhone();
					t = new String[1][3]; // 创建正确大小的二维数组
					t[0]=paramsDetail;
					//调用RlySmsUtil的sendBatchSms方法
					sendResult = rlySmsUtil.sendBatchSms(phonesArr, templeteVo.getTempleteCode(), t,templeteVo.getAppId());
					handleSmsRes(sendResult, errorList, updatePre, smsEmployee);

				}
			}
		} else {
			TEmployeeInfo info;
			for (SendMessageUpdateVo updateVo : voList) {
				paramsDetail = new String[3];
				phonesArr = new String[1];
				EmployeeRegistrationPre updatePre;
				info = employeeInfoMapper.selectById(updateVo.getId());
				if (Common.isNotNull(info)) {
					//如果有入职待建档数据同步更新
					updatePre = baseMapper.selectOne(Wrappers.<EmployeeRegistrationPre>query().lambda()
							.eq(EmployeeRegistrationPre::getEmpIdcard, info.getEmpIdcard())
							.eq(EmployeeRegistrationPre::getDeptId, updateVo.getDeptId())
							.eq(EmployeeRegistrationPre::getProcessStatus, CommonConstants.ZERO_STRING)
							.last(CommonConstants.LAST_ONE_SQL));
					if (Common.isNotNull(updatePre)) {
						updatePre.setProcessStatus(CommonConstants.ONE_STRING);
					}
					//生成短信发送的记录
					TRegisteWarningEmployee smsEmployee = new TRegisteWarningEmployee();
					smsEmployee.setEmpName(info.getEmpName());
					smsEmployee.setEmpPhone(info.getEmpPhone());
					smsEmployee.setSendDate(DateUtil.getCurrentDateTime());
					smsEmployee.setSendMethod(CommonConstants.ONE_INT);
					smsEmployee.setEmpIdcard(info.getEmpIdcard());
					smsEmployee.setWarningId(info.getId());
					smsEmployee.setType(CommonConstants.TWO_STRING);
					smsEmployee.setDeptId(updateVo.getDeptId());
					employeeService.save(smsEmployee);
					paramsDetail[0] = smsEmployee.getEmpName()!=null?smsEmployee.getEmpName():"";
					paramsDetail[1] = smsEmployee.getId()!=null?smsEmployee.getId().toString():"";
					paramsDetail[2] = contactTel;
					if (smsEmployee.getEmpPhone() == null){
						smsEmployee.setMessage("短信发送失败: 电话不可为空！");
						employeeService.updateById(smsEmployee);
						continue;
					}
					if (null == templeteVo ||  null == templeteVo.getTempleteCode()){
						smsEmployee.setMessage("短信发送失败: 模板不可为空！");
						employeeService.updateById(smsEmployee);
						continue;
					}
					phonesArr[0]= smsEmployee.getEmpPhone();

					t = new String[1][3]; // 创建正确大小的二维数组
					t[0]=paramsDetail;
					//调用RlySmsUtil的sendBatchSms方法
					sendResult = rlySmsUtil.sendBatchSms(phonesArr, templeteVo.getTempleteCode(), t,templeteVo.getAppId());
					handleSmsRes(sendResult, errorList, updatePre, smsEmployee);
				}
			}
		}
		if (!errorList.isEmpty() && errorList.stream().allMatch(e -> e.equals("短信发送失败"))) {
			return R.ok("短信发送失败");
		}
		return R.ok("短信发送成功");
	}

	private void handleSmsRes(HashMap<String, Object> sendResult, List<String> errorList, EmployeeRegistrationPre updatePre, TRegisteWarningEmployee smsEmployee) {
		HashMap<String, Object> detail;
		HashMap<String, Object> data;
		if (null != sendResult && "000000".equals(sendResult.get("statusCode"))) {
			// 成功情况处理
			data = (HashMap<String, Object>) sendResult.get("data");
			detail = null;
			if (data != null){
				detail = (HashMap<String, Object>) data.get("templateSMS");
			}
			String smsMessageSid = "";
			if (detail != null){
				smsMessageSid = detail.get("smsMessageSid").toString();
			}
			smsEmployee.setBizId(smsMessageSid);
			smsEmployee.setMessage("短信发送成功");
			employeeService.updateById(smsEmployee);
			if (Common.isNotNull(updatePre)) {
				this.updateById(updatePre);
			}
		} else {
			// 失败情况处理
			String errorMsg = "未知错误";
			if (sendResult != null) {
				errorMsg = "错误码=" + sendResult.get("statusCode") + " 错误信息=" + sendResult.get("statusMsg");
			}
			smsEmployee.setMessage("短信发送失败: " + errorMsg);
			employeeService.updateById(smsEmployee);
			errorList.add("短信发送失败");
		}
	}

	@Override
	public void updatePreStatusToEnd(String deptNo, String empIdcard) {
		EmployeeRegistrationPre registrationPre = baseMapper.selectOne(Wrappers.<EmployeeRegistrationPre>query().lambda()
				.eq(EmployeeRegistrationPre::getEmpIdcard, empIdcard)
				.eq(EmployeeRegistrationPre::getDeptNo, deptNo)
				.in(EmployeeRegistrationPre::getProcessStatus, CommonConstants.processPreArchivesStatus)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(registrationPre)) {
			registrationPre.setProcessStatus(CommonConstants.FOUR_STRING);
			baseMapper.updateById(registrationPre);
		}
	}

	@Override
	public void updatePreStatusToOne(String deptNo, String empIdcard) {
		EmployeeRegistrationPre registrationPre = baseMapper.selectOne(Wrappers.<EmployeeRegistrationPre>query().lambda()
				.eq(EmployeeRegistrationPre::getEmpIdcard, empIdcard)
				.eq(EmployeeRegistrationPre::getDeptNo, deptNo)
				.eq(EmployeeRegistrationPre::getProcessStatus, CommonConstants.TWO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(registrationPre)) {
			registrationPre.setProcessStatus(CommonConstants.ONE_STRING);
			baseMapper.updateById(registrationPre);
		}
	}

	@Override
	public void updatePreStatusToTwo(String deptId, String empIdCard) {
		EmployeeRegistrationPre registrationPre = baseMapper.selectOne(Wrappers.<EmployeeRegistrationPre>query().lambda()
				.eq(EmployeeRegistrationPre::getEmpIdcard, empIdCard)
				.eq(EmployeeRegistrationPre::getDeptId, deptId)
				.eq(EmployeeRegistrationPre::getProcessStatus, CommonConstants.ONE_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(registrationPre)) {
			registrationPre.setProcessStatus(CommonConstants.TWO_STRING);
			baseMapper.updateById(registrationPre);
		}
	}

	@Override
	public R<EmployeeInfoMsgVo> getEmployeeInfo(String id) {
		//获取人员档案id
		EmployeeInfoMsgVo msgInfoVo = baseMapper.getEmployeeArchivesInfo(id, CommonConstants.preMainStatus);
		if (Common.isEmpty(msgInfoVo)) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		//获取预入职信息，如果有的话提示
		if (Common.isNotNull(msgInfoVo)) {
			TPreEmpMain empMain = empMainMapper.selectOne(Wrappers.<TPreEmpMain>query().lambda()
					.eq(TPreEmpMain::getEmpIdcard, msgInfoVo.getCard())
					.eq(TPreEmpMain::getDeptId, msgInfoVo.getDeptId())
					.in(TPreEmpMain::getStatus, CommonConstants.preMainStatus)
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(empMain)) {
				msgInfoVo.setMessage("信息审核中，请耐心等待!");
			}
			return R.ok(msgInfoVo);
		}
		return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
	}

	@Override
	public R<EmployeeInfoMsgVo> getGzEmployeeInfo(EmployeeInfoMsgVo vo) {
		if (Common.isEmpty(vo)) {
			return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
		}
		//短信入口
		if (Common.isNotNull(vo.getDetailId())) {
			//获取人员档案id
			EmployeeInfoMsgVo msgInfoVo = baseMapper.getEmployeeArchivesInfo(vo.getDetailId(), Stream.of("4").collect(Collectors.toList()));
			if (Common.isEmpty(msgInfoVo)) {
				return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
			}
			//获取预入职信息，如果有的话提示
			if (Common.isNotNull(msgInfoVo) && Common.isNotNull(msgInfoVo.getDetailId())) {
				TGzOfferInfo empMain = gzOfferInfoMapper.selectOne(Wrappers.<TGzOfferInfo>query().lambda()
						.eq(TGzOfferInfo::getId, Integer.valueOf(msgInfoVo.getDetailId()))
						.ne(TGzOfferInfo::getOfferStatus, CommonConstants.NINE_STRING)
						.last(CommonConstants.LAST_ONE_SQL));
				if (Common.isNotNull(empMain)) {
					msgInfoVo.setMessage("当前Offer不符合档案采集状态，禁止操作");
				}
				return R.ok(msgInfoVo);
			}
		}
		//二维码入口
		if (Common.isNotNull(vo.getCard()) && Common.isNotNull(vo.getName())) {
			//获取预入职信息，如果有的话提示
			TGzOfferInfo empMain = gzOfferInfoMapper.selectOne(Wrappers.<TGzOfferInfo>query().lambda()
					.eq(TGzOfferInfo::getNationalId, vo.getCard())
					.eq(TGzOfferInfo::getName, vo.getName())
					.eq(TGzOfferInfo::getOfferStatus, CommonConstants.NINE_STRING)
					.orderByDesc(TGzOfferInfo::getCreateTime)
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isEmpty(empMain)) {
				vo.setMessage("当前Offer不符合档案采集状态，禁止操作");
			} else {
				vo.setPhone(empMain.getPhone());
				vo.setDetailId(empMain.getId().toString());
			}
			return R.ok(vo);
		}
		return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
	}

	/**
	 * @Description: 获取前端客服的所有项目权限
	 * @Author: huych
	 * @Date: 2025/3/13 17:02
	 * @return:
	 **/
	public void initSearchVo(EmployeeRegistrationPreSearchVo 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);
			//获取项目信息
			List<String> deptNos = tSettleDomainService.getAllDeptByCustomerLoginName(user.getUsername());
			if (null != deptNos && !deptNos.isEmpty()) {
				searchVo.setDeptNoList(deptNos);
			} else {
				searchVo.setId(CommonConstants.ONE_STRING_NEGATE);
			}
		}
	}

	/**
	 * @Description: 批量发送短信
	 * @Author: huych
	 * @Date: 2025/3/18 17:02
	 * @return:
	 **/
	public AliSmsResult sendMessage(List<String> phones, List<RegistParamVo> params) {
		List<String> signNames = new ArrayList<>();
		MessageTempleteVo templeteVo = baseMapper.selectTempleteVo(CommonConstants.ONE_STRING);
		for (int i = 0; i < phones.size(); i++) {
			signNames.add(templeteVo.getSignName());
		}
		return YiFuSmsUtil.sendRegistBatchSms(phones, params, signNames, templeteVo.getTempleteCode());
	}


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

	/**
	 * @Description: 判断简档详档（员工类型：代理的是简档，“非代理”且员工合同类型为：空、标准合同、劳务派遣合同、补贴合同 是详档，其余为简档）
	 * @Author: hgw
	 * @Date: 2025/3/20 15:22
	 * @return: java.lang.String
	 **/
	@Override
	public String judgeIsSimple(String empIdCard, String deptId) {
		// 类型1详档2简档
		String type = baseMapper.judegIsSimpleByPre(empIdCard, deptId);
		if (Common.isEmpty(type)) {
			type = baseMapper.judegIsSimpleByEmpProject(empIdCard, deptId);
		}
		if (Common.isEmpty(type)) {
			type = CommonConstants.ONE_STRING;
		}
		return type;
	}

	/**
	 * @Description: 获取员工类型与档案地市 -优先从档案维护任务表
	 * @Author: hgw
	 * @Date: 2025/3/21 11:26
	 * @return: com.yifu.cloud.plus.v1.yifu.archives.entity.EmployeeRegistrationPre
	 **/
	@Override
	public EmployeeRegistrationPre getPreInfo(String empIdCard, String deptId) {
		// 类型1详档2简档
		EmployeeRegistrationPre pre = baseMapper.getPreByPre(empIdCard, deptId);
		if (Common.isEmpty(pre) || Common.isEmpty(pre.getId())) {
			pre = baseMapper.getPreByEmpProject(empIdCard, deptId);
		}
		return pre;
	}

	/**
	 * @param id 入职确认表ID
	 * @Description: 根据ID获取商险待购买
	 * @Author: hgw
	 * @Date: 2025/4/9 15:00
	 * @return: java.util.List<com.yifu.cloud.plus.v1.yifu.insurances.entity.TEmployeeInsurancePre>
	 **/
	@Override
	public EmployeeRegistrationPre getEmployeeRegistrationPreById(String id) {
		EmployeeRegistrationPre pre = this.getById(id);
		if (pre != null) {
			//判断合同是否已签订 是的话展示商险明细 否的话查询商险待购买数据
			// 查已购买商险明细
			R<EmployeePreInsuranceListVo> sdr = HttpDaprUtil.invokeMethodPost(daprInsurancesProperties.getAppUrl()
					, daprInsurancesProperties.getAppId()
					, "/temployeeinsurancepre/inner/getExitInsuranceListByEmpPreId", id
					, EmployeePreInsuranceListVo.class, SecurityConstants.FROM_IN);
			if (sdr != null && sdr.getData() != null && sdr.getData().getPreList() != null &&
					!sdr.getData().getPreList().isEmpty()) {
				pre.setExitInsuranceInfoList(sdr.getData().getPreList());
			}

			// 查原商险
			R<EmployeePreLogListVo> sdrOld = HttpDaprUtil.invokeMethodPost(daprInsurancesProperties.getAppUrl()
					, daprInsurancesProperties.getAppId()
					, "/temployeeinsurancepre/inner/getListByEmpPreId", id, EmployeePreLogListVo.class
					, SecurityConstants.FROM_IN);
			List<TEmployeeInsurancePre> oldList;
			if (sdrOld != null && sdrOld.getData() != null && sdrOld.getData().getPreList() != null &&
					!sdrOld.getData().getPreList().isEmpty()) {
				oldList = sdrOld.getData().getPreList();
				for (TEmployeeInsurancePre oldInsurance : oldList) {
					if (Common.isNotNull(oldInsurance.getProcessStatus())
							&& (CommonConstants.THREE_STRING.equals(oldInsurance.getProcessStatus())
							|| CommonConstants.FOUR_STRING.equals(oldInsurance.getProcessStatus())
							|| CommonConstants.SIX_STRING.equals(oldInsurance.getProcessStatus()))) {
						oldInsurance.setModelType(CommonConstants.FOUR_STRING);
					}
				}
				pre.setInsurancePreList(oldList);
			}
			//获取合同待签订数据
			TEmployeeContractPre contract = contractPreMapper.selectOne(Wrappers.<TEmployeeContractPre>query().lambda()
					.eq(TEmployeeContractPre::getRegisterId, id)
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(contract)) {
				//特殊状态处理
				if (Common.isNotNull(contract.getChangeTypeReason())) {
					contract.setSignType(CommonConstants.ZERO_STRING);
				}
				//附件赋值
				List<TAttaInfo> attaContractInfo = attaInfoService.list(Wrappers.<TAttaInfo>query().lambda()
						.eq(TAttaInfo::getDomainId, contract.getId()));
				if (Common.isNotNull(contract.getSignType()) && CommonConstants.ZERO_STRING.equals(contract.getSignType())
						&& Common.isNotNull(contract.getContractId())) {
					attaContractInfo = attaInfoService.list(Wrappers.<TAttaInfo>query().lambda()
							.eq(TAttaInfo::getDomainId, contract.getContractId()));
				}
				// 如果附件信息非空，则为每个附件生成可访问的URL，并将其添加到员工注册信息中
				if (attaContractInfo != null && !attaContractInfo.isEmpty()) {
					URL url;
					for (TAttaInfo a : attaContractInfo) {
						url = ossUtil.getObjectUrl(null, a.getAttaSrc());
						a.setAttaUrl(null != url ? url.toString() : "");
					}
					contract.setAttaList(attaContractInfo);
				}
				pre.setEmployeeContractPre(contract);
			}

			// 查询与员工相关的附件信息
			List<TAttaInfo> attaInfo = attaInfoService.list(Wrappers.<TAttaInfo>query().lambda().eq(TAttaInfo::getDomainId, id));
			// 如果附件信息非空，则为每个附件生成可访问的URL，并将其添加到员工注册信息中
			if (attaInfo != null && !attaInfo.isEmpty()) {
				URL url;
				for (TAttaInfo a : attaInfo) {
					url = ossUtil.getObjectUrl(null, a.getAttaSrc());
					a.setAttaUrl(null != url ? url.toString() : "");
				}
				pre.setAttaList(attaInfo);
			}
			// 查已购买社保明细
			R<EmployeePreSocialListVo> socialSdr = socialDaprUtils.getSocialPreInfoList(id);
			if (socialSdr != null && socialSdr.getData() != null) {
				if (null != socialSdr.getData().getExitSocialInfoList()) {
					pre.setExitSocialInfoList(socialSdr.getData().getExitSocialInfoList());
				} else if (null != socialSdr.getData().getDispatchInfoPreVo()) {
					pre.setDispatchInfoPreVo(socialSdr.getData().getDispatchInfoPreVo());
				}
			}
		}
		return pre;
	}

}
