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

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
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.config.WxConfig;
import com.yifu.cloud.plus.v1.csp.constants.RegistConstants;
import com.yifu.cloud.plus.v1.csp.entity.EmployeeRegistration;
import com.yifu.cloud.plus.v1.csp.entity.TOperationLog;
import com.yifu.cloud.plus.v1.csp.mapper.EmployeeRegistrationMapper;
import com.yifu.cloud.plus.v1.csp.service.EmployeeRegistrationService;
import com.yifu.cloud.plus.v1.csp.service.TOperationLogService;
import com.yifu.cloud.plus.v1.csp.vo.EmployeeRegistrationExportVo;
import com.yifu.cloud.plus.v1.csp.vo.EmployeeRegistrationHrExportVo;
import com.yifu.cloud.plus.v1.csp.vo.EmployeeRegistrationSearchVo;
import com.yifu.cloud.plus.v1.csp.vo.EmployeeRegistrationVo;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysUser;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.SysCspDeptVo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeProjectBelongDept;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EmpProjectStatusVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TEmployeeProjectBelongDeptSearchCspVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainSelectVo;
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.vo.UserPermissionVo;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprArchivesProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.ArchivesDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.UpmsDaprUtils;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.insurances.util.ValidityUtil;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * 入离职登记表
 *
 * @author huych
 * @date 2025-02-25 14:48:11
 */
@Log4j2
@Service
@AllArgsConstructor
@EnableConfigurationProperties(DaprArchivesProperties.class)
public class EmployeeRegistrationServiceImpl extends ServiceImpl<EmployeeRegistrationMapper, EmployeeRegistration> implements EmployeeRegistrationService {

	private final DaprArchivesProperties archivesProperties;

	@Autowired
	private ArchivesDaprUtil archivesDaprUtil;

	@Autowired
	private WxConfig wxConfig;

	@Autowired
	private UpmsDaprUtils upmsDaprUtils;

	private final TOperationLogService logService;

	/**
	 * 入离职登记表简单分页查询
	 *
	 * @param employeeRegistration 入离职登记表
	 * @return
	 */
	@Override
	public IPage<EmployeeRegistration> getEmployeeRegistrationPage(Page<EmployeeRegistration> page, EmployeeRegistrationSearchVo employeeRegistration) {
		getDtpeAuth(employeeRegistration);
		return baseMapper.getEmployeeRegistrationPage(page, employeeRegistration);
	}

	/**
	 * hr入离职登记表代办列表简单分页查询
	 *
	 * @param employeeRegistration 入离职登记表
	 * @return
	 */
	@Override
	public IPage<EmployeeRegistration> getHrEmployeeRegistrationPage(Page<EmployeeRegistration> page, EmployeeRegistrationSearchVo employeeRegistration) {
		YifuUser user = SecurityUtils.getUser();
		long roleId = 1839501715787390978L;
		boolean isSsc =	this.haveRole(user, roleId);
		if (isSsc) {
			employeeRegistration.setCustomerUserLoginname(null);
		}
		return baseMapper.getEmployeeRegistrationPage(page, employeeRegistration);
	}

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

	/**
	 * 入离职登记表批量导出
	 *
	 * @param searchVo 入离职登记表
	 * @return
	 */
	@Override
	public void listHrExport(HttpServletResponse response, EmployeeRegistrationSearchVo searchVo) {
		String fileName = "入离职待办任务表批量导出" + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<EmployeeRegistrationHrExportVo> list = new ArrayList<>();
		long count = baseMapper.selectExportCount(searchVo);
		try (ServletOutputStream out = response.getOutputStream()) {
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, CommonConstants.UTF8));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, EmployeeRegistrationHrExportVo.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = baseMapper.selectHrExportList(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();
			}
			out.flush();
			excelWriter.finish();
		} catch (Exception e) {
			log.error("执行异常", e);
		}
	}

	@Override
	public R<List<ErrorMessage>> importDiy(InputStream inputStream,String deptId) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<EmployeeRegistrationVo> util1 = new ExcelUtil<>(EmployeeRegistrationVo.class);
		YifuUser user = SecurityUtils.getUser();
		//获取项目信息
		R<TSettleDomainSelectVo> domainR = archivesDaprUtil.getSettleDomainSelectVoById(deptId);

		if (null == domainR || null == domainR.getData()) {
			errorMessageList.add(new ErrorMessage(-1, "访问员工基础服务异常："));
			return R.ok(errorMessageList);
		}
		TSettleDomainSelectVo selectVo = domainR.getData();
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, EmployeeRegistrationVo.class, new ReadListener<EmployeeRegistrationVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT1;
				/**
				 *临时存储
				 */
				private List<EmployeeRegistrationVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(EmployeeRegistrationVo data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex + 1);
					ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)) {
						errorMessage.setData(data);
						errorMessageList.add(errorMessage);
					} else {
						cachedDataList.add(data);
					}
					if (cachedDataList.size() >= BATCH_COUNT) {
						saveData();
						// 存储完成清理 list
						cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
					}
				}

				@Override
				public void doAfterAllAnalysed(AnalysisContext context) {
					saveData();
				}

				/**
				 * 加上存储数据库
				 */
				private void saveData() {
					log.info("{}条数据，开始存储数据库！", cachedDataList.size());
					importEmployeeRegistration(cachedDataList, errorMessageList,user, selectVo);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		return R.ok(errorMessageList);
	}

	private void importEmployeeRegistration(List<EmployeeRegistrationVo> excelVOList,
											List<ErrorMessage> errorMessageList,YifuUser user,TSettleDomainSelectVo selectVo) {

		Map<String, String> exitMap = new HashMap<>();
		EmployeeRegistrationVo excel;
		int inNum = 0;
		int outNum = 0;
		List<EmployeeRegistration> insertList = new ArrayList<>();
		for (int i = 0; i < excelVOList.size(); i++) {
			excel = excelVOList.get(i);
			// 插入
			EmployeeRegistration insert = new EmployeeRegistration();
			BeanUtil.copyProperties(excel, insert);
			//表数据验重
			//表内数据重复 员工姓名、员工身份证号码、反馈类型
			StringBuilder errorTemp = new StringBuilder();
			errorTemp.append(excel.getEmployeeName());
			errorTemp.append("_");
			errorTemp.append(excel.getEmpIdcard());
			errorTemp.append("_");
			errorTemp.append(excel.getFeedbackType());
			if (null == exitMap.get(errorTemp.toString())) {
				exitMap.put(errorTemp.toString(), "1");
			} else {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), RegistConstants.IMPORT_EXIT_CHECK, excel));
				continue;
			}
			insert.setDeptNo(selectVo.getDepartNo());
			String error = registCheck(insert);
			if (null != error) {
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(), error, excel));
				continue;
			}
			initRegistInfo(insert,user, selectVo);
			insertList.add(insert);
			//新增记录,新增操作记录
			baseMapper.insert(insert);
			if (CommonConstants.ONE_STRING.equals(insert.getFeedbackType())) {
				inNum ++;
			} else {
				outNum ++;
			}
			logService.saveLog(insert.getId(), CommonConstants.ZERO_STRING,RegistConstants.MESSAGE_REGIST, LocalDateTime.now(),
					insert.getRegistorUsername(),null);
		}
		if (!Common.isEmpty(insertList)) {
			insertList.clear();
			//发送企业微信待办
			EmployeeRegistration msgRegistration = new EmployeeRegistration();
			msgRegistration.setInNum(inNum);
			msgRegistration.setOutNum(outNum);
			msgRegistration.setCustomerUserLoginname(selectVo.getCsLoginName());
			msgRegistration.setDeptName(selectVo.getDepartName());
			msgRegistration.setDeptNo(selectVo.getDepartNo());
			//企业微信消息提醒
			sendMessageToWx(msgRegistration, CommonConstants.THREE_STRING);
		}

	}

	public R registAdd(EmployeeRegistration registration) {
		//提交校验内容：
		//1、身份证号位数、手机号码位数及格式，就职岗位下拉选择“内勤、揽投员、其他”
		//2、按照类型、按照身份证号、按照项目进行去重校验
		String errorInfo = registCheck(registration);
		if (null != errorInfo) {
			return R.failed(errorInfo);
		} else {
			baseMapper.insert(registration);
		}
		//企业微信消息提醒
		sendMessageToWx(registration,registration.getFeedbackType());
		//操作记录
		logService.saveLog(registration.getId(), CommonConstants.ZERO_STRING,RegistConstants.MESSAGE_REGIST, LocalDateTime.now(),
				registration.getRegistorUsername(),null);
		return R.ok();
	}

	public R confirmSubmit(EmployeeRegistration registration) {
		YifuUser user = SecurityUtils.getUser();
		EmployeeRegistration registrationNow = baseMapper.selectById(registration.getId());
		if (Common.isEmpty(registrationNow) || !CommonConstants.ONE_STRING.equals(registrationNow.getProcessStatus())) {
			return R.failed(RegistConstants.NO_DATA_TO_HANDLE);
		}
		//点击“接收确认”的时候，监测到该人员该项目下已有在项的档案时，再次提醒：该人员已在项，
		//状态将更新成“已处理”；处理记录中，针对此情况，记录真实的进项时间，备注：先于登记入项
		EmpProjectStatusVo vo = new EmpProjectStatusVo();
		vo.setEmpIdcard(registrationNow.getEmpIdcard());
		vo.setDeptNo(registrationNow.getDeptNo());
		EmpProjectStatusVo exit;
		if (CommonConstants.ONE_STRING.equals(registrationNow.getFeedbackType())) {
			exit = getEmpProjectStatus(vo);
		} else {
			exit = getOutEmpProjectStatus(vo);
		}
		if (Common.isNotNull(exit)) {
			return R.ok(exit);
		}
		registrationNow.setProcessStatus(CommonConstants.ZERO_STRING);
		baseMapper.updateById(registrationNow);
		logService.saveLog(registration.getId(), CommonConstants.ZERO_STRING,RegistConstants.CONFIRM_SUBMIT, LocalDateTime.now(),
				user.getNickname(),null);
		return R.ok();
	}

	public R updateRegist(EmployeeRegistration registration) {
		YifuUser user = SecurityUtils.getUser();
		EmployeeRegistration registrationNow = baseMapper.selectById(registration.getId());
		if (Common.isEmpty(registrationNow) || !CommonConstants.ONE_STRING.equals(registrationNow.getProcessStatus())) {
			return R.failed(RegistConstants.NO_DATA_TO_HANDLE);
		}
		registrationNow.setProcessStatus(CommonConstants.TWO_STRING);
		logService.saveLog(registration.getId(), CommonConstants.ZERO_STRING,RegistConstants.CONFIRM_SUBMIT, LocalDateTime.now(),
				user.getNickname(),null);
		logService.saveLog(registration.getId(), CommonConstants.ZERO_STRING,RegistConstants.MESSAGE_FINISH, registration.getProjectCreateTime(),
				user.getNickname(),CommonConstants.ONE_STRING.equals(registrationNow.getFeedbackType())
						? RegistConstants.BEFORE_IN_PROJECT :RegistConstants.BEFORE_OUT_PROJECT);
		SysCspDeptVo vo = new SysCspDeptVo();
		if (CommonConstants.ONE_STRING.equals(registrationNow.getFeedbackType())) {
			vo.setDepartName(registrationNow.getEmpDeptname());
			vo.setDepartId(Long.valueOf(registrationNow.getEmpDeptid()));
		}
		vo.setProjectId(registration.getEmpProjectId());
		archivesDaprUtil.saveOrDeleteDeptRelation(vo);
		baseMapper.updateById(registrationNow);
		return R.ok();
	}

	//单个新增、导入校验
	private String registCheck(EmployeeRegistration registration) {
		//定义判别用户身份证号的正则表达式（要么是15位，要么是18位，最后一位可以为字母）
		Pattern idNumPattern = compile("(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])");
		//通过Pattern获得Matcher
		Matcher idNumMatcher = idNumPattern.matcher(registration.getEmpIdcard());
		if (!idNumMatcher.matches()) {
			return RegistConstants.IDCARD_FORMAT_ERROR;
		}
		if (!ValidityUtil.validateEmpPhone(registration.getEmpPhone())) {
			return RegistConstants.PHONE_FORMAT_ERROR;
		}
		EmployeeRegistration exit = baseMapper.selectOne(Wrappers.<EmployeeRegistration>query().lambda()
				.eq(EmployeeRegistration::getEmpIdcard, registration.getEmpIdcard())
				.eq(EmployeeRegistration::getDeptNo, registration.getDeptNo())
				.eq(EmployeeRegistration::getFeedbackType, registration.getFeedbackType())
				.in(EmployeeRegistration::getProcessStatus, CommonConstants.processStatus)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(exit)) {
			return RegistConstants.REGIST_SAME_CHECK;
		}
		//针对离职的判断人员项目档案状态是否正常
		if (CommonConstants.TWO_STRING.equals(registration.getFeedbackType())) {
			EmpProjectStatusVo vo = new EmpProjectStatusVo();
			vo.setEmpIdcard(registration.getEmpIdcard());
			vo.setDeptNo(registration.getDeptNo());
			EmpProjectStatusVo exitVo = getEmpProjectStatus(vo);
			if (Common.isEmpty(exitVo)) {
				return RegistConstants.EMP_PROJECT_EXIT_CHECK;
			}
		}
		return null;
	}

	//获取人员档案信息
	private EmpProjectStatusVo getEmpProjectStatus(EmpProjectStatusVo vo) {
		//找到不在项人员的身份证信息
		R<EmpProjectStatusVo> sdr = HttpDaprUtil.invokeMethodPost(archivesProperties.getAppUrl(), archivesProperties.getAppId()
				, "/temployeeproject/inner/getEmpProjectStatus", vo, EmpProjectStatusVo.class, SecurityConstants.FROM_IN);
		if (sdr != null && sdr.getData() != null) {
			vo = sdr.getData();
			return vo;
		} else {
			return null;
		}
	}

	//获取减项人员档案信息
	private EmpProjectStatusVo getOutEmpProjectStatus(EmpProjectStatusVo vo) {
		//找到不在项人员的身份证信息
		R<EmpProjectStatusVo> sdr = HttpDaprUtil.invokeMethodPost(archivesProperties.getAppUrl(), archivesProperties.getAppId()
				, "/temployeeproject/inner/getOutEmpProjectStatus", vo, EmpProjectStatusVo.class, SecurityConstants.FROM_IN);
		if (sdr != null && sdr.getData() != null) {
			vo = sdr.getData();
			return vo;
		} else {
			return null;
		}
	}

	//数据初始化
	private void initRegistInfo(EmployeeRegistration insert,YifuUser user,TSettleDomainSelectVo selectVo) {
		SysCspDeptVo vo = new SysCspDeptVo();
		vo.setUserId(user.getId());
		vo.setProjectId(selectVo.getId());
		R<SysCspDeptVo> booleanR = upmsDaprUtils.selectCspDeptByUserDeptId(vo);
		if (Common.isNotNull(booleanR) && Common.isNotNull(booleanR.getData())
				&& Common.isNotNull(booleanR.getData().getDepartId()) && Common.isNotNull(booleanR.getData().getDepartName())) {
			vo = booleanR.getData();
			insert.setRegistorDeptname(vo.getDepartName());
			insert.setRegistorDeptid(vo.getDepartId().toString());
			insert.setEmpDeptid(vo.getDepartId().toString());
			insert.setEmpDeptname(vo.getDepartName());
		} else {
			insert.setRegistorDeptname(user.getDeptName());
			insert.setRegistorDeptid(user.getDeptId().toString());
			insert.setEmpDeptid(user.getDeptId().toString());
			insert.setEmpDeptname(user.getDeptName());
		}
		insert.setRegistorUsername(user.getNickname());
		insert.setRegistorPhone(user.getPhone());
		insert.setCustomerPhone(selectVo.getCsPhone());
		insert.setCustomerUsername(selectVo.getCsName());
		insert.setCustomerUserLoginname(selectVo.getCsLoginName());
		insert.setDeptName(selectVo.getDepartName());
		insert.setDeptId(selectVo.getId());
	}

	//发送企业微信待办
	private void sendMessageToWx(EmployeeRegistration registration, String type) {
		//获取前端客服
		SysUser user;
		if (Common.isEmpty(registration.getCustomerUserLoginname())) {
			return;
		}
		R<SysUser> res = upmsDaprUtils.getSimpleUserByLoginName(registration.getCustomerUserLoginname());
		if (Common.isNotNull(res) && Common.isNotNull(res.getData())){
			user = res.getData();
		}else {
			return;
		}
		StringBuilder sendUser = null;
		if (Common.isNotKong(user.getWxMessage())) {
			sendUser = new StringBuilder(user.getWxMessage());
		}
		if (sendUser != null) {
			RestTemplate restTemplate = new RestTemplate();
			Map<String, Object> requestMap = new HashMap<>();
			Map<String, Object> textcard = new HashMap<>();
			String authUrl = String.format(SecurityConstants.WX_GET_MESSAGE_AUTH_URL, wxConfig.getCorpid(), wxConfig.getDomainName()+"/auth/oauth/wxLogin", "66"+registration.getId());
			StringBuilder description = new StringBuilder();
			String title = "";
			if (CommonConstants.ONE_STRING.equals(type) || CommonConstants.TWO_STRING.equals(type)) {
				title = CommonConstants.ONE_STRING.equals(type) ? "人员入职提醒：":"人员离职提醒：";
				description.append(CommonConstants.ONE_STRING.equals(type) ? "入职日期：":"离职日期：")
						.append(DateUtil.dateToString(registration.getJoinLeaveDate(),DateUtil.ISO_EXPANDED_DATE_FORMAT)).append("<br>");
				description.append("项目名称：").append(registration.getDeptName()).append("<br>");
				description.append("项目编码：").append(registration.getDeptNo()).append("<br>");
				description.append("员工姓名：").append(registration.getEmployeeName()).append("<br>");
				description.append("身份证号：").append(registration.getEmpIdcard()).append("<br>");
				description.append("手机号码：").append(registration.getEmpPhone()).append("<br>");
			} else {
				title = "人员批量入离职提醒";
				description.append("项目名称：").append(registration.getDeptName()).append("<br>");
				description.append("项目编码：").append(registration.getDeptNo()).append("<br>");
				description.append("入职人数：").append(registration.getInNum()).append("<br>");
				description.append("离职人数：").append(registration.getOutNum()).append("<br>");
			}
			textcard.put("title", title);
			textcard.put("url", authUrl);
			textcard.put("description", description.toString());
			requestMap.put("touser", sendUser);
			requestMap.put("agentid", wxConfig.getAgentid());
			requestMap.put("msgtype", "textcard");
			requestMap.put("textcard", textcard);
			// 必须加上header说明
			if (!wxConfig.sendTextCard(restTemplate, requestMap)) {
				wxConfig.sendTextCard(restTemplate, requestMap);
			}
			//企业微信发送记录
			logService.saveLog(user.getUserId(), CommonConstants.ZERO_STRING,"企业微信消息提醒", LocalDateTime.now(),
					registration.getRegistorUsername(),"提醒人：" +  user.getNickname());
		}
	}

	/**
	 * @param searchCspVo 身份证与类型
	 * @Description: 获取已接收的入离职申请，同步所属部门到项目档案里
	 * @Author: hgw
	 * @Date: 2025/3/3 16:57
	 * @return: com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeProjectBelongDept
	 **/
	@Override
	public TEmployeeProjectBelongDept getZeroRegistrationAndUpdateTwo(TEmployeeProjectBelongDeptSearchCspVo searchCspVo) {
		List<TEmployeeProjectBelongDept> belongDeptList = baseMapper.getZeroRegistrationByIdCard(searchCspVo);
		if (belongDeptList != null && !belongDeptList.isEmpty()) {
			// 1：加日志
			if (doSaveLogBatch(searchCspVo, belongDeptList)) return null;
			// 更新为已处理
			baseMapper.updateTwoRegistrationByIdCard(searchCspVo);
			return belongDeptList.get(0);
		} else {
			return null;
		}

	}

	/**
	 * @Description: 批量处理日志
	 * @Author: hgw
	 * @Date: 2025/3/4 10:41
	 * @return: boolean
	 **/
	private boolean doSaveLogBatch(TEmployeeProjectBelongDeptSearchCspVo searchCspVo, List<TEmployeeProjectBelongDept> belongDeptList) {
		TOperationLog log;
		List<TOperationLog> logList = new ArrayList<>();
		String title = "已处理";
		for (TEmployeeProjectBelongDept belongDept : belongDeptList) {
			log = new TOperationLog();
			log.setMainId(belongDept.getId());
			log.setType(CommonConstants.ZERO_STRING);
			log.setTitle(title);
			log.setOperationTime(searchCspVo.getEmpCreateAndLeaveTime());
			log.setOperationName(searchCspVo.getEmpCreateAndLeaveUser());
			if (searchCspVo.getEmpCreateAndLeaveTime() != null && belongDept.getLogCreateTime() != null
					&& searchCspVo.getEmpCreateAndLeaveTime().isBefore(belongDept.getLogCreateTime())) {
				if (CommonConstants.ONE_STRING.equals(searchCspVo.getFeedbackType())) {
					log.setRemark("入职登记前已增员");
				} else {
					log.setRemark("离职登记前已减员");
				}
			}
			log.setCreateBy(searchCspVo.getUserId());
			log.setCreateName(searchCspVo.getUserName());
			log.setCreateTime(LocalDateTime.now());
			logList.add(log);
		}
		if (!logList.isEmpty()) {
			logService.saveBatch(logList);
		}
		return false;
	}

	/**
	 * @Description: 获取部门权限
	 * @Author: huych
	 * @Date: 2025/3/4 10:41
	 * @return:
	 **/
	private void getDtpeAuth(EmployeeRegistrationSearchVo searchVo) {
		YifuUser user = SecurityUtils.getUser();
		if (null != user && Common.isNotNull(user.getId())) {
			List<UserPermissionVo> cspPermList = user.getCspPermMap();
			if (Common.isNotNull(cspPermList)) {
				// 获取用户在当前项目下的权限
				UserPermissionVo authority = null;
				for (UserPermissionVo userPermissionVo : cspPermList) {
					if (searchVo.getDeptNo().equals(userPermissionVo.getProjectNo())) {
						authority = userPermissionVo;
					}
				}
				if (Common.isNotNull(authority) && !authority.isHaveAll()) {
					if (Common.isNotNull(authority.getDepartIdSet())) {
						searchVo.setDepartIdSet(authority.getDepartIdSet());
					} else {
						searchVo.setId(CommonConstants.ONE_STRING_NEGATE);
					}
				}
			}
		}
	}

	public boolean haveRole(YifuUser user, long roleId) {
		List<Long> roleList = user.getClientRoleMap().get(ClientNameConstants.CLIENT_MVP);
		for (Long role : roleList) {
			if (role == roleId) {
				return true;
			}
		}
		return false;
	}
}
