/*
 *    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 cn.hutool.core.util.StrUtil;
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.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.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.archives.vo.FamilySearchVO;
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 org.springframework.transaction.annotation.Transactional;

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 TEmpFamilyServiceImpl extends ServiceImpl<TEmpFamilyMapper, TEmpFamily> implements TEmpFamilyService {

	private final TEmployeeInfoMapper employeeInfoMapper;
	/**
	 * @Author fxj
	 * @Description  家庭信息 批量导入
	 * @Date 9:45 2022/6/20
	 * @Param
	 * @return
	**/
	@Transactional
	@Override
	public void importEmpFamily(List<EmpFamilyExcelVO> excelVOList,List<ErrorMessage> errorMessageList) {
		// 个性化校验逻辑
		List<TEmpFamily> list = null;
		if (Common.isNotNull(excelVOList)){
			this.list(Wrappers.<TEmpFamily>query().lambda()
					.in(TEmpFamily::getEmpIdcard,excelVOList.stream().map(EmpFamilyExcelVO::getEmpIdcard).collect(Collectors.toList()))
					.eq(TEmpFamily::getDeleteFlag,CommonConstants.ZERO_STRING));
		}
		TEmployeeInfo emp;
		TEmpFamily  exist;
		ErrorMessage errorMsg;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			// 已有验证报错直接下一个
			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));
			errorMsg = checkRes(list, emp, excel);
			if (Common.isNotNull(errorMsg)){
				errorMessageList.add(errorMsg);
				continue;
			}
			excel.setEmpName(emp.getEmpName());

			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)){
				errorMessageList.add(new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_FAMILY_NAME_EXISTING)));
				continue;
			}
			// 数据合法情况
			insertExcel(excel,emp);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(),CommonConstants.SAVE_SUCCESS));
		}
	}

	private ErrorMessage checkRes(List<TEmpFamily> list, TEmployeeInfo emp, EmpFamilyExcelVO 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.getFamilyName().equals(info.getFamilyName())
					&& excel.getEmpIdcard().equals(info.getEmpIdcard()));

			if (match) {
				return new ErrorMessage(excel.getRowIndex(),MsgUtils.getMessage(ErrorCodes.ARCHIVES_EMP_FAMILY_NAME_EXISTING));
			}
		}
		return null;
	}

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

	@Override
	public R<Boolean> removeByIdsDiy(List<String> idList) {
		LambdaUpdateWrapper<TEmpFamily> updateWrapper = new UpdateWrapper<TEmpFamily>().lambda();
		updateWrapper.set(TEmpFamily::getDeleteFlag,CommonConstants.ONE_STRING).in(TEmpFamily::getId,idList);
		return R.ok(this.update(updateWrapper));
	}

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

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

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

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

				@Override
				public void invoke(EmpFamilyExcelVO 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());
					importEmpFamily(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(FamilySearchVO entity){
		LambdaQueryWrapper<TEmpFamily> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(TEmpFamily::getDeleteFlag,CommonConstants.ZERO_STRING);
		if (ArrayUtil.isNotEmpty(entity.getCreateTimes())) {
			wrapper.ge(TEmpFamily::getCreateTime, entity.getCreateTimes()[0])
					.le(TEmpFamily::getCreateTime,
							entity.getCreateTimes()[1]);
		}
		if (Common.isNotNull(entity.getEmpName())){
			wrapper.likeRight(TEmpFamily::getEmpName,entity.getEmpName());
		}
		if (Common.isNotNull(entity.getEmpIdcard())){
			wrapper.likeRight(TEmpFamily::getEmpIdcard,entity.getEmpIdcard());
		}
		if (Common.isNotNull(entity.getCreateName())){
			wrapper.eq(TEmpFamily::getCreateName,entity.getCreateName());
		}
		return wrapper;
	}

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