/*
 *    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.TEmpBadRecord;
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.DisabilitySearchVo;
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.*;
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.List;
import java.util.stream.Collectors;

/**
 * 员工伤残信息表
 *
 * @author fxj
 * @date 2022-06-18 09:39:46
 */
@Log4j2
@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 void importTmpDisability(List<EmpDisabilityExcelVO> excelVOList, List<ErrorMessage> errorMessageList) {
		// 个性化校验逻辑
		List<TEmpDisabilityInfo> list = null;
		if (Common.isNotNull(excelVOList)){
			this.list(Wrappers.<TEmpDisabilityInfo>query().lambda()
					.in(TEmpDisabilityInfo::getEmpIdcard,excelVOList.stream().map(EmpDisabilityExcelVO::getEmpIdcard).collect(Collectors.toList()))
					.eq(TEmpDisabilityInfo::getDeleteFlag,CommonConstants.ZERO_STRING));
		}
		TEmployeeInfo emp;
		TEmpDisabilityInfo  exist;
		ErrorMessage errorMsg;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			// 已有验证报错直接下一个
			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));
			errorMsg = checkRes(list, emp, excel);
			if (Common.isNotNull(errorMsg)){
				errorMessageList.add(errorMsg);
				continue;
			}
			excel.setEmpName(emp.getEmpName());
			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)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_DISABILITY_NAME_EXISTING)));
				continue;
			}
			// 数据合法情况
			if (CommonConstants.ZERO_STRING.equals(excel.getOccupationalDiseaseFlag())
					&& Common.isEmpty(excel.getOccupationalDisease())){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"职业病名称不可为空！"));
				continue;
			}
			if (CommonConstants.ZERO_STRING.equals(excel.getInfectiousDiseaseFlag())
					&& Common.isEmpty(excel.getInfectiousName())){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"传染病名称不可为空！"));
				continue;
			}
			if (CommonConstants.ZERO_STRING.equals(excel.getDisabilityFlag())){
				if (Common.isEmpty(excel.getDisabilityName())){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"伤残病名称不可为空！"));
					continue;
				}
				if (Common.isEmpty(excel.getDisabilityLevel())){
					errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"伤残等级不可为空！"));
					continue;
				}
			}
			if (Common.isEmpty(excel.getOtherFlag())){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),"是否从事过井下、高空、高温、特别繁重体力劳动以及有毒有害工种 不可为空！"));
				continue;
			}
			// 数据合法情况
			insertExcel(excel,emp);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(),CommonConstants.SAVE_SUCCESS));
		}
	}
	private ErrorMessage checkRes(List<TEmpDisabilityInfo> list, TEmployeeInfo emp,EmpDisabilityExcelVO 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 -> excel.getDisabilityName().equals(info.getDisabilityName())
					&& excel.getEmpIdcard().equals(info.getEmpIdcard()));

			if (match) {
				return new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_DISABILITY_NAME_EXISTING));
			}
		}
		return null;
	}
	@Override
	public R<Boolean> saveDiy(TEmpDisabilityInfo tEmpDisabilityInfo) {
		TEmpDisabilityInfo exist = baseMapper.selectOne(Wrappers.<TEmpDisabilityInfo>query().lambda()
				.eq(TEmpDisabilityInfo::getEmpIdcard,tEmpDisabilityInfo.getEmpIdcard())
				.eq(TEmpDisabilityInfo::getDisabilityName,tEmpDisabilityInfo.getDisabilityName())
				.eq(TEmpDisabilityInfo::getDeleteFlag,CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(exist)){
			return R.failed(MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_DISABILITY_NAME_EXISTING));
		}
		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();
		}
	}

	@Override
	public IPage<TEmpDisabilityInfo> pageDiy(Page page, DisabilitySearchVo searchVo) {
		LambdaQueryWrapper<TEmpDisabilityInfo> wrapper = buildQueryWrapper(searchVo);
		wrapper.orderByDesc(BaseEntity::getCreateTime);
		return baseMapper.selectPage(page,wrapper);
	}

	@Override
	public List<TEmpDisabilityInfo> getTEmpDisabilityInfoNoPage(DisabilitySearchVo searchVo) {
		LambdaQueryWrapper<TEmpDisabilityInfo> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)){
			wrapper.in(TEmpDisabilityInfo::getId,idList);
		}
		wrapper.orderByDesc(BaseEntity::getCreateTime);
		return baseMapper.selectList(wrapper);
	}

	@Override
	public R<Boolean> updateByIdDiy(TEmpDisabilityInfo tEmpDisabilityInfo) {
		TEmpDisabilityInfo exist = baseMapper.selectOne(Wrappers.<TEmpDisabilityInfo>query().lambda()
				.eq(TEmpDisabilityInfo::getEmpIdcard,tEmpDisabilityInfo.getEmpIdcard())
				.ne(TEmpDisabilityInfo::getId,tEmpDisabilityInfo.getId())
				.eq(TEmpDisabilityInfo::getDisabilityName,tEmpDisabilityInfo.getDisabilityName())
				.eq(TEmpDisabilityInfo::getDeleteFlag,CommonConstants.ZERO_STRING)
				.last(CommonConstants.LAST_ONE_SQL));
		if (Common.isNotNull(exist)){
			return	R.failed(MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_DISABILITY_NAME_EXISTING));
		}
		baseMapper.updateById(tEmpDisabilityInfo);
		return R.ok();
	}

	@Override
	public R<List<ErrorMessage>> importTmpDisabilityDiy(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<EmpDisabilityExcelVO> util1 = new ExcelUtil<>(EmpDisabilityExcelVO.class);;
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {

			EasyExcel.read(inputStream, EmpDisabilityExcelVO.class, new ReadListener<EmpDisabilityExcelVO>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<EmpDisabilityExcelVO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(EmpDisabilityExcelVO 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());
					importTmpDisability(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);
	}

	private LambdaQueryWrapper buildQueryWrapper(DisabilitySearchVo entity){
		LambdaQueryWrapper<TEmpDisabilityInfo> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(TEmpDisabilityInfo::getDeleteFlag,CommonConstants.ZERO_STRING);
		if (ArrayUtil.isNotEmpty(entity.getCreateTimes())) {
			wrapper.ge(TEmpDisabilityInfo::getCreateTime, entity.getCreateTimes()[0])
					.le(TEmpDisabilityInfo::getCreateTime,
							entity.getCreateTimes()[1]);
		}
		if (Common.isNotNull(entity.getEmpName())){
			wrapper.likeRight(TEmpDisabilityInfo::getEmpName,entity.getEmpName());
		}
		if (Common.isNotNull(entity.getEmpIdcard())){
			wrapper.likeRight(TEmpDisabilityInfo::getEmpIdcard,entity.getEmpIdcard());
		}
		if (Common.isNotNull(entity.getCreateName())){
			wrapper.eq(TEmpDisabilityInfo::getCreateName,entity.getCreateName());
		}
		return wrapper;
	}

	/**
	 * 插入excel
	 */
	private void insertExcel(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());
		insert.setSettleDomain(emp.getDeptId());
		this.save(insert);
	}

	@Override
	public TEmpDisabilityInfo getByEmpId(String empId) {
		return baseMapper.selectOne(Wrappers.<TEmpDisabilityInfo>query().lambda().eq(TEmpDisabilityInfo::getEmpId, empId).last(CommonConstants.LAST_ONE_SQL));
	}

}
