/*
 *    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 cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.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.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.validation.BindingResult;

import java.util.*;

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

	private final TEmployeeInfoMapper employeeInfoMapper;

	private final TAttaInfoMapper attaInfoMapper;

	@Override
	public R<List<ErrorMessage>> importEmpWorkRecord(List<EmpWorkRecordExcelVO> 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<TEmpWorkRecording> list = this.list();
		TEmployeeInfo emp;
		TEmpWorkRecording  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<>();
			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));
			checkRes(list, emp, errorMsg, excel);
			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)){
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_WORK_RECORD_EXISTING, excel.getEmpName()));
			}
			// 数据合法情况
			if (CollUtil.isEmpty(errorMsg)) {
				insertExcelPost(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);
	}

	@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) {
		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 void checkRes(List<TEmpWorkRecording> list, TEmployeeInfo emp, Set<String> errorMsg, EmpWorkRecordExcelVO excel) {
		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.getWorkDepart().equals(info.getWorkDepart())
				&& excel.getWorkUnit().equals(info.getWorkUnit())
				&& excel.getEmpIdcard().equals(info.getEmpIdcard()));

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

	/**
	 * 插入excel work record
	 */
	private void insertExcelPost(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());
		this.save(insert);
	}
}
