/*
 *    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.ExcelWriter;
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.alibaba.excel.write.metadata.WriteSheet;
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.*;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TPreEmpMainMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.*;
import com.yifu.cloud.plus.v1.yifu.archives.vo.PreEmpMainDetailVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TPreEmpMainSearchVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TPreEmpMainVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 预入职-主表
 *
 * @author hgw
 * @date 2024-06-17 11:31:08
 */
@Log4j2
@AllArgsConstructor
@Service
public class TPreEmpMainServiceImpl extends ServiceImpl<TPreEmpMainMapper, TPreEmpMain> implements TPreEmpMainService {
	// 预入职-员工不良记录表
	private final TPreEmpBadRecordService tPreEmpBadRecordService;
	// 预入职-员工工作履历信息表
	private final TPreEmpWorkRecordingService tPreEmpWorkRecordingService;
	// 预入职-紧急联络人
	private final TPreEmpContactInfoService tPreEmpContactInfoService;
	// 预入职-员工申明
	private final TPreEmpDeclarationService tPreEmpDeclarationService;
	// 预入职-员工伤残信息表
	private final TPreEmpDisabilityInfoService tPreEmpDisabilityInfoService;
	// 预入职-员工学历信息表
	private final TPreEmpEducationService tPreEmpEducationService;
	// 预入职-员工家庭信息表
	private final TPreEmpFamilyService tPreEmpFamilyService;
	// 预入职-人员档案表
	private final TPreEmployeeInfoService tPreEmployeeInfoService;
	// 预入职-项目档案表
	private final TPreEmployeeProjectService tPreEmployeeProjectService;
	// 预入职-员工职业资格信息表
	private final TPreEmpProfessionalQualificationService tPreEmpProfessionalQualificationService;
	// 附件21（预入职申明签名）；22（预入职确认签名）；23（预入职pdf文件)
	private final TAttaInfoService tAttaInfoService;

	/**
	 * 预入职-主表简单分页查询
	 *
	 * @param tPreEmpMain 预入职-主表
	 * @return
	 */
	@Override
	public IPage<TPreEmpMain> getTPreEmpMainPage(Page<TPreEmpMain> page, TPreEmpMainSearchVo tPreEmpMain) {
		return baseMapper.getTPreEmpMainPage(page, tPreEmpMain);
	}

	/**
	 * @Description: 详情
	 * @Author: hgw
	 * @Date: 2024/6/17 17:19
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<com.yifu.cloud.plus.v1.yifu.archives.vo.PreEmpMainDetailVo>
	 **/
	@Override
	public R<PreEmpMainDetailVo> getInfoById(String id) {
		TPreEmpMain main = this.getById(id);
		PreEmpMainDetailVo vo = new PreEmpMainDetailVo();
		if (main != null && main.getId() != null) {
			vo.setMain(main);
			// 预入职-员工不良记录表
			List<TPreEmpBadRecord> tPreEmpBadRecord = tPreEmpBadRecordService.getTPreEmpBadRecordList(id);
			vo.setTPreEmpBadRecord(tPreEmpBadRecord);
			// 预入职-紧急联络人
			List<TPreEmpContactInfo> tPreEmpContactInfo = tPreEmpContactInfoService.getTPreEmpContactInfoList(id);
			vo.setTPreEmpContactInfo(tPreEmpContactInfo);
			// 预入职-员工申明
			TPreEmpDeclaration tPreEmpDeclaration = tPreEmpDeclarationService.getTPreEmpDeclarationList();
			vo.setTPreEmpDeclaration(tPreEmpDeclaration);
			// 预入职-员工伤残信息表
			List<TPreEmpDisabilityInfo> tPreEmpDisabilityInfo = tPreEmpDisabilityInfoService.getTPreEmpDisabilityInfoList(id);
			vo.setTPreEmpDisabilityInfo(tPreEmpDisabilityInfo);
			// 预入职-员工学历信息表
			List<TPreEmpEducation> tPreEmpEducation = tPreEmpEducationService.getTPreEmpEducationList(id);
			vo.setTPreEmpEducation(tPreEmpEducation);
			// 预入职-员工家庭信息表
			List<TPreEmpFamily> tPreEmpFamily = tPreEmpFamilyService.getTPreEmpFamilyList(id);
			vo.setTPreEmpFamily(tPreEmpFamily);
			// 预入职-人员档案表
			List<TPreEmployeeInfo> tPreEmployeeInfo = tPreEmployeeInfoService.getTPreEmployeeInfoList(id);
			vo.setTPreEmployeeInfo(tPreEmployeeInfo);
			// 预入职-项目档案表
			List<TPreEmployeeProject> tPreEmployeeProject = tPreEmployeeProjectService.getTPreEmployeeProjectList(id);
			vo.setTPreEmployeeProject(tPreEmployeeProject);
			// 预入职-员工职业资格信息表
			List<TPreEmpProfessionalQualification> tPreEmpProfessionalQualification = tPreEmpProfessionalQualificationService.getTPreEmpProfessionalQualificationList(id);
			vo.setTPreEmpProfessionalQualification(tPreEmpProfessionalQualification);
			// 预入职-员工工作履历信息表
			List<TPreEmpWorkRecording> tPreEmpWorkRecording = tPreEmpWorkRecordingService.getTPreEmpWorkRecordingList(id);
			vo.setTPreEmpWorkRecording(tPreEmpWorkRecording);

			// 预入职-附件 21（预入职申明签名）；22（预入职确认签名）；23（预入职pdf文件)
			List<TAttaInfo> attaInfoList = tAttaInfoService.getTAttaInfoListByDoMainId(id);
			vo.setAttaInfoList(attaInfoList);
			return R.ok(vo);
		} else {
			return R.failed("根据ID，未找到预入职主表！");
		}
	}

	/**
	 * @param vo
	 * @Description: 草稿
	 * @Author: hgw
	 * @Date: 2024/6/17 17:42
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.Boolean>
	 **/
	@Override
	public R<String> saveDraftPreEmpMain(PreEmpMainDetailVo vo) {
		return saveBase(vo, CommonConstants.ZERO_STRING);
	}

	/**
	 * @param vo
	 * @Description: 保存
	 * @Author: hgw
	 * @Date: 2024/6/17 17:42
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.Boolean>
	 **/
	@Override
	public R<String> savePreEmpMain(PreEmpMainDetailVo vo) {
		return saveBase(vo, CommonConstants.ONE_STRING);
	}

	/**
	 * @Description: 核心保存
	 * @Author: hgw
	 * @Date: 2024/6/17 17:44
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	private R<String> saveBase(PreEmpMainDetailVo vo, String status) {
		TPreEmpMain main = vo.getMain();
		if (main != null && Common.isNotNull(main.getEmpIdcard())) {
			main.setStatus(status);
			this.saveOrUpdate(main);
			String mainId = main.getId();

			// 预入职-员工不良记录表
			List<TPreEmpBadRecord> tPreEmpBadRecord = vo.getTPreEmpBadRecord();
			if (tPreEmpBadRecord != null) {
				for (TPreEmpBadRecord info : tPreEmpBadRecord) {
					info.setPreMainId(mainId);
				}
				tPreEmpBadRecordService.saveOrUpdateBatch(tPreEmpBadRecord);
			}
			// 预入职-紧急联络人
			List<TPreEmpContactInfo> tPreEmpContactInfo = vo.getTPreEmpContactInfo();
			if (tPreEmpContactInfo != null) {
				for (TPreEmpContactInfo info : tPreEmpContactInfo) {
					info.setPreMainId(mainId);
				}
				tPreEmpContactInfoService.saveOrUpdateBatch(tPreEmpContactInfo);
			}
			// 预入职-员工伤残信息表
			List<TPreEmpDisabilityInfo> tPreEmpDisabilityInfo = vo.getTPreEmpDisabilityInfo();
			if (tPreEmpDisabilityInfo != null) {
				for (TPreEmpDisabilityInfo info : tPreEmpDisabilityInfo) {
					info.setPreMainId(mainId);
				}
				tPreEmpDisabilityInfoService.saveOrUpdateBatch(tPreEmpDisabilityInfo);
			}
			// 预入职-员工学历信息表
			List<TPreEmpEducation> tPreEmpEducation = vo.getTPreEmpEducation();
			if (tPreEmpEducation != null) {
				for (TPreEmpEducation info : tPreEmpEducation) {
					info.setPreMainId(mainId);
				}
				tPreEmpEducationService.saveOrUpdateBatch(tPreEmpEducation);
			}
			// 预入职-员工家庭信息表
			List<TPreEmpFamily> tPreEmpFamily = vo.getTPreEmpFamily();
			if (tPreEmpFamily != null) {
				for (TPreEmpFamily info : tPreEmpFamily) {
					info.setPreMainId(mainId);
				}
				tPreEmpFamilyService.saveOrUpdateBatch(tPreEmpFamily);
			}
			// 预入职-人员档案表
			List<TPreEmployeeInfo> tPreEmployeeInfo = vo.getTPreEmployeeInfo();
			if (tPreEmployeeInfo != null) {
				for (TPreEmployeeInfo info : tPreEmployeeInfo) {
					info.setPreMainId(mainId);
				}
				tPreEmployeeInfoService.saveOrUpdateBatch(tPreEmployeeInfo);
			}
			// 预入职-项目档案表
			List<TPreEmployeeProject> tPreEmployeeProject = vo.getTPreEmployeeProject();
			if (tPreEmployeeProject != null) {
				for (TPreEmployeeProject info : tPreEmployeeProject) {
					info.setPreMainId(mainId);
				}
				tPreEmployeeProjectService.saveOrUpdateBatch(tPreEmployeeProject);
			}
			// 预入职-员工职业资格信息表
			List<TPreEmpProfessionalQualification> tPreEmpProfessionalQualification = vo.getTPreEmpProfessionalQualification();
			if (tPreEmpProfessionalQualification != null) {
				for (TPreEmpProfessionalQualification info : tPreEmpProfessionalQualification) {
					info.setPreMainId(mainId);
				}
				tPreEmpProfessionalQualificationService.saveOrUpdateBatch(tPreEmpProfessionalQualification);
			}
			// 预入职-员工工作履历信息表
			List<TPreEmpWorkRecording> tPreEmpWorkRecording = vo.getTPreEmpWorkRecording();
			if (tPreEmpWorkRecording != null) {
				for (TPreEmpWorkRecording info : tPreEmpWorkRecording) {
					info.setPreMainId(mainId);
				}
				tPreEmpWorkRecordingService.saveOrUpdateBatch(tPreEmpWorkRecording);
			}
			return R.ok("成功");
		} else {
			return R.failed("身份证不可为空！");
		}
	}

	/**
	 * 预入职-主表批量导出
	 *
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TPreEmpMainSearchVo searchVo) {
		String fileName = "预入职-主表批量导出" + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<TPreEmpMain> list = new ArrayList<>();
		long count = noPageCountDiy(searchVo);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, CommonConstants.UTF8));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, TPreEmpMain.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = noPageDiy(searchVo);
					if (Common.isNotNull(list)) {
						ExcelUtil<TPreEmpMain> util = new ExcelUtil<>(TPreEmpMain.class);
						for (TPreEmpMain vo : list) {
							util.convertEntity(vo, null, null, null);
						}
					}
					if (Common.isNotNull(list)) {
						WriteSheet writeSheet = EasyExcel.writerSheet("预入职-主表" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcel.writerSheet("预入职-主表" + index).build();
				excelWriter.write(list, writeSheet);
			}
			if (Common.isNotNull(list)) {
				list.clear();
			}
			out.flush();
			excelWriter.finish();
		} catch (Exception e) {
			log.error("执行异常", e);
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

	@Override
	public List<TPreEmpMain> noPageDiy(TPreEmpMainSearchVo searchVo) {
		LambdaQueryWrapper<TPreEmpMain> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)) {
			wrapper.in(TPreEmpMain::getId, idList);
		}
		if (searchVo.getLimitStart() >= 0 && searchVo.getLimitEnd() > 0) {
			wrapper.last(" limit " + searchVo.getLimitStart() + "," + searchVo.getLimitEnd());
		}
		wrapper.orderByDesc(BaseEntity::getCreateTime);
		return baseMapper.selectList(wrapper);
	}

	private Long noPageCountDiy(TPreEmpMainSearchVo searchVo) {
		LambdaQueryWrapper<TPreEmpMain> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)) {
			wrapper.in(TPreEmpMain::getId, idList);
		}
		return baseMapper.selectCount(wrapper);
	}

	private LambdaQueryWrapper buildQueryWrapper(TPreEmpMainSearchVo entity) {
		LambdaQueryWrapper<TPreEmpMain> wrapper = Wrappers.lambdaQuery();
		if (ArrayUtil.isNotEmpty(entity.getCreateTimes())) {
			wrapper.ge(TPreEmpMain::getCreateTime, entity.getCreateTimes()[0])
					.le(TPreEmpMain::getCreateTime,
							entity.getCreateTimes()[1]);
		}
		if (Common.isNotNull(entity.getCreateName())) {
			wrapper.eq(TPreEmpMain::getCreateName, entity.getCreateName());
		}
		return wrapper;
	}

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

				@Override
				public void invoke(TPreEmpMainVo 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());
					importTPreEmpMain(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 void importTPreEmpMain(List<TPreEmpMainVo> excelVOList, List<ErrorMessage> errorMessageList) {
		// 个性化校验逻辑
		ErrorMessage errorMsg;
		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			TPreEmpMainVo excel = excelVOList.get(i);
			// 数据合法情况 TODO

			// 插入
			insertExcel(excel);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS));
		}
	}

	/**
	 * 插入excel bad record
	 */
	private void insertExcel(TPreEmpMainVo excel) {
		TPreEmpMain insert = new TPreEmpMain();
		BeanUtil.copyProperties(excel, insert);
		this.save(insert);
	}
}
