/*
 *    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.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
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.*;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 员工职业资格信息表
 *
 * @author fxj
 * @date 2022-06-18 09:39:46
 */
@Log4j2
@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) {

		TEmpProfessionalQualification exist = baseMapper.selectOne(Wrappers.<TEmpProfessionalQualification>query().lambda()
				.eq(TEmpProfessionalQualification::getEmpIdcard,qualification.getEmpIdcard())
				.eq(TEmpProfessionalQualification::getQualificationLevel,qualification.getQualificationLevel())
				.eq(TEmpProfessionalQualification::getQualificationType,qualification.getQualificationType())
				.eq(TEmpProfessionalQualification::getDeleteFlag,CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(exist)){
			return R.failed(MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_CERTIFICATE_NAME_EXISTING));
		}

		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 = null;
		if (Common.isNotNull(excelVOList)){
			list = this.list(Wrappers.<TEmpProfessionalQualification>query().lambda()
					.in(TEmpProfessionalQualification::getEmpIdcard,excelVOList.stream().map(EmpCertificateExcelVO::getEmpIdcard).collect(Collectors.toList()))
					.eq(TEmpProfessionalQualification::getDeleteFlag,CommonConstants.ZERO_STRING));
		}
		TEmployeeInfo emp;
		TEmpProfessionalQualification  exist;
		ErrorMessage errorMsg;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			// 已有验证报错直接下一个
			EmpCertificateExcelVO excel = excelVOList.get(i);
			if (Common.isNotNull(excel.getDeclareYear()) &&
					Integer.parseInt(excel.getDeclareYear()) > DateUtil.getYearOfInt(new Date())){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_CERTIFICATE_DECLARE_YEAR_ERROR)));
				continue;
			}
			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;
			}
			excel.setEmpName(emp.getEmpName());
			excel.setEmpIdcard(emp.getEmpIdcard());
			exist = baseMapper.selectOne(Wrappers.<TEmpProfessionalQualification>query().lambda()
					.eq(TEmpProfessionalQualification::getEmpIdcard,excel.getEmpIdcard())
					.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());
		insert.setSettleDomain(emp.getDeptId());
		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(Integer.toString(emp.getFileStatus()))){
			return new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_REDUCED));
		}
		if (Common.isNotNull(list)){
			// 检查添加是否已经存在
			boolean match = list.stream().anyMatch(info ->
					((Common.isEmpty(excel.getQualificationLevel()) && Common.isNotNull(info.getQualificationLevel()))
					|| (Common.isNotNull(excel.getQualificationLevel())
					&& 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);
	}

	@Override
	public R<List<ErrorMessage>> importEmpCertificateDiy(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<EmpCertificateExcelVO> util1 = new ExcelUtil<>(EmpCertificateExcelVO.class);;
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, EmpCertificateExcelVO.class, new ReadListener<EmpCertificateExcelVO>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<EmpCertificateExcelVO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(EmpCertificateExcelVO data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex+1);
					ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)){
						errorMessageList.add(errorMessage);
					}else {
						cachedDataList.add(data);
					}
					if (cachedDataList.size() >= BATCH_COUNT) {
						saveData();
						// 存储完成清理 list
						cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
					}
				}

				@Override
				public void doAfterAllAnalysed(AnalysisContext context) {
					saveData();
				}

				/**
				 * 加上存储数据库
				 */
				private void saveData() {
					log.info("{}条数据，开始存储数据库！", cachedDataList.size());
					importEmpCertificate(cachedDataList,errorMessageList);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		}catch (Exception e){
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR,e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		return  R.ok(errorMessageList);
	}

	@Override
	public R<Boolean> updateByIdDiy(TEmpProfessionalQualification qualification) {
		TEmpProfessionalQualification exist = baseMapper.selectOne(Wrappers.<TEmpProfessionalQualification>query().lambda()
				.ne(TEmpProfessionalQualification::getId,qualification.getId())
				.eq(TEmpProfessionalQualification::getEmpIdcard,qualification.getEmpIdcard())
				.eq(TEmpProfessionalQualification::getQualificationLevel,qualification.getQualificationLevel())
				.eq(TEmpProfessionalQualification::getQualificationType,qualification.getQualificationType())
				.eq(TEmpProfessionalQualification::getDeleteFlag,CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(exist)){
			return R.failed(MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_CERTIFICATE_NAME_EXISTING));
		}
		int res = baseMapper.updateById(qualification);
		if (res < 0){
			return R.failed();
		}
		return R.ok();
	}

	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;
	}
}
