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.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.csp.entity.EmployeeRegistration;
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.EmployeeRegistrationPreMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TCompleteMonitorMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TPreEmpMainMapper;
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.util.equator.HrEquator;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
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.EmployeePreLogListVo;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.TEmployeeInsuranceExitCheckVo;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.TEmployeeInsurancePreVo;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.TEmployeeInsuranceSelectVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TEmployeeInsuranceWorkDayVo;
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.URLEncoder;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 入职待建档表
 *
 * @author huych
 * @date 2025-03-12 17:14:19
 */
@Log4j2
@Service
@RequiredArgsConstructor
@EnableConfigurationProperties(DaprInsurancesProperties.class)
public class EmployeeRegistrationPreServiceImpl extends ServiceImpl<EmployeeRegistrationPreMapper, EmployeeRegistrationPre> implements EmployeeRegistrationPreService {

	private final DaprInsurancesProperties daprInsurancesProperties;

	@Autowired
	private InsuranceDaprUtil insuranceDaprUtil;

	@Autowired
	private SocialDaprUtils socialDaprUtils;

	@Autowired
	private CspDaprUtils cspDaprUtils;

	@Autowired
	private TEmployeeLogService tEmployeeLogService;

	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;

	@Autowired
	@Lazy
	private ScheduleService scheduleService;

    /**
     * 入职待建档表简单分页查询
     * @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
	@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);
		}
		baseMapper.insert(pre);
		if (Common.isNotNull(preExit)) {
			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);
			}
			tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[4],
					pre.getId(), "", preExit, pre, pre.getCreateBy(), pre.getCreateName());
		}
		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();
	}

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

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

		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 (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) {
					keyMap.put(key, CommonConstants.ONE_INT);
				} else {
					return R.failed("保险公司、险种、购买标准、保单起、止日期不可同时重复！");
				}
				// 2：是否工作日判断
				String error = checkInsuranceBuy(insurancePreVo);
				if (null != error) {
					return R.failed(error);
				}

				insurancePreVo.setEmpIdcard(employeeRegistrationPre.getEmpIdcard());
				insurancePreVo.setDeptNo(employeeRegistrationPre.getDeptNo());
				//商险是否存在判断
				preVo = new TEmployeeInsurancePreVo();
				preVo.setEmployeeName(employeeRegistrationPre.getEmployeeName());
				preVo.setEmpIdcard(employeeRegistrationPre.getEmpIdcard());
				preVo.setBuyStandard(insurancePreVo.getBuyStandard());
				preVo.setInsuranceTypeName(insurancePreVo.getInsuranceTypeName());
				preVo.setInsuranceCompanyName(insurancePreVo.getInsuranceCompanyName());
				preVo.setPolicyStart(insurancePreVo.getPolicyStart());
				preVo.setPolicyEnd(insurancePreVo.getPolicyEnd());
				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 (!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())) {
						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 {
			// 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("含有不可删除的商险，请刷新后再修改！");
					}
				}
			}
		}

		//操作记录中字典值的转化
		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);

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

	private void initInsurancePreInfo(EmployeeRegistrationPre registration, TEmployeeInsurancePre preVo,
									  YifuUser user, String id) {
		preVo.setRegisterId(id);
		preVo.setCustomerUsername(registration.getCustomerUsername());
		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());
		/*if (Common.isNotNull(preVo.getPolicyStartType()) && CommonConstants.ONE_STRING.equals(preVo.getPolicyStartType())) {
			preVo.setPolicyStart(preVo.getJoinLeaveDate());
		}
		//预计派单日期
		if (Common.isEmpty(preVo.getExpectedCollectionTime())) {
			TEmployeeInsuranceWorkDayVo dayVo = new TEmployeeInsuranceWorkDayVo();
			dayVo.setType(CommonConstants.ONE_STRING);
			if (preVo.getBuyType() ==1) {
				dayVo.setRegistDate(preVo.getPolicyStart());
			} else {
				dayVo.setRegistDate(preVo.getJoinLeaveDate());
			}
			R<TEmployeeInsuranceWorkDayVo> dataR = socialDaprUtils.getBeforeOrAfterWorkDay(dayVo);
			if (Common.isNotNull(dataR) && Common.isNotNull(dataR.getData())
					&& Common.isNotNull(dataR.getData().getRegistDate())) {
				preVo.setExpectedCollectionTime(dataR.getData().getRegistDate());
			} else {
				preVo.setExpectedCollectionTime(preVo.getPolicyStart());
			}
		}*/
		//preVo.setExpectedCollectionTime(DateUtil.parseDate(DateUtil.dateToString( preVo.getExpectedCollectionTime(), DateUtil.ISO_EXPANDED_DATE_FORMAT) + " 14:00", DateUtil.DATETIME_PATTERN_MINUTE));
	}

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

	private String checkInsuranceBuy(TEmployeeInsurancePre preVo) {
		//新增判断保单开始日期
		TEmployeeInsuranceWorkDayVo vo = new TEmployeeInsuranceWorkDayVo();
		R<Boolean> dataR;
		if (preVo.getBuyType() == 1) {
			vo.setRegistDate(preVo.getPolicyStart());
			dataR = socialDaprUtils.checkIsWorkDay(vo);
			if (Common.isNotNull(dataR) && Boolean.TRUE.equals(dataR.getData())) {
				return "新增类型的保单开始日期不能为工作日;";
			}
		}
		if (preVo.getBuyType() == 3 && Common.isNotNull(preVo.getExpectedCollectionTime())){
			// 将 LocalDateTime 转换为 java.util.Date
			vo.setRegistDate(DateUtil.convertToDateByLocalDateTime(preVo.getExpectedCollectionTime()));
			dataR = socialDaprUtils.checkIsWorkDay(vo);
			if (Common.isNotNull(dataR) && Boolean.TRUE.equals(dataR.getData())) {
				return "批增类型的预计派单日期不能为工作日;";
			}
		}
		if (preVo.getBuyType() == 4 && Common.isNotNull(preVo.getExpectedCollectionTime())){
			vo.setRegistDate(DateUtil.convertToDateByLocalDateTime(preVo.getExpectedCollectionTime()));
			dataR = socialDaprUtils.checkIsWorkDay(vo);
			if (Common.isNotNull(dataR) && Boolean.TRUE.equals(dataR.getData())) {
				return "替换类型的预计派单日期不能为工作日;";
			}
		}
		return null;
	}

	// 商险是否存在判断 type 1 单个接收 2 批量接收
	private TEmployeeInsuranceExitCheckVo checkInsuranceExit(TEmployeeInsurancePreVo preVo) {
		//查询入职确认信息数据
		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().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);
					}
				}
			}
		}
		//组装错误信息
		if (erorFlag) {
			TEmployeeInsuranceExitCheckVo exitCheckVo = new TEmployeeInsuranceExitCheckVo();
			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("存在流程中/已完结的商险数据");
			return exitCheckVo;
		} else {
			return null;
		}
	}

	@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) {
		//获取短信待发放和信息待填写的数据
		List<String> errorList = new ArrayList<>();
		if (CommonConstants.ONE_STRING.equals(type)) {
			for(SendMessageUpdateVo updateVo:voList) {
				RegistParamVo paramVo = new RegistParamVo();
				List<RegistParamVo> params = new ArrayList<>();
				List<String> phones = new ArrayList<>();
				EmployeeRegistrationPre updatePre;
				AliSmsResult res;
				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)) {
					paramVo.setName(updatePre.getEmployeeName());
					phones.add(updatePre.getEmpPhone());
					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);
					paramVo.setLink(smsEmployee.getId().toString());
					params.add(paramVo);
					res = sendMessage(phones, params);
					if (null != res && null != res.getBizId()) {
						smsEmployee.setBizId(res.getBizId());
						smsEmployee.setMessage(res.getMessage());
						employeeService.updateById(smsEmployee);
						this.updateById(updatePre);
					} else {
						smsEmployee.setMessage("短信发送失败");
						employeeService.updateById(smsEmployee);
						errorList.add("短信发送失败");
					}
				}
			}
		} else {
			TEmployeeInfo info;
			for(SendMessageUpdateVo updateVo:voList) {
				RegistParamVo paramVo = new RegistParamVo();
				List<RegistParamVo> params = new ArrayList<>();
				List<String> phones = new ArrayList<>();
				EmployeeRegistrationPre updatePre;
				AliSmsResult res;
				info = employeeInfoMapper.selectById(updateVo.getId());
				if (Common.isNotNull(info)) {
					paramVo.setName(info.getEmpName());
					phones.add(info.getEmpPhone());
					//如果有入职待建档数据同步更新
					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);
					paramVo.setLink(smsEmployee.getId().toString());
					params.add(paramVo);
					res = sendMessage(phones, params);
					if (null != res && null != res.getBizId()) {
						smsEmployee.setBizId(res.getBizId());
						smsEmployee.setMessage(res.getMessage());
						employeeService.updateById(smsEmployee);
						if (Common.isNotNull(updatePre)) {
							this.updateById(updatePre);
						}
					} else {
						smsEmployee.setMessage("短信发送失败");
						employeeService.updateById(smsEmployee);
						errorList.add("短信发送失败");
					}
				}
			}
		}
		if (!errorList.isEmpty() && errorList.stream().allMatch(e->e.equals("短信发送失败"))) {
			return R.ok("短信发送失败");
		}
		return R.ok("短信发送成功");
	}

	@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);
		//获取预入职信息，如果有的话提示
		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);
	}

	/**
	 * @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<EmployeePreLogListVo> sdr = HttpDaprUtil.invokeMethodPost(daprInsurancesProperties.getAppUrl(), daprInsurancesProperties.getAppId()
					, "/temployeeinsurancepre/inner/getListByEmpPreId", id, EmployeePreLogListVo.class, SecurityConstants.FROM_IN);
			List<TEmployeeInsurancePre> oldList;
			if (sdr != null && sdr.getData() != null && sdr.getData().getPreList() != null && !sdr.getData().getPreList().isEmpty()) {
				oldList = sdr.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);
			}
		}
		return pre;
	}

}
