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.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.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.util.CspDaprUtils;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.MenuUtil;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

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

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

	@Autowired
	private CspDaprUtils cspDaprUtils;

	@Autowired
	private TEmployeeLogService tEmployeeLogService;

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

	@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
	public R updateCommonInfo(EmployeeRegistrationPre employeeRegistrationPre) {
		EmployeeRegistrationPre updatePre = baseMapper.selectById(employeeRegistrationPre.getId());
		if (Common.isEmpty(updatePre)) {
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}
		//旧的对象，用来对比变更参数
		EmployeeRegistrationPre comparePre = baseMapper.selectById(employeeRegistrationPre.getId());
		//操作记录中字典值的转化
		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;
				}
			}
		}
		YifuUser user = SecurityUtils.getUser();
		try {
			updatePre.setServerItem(employeeRegistrationPre.getServerItem());
			updatePre.setEmpNature(employeeRegistrationPre.getEmpNature());
			updatePre.setContractType(employeeRegistrationPre.getContractType());
			updatePre.setFileProvince(employeeRegistrationPre.getFileProvince());
			updatePre.setFileCity(employeeRegistrationPre.getFileCity());
			updatePre.setFileTown(employeeRegistrationPre.getFileTown());
			updatePre.setContractSubName(null == employeeRegistrationPre.getContractSubName() ? "" : employeeRegistrationPre.getContractSubName());
			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);
			}
			tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[4],
					employeeRegistrationPre.getId().toString(), "", comparePre, employeeRegistrationPre,user);
		} catch (Exception e) {
			log.error("生成入职待确认信息修改操作日志异常", e);
		}
		return R.ok();
	}

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

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

}
