/*
 *    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 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.TEmpEducation;
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.TEmpEducationMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmpEducationService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EducationSearchVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EmpEducationExcelVO;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EmpEducationUpdateExcelVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EmpEducationUpdateVO;
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 org.springframework.transaction.annotation.Transactional;

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 TEmpEducationServiceImpl extends ServiceImpl<TEmpEducationMapper, TEmpEducation> implements TEmpEducationService {

	private final TEmployeeInfoMapper employeeInfoMapper;

	private final TAttaInfoMapper attaInfoMapper;

	/**
	 * @Author fxj
	 * @Description  批量导入学历信息
	 * @Date 16:16 2022/6/20
	**/
	@Transactional
	@Override
	public void importEmpEducation(List<EmpEducationExcelVO> excelVOList, List<ErrorMessage> errorMessageList) {
		/// 个性化校验逻辑
		List<TEmpEducation> list = null;
		if (Common.isNotNull(excelVOList)){
			this.list(Wrappers.<TEmpEducation>query().lambda()
					.in(TEmpEducation::getEmpIdcard,excelVOList.stream().map(EmpEducationExcelVO::getEmpIdcard).collect(Collectors.toList()))
					.eq(TEmpEducation::getDeleteFlag,CommonConstants.ZERO_STRING));
		}
		TEmployeeInfo emp;
		TEmpEducation  exist;
		ErrorMessage errorMsg;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			// 已有验证报错直接下一个
			EmpEducationExcelVO 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(emp, excel,list);
			if (Common.isNotNull(errorMsg)){
				errorMessageList.add(errorMsg);
				continue;
			}
			excel.setEmpName(emp.getEmpName());
			exist = baseMapper.selectOne(Wrappers.<TEmpEducation>query().lambda()
					.eq(TEmpEducation::getEmpIdcard,excel.getEmpIdcard())
					.eq(TEmpEducation::getEducationName,excel.getEducationName())
					.eq(TEmpEducation::getDeleteFlag,CommonConstants.ZERO_STRING)
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(exist)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_EDUCATION_EXISTING)));
			}
			// 数据合法情况
			insertExcel(excel,emp);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(),CommonConstants.SAVE_SUCCESS));
		}
	}

	/**
	 * @Author fxj
	 * @Description 更新学历信息
	 * @Date 16:17 2022/6/20
	**/
	@Transactional
	@Override
	public R<Boolean> updateByIdDiy(TEmpEducation tEmpEducation) {
		TEmpEducation education = baseMapper.selectOne(Wrappers.<TEmpEducation>query().lambda()
				.eq(TEmpEducation::getEmpIdcard,tEmpEducation.getEmpIdcard())
				.eq(TEmpEducation::getEducationName,tEmpEducation.getEducationName())
				.ne(TEmpEducation::getId,tEmpEducation.getId())
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(education)){
			return R.failed(MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_EDUCATION_EXISTING, tEmpEducation.getEducationName()));
		}
		updateEducationOfEmp(tEmpEducation);
		baseMapper.updateById(tEmpEducation);
		return R.ok();
	}

	/**
	 * @Author fxj
	 * @Description  保存 学历信息
	 * @Date 16:17 2022/6/20
	**/
	@Transactional
	@Override
	public R<Boolean> saveDiy(TEmpEducation tEmpEducation) {
		TEmpEducation education = baseMapper.selectOne(Wrappers.<TEmpEducation>query().lambda()
				.eq(TEmpEducation::getEmpIdcard,tEmpEducation.getEmpIdcard())
				.eq(TEmpEducation::getEducationName,tEmpEducation.getEducationName())
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(education)){
			return R.failed(MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_EDUCATION_EXISTING, tEmpEducation.getEducationName()));
		}
		//更新档案信息
		updateEducationOfEmp(tEmpEducation);
		tEmpEducation.setDeleteFlag(CommonConstants.ZERO_STRING);
		baseMapper.insert(tEmpEducation);
		//更新附件信息
		List<String> ids;
		if (Common.isNotNull(tEmpEducation.getAttaIds())){
			ids = Common.initStrToList(tEmpEducation.getAttaIds(),CommonConstants.COMMA_STRING);
			attaInfoMapper.updateDomainId(tEmpEducation.getId(),ids);
		}
		return R.ok();
	}

	/**
	 * @Author fxj
	 * @Description  批量更新学历
	 * @Date 16:25 2022/6/20
	**/
	@Override
	public void importEmpEducationUpdate(List<EmpEducationUpdateExcelVo> excelVOList, List<ErrorMessage> errorMessageList) {
		TEmpEducation temp;
		TEmpEducation  exist;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			// 已有验证报错直接下一个
			EmpEducationUpdateExcelVo excel = excelVOList.get(i);
			temp =  baseMapper.selectOne(Wrappers.<TEmpEducation>query().lambda()
					.eq(TEmpEducation::getId,excel.getId())
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isEmpty(temp)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),CommonConstants.PARAM_IS_NOT_ERROR));
				continue;
			}
			exist = baseMapper.selectOne(Wrappers.<TEmpEducation>query().lambda()
					.ne(TEmpEducation::getId,excel.getId())
					.eq(TEmpEducation::getEmpIdcard,temp.getEmpIdcard())
					.eq(TEmpEducation::getEducationName,excel.getEducationName())
					.eq(TEmpEducation::getDeleteFlag,CommonConstants.ZERO_STRING)
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(exist)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_EDUCATION_EXISTING)));
				continue;
			}
			// 数据合法情况
			updateExcel(excel,temp);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(),CommonConstants.UPDATE_SUCCESS));

		}
	}

	private void updateExcel(EmpEducationUpdateExcelVo excel, TEmpEducation temp) {
		TEmpEducation update = new TEmpEducation();
		BeanUtil.copyProperties(excel, update);
		if (Common.isNotNull(temp)){
			update.setEmpId(temp.getEmpId());
			update.setEmpIdcard(temp.getEmpIdcard());
			update.setEmpName(temp.getEmpName());
			update.setEmpCode(temp.getEmpCode());
		}
		// 更新档案学历信息
		updateEducationOfEmp(update);
		this.updateById(update);
	}

	private ErrorMessage checkRes(TEmployeeInfo emp,EmpEducationExcelVO excel, List<TEmpEducation> list) {
		if (Common.isEmpty(emp)){
			return new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_NOT_EXIST));
		}
		if (Common.isNotNull(emp.getFileStatus())
				&& CommonConstants.ONE_STRING.equals(Integer.toString(emp.getFileStatus()))){
			return new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_REDUCED));
		}
		if (Common.isNotNull(list)){
			// 检查添加是否已经存在
			boolean match = list.stream().anyMatch(info -> excel.getEducationName().equals(info.getEducationName())
					&& excel.getEmpIdcard().equals(info.getEmpIdcard()));

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

	private void updateEducationOfEmp(TEmpEducation education) {
		if (CommonConstants.ZERO_STRING.equals(education.getHighIdentification())){
			EmpEducationUpdateVO updateVo = new EmpEducationUpdateVO();
			BeanUtil.copyProperties(education, updateVo);
			if (Integer.parseInt(education.getEducationName()) >= CommonConstants.FOUR_INT){
				updateVo.setIsCollege(CommonConstants.ZERO_INT);
			}else {
				updateVo.setIsCollege(CommonConstants.ONE_INT);
			}
			updateVo.setHighIdentification(updateVo.getEducationName());
			employeeInfoMapper.updateEducationOfEmp(updateVo);
			// 所有学历更新为非最高学历
			baseMapper.updateHighIdentification(education.getEmpIdcard());
		}
	}

	/**
	 * 插入excel education
	 */
	private void insertExcel(EmpEducationExcelVO excel, TEmployeeInfo emp) {
		TEmpEducation insert = new TEmpEducation();
		BeanUtil.copyProperties(excel, insert);
		insert.setDeleteFlag(CommonConstants.ZERO_STRING);
		insert.setEmpCode(emp.getEmpCode());
		insert.setEmpId(emp.getId());
		// 更新档案学历信息
		updateEducationOfEmp(insert);
		this.save(insert);
	}
	/**
	 * @Author fxj
	 * @Description 档案新增或更新学历专用接口
	 * @Date 9:35 2022/6/22
	**/
	@Transactional
	@Override
	public R<Boolean> insertEducationOfEmp(TEmpEducation education){
		if (Common.isEmpty(education) && Common.isEmpty(education.getHighIdentification())){
			return R.failed(CommonConstants.SAVE_FAILED);
		}
		if (CommonConstants.ZERO_STRING.equals(education.getHighIdentification())){
			baseMapper.updateHighIdentification(education.getEmpIdcard());
		}
		TEmpEducation  exist = baseMapper.selectOne(Wrappers.<TEmpEducation>query().lambda()
				.eq(TEmpEducation::getEducationName,education.getEducationName())
				.eq(TEmpEducation::getDeleteFlag,CommonConstants.ZERO_STRING)
				.eq(TEmpEducation::getEmpIdcard,education.getEmpIdcard())
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(exist)){
			exist.setHighIdentification(education.getHighIdentification());
			exist.setSchool(education.getSchool());
			exist.setMajor(education.getMajor());
			exist.setEntryDate(education.getEntryDate());
			exist.setGradutionDate(education.getGradutionDate());
			baseMapper.updateById(exist);
		}else {
			baseMapper.insert(education);
		}
		return R.ok();
	}

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

	@Override
	public List<TEmpEducation> getTEmpEducationNoPage(EducationSearchVo searchVo) {
		LambdaQueryWrapper<TEmpEducation> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)){
			wrapper.in(TEmpEducation::getId,idList);
		}
		return baseMapper.selectList(wrapper);
	}

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

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

				@Override
				public void invoke(EmpEducationExcelVO 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());
					importEmpEducation(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);
	}

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

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