/*
 *    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.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.TEmpProfessionalQualification;
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.TEmpProfessionalQualificationMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmpProfessionalQualificationService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.CertifySearchVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EmpCertificateExcelVO;
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.ErrorMessage;
import com.yifu.cloud.plus.v1.yifu.common.core.util.MsgUtils;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 员工职业资格信息表
 *
 * @author fxj
 * @date 2022-06-18 09:39:46
 */
@RequiredArgsConstructor
@Service
public class TEmpProfessionalQualificationServiceImpl extends ServiceImpl<TEmpProfessionalQualificationMapper, TEmpProfessionalQualification> implements TEmpProfessionalQualificationService {

	private final TAttaInfoMapper attaInfoMapper;

	private final TEmployeeInfoMapper employeeInfoMapper;

	@Override
	public R<Boolean> saveDiy(TEmpProfessionalQualification qualification) {
		qualification.setDeleteFlag(CommonConstants.ZERO_STRING);
		int res  = baseMapper.insert(qualification);
		if (res <= CommonConstants.ZERO_INT){
			return R.failed();
		}
		//更新附件信息
		List<String> ids;
		if (Common.isNotNull(qualification.getAttaIds())){
			ids = Common.initStrToList(qualification.getAttaIds(), CommonConstants.COMMA_STRING);
			attaInfoMapper.updateDomainId(qualification.getId(),ids);
		}
		return R.ok();
	}

	@Override
	public void importEmpCertificate(List<EmpCertificateExcelVO> excelVOList, List<ErrorMessage> errorMessageList) {
		List<TEmpProfessionalQualification> list = this.list();
		TEmployeeInfo emp;
		TEmpProfessionalQualification  exist;
		ErrorMessage errorMsg;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			// 已有验证报错直接下一个
			EmpCertificateExcelVO 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(list, emp, excel);
			if (Common.isNotNull(errorMsg)){
				errorMessageList.add(errorMsg);
				continue;
			}
			exist = baseMapper.selectOne(Wrappers.<TEmpProfessionalQualification>query().lambda()
					.eq(TEmpProfessionalQualification::getQualificationLevel,excel.getQualificationLevel())
					.eq(TEmpProfessionalQualification::getQualificationType,excel.getQualificationType())
					.eq(TEmpProfessionalQualification::getDeleteFlag,CommonConstants.ZERO_STRING)
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(exist)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_CERTIFICATE_NAME_EXISTING)));
				continue;
			}
			insertExcel(excel,emp);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(),CommonConstants.SAVE_SUCCESS));
		}
	}

	/**
	 * 插入excel
	 */
	private void insertExcel(EmpCertificateExcelVO excel, TEmployeeInfo emp) {
		TEmpProfessionalQualification insert = new TEmpProfessionalQualification();
		BeanUtil.copyProperties(excel, insert);
		insert.setDeleteFlag(CommonConstants.ZERO_STRING);
		insert.setEmpCode(emp.getEmpCode());
		insert.setEmpId(emp.getId());
		this.save(insert);
	}
	private ErrorMessage checkRes(List<TEmpProfessionalQualification> list, TEmployeeInfo emp, EmpCertificateExcelVO excel) {
		if (Common.isEmpty(emp)){
			return new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_NOT_EXIST));
		}
		if (CommonConstants.ONE_STRING.equals(emp.getFileStatus())){
			return new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_REDUCED));
		}
		// 检查添加是否已经存在
		boolean match = list.stream().anyMatch(info -> excel.getQualificationLevel()
				.equals(info.getQualificationLevel())
				&& excel.getEmpIdcard().equals(info.getEmpIdcard())
				&& excel.getQualificationType().equals(info.getQualificationType()));

		if (match) {
			return new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_CERTIFICATE_NAME_EXISTING));
		}
		return null;
	}
	@Override
	public List<TEmpProfessionalQualification> getDataNoPage(CertifySearchVo searchVo) {
		LambdaQueryWrapper<TEmpProfessionalQualification> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)){
			wrapper.in(TEmpProfessionalQualification::getId,idList);
		}
		return baseMapper.selectList(wrapper);
	}

	@Override
	public IPage<TEmpProfessionalQualification> pageDiy(Page page, CertifySearchVo searchVo) {
		LambdaQueryWrapper<TEmpProfessionalQualification> wrapper = buildQueryWrapper(searchVo);
		wrapper.orderByDesc(BaseEntity::getCreateTime);
		return baseMapper.selectPage(page,wrapper);
	}
	private LambdaQueryWrapper buildQueryWrapper(CertifySearchVo entity){
		LambdaQueryWrapper<TEmpProfessionalQualification> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(TEmpProfessionalQualification::getDeleteFlag,CommonConstants.ZERO_STRING);
		if (ArrayUtil.isNotEmpty(entity.getCreateTimes())) {
			wrapper.ge(TEmpProfessionalQualification::getCreateTime, entity.getCreateTimes()[0])
					.le(TEmpProfessionalQualification::getCreateTime,
							entity.getCreateTimes()[1]);
		}
		if (Common.isNotNull(entity.getEmpName())){
			wrapper.likeRight(TEmpProfessionalQualification::getEmpName,entity.getEmpName());
		}
		if (Common.isNotNull(entity.getEmpIdcard())){
			wrapper.likeRight(TEmpProfessionalQualification::getEmpIdcard,entity.getEmpIdcard());
		}
		if (Common.isNotNull(entity.getCreateName())){
			wrapper.eq(TEmpProfessionalQualification::getCreateName,entity.getCreateName());
		}
		return wrapper;
	}
}
