/*
 *    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.TEmpDisabilityInfo;
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.TEmpDisabilityInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmpDisabilityInfoService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EmpDisabilityExcelVO;
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 TEmpDisabilityInfoServiceImpl extends ServiceImpl<TEmpDisabilityInfoMapper, TEmpDisabilityInfo> implements TEmpDisabilityInfoService {

	private final TAttaInfoMapper attaInfoMapper;

	private final TEmployeeInfoMapper employeeInfoMapper;
	/**
	 * @Author fxj
	 * @Description  员工伤残信息导入
	 * @Date 10:41 2022/6/18
	 * @Param
	 * @return
	**/
	@Override
	public R<List<ErrorMessage>> importTmpDisability(List<EmpDisabilityExcelVO> excelVOList, BindingResult bindingResult) {
		// 通用校验获取失败的数据
		List<ErrorMessage> errorList = (List<ErrorMessage>) bindingResult.getTarget();
		Map<Long,ErrorMessage> errorMsgMap = new HashMap<>();
		if (Common.isNotNull(errorList)){
			errorList.stream().forEach(errorMessage -> errorMsgMap.put(errorMessage.getLineNum(),errorMessage));
		}
		// 个性化校验逻辑
		List<TEmpDisabilityInfo> list = this.list();
		TEmployeeInfo emp;
		TEmpDisabilityInfo exist;
		Set<String> errorMsg;
		List<ErrorMessage> temp = new ArrayList<>();
		ErrorMessage errorMessage;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			// 已有验证报错直接下一个
			errorMessage = errorMsgMap.get(i+2);
			if (Common.isNotNull(errorMessage)){
				temp.add(errorMessage);
				errorMsgMap.remove(i+2);
				continue;
			}
			errorMsg = new HashSet<>();
			EmpDisabilityExcelVO 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.<TEmpDisabilityInfo>query().lambda()
					.eq(TEmpDisabilityInfo::getEmpIdcard,excel.getEmpIdcard())
					.eq(TEmpDisabilityInfo::getDisabilityName,excel.getDisabilityName())
					.eq(TEmpDisabilityInfo::getDeleteFlag,CommonConstants.ZERO_STRING)
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(exist)){
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_DISABILITY_NAME_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);
	}
	private void checkRes(List<TEmpDisabilityInfo> list, TEmployeeInfo emp, Set<String> errorMsg, EmpDisabilityExcelVO 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.getDisabilityName().equals(info.getDisabilityName())
				&& excel.getEmpIdcard().equals(info.getEmpIdcard()));

		if (match) {
			errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_DISABILITY_NAME_EXISTING, excel.getEmpName()));
			return;
		}
	}
	@Override
	public R<Boolean> saveDiy(TEmpDisabilityInfo tEmpDisabilityInfo) {
		tEmpDisabilityInfo.setDeleteFlag(CommonConstants.ZERO_STRING);
		int res  = baseMapper.insert(tEmpDisabilityInfo);
		if (res > CommonConstants.ZERO_INT){
			//更新附件信息
			List<String> ids;
			if (Common.isNotNull(tEmpDisabilityInfo.getAttaIds())){
				ids = Common.initStrToList(tEmpDisabilityInfo.getAttaIds(), CommonConstants.COMMA_STRING);
				attaInfoMapper.updateDomainId(tEmpDisabilityInfo.getId(),ids);
			}
			return R.ok();
		}else {
			return R.failed();
		}
	}

	/**
	 * 插入excel
	 */
	private void insertExcelPost(EmpDisabilityExcelVO excel, TEmployeeInfo emp) {
		TEmpDisabilityInfo insert = new TEmpDisabilityInfo();
		BeanUtil.copyProperties(excel, insert);
		insert.setDeleteFlag(CommonConstants.ZERO_STRING);
		insert.setEmpCode(emp.getEmpCode());
		insert.setEmpId(emp.getId());
		this.save(insert);
	}
}
