/*
 *    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.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
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.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.yifu.archives.entity.TEmpWorkRecording;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeInfo;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TAttaInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmpWorkRecordingMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmpWorkRecordingService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EmpWorkRecordExcelVO;
import com.yifu.cloud.plus.v1.yifu.archives.vo.WorkRecordSearchVO;
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.mybatis.base.BaseEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 员工工作履历信息表
 *
 * @author fxj
 * @date 2022-06-18 09:39:46
 */
@Log4j2
@RequiredArgsConstructor
@Service
public class TEmpWorkRecordingServiceImpl extends ServiceImpl<TEmpWorkRecordingMapper, TEmpWorkRecording> implements TEmpWorkRecordingService {

	private final TEmployeeInfoMapper employeeInfoMapper;

	private final TAttaInfoMapper attaInfoMapper;

	@Override
	public void importEmpWorkRecord(List<EmpWorkRecordExcelVO> excelVOList, List<ErrorMessage> errorMessageList) {
		// 个性化校验逻辑
		List<TEmpWorkRecording> list =null;
		if (Common.isNotNull(excelVOList)){
			this.list(Wrappers.<TEmpWorkRecording>query().lambda()
					.in(TEmpWorkRecording::getEmpIdcard,excelVOList.stream().map(EmpWorkRecordExcelVO::getEmpIdcard).collect(Collectors.toList()))
					.eq(TEmpWorkRecording::getDeleteFlag,CommonConstants.ZERO_STRING));
		}
		TEmployeeInfo emp;
		TEmpWorkRecording  exist;
		ErrorMessage errorMsg;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			// 已有验证报错直接下一个
			EmpWorkRecordExcelVO excel = excelVOList.get(i);
			emp = employeeInfoMapper.selectOne(Wrappers.<TEmployeeInfo>query().lambda()
					.eq(TEmployeeInfo::getEmpIdcard,excel.getEmpIdcard())
					.eq(TEmployeeInfo::getDeleteFlag,CommonConstants.ZERO_STRING)
					.last(CommonConstants.LAST_ONE_SQL));
			errorMsg = checkRes(list, emp, excel);
			if (Common.isNotNull(errorMsg)){
				errorMessageList.add(errorMsg);
				continue;
			}
			excel.setEmpName(emp.getEmpName());
			exist = baseMapper.selectOne(Wrappers.<TEmpWorkRecording>query().lambda()
					.eq(TEmpWorkRecording::getEmpIdcard,excel.getEmpIdcard())
					.eq(TEmpWorkRecording::getWorkUnit,excel.getWorkUnit())
					.eq(TEmpWorkRecording::getWorkDepart,excel.getWorkDepart())
					.eq(TEmpWorkRecording::getDeleteFlag,CommonConstants.ZERO_STRING)
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(exist)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_WORK_RECORD_EXISTING)));
				continue;
			}
			if (Common.isEmpty(excel.getEndDate())){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.EMP_WORKING_RECODE_END_DATE_NOT_EMPTY)));
				continue;
			}
			if (Common.isEmpty(excel.getWorkJob())){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.EMP_WORKING_JOB_NOT_EMPTY)));
				continue;
			}
			// 数据合法情况
			insertExcel(excel,emp);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(),CommonConstants.SAVE_SUCCESS));
		}
	}

	@Override
	public R<Boolean> updateByIdDiy(TEmpWorkRecording recording) {
		String res = checkRepeat(recording);
		if (Common.isEmpty(res)){
			return R.ok(this.updateById(recording));
		}else {
			return R.failed(res);
		}
	}

	@Override
	public R<Boolean> saveDiy(TEmpWorkRecording recording) {
		if (Common.isEmpty(recording.getEndDate())){
			return R.failed("结束日期必填");
		}
		recording.setDeleteFlag(CommonConstants.ZERO_STRING);
		String res = checkRepeat(recording);
		if (Common.isEmpty(res)){
			this.save(recording);
			return R.ok();
		}else {
			return R.failed(res);
		}
	}

	public String checkRepeat(TEmpWorkRecording recording) {
		LambdaQueryWrapper<TEmpWorkRecording> wrapper = Wrappers.lambdaQuery();
		if (StrUtil.isNotBlank(recording.getEmpIdcard())){
			wrapper.eq(TEmpWorkRecording::getEmpIdcard,recording.getEmpIdcard());
		}
		if (StrUtil.isNotBlank(recording.getWorkDepart())){
			wrapper.eq(TEmpWorkRecording::getWorkDepart,recording.getWorkDepart());
		}
		if (StrUtil.isNotBlank(recording.getWorkUnit())){
			wrapper.eq(TEmpWorkRecording::getWorkUnit,recording.getWorkUnit());
		}
		if (StrUtil.isNotBlank(recording.getId())){
			wrapper.ne(TEmpWorkRecording::getId,recording.getId());
		}
		wrapper.eq(TEmpWorkRecording::getDeleteFlag,CommonConstants.ZERO_STRING);
		wrapper.last(CommonConstants.LAST_ONE_SQL);
		if (Common.isNotNull(baseMapper.selectOne(wrapper))){
			return MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_WORK_RECORD_EXISTING, recording.getEmpName());
		}
		return null;
	}

	private ErrorMessage checkRes(List<TEmpWorkRecording> list, TEmployeeInfo emp, EmpWorkRecordExcelVO excel) {
		if (Common.isEmpty(emp)){
			return new com.yifu.cloud.plus.v1.yifu.common.core.util.ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_NOT_EXIST));
		}
		if (CommonConstants.ONE_STRING.equals(Integer.toString(emp.getFileStatus()))){
			return new com.yifu.cloud.plus.v1.yifu.common.core.util.ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_REDUCED));
		}
		if (Common.isNotNull(list)){
			// 检查添加是否已经存在
			boolean match = list.stream().anyMatch(info -> excel.getWorkDepart().equals(info.getWorkDepart())
					&& excel.getWorkUnit().equals(info.getWorkUnit())
					&& excel.getEmpIdcard().equals(info.getEmpIdcard()));

			if (match) {
				return new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_WORK_RECORD_EXISTING));
			}
		}
		return null;
	}

	/**
	 * 插入excel work record
	 */
	private void insertExcel(EmpWorkRecordExcelVO excel, TEmployeeInfo emp) {
		TEmpWorkRecording insert = new TEmpWorkRecording();
		BeanUtil.copyProperties(excel, insert);
		insert.setDeleteFlag(CommonConstants.ZERO_STRING);
		insert.setEmpCode(emp.getEmpCode());
		insert.setEmpId(emp.getId());
		insert.setSettleDomain(emp.getDeptId());
		this.save(insert);
	}

	@Override
	public IPage<TEmpWorkRecording> pageDiy(Page page, WorkRecordSearchVO tEmpWorkRecording) {
		LambdaQueryWrapper<TEmpWorkRecording> wrapper = buildQueryWrapper(tEmpWorkRecording);
		wrapper.orderByDesc(BaseEntity::getCreateTime);
		return baseMapper.selectPage(page,wrapper);
	}

	@Override
	public List<TEmpWorkRecording> getTEmpWorkRecordingNoPage(WorkRecordSearchVO searchVo) {
		LambdaQueryWrapper<TEmpWorkRecording> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)){
			wrapper.in(TEmpWorkRecording::getId,idList);
		}
		wrapper.orderByDesc(BaseEntity::getCreateTime);
		return baseMapper.selectList(wrapper);
	}

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

				@Override
				public void invoke(EmpWorkRecordExcelVO 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());
					importEmpWorkRecord(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 LambdaQueryWrapper buildQueryWrapper(WorkRecordSearchVO entity){
		LambdaQueryWrapper<TEmpWorkRecording> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(TEmpWorkRecording::getDeleteFlag,CommonConstants.ZERO_STRING);
		if (ArrayUtil.isNotEmpty(entity.getCreateTimes())) {
			wrapper.ge(TEmpWorkRecording::getCreateTime, entity.getCreateTimes()[0])
					.le(TEmpWorkRecording::getCreateTime,
							entity.getCreateTimes()[1]);
		}
		if (Common.isNotNull(entity.getEmpName())){
			wrapper.likeRight(TEmpWorkRecording::getEmpName,entity.getEmpName());
		}
		if (Common.isNotNull(entity.getEmpIdcard())){
			wrapper.likeRight(TEmpWorkRecording::getEmpIdcard,entity.getEmpIdcard());
		}
		if (Common.isNotNull(entity.getCreateName())){
			wrapper.eq(TEmpWorkRecording::getCreateName,entity.getCreateName());
		}
		return wrapper;
	}

	@Override
	public List<TEmpWorkRecording> getListByEmpId(String empId) {
		return baseMapper.selectList(Wrappers.<TEmpWorkRecording>query().lambda().eq(TEmpWorkRecording::getEmpId, empId).eq(TEmpWorkRecording::getDeleteFlag, CommonConstants.ZERO_STRING));
	}

}
