/*
 *    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.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.plugin.excel.vo.ErrorMessage;
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.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.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.MsgUtils;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;

import java.util.*;

/**
 * 员工学历信息表
 *
 * @author fxj
 * @date 2022-06-18 09:39:46
 */
@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 R<List<ErrorMessage>> importEmpEducation(List<EmpEducationExcelVO> 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<TEmpEducation> list = this.list();
		TEmployeeInfo emp;
		TEmpEducation  exist;
		Set<String> errorMsg;
		ErrorMessage errorMessage;
		List<ErrorMessage> temp = new ArrayList<>();
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			errorMessage = errorMsgMap.get(i+2);
			// 已有验证报错直接下一个
			if (Common.isNotNull(errorMsgMap.get(i+2))){
				temp.add(errorMessage);
				errorMsgMap.remove(i+2);
				continue;
			}
			errorMsg = new HashSet<>();
			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));
			checkRes(emp, errorMsg, excel, list);
			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)){
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_EDUCATION_EXISTING, excel.getEducationName()));
			}
			// 数据合法情况
			if (CollUtil.isEmpty(errorMsg)) {
				insertExcel(excel,emp);
				errorMsg.add(CommonConstants.SAVE_SUCCESS);
				temp.add(new ErrorMessage((long) (i + 2), errorMsg));
			} else {
				// 数据不合法
				temp.add(new ErrorMessage((long) (i + 2), errorMsg));
			}
		}
		temp.addAll(errorMsgMap.values());
		return R.ok(temp);
	}

	/**
	 * @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 R<List<ErrorMessage>> importEmpEducationUpdate(List<EmpEducationUpdateExcelVo> 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));
		}
		// 个性化校验逻辑
		Set<String> errorMsg;
		ErrorMessage errorMessage;
		List<ErrorMessage> temp = new ArrayList<>();
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			// 已有验证报错直接下一个
			errorMessage = errorMsgMap.get(i+2);
			if (Common.isNotNull(errorMessage)){
				temp.add(errorMessage);
				continue;
			}
			errorMsg = new HashSet<>();
			EmpEducationUpdateExcelVo excel = excelVOList.get(i);
			// 数据合法情况
			if (CollUtil.isEmpty(errorMsg)) {
				updateExcel(excel);
				errorMsg.add(CommonConstants.UPDATE_SUCCESS);
				temp.add(new ErrorMessage((long) (i + 2), errorMsg));
			} else {
				// 数据不合法
				temp.add(new ErrorMessage((long) (i + 2), errorMsg));
			}
		}
		temp.addAll(errorMsgMap.values());
		return R.ok(temp);
	}

	private void updateExcel(EmpEducationUpdateExcelVo excel) {
		TEmpEducation update = new TEmpEducation();
		BeanUtil.copyProperties(excel, update);
		// 更新档案学历信息
		updateEducationOfEmp(update);
		this.updateById(update);
	}

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

		if (match) {
			errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_EDUCATION_EXISTING, excel.getEmpName()));
			return;
		}
	}

	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);
			}
			employeeInfoMapper.updateEducationOfEmp(updateVo);
		}
	}

	/**
	 * 插入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();
	}

}
