/*
 *    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.salary.service.impl;

import cn.hutool.core.bean.BeanUtil;
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.check.entity.TCheckBankNo;
import com.yifu.cloud.plus.v1.check.entity.TCheckIdCard;
import com.yifu.cloud.plus.v1.check.entity.TCheckMobile;
import com.yifu.cloud.plus.v1.check.vo.CheckBankNoVo;
import com.yifu.cloud.plus.v1.check.vo.CheckBatchVo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TSettleDomain;
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.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.config.DaprCheckProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryAccountItem;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryEmpModLog;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryEmployee;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TSalaryAccountMapper;
import com.yifu.cloud.plus.v1.yifu.salary.mapper.TSalaryEmployeeMapper;
import com.yifu.cloud.plus.v1.yifu.salary.service.TBankSetService;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSalaryEmpModLogService;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSalaryEmployeeService;
import com.yifu.cloud.plus.v1.yifu.salary.util.SalaryConstants;
import com.yifu.cloud.plus.v1.yifu.salary.vo.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 薪酬人员表
 *
 * @author hgw
 * @date 2022-08-05 11:40:14
 */
@Log4j2
@Service
@EnableConfigurationProperties({DaprCheckProperties.class})
public class TSalaryEmployeeServiceImpl extends ServiceImpl<TSalaryEmployeeMapper, TSalaryEmployee> implements TSalaryEmployeeService {

	@Autowired
	private DaprCheckProperties checkProperties;

	@Autowired
	private TBankSetService tBankSetService;

	@Autowired
	private TSalaryEmpModLogService logService;
	@Autowired
	private TSalaryAccountMapper salaryAccountMapper;
	/**
	 * 薪酬人员表简单分页查询
	 *
	 * @param tSalaryEmployee 薪酬人员表
	 * @return
	 */
	@Override
	public IPage<TSalaryEmployee> getTSalaryEmployeePage(Page<TSalaryEmployee> page, TSalaryEmployeeSearchVo tSalaryEmployee) {
		return baseMapper.getTSalaryEmployeePage(page, tSalaryEmployee);
	}

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

	@Override
	public List<TSalaryEmployeeExportVo> noPageDiy(TSalaryEmployeeSearchVo searchVo) {
		return baseMapper.noPageDiy(searchVo,Common.getList(searchVo.getIds()));
	}

	@Override
	public TSalaryAccountItem selectByIdcard(String idCard,String nowMonth) {
		return  baseMapper.selectByIdCard(idCard,nowMonth);
	}

	private Long noPageCountDiy(TSalaryEmployeeSearchVo searchVo) {
		LambdaQueryWrapper<TSalaryEmployee> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)) {
			wrapper.in(TSalaryEmployee::getId, idList);
		}
		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.selectCount(wrapper);
	}

	private LambdaQueryWrapper buildQueryWrapper(TSalaryEmployeeSearchVo entity) {
		LambdaQueryWrapper<TSalaryEmployee> wrapper = Wrappers.lambdaQuery();
		wrapper.ne(TSalaryEmployee::getId,CommonConstants.ZERO_STRING);
		if (ArrayUtil.isNotEmpty(entity.getCreateTimes())) {
			wrapper.ge(TSalaryEmployee::getCreateTime, entity.getCreateTimes()[0])
					.le(TSalaryEmployee::getCreateTime,
							entity.getCreateTimes()[1]);
		}
		if (Common.isNotNull(entity.getCreateName())) {
			wrapper.eq(TSalaryEmployee::getCreateName, entity.getCreateName());
		}
		if (Common.isNotNull(entity.getEmpName())) {
			wrapper.eq(TSalaryEmployee::getEmpName, entity.getEmpName());
		}
		if (Common.isNotNull(entity.getEmpIdcard())) {
			wrapper.eq(TSalaryEmployee::getEmpIdcard, entity.getEmpIdcard());
		}
		return wrapper;
	}

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

				@Override
				public void invoke(TSalaryEmployeeVo 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());
					importTSalaryEmployee(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 importTSalaryEmployee(List<TSalaryEmployeeVo> excelVOList, List<ErrorMessage> errorMessageList) {
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			TSalaryEmployeeVo excel = excelVOList.get(i);
			// 数据合法情况

			// 插入
			insertExcel(excel);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS));
		}
	}

	/**
	 * 插入excel bad record
	 */
	private void insertExcel(TSalaryEmployeeVo excel) {
		TSalaryEmployee insert = new TSalaryEmployee();
		BeanUtil.copyProperties(excel, insert);
		this.save(insert);
	}

	/**
	 * @param notLabour 是：非劳务费人员。 否：劳务费，不保存
	 * @param employee
	 * @Description: 新建薪资员工，返回值为null，保存成功。其余都是失败原因
	 * @Author: hgw
	 * @Date: 2022/8/17 16:17
	 * @return: java.lang.String
	 **/
	@Override
	public String saveNewSalaryEmployee(boolean notLabour,TSalaryEmployee employee) {
		String pre = this.checkNewEmpBankAndPhone(employee, false);
		if (pre != null) {return pre;}
		if (notLabour) {
			this.save(employee);
		}
		return null;
	}

	@Override
	public String saveNewEmployeeList(List<TSalaryEmployee> saveNewEmpList, List<ErrorMessage> errorList) {
		if (saveNewEmpList != null && !saveNewEmpList.isEmpty()) {
			// 银行卡
			List<TCheckBankNo> bankList = new ArrayList<>();
			List<String> phoneList = new ArrayList<>();
			TCheckBankNo checkBankNo;
			for (TSalaryEmployee employee : saveNewEmpList) {
				// cyx-mvp1.7.0：调整 代发户的新员工也校验银行卡号
				if (Common.isNotNull(employee.getBankNo())
						//&& (Common.isEmpty(employee.getIssueStatus()) || employee.getIssueStatus().equals(CommonConstants.ZERO_INT))
						&& (Common.isEmpty(employee.getSalaryGiveTime())
						|| CommonConstants.ZERO_STRING.equals(employee.getSalaryGiveTime())
						|| (CommonConstants.ONE_STRING.equals(employee.getSalaryGiveTime()) && Common.isNotNull(employee.getBankNo())))) {
					checkBankNo = new TCheckBankNo();
					checkBankNo.setName(employee.getEmpName());
					checkBankNo.setBankNo(employee.getBankNo());
					bankList.add(checkBankNo);
				}
				if (Common.isNotNull(employee.getEmpPhone())) {
					phoneList.add(employee.getEmpPhone());
				}

			}
			// 批量校验 卡号与手机号
			Map<String, Boolean> bankMap = new HashMap<>();
			Map<String, Boolean> phoneMap = new HashMap<>();
			if (!bankList.isEmpty()) {
				R<CheckBatchVo> checkListR = HttpDaprUtil.invokeMethodPost(checkProperties.getAppUrl(), checkProperties.getAppId()
						, "/tcheckbankno/inner/checkBankNoBatch", bankList, CheckBatchVo.class, SecurityConstants.FROM_IN);
				if (checkListR != null && checkListR.getData() != null) {
					bankMap = checkListR.getData().getCheckMap();
				}
			}
			if (!phoneList.isEmpty()) {
				R<CheckBatchVo> phoneR = HttpDaprUtil.invokeMethodPost(checkProperties.getAppUrl(), checkProperties.getAppId()
						, "/tcheckmobile/inner/checkMobileBatch", phoneList, CheckBatchVo.class, SecurityConstants.FROM_IN);
				if (phoneR != null && phoneR.getData() != null) {
					phoneMap = phoneR.getData().getCheckMap();
				}
			}

			boolean isFalse = false;
			for (TSalaryEmployee employee : saveNewEmpList) {
				// cyx-mvp1.7.0：调整 代发户的新员工也校验银行卡号
				if (Common.isNotNull(employee.getBankNo())
						//&& (Common.isEmpty(employee.getIssueStatus()) || employee.getIssueStatus().equals(CommonConstants.ZERO_INT))
						&& (Common.isEmpty(employee.getSalaryGiveTime())
							|| CommonConstants.ZERO_STRING.equals(employee.getSalaryGiveTime())
							|| (CommonConstants.ONE_STRING.equals(employee.getSalaryGiveTime()) && Common.isNotNull(employee.getBankNo())))) {
					if (bankMap.get(employee.getBankNo()) != null) {
						// log.info("走到了》》》》saveNewEmpList---校验银行卡号>>{}",bankMap.get(employee.getBankNo()));
						if (Boolean.FALSE.equals(bankMap.get(employee.getBankNo()))) {
							errorList.add(new ErrorMessage((employee.getLineNums()  ), "第" + (employee.getLineNums()  ) + "行：该员工新建失败：【姓名与卡号验证：认证不一致】"));
							isFalse = true;
						}
					} else {
						errorList.add(new ErrorMessage((employee.getLineNums()  ), "第" + (employee.getLineNums()  ) + "行：该员工新建失败：【姓名与卡号验证：" + SalaryConstants.CHECK_NO_RESPONSE + "】"));
						isFalse = true;
					}
				}
				if (phoneMap.get(employee.getEmpPhone()) != null) {
					if (Boolean.FALSE.equals(phoneMap.get(employee.getEmpPhone()))) {
						errorList.add(new ErrorMessage((employee.getLineNums()  ), "第" + (employee.getLineNums()  ) + "行：该员工新建失败：【手机号验证：手机号错误】"));
						isFalse = true;
					}
				} else {
					errorList.add(new ErrorMessage((employee.getLineNums()  ), "第" + (employee.getLineNums()  ) + "行：该员工新建失败：【手机号验证：" + SalaryConstants.CHECK_NO_RESPONSE + "】"));
					isFalse = true;
				}
			}
			if (isFalse) {
				return null;
			}
			doSetIntegerArea(saveNewEmpList);
			this.saveBatch(saveNewEmpList);
		}
		return null;
	}

	@Override
	public String updateEmployeeBankList(List<TSalaryEmployee> updateEmployeeBankList
			, Map<String, TSalaryEmployee> updateEmpBankMap, List<ErrorMessage> errorList) {
		if (updateEmployeeBankList != null && !updateEmployeeBankList.isEmpty()) {
			// 银行卡
			List<TCheckBankNo> bankList = new ArrayList<>();
			TCheckBankNo checkBankNo;
			for (TSalaryEmployee employee : updateEmployeeBankList) {
				// cyx-mvp1.7.0：调整 代发户的新员工也校验银行卡号
				if (Common.isNotNull(employee.getBankNo())
						//&& (Common.isEmpty(employee.getIssueStatus()) || employee.getIssueStatus().equals(CommonConstants.ZERO_INT))
				) {
					checkBankNo = new TCheckBankNo();
					checkBankNo.setName(employee.getEmpName());
					checkBankNo.setBankNo(employee.getBankNo());
					bankList.add(checkBankNo);
				}
			}
			// 批量校验 卡号与手机号
			Map<String, Boolean> bankMap = new HashMap<>();
			if (!bankList.isEmpty()) {
				R<CheckBatchVo> checkListR = HttpDaprUtil.invokeMethodPost(checkProperties.getAppUrl(), checkProperties.getAppId()
						, "/tcheckbankno/inner/checkBankNoBatch", bankList, CheckBatchVo.class, SecurityConstants.FROM_IN);
				if (checkListR != null && checkListR.getData() != null) {
					bankMap = checkListR.getData().getCheckMap();
				}
			}
			boolean isFalse = false;
			String areaProvince;
			String areaCity;
			TSalaryEmployee oldEmp;
			ExcelUtil<TSalaryEmployee> util = new ExcelUtil<>(TSalaryEmployee.class);
			TSalaryEmpModLog empLog;
			List<TSalaryEmpModLog> saveLogList = new ArrayList<>();
			for (TSalaryEmployee employee : updateEmployeeBankList) {
				if (Common.isNotNull(employee.getBankNo())) {
					// cyx-mvp1.7.0：调整 代发户的新员工也校验银行卡号
						//if (Common.isEmpty(employee.getIssueStatus()) || employee.getIssueStatus().equals(CommonConstants.ZERO_INT)) {
							oldEmp = updateEmpBankMap.get(employee.getEmpIdcard());
							if (oldEmp != null) {
								if (Common.isNotNull(employee.getBankProvince())) {
									areaProvince = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + employee.getBankProvince().trim());
									if (Common.isNotNull(areaProvince)) {
										if (Common.isNotNull(employee.getBankCity())) {
											areaCity = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + employee.getBankCity().trim()
													+ CommonConstants.DOWN_LINE_STRING + employee.getBankProvince().trim());
											if (Common.isNotNull(areaCity)) {
												employee.setBankCity(areaCity);
											} else {
												errorList.add(new ErrorMessage((employee.getLineNums()), "第" + (employee.getLineNums()) + "行：该员工更新失败：【" + SalaryConstants.CITY_ERROR + "】"));
												isFalse = true;
											}
										}
										employee.setBankProvince(areaProvince);
									} else {
										errorList.add(new ErrorMessage((employee.getLineNums()), "第" + (employee.getLineNums()) + "行：该员工更新失败：【" + SalaryConstants.PROVINCE_ERROR + "】"));
										isFalse = true;
									}
								}
								// log.info("走到了》》》》updateEmployeeBank校验银行卡号>>{}",bankMap.get(employee.getBankNo()));
								// log.info("走到了》》》》updateEmployeeBank校验银行卡号>>employee>>{}",employee.toString());
								// 有变更才更新
								if ((Common.isNotNull(employee.getBankNo()) && !employee.getBankNo().equals(oldEmp.getBankNo()))
										|| (Common.isNotNull(employee.getBankProvince()) && !employee.getBankProvince().equals(oldEmp.getBankProvince()))
										|| (Common.isNotNull(employee.getBankCity()) && !employee.getBankCity().equals(oldEmp.getBankCity()))
										|| (Common.isNotNull(employee.getBankName()) && !employee.getBankName().equals(oldEmp.getBankName()))
										|| (Common.isNotNull(employee.getBankSubName()) && !employee.getBankSubName().equals(oldEmp.getBankSubName()))
								) {
									if (bankMap.get(employee.getBankNo()) != null) {
										if (Boolean.FALSE.equals(bankMap.get(employee.getBankNo()))) {
											errorList.add(new ErrorMessage((employee.getLineNums()), "第" + (employee.getLineNums()) + "行：该员工更新失败：【姓名与卡号验证：认证不一致】"));
											isFalse = true;
										}
									} else {
										errorList.add(new ErrorMessage((employee.getLineNums()), "第" + (employee.getLineNums()) + "行：该员工更新失败：【姓名与卡号验证：" + SalaryConstants.CHECK_NO_RESPONSE + "】"));
										isFalse = true;
									}
									if (!isFalse) {
										empLog = logService.checkEditToLog(employee, oldEmp, CommonConstants.FOUR_STRING, employee.getCreateName(), util);
										if (empLog != null) {
											saveLogList.add(empLog);
										}
									}

								}
							}
						//}
//						else if (employee.getIssueStatus().equals(CommonConstants.ONE_INT) && Common.isNotNull(employee.getBankProvince())) {
//							areaProvince = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + employee.getBankProvince().trim());
//							if (Common.isNotNull(areaProvince)) {
//								if (Common.isNotNull(employee.getBankCity())) {
//									areaCity = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + employee.getBankCity().trim()
//											+ CommonConstants.DOWN_LINE_STRING + employee.getBankProvince().trim());
//									if (Common.isNotNull(areaCity)) {
//										employee.setBankCity(areaCity);
//									} else {
//										employee.setBankCity(null);
//									}
//								}
//								employee.setBankProvince(areaProvince);
//							} else {
//								employee.setBankProvince(null);
//							}
//						}
				}
			}
			if (isFalse) {
				return null;
			}
			doSetIntegerArea(updateEmployeeBankList);
			// 更新人员
			this.updateBatchById(updateEmployeeBankList);
			// 新增日志
			logService.saveBatch(saveLogList);
		}
		return null;
	}

	// 批量处理字段为汉字的区域
	private void doSetIntegerArea(List<TSalaryEmployee> updateEmpList) {
		for (TSalaryEmployee employee : updateEmpList) {
			doSetIntegerAreaByEmp(employee);
		}
	}

	// 批量处理字段为汉字的区域-单个员工
	private void doSetIntegerAreaByEmp(TSalaryEmployee employee) {
		String areaProvince;
		String areaCity;
		if (Common.isNotNull(employee.getBankProvince()) && regNumber(employee.getBankProvince())) {
			areaProvince = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + employee.getBankProvince().trim());
			if (Common.isNotNull(areaProvince)) {
				if (Common.isNotNull(employee.getBankCity()) && regNumber(employee.getBankCity())) {
					areaCity = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + employee.getBankCity().trim()
							+ CommonConstants.DOWN_LINE_STRING + employee.getBankProvince().trim());
					if (Common.isNotNull(areaCity)) {
						employee.setBankCity(areaCity);
					}
				}
				employee.setBankProvince(areaProvince);
			}
		}
	}

	private static boolean regNumber(String content) {
		boolean flag = true;
		Pattern p = Pattern.compile("^[0-9]*$");
		Matcher m = p.matcher(content);
		if (m.matches()) {
			flag = false;
		}
		return flag;
	}

	/**
	 * @param employee
	 * @Description: 校验卡号与手机号
	 * @Author: hgw
	 * @Date: 2023/1/17 16:27
	 * @return: java.lang.String
	 **/
	private String checkNewEmpBankAndPhone(TSalaryEmployee employee, boolean isCheckIdCard) {
		if (Common.isNotNull(employee.getEmpName()) && Common.isNotNull(employee.getEmpIdcard())) {
			// 身份证校验（薪资人员导入才需要）
			if (isCheckIdCard) {
				// 调用校验服务
				String pre = "姓名与身份证验证：";
				TCheckIdCard checkIdCard = new TCheckIdCard();
				checkIdCard.setName(employee.getEmpName());
				checkIdCard.setIdCard(employee.getEmpIdcard());
				R<TCheckIdCard> checkListR = HttpDaprUtil.invokeMethodPost(checkProperties.getAppUrl(), checkProperties.getAppId()
						, "/tcheckidcard/inner/checkIdCardSingle", checkIdCard, TCheckIdCard.class, SecurityConstants.FROM_IN);
				if (checkListR != null && checkListR.getData() != null) {
					TCheckIdCard check = checkListR.getData();
					if (check == null || Common.isEmpty(check.getIsTrue())) {
						return pre + "校验服务器未返回，请联系管理员！";
					} else if (check.getIsTrue() == CommonConstants.ZERO_INT) {
						return pre + check.getReason();
					}
				} else {
					return pre + "校验服务器未返回，请联系管理员！";
				}
			}
			// 银行卡
			// 代发户的，不校验卡号，下次使用的时候校验卡号
			// cyx-mvp1.7.0： 本次是代发户，是新员工，也要要校验银行卡(但是薪酬导入类型是劳务费才会走到这里)
			if (Common.isNotNull(employee.getBankNo())) {
			//if (Common.isNotNull(employee.getBankNo()) && (Common.isEmpty(employee.getIssueStatus()) || employee.getIssueStatus().equals(CommonConstants.ZERO_INT))) {
				// 调用校验服务
				TCheckBankNo checkBankNo = new TCheckBankNo();
				checkBankNo.setName(employee.getEmpName());
				checkBankNo.setBankNo(employee.getBankNo());
				R<CheckBankNoVo> checkListR = HttpDaprUtil.invokeMethodPost(checkProperties.getAppUrl(), checkProperties.getAppId()
						, "/tcheckbankno/inner/checkBankNo", checkBankNo, CheckBankNoVo.class, SecurityConstants.FROM_IN);
				String pre = "姓名与卡号验证：";
				if (checkListR != null && checkListR.getData() != null) {
					CheckBankNoVo vo = checkListR.getData();
					TCheckBankNo check = (null == vo.getRes()) ? null : vo.getRes().getData();
					if (Common.isEmpty(vo)) {
						return pre + SalaryConstants.CHECK_NO_RESPONSE;
					} else if (!CommonConstants.SUCCESS.equals(vo.getRes().getCode())) {
						return pre + vo.getRes().getMsg();
					} else if (check != null && !check.getResult().equals(CommonConstants.ZERO_ONE)) {
						return pre + check.getRemark();
					}
				} else {
					return pre + SalaryConstants.CHECK_NO_RESPONSE;
				}
			}
			// 手机号
			if (Common.isNotNull(employee.getEmpPhone())) {
				// 调用校验服务-校验手机号
				TCheckMobile checkMobile = new TCheckMobile();
				checkMobile.setMobile(employee.getEmpPhone());
				R<TCheckMobile> a = HttpDaprUtil.invokeMethodPost(checkProperties.getAppUrl(), checkProperties.getAppId()
						, "/tcheckmobile/inner/checkOneMobile", checkMobile, TCheckMobile.class, SecurityConstants.FROM_IN);
				String pre = "手机号验证：";
				if (a != null && a.getData() != null) {
					checkMobile = a.getData();
					if (checkMobile != null && Common.isNotNull(checkMobile.getStatus())) {
						if (!CommonConstants.ONE_STRING.equals(checkMobile.getStatus())) {
							return pre + checkMobile.getMessage();
						}
					} else {
						return pre + "校验服务未找到手机号，请联系管理员！";
					}
				}
			}
		}
		return null;
	}

	@Override
	public R<List<ErrorMessage>> batchUpdateSalaryEmployee(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<TSalaryEmployeeUpdateVo> util1 = new ExcelUtil<>(TSalaryEmployeeUpdateVo.class);
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {

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

				@Override
				public void invoke(TSalaryEmployeeUpdateVo 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());
					if (!cachedDataList.isEmpty()) {
						updateTSalaryEmployee(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);
		}
		boolean isTrue = true;
		for (ErrorMessage message : errorMessageList) {
			if (!CommonConstants.SAVE_SUCCESS.equals(message.getMessage())) {
				isTrue = false;
				break;
			}
		}
		if (isTrue) {
			return R.ok();
		} else {
			return R.ok(errorMessageList);
		}
	}

	/**
	 * @Description: 批量更新
	 * @Author: hgw
	 * @Date: 2022/10/10 17:56
	 * @return: void
	 **/
	public void updateTSalaryEmployee(List<TSalaryEmployeeUpdateVo> excelVOList, List<ErrorMessage> errorMessageList) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)){
			errorMessageList.add(new ErrorMessage(CommonConstants.ONE_INT_NEGATE, CommonConstants.USER_FAIL));
			return;
		}
		/// 个性化校验逻辑
		TSalaryEmployeeUpdateVo excel;
		List<String> idCardList = new ArrayList<>();
		// 执行数据插入操作 组装
		for (TSalaryEmployeeUpdateVo vo : excelVOList) {
			idCardList.add(vo.getEmpIdcard());
		}
		List<TSalaryEmployee> empList = baseMapper.getListByIdCard(idCardList);
		// 人员Map
		Map<String, TSalaryEmployee> empMap = new HashMap<>();
		for (TSalaryEmployee e : empList) {
			empMap.put(e.getEmpIdcard(), e);
		}
		TSalaryEmployee emp;
		// 开户行省市的区域暂存
		String areaStr;
		boolean curTaxMonth;
		Map<String, String> bankMap = tBankSetService.getBankMap(null);
		ExcelUtil<TSalaryEmployee> util = new ExcelUtil<>(TSalaryEmployee.class);
		TSalaryEmployee old =null;
		for (int i = 0; i < excelVOList.size(); i++) {
			excel = excelVOList.get(i);
			if (excel != null) {
				if (Common.isNotNull(excel.getEmpIdcard())) {
					emp = empMap.get(excel.getEmpIdcard());
					old = new TSalaryEmployee();
					if (Common.isNotNull(emp) && Common.isNotNull(emp.getId())) {
						BeanUtil.copyProperties(emp,old);
						curTaxMonth = false;
						if (Common.isNotNull(emp.getTaxMonth()) && Common.isNotNull(excel.getTaxMonth()) && emp.getTaxMonth().length()==6) {
							curTaxMonth = true;
						} else if (Common.isNotNull(excel.getTaxMonth())) {
							emp.setTaxMonth(excel.getTaxMonth());
						}
						if (Common.isNotNull(excel.getBankName())) {
							if (bankMap.get(excel.getBankName()) == null) {
								errorMessageList.add(new ErrorMessage(excel.getRowIndex(), SalaryConstants.BANK_NAME_ERROR));
								continue;
							}
							emp.setBankName(excel.getBankName());
						}
						if (Common.isNotNull(excel.getBankSubName())) {
							emp.setBankSubName(excel.getBankSubName());
						}
						if (Common.isNotNull(excel.getBankProvince())) {
							areaStr = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getBankProvince().trim());
							if (Common.isNotNull(areaStr)) {
								emp.setBankProvince(areaStr);
								if (Common.isNotNull(excel.getBankCity())) {
									areaStr = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getBankCity().trim()
											+ CommonConstants.DOWN_LINE_STRING + excel.getBankProvince().trim());
									if (Common.isNotNull(areaStr)) {
										emp.setBankCity(areaStr);
									} else {
										errorMessageList.add(new ErrorMessage(excel.getRowIndex(), SalaryConstants.CITY_ERROR));
										continue;
									}
								}
							} else {
								errorMessageList.add(new ErrorMessage(excel.getRowIndex(), SalaryConstants.PROVINCE_ERROR));
								continue;
							}
						}
						if (Common.isNotNull(excel.getBankNo())) {
							emp.setBankNo(excel.getBankNo());
						}
						if (Common.isNotNull(excel.getEmpPhone())) {
							emp.setEmpPhone(excel.getEmpPhone());
						}
						if (Common.isNotNull(excel.getEmpName())) {
							emp.setEmpName(excel.getEmpName());
						}
						// 2024-2-4 16:05:56 hgw 银行卡需要校验
						String pre = getCheckBankNo(emp, old);
						if (pre != null) {
							errorMessageList.add(new ErrorMessage(excel.getRowIndex(), pre));
							continue;
						}
						// 变更日志 fxj 2023-10-24
						logService.initModLog(old,emp,CommonConstants.ONE_STRING,user.getNickname(),util);
						baseMapper.updateById(emp);
						if (curTaxMonth) {
							errorMessageList.add(new ErrorMessage(excel.getRowIndex(), SalaryConstants.CUR_TAX_INFO));
						} else {
							errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS));
						}
					} else {
						errorMessageList.add(new ErrorMessage(excel.getRowIndex(), SalaryConstants.NOT_HAVE_EMP));
					}
				} else {
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(), SalaryConstants.ID_CARD_MUST));
				}
			} else {
				errorMessageList.add(new ErrorMessage(CommonConstants.ZERO_INT, SalaryConstants.DATA_MUST));
			}
		}
	}

	@Override
	public TSalaryEmployee getByEmpIdCard(String empIdCard) {
		return baseMapper.getByEmpIdCard(empIdCard);
	}

	@Override
	public Map<String, TSalaryEmployee> getByEmpIdCardList(List<String> idCardList) {
		List<TSalaryEmployee> empList = baseMapper.getListByIdCard(idCardList);
		Map<String, TSalaryEmployee> map = new HashMap<>();
		if (empList != null && !empList.isEmpty()) {
			for (TSalaryEmployee e : empList) {
				map.put(e.getEmpIdcard(), e);
			}
		}
		return map;
	}

	/**
	 * @param employee
	 * @Description: 代发户的，下次校验银行卡，同时变更校验flag
	 * @Author: hgw
	 * @Date: 2023/1/10 18:10
	 * @return: boolean ： true：已验证通过；false：银行卡校验失败
	 **/
	@Override
	public boolean checkBankInfo(TSalaryEmployee employee) {
		// 调用校验服务
		TCheckBankNo checkIdCard = new TCheckBankNo();
		checkIdCard.setName(employee.getEmpName());
		checkIdCard.setBankNo(employee.getBankNo());
		R<CheckBankNoVo> checkListR = HttpDaprUtil.invokeMethodPost(checkProperties.getAppUrl(), checkProperties.getAppId()
				, "/tcheckbankno/inner/checkBankNo", checkIdCard, CheckBankNoVo.class, SecurityConstants.FROM_IN);
		if (checkListR != null && checkListR.getData() != null) {
			CheckBankNoVo vo = checkListR.getData();
			TCheckBankNo check = (null == vo.getRes()) ? null : vo.getRes().getData();
			if (check != null && check.getResult().equals(CommonConstants.ZERO_ONE)) {
				employee.setIssueStatus(CommonConstants.ZERO_INT);
				doSetIntegerAreaByEmp(employee);
				this.updateById(employee);
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	@Override
	public boolean checkBankInfoList(List<TSalaryEmployee> empList, List<ErrorMessage> errorList) {
		// 批量校验 卡号与手机号
		Map<String, Boolean> bankMap = new HashMap<>();
		List<TCheckBankNo> bankList = new ArrayList<>();
		TCheckBankNo checkBankNo;
		for (TSalaryEmployee employee : empList) {
			if (Common.isNotNull(employee.getBankNo())) {
				checkBankNo = new TCheckBankNo();
				checkBankNo.setName(employee.getEmpName());
				checkBankNo.setBankNo(employee.getBankNo());
				bankList.add(checkBankNo);
			}
		}
		if (!bankList.isEmpty()) {
			R<CheckBatchVo> checkListR = HttpDaprUtil.invokeMethodPost(checkProperties.getAppUrl(), checkProperties.getAppId()
					, "/tcheckbankno/inner/checkBankNoBatch", bankList, CheckBatchVo.class, SecurityConstants.FROM_IN);
			if (checkListR != null && checkListR.getData() != null) {
				bankMap = checkListR.getData().getCheckMap();
			}
			for (TSalaryEmployee employee : empList) {
				employee.setIssueStatus(CommonConstants.ZERO_INT);
				if (bankMap.get(employee.getBankNo()) != null && Boolean.FALSE.equals(bankMap.get(employee.getBankNo()))) {
					errorList.add(new ErrorMessage((employee.getLineNums()  ), "第" + (employee.getLineNums()  )
							+ "行：-上次代发户未校验【姓名与卡号】，本次校验结果：不匹配。请去薪酬人员查询处更新卡号信息！"));
					return false;
				}

			}
			doSetIntegerArea(empList);
			this.saveOrUpdateBatch(empList);
		}
		return true;
	}

	/**
	 * @param vo
	 * @Description: 批量更新-薪资人员信息
	 * @Author: hgw
	 * @Date: 2022/10/10 17:17
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.util.List < com.yifu.cloud.plus.v1.yifu.common.core.util.ErrorMessage>>
	 **/
	@Override
	public R<List<ErrorMessage>> importEmployee(SalaryEmployeeImportVo vo) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		List<String> idCardList = new ArrayList<>();
		// 执行数据插入操作 组装
		List<TSalaryEmployee> excelVOList = vo.getEmpList();
		for (TSalaryEmployee emp : excelVOList) {
			idCardList.add(emp.getEmpIdcard());
		}
		List<TSalaryEmployee> empList = baseMapper.getListByIdCard(idCardList);
		// 人员Map
		Map<String, TSalaryEmployee> empMap = new HashMap<>();
		for (TSalaryEmployee e : empList) {
			empMap.put(e.getEmpIdcard(), e);
		}
		TSalaryEmployee emp;
		// 开户行省市的区域暂存
		String areaProvince;
		String areaCity;
		boolean curTaxMonth;
		TSalaryEmployee excel;
		// 是否可更新
		boolean canUpdate = Common.isNotNull(vo.getIsUpdate()) && CommonConstants.ONE_STRING.equals(vo.getIsUpdate());
		List<TSalaryEmployee> saveList = new ArrayList<>();
		List<TSalaryEmployee> updateList = new ArrayList<>();
		TSettleDomain dept = vo.getDept();
		Map<String, String> bankMap = tBankSetService.getBankMap(null);

		// 校验卡号所用的
		Map<String, Boolean> bankCheckMap = new HashMap<>();
		List<TCheckBankNo> bankList = new ArrayList<>();
		TCheckBankNo checkBankNo;

		for (int i = 0; i < excelVOList.size(); i++) {
			excel = excelVOList.get(i);
			if (excel != null) {
				if (Common.isNotNull(excel.getEmpIdcard())) {
					emp = empMap.get(excel.getEmpIdcard());
					if (Common.isNotNull(emp)) {
						if (canUpdate) {
							curTaxMonth = false;
							if (Common.isNotNull(emp.getTaxMonth())) {
								curTaxMonth = true;
							} else if (Common.isNotNull(excel.getTaxMonth())) {
								if (excel.getTaxMonth().length() == 6) {
									try {
										Integer.parseInt(excel.getTaxMonth());
									} catch (NumberFormatException e) {
										errorMessageList.add(new ErrorMessage((i  ), "新增员工，计税月份错误"));
										continue;
									}
									emp.setTaxMonth(excel.getTaxMonth());
								} else {
									errorMessageList.add(new ErrorMessage((i  ), SalaryConstants.TAX_MONTH_LENGTH));
									continue;
								}
							}
							if (Common.isNotNull(excel.getBankName())) {
								if (bankMap.get(excel.getBankName()) == null) {
									errorMessageList.add(new ErrorMessage((i  ), SalaryConstants.BANK_NAME_ERROR));
									continue;
								}
								emp.setBankName(excel.getBankName());
							}
							if (Common.isNotNull(excel.getBankSubName())) {
								emp.setBankSubName(excel.getBankSubName());
							}
							if (Common.isNotNull(excel.getBankProvince())) {
								areaProvince = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getBankProvince().trim());
								if (Common.isNotNull(areaProvince)) {
									emp.setBankProvince(areaProvince);
									if (Common.isNotNull(excel.getBankCity())) {
										areaCity = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getBankCity().trim()
												+ CommonConstants.DOWN_LINE_STRING + excel.getBankProvince().trim());
										if (Common.isNotNull(areaCity)) {
											emp.setBankCity(areaCity);
										} else {
											errorMessageList.add(new ErrorMessage((i  ), SalaryConstants.CITY_ERROR));
											continue;
										}
									}
								} else {
									errorMessageList.add(new ErrorMessage((i  ), SalaryConstants.PROVINCE_ERROR));
									continue;
								}
							}
							if (Common.isNotNull(excel.getBankNo())) {
								emp.setBankNo(excel.getBankNo());
							}
							if (Common.isNotNull(excel.getEmpPhone())) {
								emp.setEmpPhone(excel.getEmpPhone());
							}
							if (Common.isNotNull(excel.getEmpName())) {
								emp.setEmpName(excel.getEmpName());
							}
							emp.setUnitId(dept.getCustomerId());
							emp.setUnitName(dept.getCustomerName());
							emp.setUnitNo(dept.getCustomerNo());
							emp.setDeptId(dept.getId());
							emp.setDeptName(dept.getDepartName());
							emp.setDeptNo(dept.getDepartNo());
							emp.setInvoiceTitle(dept.getInvoiceTitleSalary());

							if (Common.isNotNull(excel.getBankNo())) {
								checkBankNo = new TCheckBankNo();
								emp.setLineNums((i  ));
								checkBankNo.setName(excel.getEmpName());
								checkBankNo.setBankNo(excel.getBankNo());
								bankList.add(checkBankNo);
							}

							updateList.add(emp);
							if (curTaxMonth) {
								errorMessageList.add(new ErrorMessage((i  ), SalaryConstants.CUR_TAX_INFO));
							} else {
								errorMessageList.add(new ErrorMessage((i  ), CommonConstants.SAVE_SUCCESS));
							}
						} else {
							errorMessageList.add(new ErrorMessage((i  ), "已存在，不可更新"));
						}
					} else {
						// 新增人员
						if (Common.isEmpty(excel.getEmpName()) || Common.isEmpty(excel.getEmpIdcard())
								|| Common.isEmpty(excel.getEmpPhone()) || Common.isEmpty(excel.getBankName())
								|| Common.isEmpty(excel.getBankNo()) || Common.isEmpty(excel.getBankProvince())
								|| Common.isEmpty(excel.getBankCity()) || Common.isEmpty(excel.getTaxMonth())) {
							errorMessageList.add(new ErrorMessage((i  ), "新增员工，除了支行，其他必填"));
							continue;
						} else {
							if (excel.getTaxMonth().length() == 6) {
								try {
									Integer.parseInt(excel.getTaxMonth());
								} catch (NumberFormatException e) {
									errorMessageList.add(new ErrorMessage((i  ), "新增员工，计税月份错误"));
									continue;
								}
							} else {
								errorMessageList.add(new ErrorMessage((i  ), SalaryConstants.TAX_MONTH_LENGTH));
								continue;
							}
							if (bankMap.get(excel.getBankName()) == null) {
								errorMessageList.add(new ErrorMessage((i  ), SalaryConstants.BANK_NAME_ERROR));
								continue;
							}
							String pre = this.checkNewEmpBankAndPhone(excel, true);
							if (pre != null) {
								errorMessageList.add(new ErrorMessage((i  ), pre));
								continue;
							} else {
								areaProvince = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getBankProvince().trim());
								if (Common.isNotNull(areaProvince)) {
									areaCity = ExcelUtil.getRedisAreaValue(CacheConstants.AREA_VALUE + excel.getBankCity().trim()
											+ CommonConstants.DOWN_LINE_STRING + excel.getBankProvince().trim());
									excel.setBankProvince(areaProvince);
									if (Common.isNotNull(areaCity)) {
										excel.setBankCity(areaCity);
									} else {
										errorMessageList.add(new ErrorMessage((i  ), SalaryConstants.CITY_ERROR));
										continue;
									}
								} else {
									errorMessageList.add(new ErrorMessage((i  ), SalaryConstants.PROVINCE_ERROR));
									continue;
								}
								excel.setUnitId(dept.getCustomerId());
								excel.setUnitName(dept.getCustomerName());
								excel.setUnitNo(dept.getCustomerNo());
								excel.setDeptId(dept.getId());
								excel.setDeptName(dept.getDepartName());
								excel.setDeptNo(dept.getDepartNo());
								excel.setInvoiceTitle(dept.getInvoiceTitleSalary());
								if (Common.isNotNull(excel.getBankNo())) {
									checkBankNo = new TCheckBankNo();
									excel.setLineNums((i  ));
									checkBankNo.setName(excel.getEmpName());
									checkBankNo.setBankNo(excel.getBankNo());
									bankList.add(checkBankNo);
								}
								saveList.add(excel);
								errorMessageList.add(new ErrorMessage((i  ), CommonConstants.SAVE_SUCCESS));
							}
						}
					}
				} else {
					errorMessageList.add(new ErrorMessage((i+2), SalaryConstants.ID_CARD_MUST));
				}
			} else {
				errorMessageList.add(new ErrorMessage(CommonConstants.ZERO_INT, SalaryConstants.DATA_MUST));
			}
		}

		if (bankList != null && !bankList.isEmpty()) {
			R<CheckBatchVo> checkListR = HttpDaprUtil.invokeMethodPost(checkProperties.getAppUrl(), checkProperties.getAppId()
					, "/tcheckbankno/inner/checkBankNoBatch", bankList, CheckBatchVo.class, SecurityConstants.FROM_IN);
			if (checkListR != null && checkListR.getData() != null) {
				bankCheckMap = checkListR.getData().getCheckMap();
			}
		}

		if (!updateList.isEmpty()) {
			List<TSalaryEmployee> newUpdateList = new ArrayList<>();
			for (TSalaryEmployee employee : updateList) {
				if (bankCheckMap.get(employee.getBankNo()) != null && Boolean.FALSE.equals(bankCheckMap.get(employee.getBankNo()))) {
					errorMessageList.add(new ErrorMessage(employee.getLineNums(), "第" + employee.getLineNums()
							+ "行：-上次代发户未校验【姓名与卡号】，本次校验结果：不匹配。请去薪酬人员查询处更新卡号信息！！"));
				} else {
					employee.setIssueStatus(CommonConstants.ZERO_INT);
					employee.setLineNums(null);
					newUpdateList.add(employee);
				}
			}
			doSetIntegerArea(newUpdateList);
			this.updateBatchById(newUpdateList);
		}
		if (!saveList.isEmpty()) {
			List<TSalaryEmployee> newSaveList = new ArrayList<>();
			for (TSalaryEmployee employee : saveList) {
				if (bankCheckMap.get(employee.getBankNo()) != null && Boolean.FALSE.equals(bankCheckMap.get(employee.getBankNo()))) {
					errorMessageList.add(new ErrorMessage(employee.getLineNums(), "第" + employee.getLineNums()
							+ "行：-上次代发户未校验【姓名与卡号】，本次校验结果：不匹配。请去薪酬人员查询处更新卡号信息！！！"));
				} else {
					employee.setIssueStatus(CommonConstants.ZERO_INT);
					employee.setLineNums(null);
					newSaveList.add(employee);
				}
			}
			doSetIntegerArea(newSaveList);
			this.saveBatch(newSaveList);
		}
		boolean isTrue = true;
		for (ErrorMessage message : errorMessageList) {
			if (!CommonConstants.SAVE_SUCCESS.equals(message.getMessage())) {
				isTrue = false;
				break;
			}
		}
		if (isTrue) {
			return R.ok();
		} else {
			return R.ok(errorMessageList);
		}
	}

	/**
	 * 同步ekp薪酬人员信息
	 *
	 * @author huyc
	 * @param vo
	 * @return {@link R}
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R updateEmployeeFromEkp(TSalaryEmployeeEkpUpdateVo vo) {
		TSalaryEmployee one = baseMapper.selectOne(Wrappers.<TSalaryEmployee>query().lambda()
				.eq(TSalaryEmployee::getEmpIdcard, vo.getEmpIdcard())
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(one)) {
			TSalaryEmployee old = new TSalaryEmployee();
			BeanUtil.copyProperties(one,old);
			one.setBankNo(vo.getBankNo());
			one.setEmpName(vo.getEmpName());
			one.setBankName(vo.getBankName());
			baseMapper.updateById(one);
			logService.initModLog(one,old,CommonConstants.TWO_STRING, "ekp",null);
		}
		return R.ok();
	}
	/**
	 * @Author fxj
	 * @Description  获取员工花名册信息信息
	 * @Date 12:08 2023/6/19
	 * @Param
	 * @return
	**/
	@Override
	public List<TSalaryEmpRosterVo> getSalaryEmpRoster(List<String> idCardList){
		if (Common.isNotNull(idCardList)){
			return baseMapper.getSalaryEmpRoster(idCardList);
		}
		return null;
	}

	@Override
	public R<Boolean> updateByIdDiy(TSalaryEmployee tSalaryEmployee) {
		if (Common.isEmpty(tSalaryEmployee.getId())){
			return R.failed(CommonConstants.PARAM_INFO_ERROR);
		}
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)){
			return R.failed(CommonConstants.USER_FAIL);
		}

		TSalaryEmployee old = baseMapper.selectById(tSalaryEmployee.getId());
		// 2024-2-4 16:05:56 hgw 银行卡需要校验
		String pre = getCheckBankNo(tSalaryEmployee, old);
		if (pre != null) {return R.failed(pre);}

		// 变更日志 fxj 2023-10-24
		logService.initModLog(tSalaryEmployee,old,CommonConstants.ZERO_STRING,user.getNickname(),null);
		int res = baseMapper.updateById(tSalaryEmployee);
		if (res >= CommonConstants.ZERO_INT){
			return R.ok();
		}else {
			return R.failed(CommonConstants.UPDATE_DATA_FAIL);
		}
	}

	/**
	 * @Description: 单个校验通用方法
	 * @Author: hgw
	 * @Date: 2024/2/4 17:15
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.Boolean>
	 **/
	private String getCheckBankNo(TSalaryEmployee tSalaryEmployee, TSalaryEmployee old) {
		if (old != null && Common.isNotNull(tSalaryEmployee.getBankNo()) && !tSalaryEmployee.getBankNo().equals(old.getBankNo())) {
			// 调用校验服务
			TCheckBankNo checkBankNo = new TCheckBankNo();
			checkBankNo.setName(tSalaryEmployee.getEmpName());
			checkBankNo.setBankNo(tSalaryEmployee.getBankNo());
			R<CheckBankNoVo> checkListR = HttpDaprUtil.invokeMethodPost(checkProperties.getAppUrl(), checkProperties.getAppId()
					, "/tcheckbankno/inner/checkBankNo", checkBankNo, CheckBankNoVo.class, SecurityConstants.FROM_IN);
			String pre = "姓名与卡号验证：";
			if (checkListR != null && checkListR.getData() != null) {
				CheckBankNoVo vo = checkListR.getData();
				TCheckBankNo check = (null == vo.getRes()) ? null : vo.getRes().getData();
				if (Common.isEmpty(vo)) {
					return pre + SalaryConstants.CHECK_NO_RESPONSE;
				} else if (!CommonConstants.SUCCESS.equals(vo.getRes().getCode())) {
					return pre + vo.getRes().getMsg();
				} else if (check != null && !check.getResult().equals(CommonConstants.ZERO_ONE)) {
					return pre + check.getRemark();
				}
			} else {
				return pre + SalaryConstants.CHECK_NO_RESPONSE;
			}
		}
		return null;
	}

	/**
	 * @param empIdCard 身份证
	 * @Description: C端预入职获取计税月份
	 * @Author: hgw
	 * @Date: 2024/7/16 16:11
	 * @return: java.lang.String
	 **/
	@Override
	public String getEmpTaxMonth(String empIdCard) {
		// 0表示 未找到薪资记录，C端可编辑
		String taxMonth = CommonConstants.ZERO_STRING;
		TSalaryEmployee employee = baseMapper.getByEmpIdCard(empIdCard);
		if (employee != null && Common.isNotNull(employee.getTaxMonth())) {
			// 查找本年度薪资，有则返回薪资人员的计税月份，无则返回空，可编辑
			int count = salaryAccountMapper.getAccountIdByIdCard(empIdCard);
			if (count > 0) {
				taxMonth = employee.getTaxMonth();
			}
		}
		return taxMonth;
	}

	/**
	 * @param empIdCard 身份证
	 * @Description: C端预入职获取薪资人员信息
	 * @Author: hgw
	 * @Date: 2024-7-23 11:21:56
	 * @return: java.lang.String
	 **/
	@Override
	public TSalaryEmployee getSalaryEmployee(String empIdCard) {
		// 0表示 未找到薪资记录，C端可编辑
		return baseMapper.getByEmpIdCard(empIdCard);
	}

	/**
	 * @Description: C端预入职获取计税月份
	 * @Author: hgw
	 * @Date: 2024/7/16 16:11
	 * @return: java.lang.String
	 **/
	@Override
	public String savePreNewEmpInfo(TSalaryEmployee newEmp) {
		// true表示 未找到薪资记录，C端可编辑计税月份
		boolean canSaveFlag = true;
		TSalaryEmployee employee = baseMapper.getByEmpIdCard(newEmp.getEmpIdcard());
		if (employee != null) {
			// 查找本年度薪资，有则返回薪资人员的计税月份，无则返回空，可编辑
			int count = salaryAccountMapper.getAccountIdByIdCard(newEmp.getEmpIdcard());
			if (count > 0) {
				canSaveFlag = false;
			}
		}
		if (employee != null) {
			String[] ignoreProperties = new String[]{"id", "createBy", "createName", "createTime"};
			// 当年有发薪纪录，不允许编辑计税月
			if (!canSaveFlag) {
				newEmp.setTaxMonth(employee.getTaxMonth());
			}
			// 变更日志 hgw 2024-7-16 18:19:57
			logService.initModLog(newEmp,employee,CommonConstants.THREE_STRING,newEmp.getCreateName(), null);
			BeanUtil.copyProperties(newEmp, employee, ignoreProperties);
			doSetIntegerAreaByEmp(employee);
			this.updateById(employee);
		} else {
			doSetIntegerAreaByEmp(newEmp);
			this.save(newEmp);
		}
		return CommonConstants.SAVE_SUCCESS;
	}

	@Override
	public Map<String, TSalaryEmployee> getSalaryEmpMap(List<String> empIdCardList) {
		List<TSalaryEmployee> list = baseMapper.getListByIdCard(empIdCardList);
		Map<String, TSalaryEmployee> salaryEmpMap = new HashMap<>();
		if (list != null && !list.isEmpty()) {
			for (TSalaryEmployee s : list) {
				salaryEmpMap.put(s.getEmpIdcard(), s);
			}
		}
		return salaryEmpMap;
	}

}
