/*
 *    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.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
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.pig4cloud.plugin.excel.vo.ErrorMessage;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TCustomerInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeProject;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TSettleDomain;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TCustomerInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeProjectMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmployeeLogService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmployeeProjectService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TSettleDomainService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EmployeeProjectExportVO;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EmployeeProjectVO;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.ErrorCodes;
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.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 项目档案表
 *
 * @author huyc
 * @date 2022-06-20 09:19:40
 */
@Service
@RequiredArgsConstructor
public class TEmployeeProjectServiceImpl extends ServiceImpl<TEmployeeProjectMapper, TEmployeeProject> implements TEmployeeProjectService {

	private final TEmployeeLogService tEmployeeLogService;

	private final TEmployeeInfoMapper tEmployeeInfoMapper;

	private final TSettleDomainService tSettleDomainService;

	private final TCustomerInfoMapper tCustomerInfoMapper;

	// 缓存信息
	private final CacheManager cacheManager;

	@Override
	public R addCheck(TEmployeeProject tEmployeeProject) {

		Map<String,Object> map = new HashMap<>();

		//身份证系统中是否已有
		TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
				.eq(TEmployeeInfo::getEmpIdcard, tEmployeeProject.getEmpIdcard())
				.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.STATUS_NORMAL));

		//项目下已有身份证信息
		TEmployeeProject employeeProject = this.getOne(Wrappers.<TEmployeeProject>query().lambda()
				.eq(TEmployeeProject::getEmpIdcard,tEmployeeProject.getEmpIdcard())
				.eq(TEmployeeProject::getDeptNo,tEmployeeProject.getDeptNo())
				.eq(TEmployeeProject::getDeleteFlag,CommonConstants.STATUS_NORMAL));
		if (!Common.isEmpty(employeeProject)) {

			//身份证实名认证
			if (!Common.isEmpty(tEmployeeInfo)) {
				if (!tEmployeeProject.getEmpName().equals(tEmployeeInfo.getEmpName())) {
					return R.failed("姓名和身份证不一致，请确认后再次新增");
				}
			}
			//项目状态为已减项
			if (CommonConstants.dingleDigitIntArray[1] == employeeProject.getProjectStatus()) {
				if (!Common.isEmpty(tEmployeeInfo)) {
					map.put("empProId",tEmployeeProject.getId());
					if (CommonConstants.STATUS_NORMAL.equals(tEmployeeInfo.getFileStatus())) {
						return R.ok(map, "该人员已减项，是否“复项”");
					} else {
						map.put("code","202");
						map.put("employeeId", tEmployeeInfo.getId());
						return R.ok(map, "该人员已减档减项，是否“复档复项”");
					}
				}
			}
			//状态为草稿、已审核
			if (CommonConstants.dingleDigitIntArray[0] == employeeProject.getStatus() ||
					CommonConstants.dingleDigitIntArray[1] == employeeProject.getStatus()) {
				return R.failed("人员已有该项目信息，禁止重复添加！");
			}
		} else {
			if (Common.isEmpty(tEmployeeInfo)) {
				return R.failed("该人员暂无档案信息，禁止关联项目，如要添加，请先至“在档人员”处建档");
			}
			//判断是否已经减档
			if (CommonConstants.ONE_STRING.equals(tEmployeeInfo.getFileStatus())) {
				map.put("employeeId", tEmployeeInfo.getId());
				map.put("code","203");
				return R.ok(map,"该人员在离职库已存在，是否“恢复档案”");
			}
		}
		return R.ok();
	}

	@Override
	public R reEmpInfo(JSONObject jsonObject) {
		if (Common.isNotNull(jsonObject)) {
			String empId = jsonObject.getString("empId");
			String empProId = jsonObject.getString("empProId");
			TEmployeeInfo tEmployeeInfoOld = tEmployeeInfoMapper.selectById(empId);
			TEmployeeProject tEmployeeProjectOld = this.getById(empProId);
			if (!Common.isEmpty(empId) && Common.isEmpty(empProId)) {
				//复档
				TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectById(empId);
				tEmployeeInfo.setFileStatus(CommonConstants.dingleDigitIntArray[0]);
				tEmployeeInfoMapper.updateById(tEmployeeInfo);
				tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0],empId,"",tEmployeeInfoOld,tEmployeeInfo);
			} else if (Common.isEmpty(empId) && !Common.isEmpty(empProId)) {
				//复项
				TEmployeeProject tEmployeeProject = this.getById(empProId);
				tEmployeeProject.setProjectStatus(CommonConstants.dingleDigitIntArray[0]);
				this.updateById(tEmployeeProject);
				tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1],"",empProId,tEmployeeProjectOld,tEmployeeProject);
			} else {
				//复档复项
				TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectById(empId);
				TEmployeeProject tEmployeeProject = this.getById(empProId);
				tEmployeeInfo.setFileStatus(CommonConstants.dingleDigitIntArray[0]);
				tEmployeeInfoMapper.updateById(tEmployeeInfo);
				tEmployeeProject.setProjectStatus(CommonConstants.dingleDigitIntArray[0]);
				this.updateById(tEmployeeProject);
				tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1],"",empProId,tEmployeeProjectOld,tEmployeeProject);
				tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0],empId,"",tEmployeeInfoOld,tEmployeeInfo);
			}
		} else {
			return R.failed("传参为空！");
		}
		return R.ok();
	}

	@Override
	public R deleteEmpPro(TEmployeeProject tEmployeeProject) {
		TEmployeeInfo tEmployeeInfoOld = tEmployeeInfoMapper.selectById(tEmployeeProject.getEmpId());
		TEmployeeProject tEmployeeProjectOld = this.getById(tEmployeeProject.getId());
		if (Common.isNotNull(tEmployeeProject)) {
			TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectById(tEmployeeProject.getEmpId());
			if (tEmployeeProject.getIsLeaveEmployee()== CommonConstants.dingleDigitIntArray[1]) {
				Long count = this.count(Wrappers.<TEmployeeProject>query().lambda()
						.eq(TEmployeeProject::getEmpId,tEmployeeProject.getEmpId())
						.eq(TEmployeeProject::getProjectStatus,CommonConstants.dingleDigitIntArray[0]));
				if (count.compareTo(CommonConstants.DEPT_TREE_ROOT_ID) >0) {
					return R.failed("该人员存在其他进行中的项目，禁止同步减档！");
				}
				tEmployeeInfo.setFileStatus(CommonConstants.dingleDigitIntArray[1]);
				tEmployeeInfoMapper.updateById(tEmployeeInfo);
			}
			tEmployeeProject.setProjectStatus(CommonConstants.dingleDigitIntArray[1]);
			this.updateById(tEmployeeProject);
			tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[0],tEmployeeInfo.getId(),"",tEmployeeProjectOld,tEmployeeInfo);
			tEmployeeLogService.saveModificationRecord(CommonConstants.dingleDigitIntArray[1],"",tEmployeeProject.getId(),tEmployeeInfoOld,tEmployeeProject);
			return R.ok();
		}
		return R.failed("传参为空！");
	}

	/**
	 * 新增档案操作记录
	 * @param excelVOList
	 * @param bindingResult
	 * @param
	 * @author huyc
	 * @date 2022-06-20 18:52:16
	 */
	@Override
	public R<List<ErrorMessage>> importListAdd(List<EmployeeProjectVO> excelVOList, BindingResult bindingResult, String idAdd) {
		// 通用校验获取失败的数据
		List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();
		Map<Long,ErrorMessage> errorMsgMap = new HashMap<>();
		if (Common.isNotNull(errorMessageList)){
			errorMessageList.stream().forEach(errorMessage -> errorMsgMap.put(errorMessage.getLineNum(),errorMessage));
		}

		List<TEmployeeInfo> insertList = new ArrayList();
		List<TEmployeeInfo> updateList = new ArrayList();
		List<TEmployeeProject> proInsList = new ArrayList();
		List<TEmployeeProject> proupdateList = new ArrayList();
		// 执行数据插入操作 组装 PostDto
		for (int i = 0; i < excelVOList.size(); i++) {
			EmployeeProjectVO excel = excelVOList.get(i);
			Set<String> errorMsg = new HashSet<>();

			// 已有验证报错直接下一个
			if (Common.isNotNull(errorMsgMap.get(i+2))){
				continue;
			}

			//根据身份证获取人员档案
			TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
					.eq(TEmployeeInfo::getEmpIdcard, excel.getEmpIdcard())
					.eq(TEmployeeInfo::getDeleteFlag, CommonConstants.STATUS_NORMAL));
			//根据身份证和项目编码获取项目档案
			TEmployeeProject tEmployeeProject = this.getOne(Wrappers.<TEmployeeProject>query().lambda()
					.eq(TEmployeeProject::getEmpIdcard, excel.getEmpIdcard())
					.eq(TEmployeeProject::getDeptNo, excel.getDeptNo())
					.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL));

			//不存在复档或复项的情况
			//档案无（在档人员、离职库皆无），项目无
			if (Common.isEmpty(tEmployeeInfo) && Common.isEmpty(tEmployeeProject)) {
				insertExcelPost(excel, insertList);
				insertExcelPro(excel, proInsList);
				//档案有（在档人员），项目无
			} else if (Common.isNotNull(tEmployeeInfo) && Common.isEmpty(tEmployeeProject)
					&& CommonConstants.dingleDigitIntArray[0] == tEmployeeInfo.getFileStatus()) {
				updateExcelPost(excel, updateList, tEmployeeInfo);
				insertExcelPro(excel, proInsList);
				//档案有（在档人员），项目有（草稿/已审核）；
			} else if (Common.isNotNull(tEmployeeInfo) && CommonConstants.dingleDigitIntArray[0] == tEmployeeInfo.getFileStatus()
					&& Common.isNotNull(tEmployeeProject) && CommonConstants.dingleDigitIntArray[0] == tEmployeeProject.getProjectStatus()) {
				updateExcelPost(excel, updateList, tEmployeeInfo);
				updateExcelPro(excel, proupdateList, tEmployeeProject);
			}

			//存在复档或复项的情况，允许复档复项
			if (CommonConstants.ZERO_STRING.equals(idAdd)) {
				//档案有（离职库），项目（已减档）
				if (Common.isNotNull(tEmployeeInfo) && CommonConstants.dingleDigitIntArray[1] == tEmployeeInfo.getFileStatus()
				&& Common.isNotNull(tEmployeeProject) && CommonConstants.dingleDigitIntArray[1] == tEmployeeProject.getProjectStatus()) {
					updateExcelPost(excel, updateList, tEmployeeInfo);
					updateExcelPro(excel, proupdateList, tEmployeeProject);
					//档案有（离职库），项目无；
				} else if (Common.isNotNull(tEmployeeInfo) && CommonConstants.dingleDigitIntArray[1] == tEmployeeInfo.getFileStatus()
					&& Common.isEmpty(tEmployeeProject) ) {
					updateExcelPost(excel, updateList, tEmployeeInfo);
					insertExcelPro(excel, proInsList);
					//档案有（在档人员），项目（已减档）
				} else if (Common.isNotNull(tEmployeeInfo) && CommonConstants.dingleDigitIntArray[0] == tEmployeeInfo.getFileStatus()
					&& Common.isNotNull(tEmployeeProject) && CommonConstants.dingleDigitIntArray[1] == tEmployeeProject.getProjectStatus()) {
					updateExcelPost(excel, updateList, tEmployeeInfo);
					updateExcelPro(excel, proupdateList, tEmployeeProject);
				}
				//不允许复档复项
			} else {
				//档案有（离职库），项目（已减档）
				if (Common.isNotNull(tEmployeeInfo) && CommonConstants.dingleDigitIntArray[1] == tEmployeeInfo.getFileStatus()
						&& Common.isNotNull(tEmployeeProject) && CommonConstants.dingleDigitIntArray[1] == tEmployeeProject.getProjectStatus()) {
					errorMsg.add(MsgUtils.getMessage(ErrorCodes.CHECKS_EMP_PROJECT_ERROR));
				} else if (Common.isNotNull(tEmployeeInfo) && CommonConstants.dingleDigitIntArray[1] == tEmployeeInfo.getFileStatus()
						&& Common.isEmpty(tEmployeeProject)) {
					errorMsg.add(MsgUtils.getMessage(ErrorCodes.CHECKS_REDUCE_EMP_ERROR));
					//档案有（在档人员），项目（已减档）
				} else if (Common.isNotNull(tEmployeeInfo) && CommonConstants.dingleDigitIntArray[0] == tEmployeeInfo.getFileStatus()
						&& Common.isNotNull(tEmployeeProject) && CommonConstants.dingleDigitIntArray[1] == tEmployeeProject.getProjectStatus()){
					errorMsg.add(MsgUtils.getMessage(ErrorCodes.CHECKS_REDUCE_PROJECT_ERROR));
				}
			}

			if (!CollUtil.isEmpty(errorMsg)) {
				errorMessageList.add(new ErrorMessage((long) (i + 2), errorMsg));
			}
		}

		try {
			if (insertList.size() > CommonConstants.dingleDigitIntArray[0]) {
				tEmployeeInfoMapper.insertExcelEmployeeInfo(insertList);
			}
			if (updateList.size() > CommonConstants.dingleDigitIntArray[0]) {
				tEmployeeInfoMapper.updateExcelEmployeeInfo(updateList);
			}
			if (proInsList.size() > CommonConstants.dingleDigitIntArray[0]) {
				baseMapper.insertExcelEmpProject(proInsList);
				List<String> idList = proInsList.stream().map(TEmployeeProject::getEmpIdcard).collect(Collectors.toList());
				List<TEmployeeInfo> updList = tEmployeeInfoMapper.selectList(Wrappers.<TEmployeeInfo>query().lambda().in(TEmployeeInfo::getEmpIdcard,idList));
				baseMapper.updateEmpIdById(updList);
			}
			if (proupdateList.size() > CommonConstants.dingleDigitIntArray[0]) {
				baseMapper.updateExcelEmpProject(proupdateList);
			}
		} catch (Exception e) {
			log.error("数据更新异常",e);
		}
		if (CollUtil.isNotEmpty(errorMessageList)) {
			return R.failed(errorMessageList);
		}
		return R.ok();
	}


	/**
	 * @Author huyc
	 * @Description  批量更新项目档案信息
	 * @Date 19:25 2022/6/21
	 **/
	@Override
	public R<List<ErrorMessage>> importEmpProjectUpdate(List<EmployeeProjectVO> excelVOList, BindingResult bindingResult) {
		// 通用校验获取失败的数据
		List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();
		Map<Long,ErrorMessage> errorMsgMap = new HashMap<>();
		if (Common.isNotNull(errorMessageList)){
			errorMessageList.stream().forEach(errorMessage -> errorMsgMap.put(errorMessage.getLineNum(),errorMessage));
		}

		List<TEmployeeProject> updateList = new ArrayList<>();
		// 个性化校验逻辑
		List<TEmployeeProject> list = this.list();

		Set<String> errorMsg;
		Map<String, Integer> checkCountMap = new HashMap<>();
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			// 已有验证报错直接下一个
			if (Common.isNotNull(errorMsgMap.get(i + 2))) {
				continue;
			}
			errorMsg = new HashSet<>();
			EmployeeProjectVO excel = excelVOList.get(i);

			String checkCount = excel.getEmpIdcard().concat(excel.getDeptNo());
			if (Common.isNotNull(checkCountMap.get(checkCount))) {
				errorMsgMap.put((i + 2L), new ErrorMessage("第" + (i + 2) + "行身份证号+项目编码与第" + checkCountMap.get(checkCount) + "行重复！"));
			} else {
				checkCountMap.put(checkCount, i + 2);
			}
			//根据身份证和项目编码获取项目档案
			TEmployeeProject tEmployeeProject = this.getOne(Wrappers.<TEmployeeProject>query().lambda()
					.eq(TEmployeeProject::getEmpIdcard, excel.getEmpIdcard())
					.eq(TEmployeeProject::getDeptNo, excel.getDeptNo())
					.eq(TEmployeeProject::getDeleteFlag, CommonConstants.STATUS_NORMAL));
			if (Common.isEmpty(tEmployeeProject)) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.CHECKS_EMP_EXIT_ERROR, excel.getEmpName()));
			}

			// 数据合法情况
			if (CollUtil.isEmpty(errorMsg)) {
				updateExcelPro(excel,updateList,tEmployeeProject);
			} else {
				// 数据不合法
				errorMessageList.add(new ErrorMessage((long) (i + 2), errorMsg));
			}
		}
		try {
			if (updateList.size() > CommonConstants.dingleDigitIntArray[0]) {
				baseMapper.updateExcelEmpProject(updateList);
			}
		} catch (Exception e) {
			log.error("数据更新异常",e);
		}
		if (CollUtil.isNotEmpty(errorMessageList)) {
			return R.failed(errorMessageList);
		}
		return R.ok();
	}

	/**
	 * 插入excel Post
	 */
	private void insertExcelPost(EmployeeProjectVO excel,List<TEmployeeInfo> insertList) {
		TEmployeeInfo insTEmployeeInfo = new TEmployeeInfo();
		BeanUtil.copyProperties(excel, insTEmployeeInfo);
		insTEmployeeInfo.setFileStatus(CommonConstants.dingleDigitIntArray[0]);
		insTEmployeeInfo.setDeleteFlag(CommonConstants.STATUS_NORMAL);
		insTEmployeeInfo.setStatus(CommonConstants.dingleDigitIntArray[0]);
		//TODO HUYC 员工编码生成规则
		insTEmployeeInfo.setEmpCode("");
		YifuUser user = SecurityUtils.getUser();
		insTEmployeeInfo.setCreateBy(user.getId());
		insTEmployeeInfo.setCreateName(user.getNickname());
		insertList.add(insTEmployeeInfo);
	}

	/**
	 * 插入excel Pro
	 */
	private void insertExcelPro(EmployeeProjectVO excel,List<TEmployeeProject> proInsList) {
		TEmployeeProject insTEmployeePro = new TEmployeeProject();
		BeanUtil.copyProperties(excel, insTEmployeePro);
		insTEmployeePro.setId(String.valueOf(UUID.randomUUID()).replaceAll("-",""));
		insTEmployeePro.setDeleteFlag(CommonConstants.STATUS_NORMAL);
		insTEmployeePro.setStatus(CommonConstants.dingleDigitIntArray[0]);
		//人员档案主表id先设置成空，后面更新id
		insTEmployeePro.setEmpId(CommonConstants.EMPTY_STRING);

		String str = "";
		String EmpNo = baseMapper.findEmployeeMaxOnlyNoByDepId(insTEmployeePro.getDeptNo());
		if (!Common.isEmpty(EmpNo)) {
			str = NoUtil.productionNo(EmpNo, CommonConstants.EMPLOYEE_INIT_NO_START);
		} else {
			str = insTEmployeePro.getDeptNo() + CommonConstants.EMPLOYEE_INIT_NO;
		}
		insTEmployeePro.setEmpNo(str);
		//员工编码生成规则
		insTEmployeePro.setEmpCode(this.getCode());
		YifuUser user = SecurityUtils.getUser();
		insTEmployeePro.setCreateBy(user.getId());
		insTEmployeePro.setCreateName(user.getNickname());
		proInsList.add(insTEmployeePro);
	}

	/**
	 * @param
	 * @Description: 获取员工主码
	 * @Author: hgw
	 * @Date: 2022/6/22 17:52
	 * @return: java.lang.String
	 **/
	private synchronized String getCode() {
		String nowDay = DateUtil.getThisDay();
		Cache cache = cacheManager.getCache(CacheConstants.EVERYDAY_EMP_CODE);
		Object nowNumObj = cache.get(nowDay);
		int nowNums = 1;
		if (!Common.isEmpty(nowNumObj)) {
			nowNums = (Integer) nowNumObj + 1;
		}
		cache.put(nowDay, nowNums);
		return this.getFiveNum(String.valueOf(nowNums));
	}

	/**
	 * @param nowNums 数字
	 * @Description: 获取五位字符型数字
	 * @Author: hgw
	 * @Date: 2022/6/21 17:35
	 * @return: 五位字符型数字
	 **/
	private String getFiveNum(String nowNums) {
		if (nowNums.length() >= 5) {
			return nowNums.substring(0, 5);
		}
		String[] zeroArr = {"0", "00", "000", "0000"};
		int num = 4 - nowNums.length();
		return zeroArr[num] + nowNums;
	}

	@Override
	public R<List<ErrorMessage>> batchRemoveByIds(String ids) {
		List<ErrorMessage> errorList = new ArrayList<ErrorMessage>();
		List<String> idsList = null;
		if (!Common.isEmpty(ids)) {
			idsList = Common.initStrToList(ids, CommonConstants.COMMA_STRING);
		} else {
			return R.failed("传参不能为空");
		}
		List<TEmployeeProject> list = new ArrayList<>();
		if (Common.isNotEmpty(idsList)) {
			list = baseMapper.selectList(Wrappers.<TEmployeeProject>query().lambda().in(TEmployeeProject::getId, idsList));
		}
		if(Common.isNotEmpty(list)) {
			int i = 0;
			for (TEmployeeProject delProject : list) {
				++i;
				Set<String> errorMsg = new HashSet<>();
				try {
					if (CommonConstants.dingleDigitIntArray[0] ==delProject.getStatus()) {
						delProject.setDeleteFlag(CommonConstants.ONE_STRING);
						baseMapper.updateById(delProject);
					}else {
						errorMsg.add(MsgUtils.getMessage(ErrorCodes.CHECKS_PROJECT_DELETE_ERROR));
						errorList.add(new ErrorMessage((long) i, errorMsg));
					}
				} catch (Exception e) {
					log.error("项目档案批量删除异常：" + e.getMessage());
					errorList.add(new ErrorMessage(MsgUtils.getMessage("项目档案批量删除异常：", e.getMessage())));
					return R.failed(errorList,CommonConstants.RESULT_DATA_FAIL);
				}
			}
		}
		if (CollUtil.isNotEmpty(errorList)) {
			return R.failed(errorList);
		}
		return R.ok();
	}

	@Override
	public IPage<TEmployeeProject> getTEmployeeProjectInfoPage(Page page, TEmployeeProject tEmployeeProject) {
		return baseMapper.getTEmployeeProjectInfoPage(page,tEmployeeProject);
	}


	/**
	 * @Author huyc
	 * @Description  批量导出项目档案信息
	 * @Date 10:55 2022/6/23
	 **/
	@Override
	public void listExportProject(EmployeeProjectExportVO projectDTO,String idstr, List<String> exportFields) {

		String fileName = "项目档案批量导出" + LocalDateTime.now() + ".xls";
		// 根据用户传入确定要导出的字段
		Set<String> includeColumnFiledNames = new HashSet<String>();
		for (String exportField : exportFields) {
			includeColumnFiledNames.add(exportField);
		}

		//获取要导出的列表
		List<EmployeeProjectExportVO> list = new ArrayList<>();

		//获取记录
		list = gettEmpProInfoExportVos(idstr, projectDTO);
		try {
			if (list.size()>0) {
				// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
				EasyExcel.write(fileName, EmployeeProjectExportVO.class).includeColumnFiledNames(includeColumnFiledNames).sheet("项目档案")
						.doWrite(list);
			}
		}catch (Exception e){
			log.error("error:" ,e);
		}
	}

	/**
	 * @param employeeInfo
	 * @Description: 新增项目档案
	 * @Author: huyc
	 * @Date: 2022/6/23 18:06
	 **/
	@Override
	public void saveEmployeeProjectInfo(TEmployeeInfo employeeInfo) {
		TEmployeeProject tEmployeeProject = new TEmployeeProject();
		tEmployeeProject.setEmpId(employeeInfo.getId());
		tEmployeeProject.setEmpCode(this.getCode());
		tEmployeeProject.setEmpNatrue(employeeInfo.getEmpNatrue());
		tEmployeeProject.setEmpName(employeeInfo.getEmpName());
		tEmployeeProject.setEmpIdcard(employeeInfo.getEmpIdcard());
		tEmployeeProject.setPost(employeeInfo.getPost());
		String str = "";
		String EmpNo = baseMapper.findEmployeeMaxOnlyNoByDepId(employeeInfo.getDeptNo());
		if (!Common.isEmpty(EmpNo)) {
			str = NoUtil.productionNo(EmpNo, CommonConstants.EMPLOYEE_INIT_NO_START);
		} else {
			str = employeeInfo.getDeptNo() + CommonConstants.EMPLOYEE_INIT_NO;
		}
		tEmployeeProject.setEmpNo(str);
		tEmployeeProject.setDeptNo(employeeInfo.getDeptNo());

		TSettleDomain tSettleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
				.eq(TSettleDomain::getDepartNo,employeeInfo.getDeptNo()).eq(TSettleDomain::getDeleteFlag,CommonConstants.STATUS_NORMAL));
		if (Common.isNotNull(tSettleDomain)) {
			tEmployeeProject.setDeptId(tSettleDomain.getId());
			tEmployeeProject.setDeptName(tSettleDomain.getDepartName());
			TCustomerInfo tCustomerInfo = tCustomerInfoMapper.selectById(tSettleDomain.getCustomerId());
			if(Common.isNotNull(tCustomerInfo)) {;
				tEmployeeProject.setUnitId(tCustomerInfo.getId());
				tEmployeeProject.setUnitNo(tCustomerInfo.getCustomerCode());
				tEmployeeProject.setUnitName(tCustomerInfo.getCustomerName());
			}
		}
		baseMapper.insert(tEmployeeProject);
	}

	/**
	 * 获取导出的项目档案列表
	 */
	private List<EmployeeProjectExportVO> gettEmpProInfoExportVos(String idstr,EmployeeProjectExportVO projectDTO) {
		List<EmployeeProjectExportVO> list;
		if (!Common.isEmpty(idstr)) {
			projectDTO.setIdList(Common.initStrToList(idstr, CommonConstants.COMMA_STRING));
		}
		list = baseMapper.getTEmployeeProjectExportPage(projectDTO);
		return list;
	}

	/**
	 * 更新人员档案
	 */
	private void updateExcelPost(EmployeeProjectVO excel,List<TEmployeeInfo> updateList,TEmployeeInfo tEmployeeInfo) {
		BeanUtil.copyProperties(excel, tEmployeeInfo);
		YifuUser user = SecurityUtils.getUser();
		tEmployeeInfo.setUpdateBy(user.getId());
		updateList.add(tEmployeeInfo);
	}

	/**
	 * 更新项目档案
	 */
	private void updateExcelPro(EmployeeProjectVO excel,List<TEmployeeProject> proupdateList,TEmployeeProject tEmployeeProject) {
		BeanUtil.copyProperties(excel, tEmployeeProject);
		YifuUser user = SecurityUtils.getUser();
		tEmployeeProject.setUpdateBy(user.getId());
		proupdateList.add(tEmployeeProject);
	}

	@Override
	public List<TEmployeeProject> getListByEmpId(String empId, int projectStatus) {
		TEmployeeProject project = new TEmployeeProject();
		project.setEmpId(empId);
		if (projectStatus == 0) {
			project.setProjectStatus(CommonConstants.ZERO_INT);
		}
		project.setDeleteFlag(CommonConstants.STATUS_NORMAL);
		return this.list(Wrappers.query(project));
	}

	@Override
	public List<TEmployeeProject> getListByEmpIdAndDeptNo(String empId, String deptNo) {
		TEmployeeProject project = new TEmployeeProject();
		project.setEmpId(empId);
		project.setDeptNo(deptNo);
		project.setDeleteFlag(CommonConstants.STATUS_NORMAL);
		return this.list(Wrappers.query(project));
	}

	@Override
	public R getItemByEmpNo(String empIdcard, String empNo) {
		TSettleDomain tSettleDomain = tSettleDomainService.getOne(Wrappers.<TSettleDomain>query().lambda()
				.eq(TSettleDomain::getDepartNo,empNo));
		TEmployeeInfo tEmployeeInfo = tEmployeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
				.eq(TEmployeeInfo::getEmpIdcard,empIdcard));
		Map<String,Object> map = new HashMap<>();
		String empCode = "";
		if (Common.isNotNull(tEmployeeInfo)) {
			empCode = tEmployeeInfo.getEmpCode();
		}
		String customerName = "";
		if (Common.isNotNull(tSettleDomain)) {
			TCustomerInfo tCustomerInfo = tCustomerInfoMapper.selectOne(Wrappers.<TCustomerInfo>query().lambda()
					.eq(TCustomerInfo::getId,tSettleDomain.getCustomerId()));
			if (Common.isNotNull(tCustomerInfo)) {
				customerName = tCustomerInfo.getCustomerName();
			}
		}
		map.put("empCode",empCode);
		map.put("itemInfo",tSettleDomain);
		map.put("customerName",customerName);
		return R.ok(map);
	}

}
