/*
 *    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.TEmpFamily;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeInfo;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmpFamilyMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmpFamilyService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EmpFamilyExcelVO;
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 TEmpFamilyServiceImpl extends ServiceImpl<TEmpFamilyMapper, TEmpFamily> implements TEmpFamilyService {

	private final TEmployeeInfoMapper employeeInfoMapper;
	/**
	 * @Author fxj
	 * @Description  家庭信息 批量导入
	 * @Date 9:45 2022/6/20
	 * @Param
	 * @return
	**/
	@Override
	public R<List<ErrorMessage>> importEmpFamily(List<EmpFamilyExcelVO> 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<TEmpFamily> list = this.list();
		TEmployeeInfo emp;
		TEmpFamily  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<>();
			EmpFamilyExcelVO 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.<TEmpFamily>query().lambda()
					.eq(TEmpFamily::getEmpIdcard,excel.getEmpIdcard())
					.eq(TEmpFamily::getFamilyName,excel.getFamilyName())
					.eq(TEmpFamily::getDeleteFlag,CommonConstants.ZERO_STRING)
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(exist)){
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_FAMILY_NAME_EXISTING, excel.getFamilyName()));
			}
			// 数据合法情况
			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<TEmpFamily> list, TEmployeeInfo emp, Set<String> errorMsg, EmpFamilyExcelVO 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.getFamilyName().equals(info.getFamilyName())
				&& excel.getEmpIdcard().equals(info.getEmpIdcard()));

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

	@Override
	public String checkRepeat(String empIdcard, String familyName, String updateId) {
		LambdaQueryWrapper<TEmpFamily> wrapper = Wrappers.lambdaQuery();
		if (StrUtil.isNotBlank(empIdcard)){
			wrapper.eq(TEmpFamily::getEmpIdcard,empIdcard);
		}
		if (StrUtil.isNotBlank(familyName)){
			wrapper.eq(TEmpFamily::getFamilyName,familyName);
		}
		if (StrUtil.isNotBlank(updateId)){
			wrapper.ne(TEmpFamily::getId,updateId);
		}
		wrapper.last(CommonConstants.LAST_ONE_SQL);
		if (Common.isNotNull(baseMapper.selectOne(wrapper))){
			return MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_FAMILY_NAME_EXISTING, familyName);
		}
		return null;
	}

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