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

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
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.conditions.query.LambdaQueryWrapper;
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.ekp.vo.EkpDeptInfoVo;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysUser;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.SysUserListVo;
import com.yifu.cloud.plus.v1.yifu.archives.config.WxConfig;
import com.yifu.cloud.plus.v1.yifu.archives.constants.ArchivesConstants;
import com.yifu.cloud.plus.v1.yifu.archives.constants.EmployeeContractConstants;
import com.yifu.cloud.plus.v1.yifu.archives.entity.*;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.*;
import com.yifu.cloud.plus.v1.yifu.archives.service.FeedBackDetailService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmpContractAlertService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
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.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.UpmsDaprUtils;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.archives.entity.SysConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 员工合同续签待办
 *
 * @author fxj
 * @date 2022-07-01 14:15:05
 */
@Log4j2
@RequiredArgsConstructor
@Service
public class TEmpContractAlertServiceImpl extends ServiceImpl<TEmpContractAlertMapper, TEmpContractAlert> implements TEmpContractAlertService {

	private final TEmployeeContractInfoMapper  contractInfoMapper;

	private final TEmployeeInfoMapper employeeInfoMapper;

	private final TEmployeeProjectMapper projectMapper;

	private final FeedBackDetailMapper feedbackDetailMapper;

	private final FeedBackDetailService feedBackDetailService;

	private final TSettleDomainMapper settleDomainMapper;

	@Autowired
	private UpmsDaprUtils upmsDaprUtils;

	@Autowired
	private SysConfigMapper sysConfigMapper;

	@Autowired
	private WxConfig wxConfig;

	@Override
	public IPage<TEmpContractAlert> pageDiy(Page page, ContractAlertSearchVo searchVo) {
		LambdaQueryWrapper<TEmpContractAlert> wrapper = buildQueryWrapper(searchVo);
		wrapper.isNotNull(TEmpContractAlert::getId);
		if (Common.isNotNull(searchVo.getContractEndStart())){
			wrapper.ge(TEmpContractAlert::getContractEnd,searchVo.getContractEndStart());
		}
		if (Common.isNotNull(searchVo.getContractEndEnd())){
			wrapper.le(TEmpContractAlert::getContractEnd,searchVo.getContractEndEnd());
		}
		if (Common.isNotNull(searchVo.getAuthSql())) {
			wrapper.last(searchVo.getAuthSql() + " order by CREATE_TIME desc");
		} else {
			wrapper.orderByDesc(BaseEntity::getCreateTime);
		}
		return baseMapper.selectPage(page,wrapper);
	}

	@Override
	public List<TEmpContractAlert> listDiy(ContractAlertSearchVo searchVo) {
		LambdaQueryWrapper<TEmpContractAlert> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		wrapper.isNotNull(TEmpContractAlert::getId);
		if (Common.isNotNull(idList)){
			wrapper.in(TEmpContractAlert::getId,idList);
		}
		if (Common.isNotNull(searchVo.getContractEndStart())){
			wrapper.ge(TEmpContractAlert::getContractEnd,searchVo.getContractEndStart());
		}
		if (Common.isNotNull(searchVo.getContractEndEnd())){
			wrapper.le(TEmpContractAlert::getContractEnd,searchVo.getContractEndEnd());
		}
		if (Common.isNotNull(searchVo.getAuthSql())) {
			if (Common.isNotNull(searchVo.getAuthSql()) && searchVo.getAuthSql().contains("a.")) {
				searchVo.setAuthSql(searchVo.getAuthSql().replace("a.", " "));
			}
			wrapper.last(searchVo.getAuthSql());
		}
		return baseMapper.selectList(wrapper);
	}

	private long noPageCountDiy(ContractAlertSearchVo searchVo) {
		LambdaQueryWrapper<TEmpContractAlert> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		wrapper.isNotNull(TEmpContractAlert::getId);
		if (Common.isNotNull(idList)){
			wrapper.in(TEmpContractAlert::getId,idList);
		}
		if (Common.isNotNull(searchVo.getContractEndStart())){
			wrapper.ge(TEmpContractAlert::getContractEnd,searchVo.getContractEndStart());
		}
		if (Common.isNotNull(searchVo.getContractEndEnd())){
			wrapper.le(TEmpContractAlert::getContractEnd,searchVo.getContractEndEnd());
		}
		if (Common.isNotNull(searchVo.getAuthSql())) {
			if (Common.isNotNull(searchVo.getAuthSql()) && searchVo.getAuthSql().contains("a.")) {
				searchVo.setAuthSql(searchVo.getAuthSql().replace("a.", " "));
			}
			wrapper.last(searchVo.getAuthSql());
		}
		if (searchVo.getLimitStart() >= 0 && searchVo.getLimitEnd() >= 0){
			wrapper.last(" limit "+ searchVo.getLimitStart() +","+ searchVo.getLimitEnd());
		}
		return baseMapper.selectCount(wrapper);
	}

	@Override
	public void listExport(HttpServletResponse response, ContractAlertSearchVo searchVo) {
		String fileName = ArchivesConstants.EMP_BAD_RECORD + LocalDateTime.now() + CommonConstants.XLSX;
		//获取要导出的列表
		List<TEmpContractAlert> list = new ArrayList<>();
		long count = noPageCountDiy(searchVo);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName  , CommonConstants.UTF8));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, TEmpBadRecord.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				WriteSheet writeSheet;
				ExcelUtil<TEmpContractAlert> util;
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = listDiy(searchVo);
					if (Common.isNotNull(list)){
						util = new ExcelUtil<>(TEmpContractAlert.class);
						for (TEmpContractAlert vo:list){
							util.convertEntity(vo,null,null,null);
						}
					}
					if (Common.isNotNull(list)){
						writeSheet = EasyExcel.writerSheet(ArchivesConstants.EMP_BAD_RECORD+index).build();
						excelWriter.write(list,writeSheet);
						index++;
						i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
					}
					if (Common.isNotNull(list)){
						list.clear();
					}
				}
				excelWriter.finish();
			}else {
				WriteSheet writeSheet = EasyExcel.writerSheet(ArchivesConstants.EMP_BAD_RECORD+index).build();
				excelWriter.write(list,writeSheet);
				excelWriter.finish();
			}
			if (Common.isNotNull(list)){
				list.clear();
			}
			out.flush();
		}catch (Exception e){
			log.error("执行异常" ,e);
		}finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

	private LambdaQueryWrapper buildQueryWrapper(ContractAlertSearchVo entity){
		LambdaQueryWrapper<TEmpContractAlert> wrapper = Wrappers.lambdaQuery();
		if (ArrayUtil.isNotEmpty(entity.getCreateTimes())) {
			wrapper.ge(TEmpContractAlert::getCreateTime, entity.getCreateTimes()[0])
					.le(TEmpContractAlert::getCreateTime,
							entity.getCreateTimes()[1]);
		}
		if (Common.isNotNull(entity.getEmpName())){
			wrapper.eq(TEmpContractAlert::getEmpName,entity.getEmpName());
		}
		if (Common.isNotNull(entity.getEmpIdcard())){
			wrapper.eq(TEmpContractAlert::getEmpIdcard,entity.getEmpIdcard());
		}
		if (Common.isNotNull(entity.getProject())){
			wrapper.eq(TEmpContractAlert::getProject,entity.getProject());
		}
		if (Common.isNotNull(entity.getProjectNo())){
			wrapper.eq(TEmpContractAlert::getProjectNo,entity.getProjectNo());
		}
		if (Common.isNotNull(entity.getEmpType())){
			wrapper.eq(TEmpContractAlert::getEmpType,entity.getEmpType());
		}
		if (Common.isNotNull(entity.getContractType())){
			wrapper.eq(TEmpContractAlert::getContractType,entity.getContractType());
		}
		if (Common.isNotNull(entity.getContractTerm())){
			wrapper.eq(TEmpContractAlert::getContractTerm,entity.getContractTerm());
		}
		if (Common.isNotNull(entity.getFileProvince())){
			wrapper.eq(TEmpContractAlert::getFileProvince,entity.getFileProvince());
		}
		if (Common.isNotNull(entity.getFileCity())){
			wrapper.eq(TEmpContractAlert::getFileCity,entity.getFileCity());
		}
		if (Common.isNotNull(entity.getFileTown())){
			wrapper.eq(TEmpContractAlert::getFileTown,entity.getFileTown());
		}

		if (Common.isNotNull(entity.getAlertPerson())){
			wrapper.eq(TEmpContractAlert::getAlertPerson,entity.getAlertPerson());
		}
		if (Common.isNotNull(entity.getDueFlag())){
			wrapper.eq(TEmpContractAlert::getDueFlag,entity.getDueFlag());
		}
		if (Common.isNotNull(entity.getHandleStatus())){
			wrapper.eq(TEmpContractAlert::getHandleStatus,entity.getHandleStatus());
		}
		if (Common.isNotNull(entity.getDaysDue())){
			wrapper.eq(TEmpContractAlert::getDaysDue,entity.getDaysDue());
		}
		if (Common.isNotNull(entity.getUnitId())) {
			wrapper.eq(TEmpContractAlert::getUnitId, entity.getUnitId());
		}
		if (Common.isNotNull(entity.getEmpPhone())) {
			wrapper.eq(TEmpContractAlert::getEmpPhone, entity.getEmpPhone());
		}
		if (Common.isNotNull(entity.getUnitNo())) {
			wrapper.eq(TEmpContractAlert::getUnitNo, entity.getUnitNo());
		}
		if (Common.isNotNull(entity.getIsFeedback())){
			wrapper.eq(TEmpContractAlert::getIsFeedback,entity.getIsFeedback());
		}
		return wrapper;
	}
	/**
	 * 定时任务生成合同续签代码信息
	 * @return R<List>
	 * @Author FXJ
	 * @Date 2022-07-4
	 **/
	@Override
	public R<Boolean> taskCreateContractAlert() {
		// 获取合同为在档、员工类型为“0外包”、“1派遣”、最近一次合同审核通过、过期或离过期还有3个月的数据
		List<TEmployeeContractInfo> alertList = contractInfoMapper.selectList(Wrappers.<TEmployeeContractInfo>query()
				.lambda().eq(TEmployeeContractInfo::getAuditStatus, CommonConstants.TWO_STRING)
				.isNotNull(TEmployeeContractInfo::getAuditTimeLast)
				.eq(TEmployeeContractInfo::getInUse,CommonConstants.ZERO_STRING)
				.eq(TEmployeeContractInfo::getContractType,CommonConstants.ONE_STRING)
				.eq(TEmployeeContractInfo::getWorkFlag,CommonConstants.ZERO_STRING)
				.ne(TEmployeeContractInfo::getSituation,"作废")
				.ne(TEmployeeContractInfo::getSituation,"终止")
				.le(TEmployeeContractInfo::getContractEnd,DateUtil.dateIncreaseByDay(
						DateUtil.dateIncreaseByMonth(DateUtil.getCurrentDateTime(),
								CommonConstants.dingleDigitIntArray[3]), CommonConstants.dingleDigitIntArray[1]))
				.eq(TEmployeeContractInfo::getDeleteFlag, CommonConstants.ZERO_STRING));
		// 获取所有未审核通过的合同数据
		List<TEmployeeContractInfo> notAccessList = contractInfoMapper.selectList(Wrappers.<TEmployeeContractInfo>query().lambda()
				.and(obj->obj.eq(TEmployeeContractInfo::getAuditStatus,CommonConstants.ZERO_STRING)
						.or().eq(TEmployeeContractInfo::getAuditStatus,CommonConstants.ONE_STRING))
				.eq(TEmployeeContractInfo::getWorkFlag,CommonConstants.ZERO_STRING)
				.eq(TEmployeeContractInfo::getDeleteFlag,CommonConstants.ZERO_STRING));
		Map<String,TEmpContractAlert> alertMap = new HashMap<>();
		Map<String,TEmpContractAlert> existMap = new HashMap<>();
		initExistMap(existMap);
		if (Common.isNotNull(alertList)) {
			Date nowDate = new Date();
			for (TEmployeeContractInfo contract:alertList){
				extracted(nowDate, contract,alertMap,existMap);
			}
		}
		if (Common.isNotNull(notAccessList) && Common.isNotNull(alertMap)){
			TEmpContractAlert exist;
			for (TEmployeeContractInfo contract:notAccessList){
				exist = alertMap.get(contract.getEmpIdcard()+CommonConstants.DOWN_LINE_STRING+contract.getDeptNo());
				if (Common.isNotNull(exist)){
					exist.setHandleStatus(CommonConstants.ONE_STRING);
					alertMap.put(contract.getEmpIdcard()+CommonConstants.DOWN_LINE_STRING+contract.getDeptNo(),exist);
				}
			}
		}
		baseMapper.truncate();
		if (Common.isNotNull(alertMap)){
			this.saveBatch(alertMap.values());
		}
		return R.ok();
	}


	private void initExistMap(Map<String, TEmpContractAlert> existMap) {
		List<TEmpContractAlert> exists = baseMapper.selectList(Wrappers.<TEmpContractAlert>query());
		if (Common.isNotNull(exists)){
			for (TEmpContractAlert alert:exists){
				existMap.put(alert.getContractId(),alert);
			}
		}
	}

	private void extracted(Date nowDate,
						   TEmployeeContractInfo contract,
						   Map<String, TEmpContractAlert> alertMap,
						   Map<String, TEmpContractAlert> existMap) {
		TEmployeeInfo employeeInfo = employeeInfoMapper.selectById(contract.getEmpId());
		if (Common.isNotNull(employeeInfo)){
			TEmployeeProject project = projectMapper.selectOne(Wrappers.<TEmployeeProject>query().lambda()
					.eq(TEmployeeProject::getEmpIdcard,employeeInfo.getEmpIdcard())
					.eq(TEmployeeProject::getDeleteFlag,CommonConstants.ZERO_STRING)
					.eq(TEmployeeProject::getDeptNo,contract.getDeptNo())
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(project)
					&& ((Common.isNotNull(project.getProjectStatus())
					&& project.getProjectStatus().intValue()== CommonConstants.ONE_INT)
					|| (
					!CommonConstants.ZERO_STRING.equals(project.getEmpNatrue())
							&& !CommonConstants.ONE_STRING.equals(project.getEmpNatrue())
							&& !CommonConstants.THREE_STRING.equals(project.getEmpNatrue()))
					)){
				return;
			}
			if (Common.isEmpty(project)){
				return;
			}
		}else {
			return;
		}
		TEmpContractAlert alert = alertMap.get(contract.getEmpIdcard()+CommonConstants.DOWN_LINE_STRING+contract.getDeptNo());
		// 存在多个审核通过的数据 用最新的审核通过的合同覆盖已有的
		if (Common.isNotNull(alert)
				&& Common.isNotNull(alert.getAuditTime())
				&& Common.isNotNull(contract.getAuditTimeLast())
				&& alert.getAuditTime().after(LocalDateTimeUtils.convertLDTToDate(contract.getAuditTimeLast()))){
			return;
		}
		TEmpContractAlert exist = null;
		if (Common.isNotNull(contract)){
			exist = existMap.get(contract.getId());
		}
		alert = new TEmpContractAlert();
		if (Common.isNotNull(exist) && Common.isNotNull(exist.getFirstAlertTime())){
			alert.setFirstAlertTime(exist.getFirstAlertTime());
		}else {
			alert.setFirstAlertTime(new Date());
		}
		FeedBackDetail feedBackDetail1 = feedbackDetailMapper.findByApplyNo(contract.getApplyNo());
		if (null != feedBackDetail1) {
			alert.setIsFeedback(feedBackDetail1.getIsFeedback());
			alert.setFeedbackDetail(feedBackDetail1.getFeedbackDetail());
			alert.setFeedbackReason(feedBackDetail1.getFeedbackReason());
			alert.setFeedbackPerson(feedBackDetail1.getFeedbackPerson());
			alert.setFeedbackTime(feedBackDetail1.getFeedbackTime());
		} else {
			alert.setIsFeedback(CommonConstants.ZERO_INT);
		}
		alert.setApplyNo(contract.getApplyNo());
		// 2023-4-3 09:38:21 hgw 添加
		alert.setUnitId(contract.getCustomerId());
		alert.setUnitName(contract.getSubjectUnit());
		alert.setUnitNo(contract.getUnitNo());
		alert.setEmpPhone(employeeInfo.getEmpPhone());
		alert.setCreateBy(contract.getCreateBy());
		alert.setCreateName(contract.getCreateName());
		alert.setContractId(contract.getId());
		alert.setAlertPerson(contract.getCreateName());
		alert.setEmpName(contract.getEmpName());
		alert.setEmpId(contract.getEmpId());
		alert.setEmpCode(contract.getEmpNo());
		alert.setDeptId(contract.getSettleDomain());
		alert.setProject(contract.getSubjectDepart());
		alert.setProjectNo(contract.getDeptNo());
		alert.setEmpIdcard(contract.getEmpIdcard());
		alert.setContractStart(contract.getContractStart());
		alert.setContractEnd(contract.getContractEnd());
		alert.setAuditTime(LocalDateTimeUtils.convertLDTToDate(contract.getAuditTimeLast()));
		//2024-09-26 添加岗位和工时制
		alert.setPost(contract.getPost());
		alert.setWorkingHours(contract.getWorkingHours());
		if (Common.isNotNull(contract.getFileProvince())){
			alert.setFileProvince(Integer.toString(contract.getFileProvince()));
		}
		if (Common.isNotNull(contract.getFileCity())){
			alert.setFileCity(Integer.toString(contract.getFileCity()));
		}
		if (Common.isNotNull(contract.getFileTown())){
			alert.setFileTown(Integer.toString(contract.getFileTown()));
		}
		alert.setEmpType(contract.getEmpNatrue());
		alert.setContractType(contract.getContractName());
		alert.setContractTerm(contract.getContractType());
		if (Common.isNotNull(alert.getContractEnd())){
			if (Common.isNotNull(contract.getContractEnd()) && DateUtil.daysBetween(alert.getContractEnd(),nowDate) > 0){
				alert.setDaysOver(DateUtil.daysBetween(alert.getContractEnd(),nowDate));
				alert.setDueFlag(CommonConstants.ONE_STRING);
				alert.setDaysDue(null);
			}else {
				alert.setDaysDue(DateUtil.daysBetween(nowDate,alert.getContractEnd()));
				alert.setDueFlag(CommonConstants.ZERO_STRING);
				alert.setDaysOver(null);
			}
		}
		alert.setHandleStatus(CommonConstants.ZERO_STRING);
		alertMap.put(alert.getEmpIdcard()+CommonConstants.DOWN_LINE_STRING+alert.getProjectNo(),alert);
	}
	@Transactional(rollbackFor = {Exception.class})
	@Override
	public boolean changeFeedBackAll(ChangeFeedBackAllVo changeFeedBackAllVo) {
		YifuUser user = SecurityUtils.getUser();
		FeedBackDetail feedbackDetail;
		List<FeedBackDetail>  details = new ArrayList<>();
		for (int i = 0; i < changeFeedBackAllVo.getIds().length; i++) {
			feedbackDetail = new FeedBackDetail();
			feedbackDetail.setFeedbackPerson(user.getNickname());
			feedbackDetail.setFeedbackTime(DateTime.now());
			feedbackDetail.setApplyNo(changeFeedBackAllVo.getIds()[i]);
			feedbackDetail.setFeedbackReason(changeFeedBackAllVo.getFeedbackReason());
			feedbackDetail.setFeedbackDetail(changeFeedBackAllVo.getFeedbackDetail());
			feedbackDetail.setIsFeedback(CommonConstants.ONE_INT);
			details.add(feedbackDetail);
		}
		if (Common.isNotEmpty(details)){
			feedBackDetailService.saveBatch(details);
		}
		changeFeedBackAllVo.setIsFeedback(CommonConstants.ONE_INTEGER);
		    changeFeedBackAllVo.setFeedbackPerson(user.getNickname());
			changeFeedBackAllVo.setFeedbackTime(DateTime.now());
	        return  baseMapper.changeFeedBackAll(changeFeedBackAllVo);
	}

	@Override
	public List<FeedBackDetail> getFeedbackDetail(String applyNo) {
		return feedbackDetailMapper.getDetail(applyNo);
	}

	/**
	 * @param inputStream
	 * @Description: 批量更新-合同续签待办
	 * @Author: hgw
	 * @Date: 2023/7/17 9:47
	 **/
	@Transactional(rollbackFor = {Exception.class})
	@Override
	public R<List<EmpContractAlertUpdateVO>> batchUpdate(InputStream inputStream) {
		List<EmpContractAlertUpdateVO> errorMessageList = new ArrayList<>();
		ExcelUtil<EmpContractAlertUpdateVO> util1 = new ExcelUtil<>(EmpContractAlertUpdateVO.class);
		Map<String,String> reasonMap = new HashMap<>();
		reasonMap.put("已确定待续签","已经和客户单位或员工沟通好，因时间或地点原因未能签订的");
		reasonMap.put("未确定是否续签","因客户单位原因，暂时不能确定是否与员工继续签订劳动合同；");
		reasonMap.put("商务合同未签","业务部门未进行商务合同的续签");
		reasonMap.put("已签待更新","已完成劳动合同续签未进行人力云系统更新的");
		reasonMap.put("离职/退休/待派减","经确定离职、退休的员工，等待人力云系统派单减少");
		reasonMap.put("产假/工伤/病假","因产假、工伤、病假原因暂时无法正常续签的");
		reasonMap.put("其他","其他原因，添加具体原因备注");

		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {

			EasyExcelFactory.read(inputStream, EmpContractAlertUpdateVO.class, new ReadListener<EmpContractAlertUpdateVO>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<EmpContractAlertUpdateVO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(EmpContractAlertUpdateVO 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)) {
						data.setErrorInfo(errorMessage.getMessage());
						errorMessageList.add(data);
					} 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());
					if (!cachedDataList.isEmpty()) {
						updateInfo(reasonMap, cachedDataList, errorMessageList);
					}
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		if (!errorMessageList.isEmpty()) {
			return R.failed(errorMessageList);
		} else {
			return R.ok();
		}
	}

	public void updateInfo(Map<String, String> reasonMap, List<EmpContractAlertUpdateVO> excelVOList, List<EmpContractAlertUpdateVO> errorMessageList) {
		YifuUser user = SecurityUtils.getUser();
		List<String> idCardList = new ArrayList<>();
		for (EmpContractAlertUpdateVO vo : excelVOList) {
			if (Common.isNotNull(vo.getEmpIdCard())) {
				idCardList.add(vo.getEmpIdCard());
			}
		}
		Map<String, TEmpContractAlert> curMap = new HashMap<>();
		if (!idCardList.isEmpty()) {
			List<TEmpContractAlert> alertList = baseMapper.getAlertInfoList(idCardList);
			if (alertList != null && !alertList.isEmpty()) {
				for (TEmpContractAlert alert : alertList) {
					curMap.put(alert.getEmpIdcard() + CommonConstants.DOWN_LINE_STRING + alert.getProjectNo(), alert);
				}
			}
		}
		TEmpContractAlert cur;
		FeedBackDetail feedbackDetail;
		List<FeedBackDetail> saveDetail = new ArrayList<>();
		List<TEmpContractAlert> updateAlert = new ArrayList<>();
		for (EmpContractAlertUpdateVO updateInfo : excelVOList) {
			if (Common.isEmpty(updateInfo.getEmpIdCard()) || Common.isEmpty(updateInfo.getProjectNo()) || Common.isEmpty(updateInfo.getFeedbackReason())) {
				updateInfo.setErrorInfo("请检查必填项！");
				errorMessageList.add(updateInfo);
				continue;
			}
			cur = curMap.get(updateInfo.getEmpIdCard() + CommonConstants.DOWN_LINE_STRING + updateInfo.getProjectNo());
			if (cur != null) {
				cur.setIsFeedback(CommonConstants.ONE_INTEGER);
				cur.setFeedbackPerson(user.getNickname());
				cur.setFeedbackTime(DateTime.now());
				cur.setFeedbackReason(updateInfo.getFeedbackReason());
				String reasonDetail = reasonMap.get(updateInfo.getFeedbackReason());
				if (Common.isEmpty(reasonDetail)) {
					updateInfo.setErrorInfo("请输入正确的未续签原因！");
					errorMessageList.add(updateInfo);
					continue;
				}
				if (Common.isNotNull(updateInfo.getFeedbackDetail())) {
					reasonDetail = updateInfo.getFeedbackDetail();
				}
				cur.setFeedbackDetail(reasonDetail);
				updateAlert.add(cur);
				feedbackDetail = new FeedBackDetail();
				feedbackDetail.setFeedbackPerson(user.getNickname());
				feedbackDetail.setFeedbackTime(DateTime.now());
				feedbackDetail.setApplyNo(cur.getApplyNo());
				feedbackDetail.setFeedbackReason(updateInfo.getFeedbackReason());
				feedbackDetail.setFeedbackDetail(reasonDetail);
				feedbackDetail.setIsFeedback(CommonConstants.ONE_INT);
				saveDetail.add(feedbackDetail);
			} else {
				updateInfo.setErrorInfo("根据身份证号与项目编码未找到要更新的数据！");
				errorMessageList.add(updateInfo);
			}
		}
		if (!saveDetail.isEmpty()) {
			feedBackDetailService.saveBatch(saveDetail);
		}
		if (!updateAlert.isEmpty()) {
			this.updateBatchById(updateAlert);
		}
	}

	@Override
	public R<List<ErrorMessage>> importDiy(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<EmployeeContractCheckVO> util1 = new ExcelUtil<>(EmployeeContractCheckVO.class);;
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, EmployeeContractCheckVO.class, new ReadListener<EmployeeContractCheckVO>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<EmployeeContractCheckVO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(EmployeeContractCheckVO 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)){
						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());
					importTCompanyInfo(cachedDataList,errorMessageList);
					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 importTCompanyInfo(List<EmployeeContractCheckVO> excelVOList, List<ErrorMessage> errorMessageList) {
		// 个性化校验逻辑
		ErrorMessage errorMsg;
		// 执行数据插入操作 组装
		String res;
		for (int i = 0; i < excelVOList.size(); i++) {
			EmployeeContractCheckVO excel = excelVOList.get(i);
			// 业务逻辑实现
			res = check(excel);
			// 插入
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(),res,null,excel.getEmpIdcard()));
		}
	}

	/**
	 * 插入excel bad record
	 */
	private String check(EmployeeContractCheckVO excel) {
		// 获取合同为在档、员工类型为“0外包”、“1派遣”、最近一次合同审核通过、过期或离过期还有3个月的数据
		List<TEmployeeContractInfo> exitist = contractInfoMapper.selectList(Wrappers.<TEmployeeContractInfo>query().lambda()
				.eq(TEmployeeContractInfo::getEmpIdcard,excel.getEmpIdcard())
				.eq(TEmployeeContractInfo::getInUse,CommonConstants.ZERO_STRING)
				.eq(TEmployeeContractInfo::getAuditStatus,CommonConstants.TWO_STRING)
				.eq(TEmployeeContractInfo::getDeleteFlag,CommonConstants.ZERO_STRING));
		if (Common.isEmpty(exitist)){
			return excel.getEmpIdcard()+":未找到审核通过的在用合同信息";
		}
		Map<String,String> map = new HashMap<>();
		String temp = null;
		String temp2;
		String mapTemp=CommonConstants.EMPTY_STRING;
		for (TEmployeeContractInfo vo:exitist){
			mapTemp = map.get(vo.getEmpIdcard());
			if (baseMapper.selectCount(Wrappers.<TEmpContractAlert>query().lambda()
					.eq(TEmpContractAlert::getEmpIdcard,vo.getEmpIdcard())
					.eq(TEmpContractAlert::getProjectNo,vo.getDeptNo())) > 0){
				mapTemp = (mapTemp==null?"身份证":mapTemp+" | 身份证")+excel.getEmpIdcard() +"合同申请编号："+vo.getApplyNo() + " 已存在合同续签提醒";
				map.put(vo.getEmpIdcard(),mapTemp);
				continue;
			}
			if ("续签".equals(vo.getSituation()) || "终止".equals(vo.getSituation())){
				//map.put(vo.getEmpIdcard(),excel.getEmpIdcard() + "续签、终止类型的合同不提示");
				mapTemp = (mapTemp==null?"身份证":mapTemp+" | 身份证")+excel.getEmpIdcard() +"合同申请编号："+vo.getApplyNo() +" 续签、终止类型的合同不提示";
				map.put(vo.getEmpIdcard(),mapTemp);
				continue;
			}
			if (Common.isNotNull(vo.getAuditStatus()) && vo.getAuditStatus().intValue() != 2){
				mapTemp = (mapTemp==null?"身份证":mapTemp+" | 身份证")+excel.getEmpIdcard() +"合同申请编号："+vo.getApplyNo() +" 合同审核不通过";
				map.put(vo.getEmpIdcard(),mapTemp);
				continue;
			}
			if (CommonConstants.ONE_STRING.equals(vo.getIsObsolete())){
				mapTemp = (mapTemp==null?"身份证":mapTemp+" | 身份证")+excel.getEmpIdcard() +"合同申请编号："+vo.getApplyNo() + " 合同已作废---IsObsolete=1 为作废";
				map.put(vo.getEmpIdcard(),mapTemp);
				continue;
			}
			if (!CommonConstants.ONE_STRING.equals(vo.getContractType())){
				mapTemp = (mapTemp==null?"身份证":mapTemp+" | 身份证")+excel.getEmpIdcard() +"合同申请编号："+vo.getApplyNo() + " 签订期限不为‘固定期限’";
				map.put(vo.getEmpIdcard(),mapTemp);
				continue;
			}
			if (!CommonConstants.ZERO_STRING.equals(vo.getWorkFlag())){
				mapTemp = (mapTemp==null?"身份证":mapTemp+" | 身份证")+excel.getEmpIdcard() +"合同申请编号："+vo.getApplyNo() +" 合同状态 非在职";
				map.put(vo.getEmpIdcard(),mapTemp);
				continue;
			}
			if (!vo.getContractEnd().before(DateUtil.dateIncreaseByDay(
					DateUtil.dateIncreaseByMonth(DateUtil.getCurrentDateTime(),
							CommonConstants.dingleDigitIntArray[3]), CommonConstants.dingleDigitIntArray[1]))){
				mapTemp = (mapTemp==null?"身份证":mapTemp+" | 身份证")+excel.getEmpIdcard() +"合同申请编号："+vo.getApplyNo() + " 合同截止时间为 "+vo.getContractEnd()+ " 未到期";
				map.put(vo.getEmpIdcard(),mapTemp);
				continue;
			}
			temp2 =check2(vo);
			if (Common.isNotNull(temp2)){
				mapTemp = (mapTemp==null?"身份证":mapTemp+" | 身份证")+excel.getEmpIdcard() +"合同申请编号："+vo.getApplyNo() + temp2;
				map.put(vo.getEmpIdcard(),mapTemp);
				continue;
			}else {
				mapTemp = (mapTemp==null?"身份证":mapTemp+" | 身份证")+excel.getEmpIdcard() +"合同申请编号："+vo.getApplyNo() + ":条件符合未生成代码提醒";
				map.put(vo.getEmpIdcard(),mapTemp);
				continue;
			}

		}
		if (!Common.isEmpty(mapTemp)){
			return mapTemp;
		}
		return excel.getEmpIdcard() + ":条件符合未生成代码提醒";
	}

	private String check2(TEmployeeContractInfo contract) {
		TEmployeeInfo employeeInfo = employeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
				.eq(TEmployeeInfo::getDeleteFlag,CommonConstants.ZERO_STRING)
				.eq(TEmployeeInfo::getEmpIdcard,contract.getEmpIdcard()).last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(employeeInfo)){
			TEmployeeProject project = projectMapper.selectOne(Wrappers.<TEmployeeProject>query().lambda()
					.eq(TEmployeeProject::getEmpIdcard,employeeInfo.getEmpIdcard())
					.eq(TEmployeeProject::getDeleteFlag,CommonConstants.ZERO_STRING)
					.eq(TEmployeeProject::getDeptNo,contract.getDeptNo())
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(project)){
				if ((Common.isNotNull(project.getProjectStatus())
						&& project.getProjectStatus().intValue()== CommonConstants.ONE_INT)){
					return "对应身份证的项目档案已减项";
				}
				if((!CommonConstants.ZERO_STRING.equals(project.getEmpNatrue())
								&& !CommonConstants.ONE_STRING.equals(project.getEmpNatrue())
								&& !CommonConstants.THREE_STRING.equals(project.getEmpNatrue()))
				){
					return "对应身份证的项目档案员工类型 非外包、派遣、内部员工";
				}
			}
			if (Common.isEmpty(project)){
				return "无合同对应项目编码的的在用项目档案 或 存在多个在用合同";
			}
		}else {
			return "无对应身份证在用档案信息";
		}
		return null;
	}

	/**
	 * @Author fxj
	 * @Description 获取合同续签但前端客服异常的数据发送给柳毅晨（可配置）
	 * @Date 17:05 2025/8/14
	 * @Param
	 * @return
	**/
	@Override
	public void pushContractAlertToWx() {
		try {
			//获取所有合同提醒的数据--去重
			List<TEmployeeContractInfo> contractAlertList = contractInfoMapper.getContractAlertDeptNosList();
			//从contractAlertList 对象的 中获取所有元素的 deptNo 属性，要去空和去重。放到 deptNos 中
			List<String> deptNos = new ArrayList<>();
			if (contractAlertList != null) {
				for (TEmployeeContractInfo contract : contractAlertList) {
					if (Common.isNotNull(contract) && !Common.isEmpty(contract.getDeptNo())) {
						deptNos.add(contract.getDeptNo());
					}
				}
			}
			//通过项目获取所有项目的前端客服信息
			List<ProjectCustomerServiceVo> deptInfoVos = settleDomainMapper.getServiceInfoByCodes(deptNos);
			//需要提醒的项目信息
			StringBuilder sb = new StringBuilder();
			if (!Common.isEmpty(deptInfoVos)){
				StringBuilder userNames = new StringBuilder();
				//获取所有项目对应的客服信息
				initUserNames(deptInfoVos, sb, userNames);
				Map<String, SysUser> sysUserMap = getSysUserMap(userNames);
				if (Common.isNotKong(sysUserMap)){
					SysUser user;
					for (ProjectCustomerServiceVo dept : deptInfoVos) {
						if (Common.isEmpty(dept.getCsLoginName())){
							continue;
						}
						user = sysUserMap.get(dept.getCsLoginName());
						if (!Common.isNotNull(user)){
							Common.appendStr(sb,dept.getDepartNo(),CommonConstants.DUNHAO_STRING);
						}else if (!CommonConstants.ZERO_STRING.equals(user.getLockFlag()) || !CommonConstants.ZERO_STRING.equals(user.getDelFlag())){
							//锁定标识：lockFlag != 0 都算作异常  删除标识：deleteFlag != 0 算作异常
							Common.appendStr(sb,dept.getDepartNo(),CommonConstants.DUNHAO_STRING);
						}
					}
				}
				if (sb.length() > 0){
					// 获取默认提醒人
					SysConfig sysConfig = sysConfigMapper.getSysConfigLimitByKey(EmployeeContractConstants.CONTRACT_ALERT_DEFAULT_PERSON);
					if (Common.isNotNull(sysConfig) && Common.isNotKong(sysConfig.getConfigValue2())){
						sendMessageToWx(sysConfig.getConfigValue2(),sb);
					}
				}
			}
		}catch (Exception e){
			// 记录日志或进行适当异常处理
			log.error("推送合同提醒到企业微信时发生异常", e);
		}

	}
	//发送企业微信待办
	private void sendMessageToWx(String useruserWx, StringBuilder content) {
		if (Common.isEmpty(useruserWx) || Common.isEmpty(content)) {
			return;
		}
		StringBuilder sendUser = null;
		if (Common.isNotKong(useruserWx)) {
			sendUser = new StringBuilder(useruserWx);
		}
		if (sendUser != null) {
			RestTemplate restTemplate = new RestTemplate();
			Map<String, Object> requestMap = new HashMap<>();
			Map<String, Object> textcard = new HashMap<>();
			textcard.put("title", "合同到期提醒");
			textcard.put("url", String.format(SecurityConstants.WX_GET_MESSAGE_AUTH_URL, wxConfig.getCorpid(), wxConfig.getDomainName() + "/auth/oauth/wxLogin", "66" ));
			content.append("的所属前端客服当前状态异常，请及时更新服务手册数据，跟进项目情况。");
			textcard.put("description", "项目编码为"+content);
			requestMap.put("touser", sendUser);
			requestMap.put("agentid", wxConfig.getAgentid());
			requestMap.put("msgtype", "textcard");
			requestMap.put("textcard", textcard);
			// 必须加上header说明
			if (!wxConfig.sendTextCard(restTemplate, requestMap)) {
				wxConfig.sendTextCard(restTemplate, requestMap);
			}
		}
	}
	private Map<String, SysUser> getSysUserMap(StringBuilder userNames) {
		Map<String, SysUser> sysUserMap = null;
		if (!Common.isEmpty(userNames.toString())) {
			try {
				R<SysUserListVo> res = upmsDaprUtils.getUserIdsByUserNames(userNames.toString());
				List<SysUser> users = null;
				if (Common.isNotNull(res) && Common.isNotNull(res.getData()) && Common.isNotNull(res.getData().getUserList())) {
					users = res.getData().getUserList();
				}
				if (Common.isNotKong(users)) {
					sysUserMap = users.stream().collect(Collectors.toMap(k -> k.getUsername(), v -> v));
				}
			}catch (Exception e){
				log.error("获取用户映射时发生异常", e);
			}
		}
		return sysUserMap;
	}

	private void initUserNames(List<ProjectCustomerServiceVo> deptInfoVos, StringBuilder sb, StringBuilder userNames) {
		// 使用 Set 来确保用户名唯一性
		Set<String> uniqueUserNames = new HashSet<>();

		for (ProjectCustomerServiceVo deptInfoVo : deptInfoVos) {
			if (Common.isNotNull(deptInfoVo)) {
				// 不为空后面要查询对应账号状态异常的
				if (Common.isNotNull(deptInfoVo.getCsLoginName())) {
					uniqueUserNames.add(deptInfoVo.getCsLoginName());
				} else {
					Common.appendStr(sb,deptInfoVo.getDepartNo(),CommonConstants.DUNHAO_STRING);
				}
			}
		}

		// 将去重后的用户名添加到 userNames 中
		for (String userName : uniqueUserNames) {
			Common.appendStr(userNames, userName,CommonConstants.COMMA_STRING);
		}
	}


}
