/*
 *    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.icbc.api.request.JftApiCommonOpenCardRequestV1;
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.service.TSettleDomainService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ClientNameConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.SecurityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.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.social.entity.TSocialFundInfo;
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;
import java.util.stream.Stream;

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

	private final TEmployeeContractInfoMapper  contractInfoMapper;

	private final TEmployeeInfoMapper employeeInfoMapper;

	private final TEmployeeProjectMapper projectMapper;

	private final FeedBackDetailMapper feedbackDetailMapper;

	private final FeedBackDetailService feedBackDetailService;

	private final TSettleDomainMapper settleDomainMapper;
	private final TAutoMainRelMapper tAutoMainRelMapper;

	private final TSettleDomainService tSettleDomainService;

	private final TEmployeeContractPreNewMapper contractPreNewMapper;

	private final TEmployeeContractPreHistoryMapper contractPreHistoryMapper;

	@Autowired
	TAutoMainRelMapper autoMainRelMapper;

	@Autowired
	private UpmsDaprUtils upmsDaprUtils;

	@Autowired
	private SysConfigMapper sysConfigMapper;

	@Autowired
	private WxConfig wxConfig;

	@Override
	public IPage<TEmpContractAlert> getAutoPage(Page page, ContractAlertSearchVo searchVo) {

		List<String> deptList = tAutoMainRelMapper.getAutoDeptNo();

		LambdaQueryWrapper<TEmpContractAlert> wrapper = buildQueryWrapper(searchVo);
		wrapper.isNotNull(TEmpContractAlert::getId);
		if (deptList != null && !deptList.isEmpty()) {
			wrapper.in(TEmpContractAlert::getProjectNo, deptList);
		}
		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 long getAutoContractCount(ContractAlertSearchVo searchVo) {
		List<String> deptList = tAutoMainRelMapper.getAutoDeptNo();
		LambdaQueryWrapper<TEmpContractAlert> wrapper = buildQueryWrapper(searchVo);
		wrapper.isNotNull(TEmpContractAlert::getId);
		if (deptList != null && !deptList.isEmpty()) {
			wrapper.in(TEmpContractAlert::getProjectNo, deptList);
		}
		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());
		}
		return baseMapper.selectCount(wrapper);
	}
	@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> noPageToAuto(ContractAlertSearchVo searchVo) {
		LambdaQueryWrapper<TEmpContractAlert> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		wrapper.isNotNull(TEmpContractAlert::getId);

		List<String> deptList = tAutoMainRelMapper.getAutoDeptNo();
		if (deptList != null && !deptList.isEmpty()) {
			wrapper.in(TEmpContractAlert::getProjectNo, deptList);
		}

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

	@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);
	}
	public List<TEmpContractAlertExportVo> listExport(ContractAlertSearchVo searchVo) {
		return baseMapper.listExport(searchVo);
	}
	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)
						.or().eq(TEmployeeContractInfo::getAuditStatus,CommonConstants.FOUR_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)) {
			List<TSettleDomain> projects = settleDomainMapper.selectList(Wrappers.<TSettleDomain>query().lambda()
					.eq(TSettleDomain::getDeleteFlag,CommonConstants.ZERO_STRING));
			List<TAutoMainRel> ruleInfos = autoMainRelMapper.selectList(Wrappers.<TAutoMainRel>query().lambda());
			//判空、判重，处理重复键和null值
			Map<String,TSettleDomain> projectMap= null;
			if (Common.isNotNull(projects)){
				projectMap = projects.stream()
						.filter(Objects::nonNull)
						.filter(project -> project.getDepartNo() != null)
						.collect(Collectors.toMap(
								TSettleDomain::getDepartNo,
								obj -> obj,
								(existing, replacement) -> existing // 保留第一个遇到的值
						));

			}
			//判空、判重，处理重复键和null值
			Map<String,TAutoMainRel> ruleMap = null;
			if (Common.isNotNull(ruleInfos)){
				ruleMap = ruleInfos.stream()
						.filter(Objects::nonNull)
						.filter(rule -> rule.getDeptNo() != null)
						.collect(Collectors.toMap(
								TAutoMainRel::getDeptNo,
								obj -> obj,
								(existing, replacement) -> existing // 保留第一个遇到的值
						));
			}
			Date nowDate = new Date();
			TAutoMainRel  ruleInfo = null;
			TSettleDomain project = null;
			for (TEmployeeContractInfo contract:alertList){
				if (Common.isNotNull(projectMap)){
					project = projectMap.get(contract.getDeptNo());
				}
				if (Common.isNotNull(ruleMap)){
					ruleInfo = ruleMap.get(contract.getDeptNo());
				}
				extracted(nowDate, contract,alertMap,existMap,project,ruleInfo);
			}
		}
		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());
		}
		//更新自动化的所有的合同办理状态
		baseMapper.updateProcessStatus();
		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,
						   TSettleDomain project,
						   TAutoMainRel rule
						   ) {
		TEmployeeInfo employeeInfo = employeeInfoMapper.selectById(contract.getEmpId());
		if (Common.isNotNull(employeeInfo)){
			TEmployeeProject empProject = 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(empProject)
					&& ((Common.isNotNull(empProject.getProjectStatus())
					&& empProject.getProjectStatus().intValue()== CommonConstants.ONE_INT)
					|| (
					!CommonConstants.ZERO_STRING.equals(empProject.getEmpNatrue())
							&& !CommonConstants.ONE_STRING.equals(empProject.getEmpNatrue())
							&& !CommonConstants.THREE_STRING.equals(empProject.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());
		}
		//获取项目信息，合同配置信息，初始化前端客服、续签状态、自动化标识
		//alert.setProcessStatus(CommonConstants.ZERO_INT);

		if (null != project){
			alert.setCsName(project.getCsName());
			alert.setCsLoginName(project.getCsLoginName());
		}

		//默认自动化为否
		alert.setAutoFlag(CommonConstants.ONE_STRING);
		if (null != rule){
			alert.setAutoFlag(CommonConstants.ZERO_STRING);
		}
		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);
		}
	}

	/**
	 * 员工合同续签待办简单分页查询
	 * @param tEmpContractAlert 员工合同续签待办
	 * @return
	 */
	@Override
	public IPage<ContractAlertAutoVo> getTEmpContractAlertAutoPage(Page<TEmpContractAlert> page, ContractAlertSearchVo tEmpContractAlert){
		// 如果查询条件续签状态为空默认查询 非已完成 状态数据
		if (!Common.isNotNull(tEmpContractAlert.getProcessStatusList())){
			tEmpContractAlert.setProcessStatusList(Stream.of("0","1","2","3","4","5","6","7","8","10","11").collect(Collectors.toList()));
		}
		//初始化客服的项目权限 ，管理员及SSC 全量
		initSearchVo(tEmpContractAlert);
		if (ArrayUtil.isNotEmpty(tEmpContractAlert.getStartEndTimecreate())
				&& tEmpContractAlert.getStartEndTimecreate().length == 2) {
			tEmpContractAlert.setExpectedCollectionTimeStart(tEmpContractAlert.getStartEndTimecreate()[0]);
			tEmpContractAlert.setExpectedCollectionTimeEnd(tEmpContractAlert.getStartEndTimecreate()[1]);
		}
		return baseMapper.getTEmpContractAlertAutoPage(page,tEmpContractAlert);
	}

	public void initSearchVo(ContractAlertSearchVo 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.TWO_STRING.equals(searchVo.getType()))) {
			//非管理员及SSC  走前端客服查询逻辑
			searchVo.setCsLoginName(user.getUsername());
		}
	}
	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;
	}

	@Override
	public Integer getTEmpContractAlertAutoCount(ContractAlertSearchVo tEmpContractAlert) {
		// 如果查询条件续签状态为空默认查询 非已完成 状态数据
		if (!Common.isNotNull(tEmpContractAlert.getProcessStatusList())){
			tEmpContractAlert.setProcessStatusList(Stream.of("0","1","2","3","4","5","6","7","8","10","11").collect(Collectors.toList()));
		}
		//初始化客服的项目权限 ，管理员及SSC 全量
		initSearchVo(tEmpContractAlert);
		return baseMapper.getTEmpContractAlertAutoCount(tEmpContractAlert);
	}

	public Integer geAutoExportCount(ContractAlertSearchVo tEmpContractAlert) {
		return baseMapper.getTEmpContractAlertAutoCount(tEmpContractAlert);
	}

	/**
	 * @Author fxj
	 * @Description 导出自动化续签待办
	 * @Date 17:01 2026/2/5
	 * @Param
	 * @return
	**/
	@Override
	public void listAutoExport(HttpServletResponse response, ContractAlertSearchVo searchVo) {
		if (Common.isNotNull(searchVo.getIds())){
			searchVo.setIdList(Arrays.asList(searchVo.getIds().split(CommonConstants.COMMA_STRING)));
		}
		// 如果查询条件续签状态为空默认查询 非已完成 状态数据
		if (!Common.isNotNull(searchVo.getProcessStatusList())){
			searchVo.setProcessStatusList(Stream.of("0","1","2","3","4","5","6","7","8","10","11").collect(Collectors.toList()));
		}
		//初始化客服的项目权限 ，管理员及SSC 全量
		initSearchVo(searchVo);
		if (ArrayUtil.isNotEmpty(searchVo.getStartEndTimecreate())
				&& searchVo.getStartEndTimecreate().length == 2) {
			searchVo.setExpectedCollectionTimeStart(searchVo.getStartEndTimecreate()[0]);
			searchVo.setExpectedCollectionTimeEnd(searchVo.getStartEndTimecreate()[1]);
		}

		//默认导出自动化的合同续签待办
		searchVo.setAutoFlag(CommonConstants.ZERO_STRING);
		String fileName = ArchivesConstants.EMP_AUTO_RENEWAL_RECORD + DateUtil.getThisTime()  + CommonConstants.XLSX;
		//获取要导出的列表
		List<TEmpContractAlertExportVo> list = new ArrayList<>();
		ServletOutputStream out = null;
		YifuUser user = SecurityUtils.getUser();
		String key = CacheConstants.EMP_CONTRACT_AUTO_RENEWAL_EXPORT + CommonConstants.DOWN_LINE_STRING +user.getId() ;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName  , CommonConstants.UTF8));
			//防止同一个人反复操作导出
			if (Common.isNotNull(redisUtil.get(key))) {
				out.write(CommonConstants.SOCIAL_EXPORT_CONTINUE.getBytes("GBK"));
				out.close();
				return;
			} else {
				redisUtil.set(key, user.getId(), 600L);
			}
			long count = this.geAutoExportCount(searchVo);
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, TEmpContractAlertExportVo.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				WriteSheet writeSheet;
				ExcelUtil<TEmpContractAlertExportVo> util;
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = listExport(searchVo);
					if (Common.isNotNull(list)){
						util = new ExcelUtil<>(TEmpContractAlertExportVo.class);
						for (TEmpContractAlertExportVo vo:list){
							util.convertEntity(vo,null,null,null);
						}
					}
					if (Common.isNotNull(list)){
						writeSheet = EasyExcel.writerSheet(ArchivesConstants.EMP_AUTO_RENEWAL_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_AUTO_RENEWAL_RECORD+index).build();
				excelWriter.write(list,writeSheet);
				excelWriter.finish();
			}
			if (Common.isNotNull(list)){
				list.clear();
			}
			out.flush();
		}catch (Exception e){
			redisUtil.remove(key);
			log.error("自动化合同续签待办导出执行异常" ,e);
		}finally {
			try {
				if (null != out) {
					out.close();
				}
				redisUtil.remove(key);
			} catch (IOException e) {
				redisUtil.remove(key);
				log.error("自动化合同续签待办导出执行异常", e);
			}
		}
	}

	/**
	 * @Author fxj
	 * @Description 获取合同对应的项目信息及手机号码
	 * @Date 11:48 2026/2/9
	**/
	@Override
	public EmpProjectVO getProjectInfoByContractId(String id) {
		EmpProjectVO vo = new EmpProjectVO();
		TEmployeeContractInfo contractInfo = contractInfoMapper.selectById(id);
		if (null != contractInfo){
			vo.setDeptNo(contractInfo.getDeptNo());
			vo.setDepartName(contractInfo.getSubjectDepart());
			vo.setEmpIdcard(contractInfo.getEmpIdcard());
			vo.setEmpName(contractInfo.getEmpName());
			vo.setEmpNatrue(contractInfo.getEmpNatrue());
			vo.setContractInfo(contractInfo);
			TEmployeeInfo employeeInfo = employeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
					.eq(TEmployeeInfo::getDeleteFlag,CommonConstants.ZERO_STRING)
					.eq(TEmployeeInfo::getEmpIdcard,contractInfo.getEmpIdcard()).last(CommonConstants.LAST_ONE_SQL));
			if (null != employeeInfo){
				vo.setEmpPhone(employeeInfo.getEmpPhone());
			}
			TEmployeeContractPreNew preNew = contractPreNewMapper.selectOne(Wrappers.<TEmployeeContractPreNew>lambdaQuery()
					.eq(TEmployeeContractPreNew::getId, contractInfo.getPreNewId()).last(CommonConstants.LAST_ONE_SQL));
			vo.setPreNew(preNew);
			TEmployeeContractPreHistory pre = contractPreHistoryMapper.selectOne(Wrappers.<TEmployeeContractPreHistory>lambdaQuery()
					.eq(TEmployeeContractPreHistory::getContractId, contractInfo.getId()).last(CommonConstants.LAST_ONE_SQL));
			vo.setPre(pre);
		}
		return vo;
	}

	/**
	 * @Author fxj
	 * @Description 通过合同提醒ID查询合同提醒信息、确认接收信息、新增续签合同信息
	 * @Date 16:57 2026/2/11
	**/
	@Override
	public R<EmpContractRenewVO> getAllRenewInfoById(String id) {
		if (!Common.isNotNull(id)){
			return R.failed(CommonConstants.PARAM_INFO_ERROR);
		}
		EmpContractRenewVO vo = new EmpContractRenewVO();
		TEmpContractAlert alert = this.getById(id);
		if (null == alert){
			return R.failed(CommonConstants.NO_DATA_TO_HANDLE);
		}

		if (Common.isNotNull(alert.getContractId())){
			TEmployeeContractPreNew preNew = contractPreNewMapper.selectOne(Wrappers.<TEmployeeContractPreNew>query().lambda()
					.eq(TEmployeeContractPreNew::getContractId,alert.getContractId())
					.last(CommonConstants.LAST_ONE_SQL));
			vo.setContractPreNew(preNew);
			if (null != preNew && Common.isNotNull(preNew.getId())){
				TEmployeeContractInfo contractInfo = contractInfoMapper.selectOne(Wrappers.<TEmployeeContractInfo>query().lambda()
						.eq(TEmployeeContractInfo::getPreNewId,preNew.getId())
						.eq(TEmployeeContractInfo::getDeleteFlag,CommonConstants.ZERO_STRING)
						.orderByDesc(TEmployeeContractInfo::getCreateTime)
						.last(CommonConstants.LAST_ONE_SQL));
				vo.setContractInfo(contractInfo);
				if (Common.isNotNull(preNew.getProcessStatus())){
					alert.setProcessStatus(Integer.parseInt(preNew.getProcessStatus()));
				}
			}else {
				alert.setProcessStatus(CommonConstants.ZERO_INT);
			}
		}
		vo.setEmpContractAlert( alert);
		return R.ok(vo);
	}

	@Override
	public R<List<ContractAlertConfirmVo>> getAutoRenewForConfirm(ContractAlertSearchVo tEmpContractAlert) {
		// 如果查询条件续签状态为空默认查询 非已完成 状态数据
		if (!Common.isNotNull(tEmpContractAlert.getProcessStatusList())){
			tEmpContractAlert.setProcessStatusList(Stream.of("0").collect(Collectors.toList()));
		}
		//初始化客服的项目权限 ，管理员及SSC 全量
		initSearchVo(tEmpContractAlert);
		return R.ok(baseMapper.getAutoRenewForConfirm(tEmpContractAlert));
	}

}
