/*
 *    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.util.ArrayUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
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.constants.ArchivesConstants;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmpBadRecord;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmpContractAlert;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TEmployeeContractInfo;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmpContractAlertMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeContractInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TEmpContractAlertService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.ContractAlertSearchVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.DateUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.ExcelUtil;
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 javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 员工合同续签待办
 *
 * @author fxj
 * @date 2022-07-01 14:15:05
 */
@RequiredArgsConstructor
@Service
public class TEmpContractAlertServiceImpl extends ServiceImpl<TEmpContractAlertMapper, TEmpContractAlert> implements TEmpContractAlertService {

	private final TEmployeeContractInfoMapper  contractInfoMapper;

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

	@Override
	public List<TEmpContractAlert> listDiy(ContractAlertSearchVo searchVo) {
		LambdaQueryWrapper<TEmpContractAlert> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)){
			wrapper.in(TEmpContractAlert::getId,idList);
		}
		return baseMapper.selectList(wrapper);
	}

	private long noPageCountDiy(ContractAlertSearchVo searchVo) {
		LambdaQueryWrapper<TEmpContractAlert> wrapper = buildQueryWrapper(searchVo);
		List<String> idList = Common.getList(searchVo.getIds());
		if (Common.isNotNull(idList)){
			wrapper.in(TEmpContractAlert::getId,idList);
		}
		if (searchVo.getLimitStart() >= 0 && searchVo.getLimitEnd() >= 0){
			wrapper.last(" limit "+ searchVo.getLimitStart() +","+ searchVo.getLimitEnd());
		}
		return baseMapper.selectCount(wrapper);
	}

	@Override
	public void listExport(HttpServletResponse response, ContractAlertSearchVo searchVo) {
		String fileName = ArchivesConstants.EMP_BAD_RECORD + LocalDateTime.now() + ".xlsx";
		//获取要导出的列表
		List<TEmpContractAlert> list = new ArrayList<>();
		long count = noPageCountDiy(searchVo);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName  , CommonConstants.UTF8));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, TEmpBadRecord.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 = listDiy(searchVo);
					if (Common.isNotNull(list)){
						ExcelUtil<TEmpContractAlert> util = new ExcelUtil<>(TEmpContractAlert.class);
						for (TEmpContractAlert vo:list){
							util.convertEntity(vo,null,null,null);
						}
					}
					if (Common.isNotNull(list)){
						WriteSheet writeSheet = EasyExcel.writerSheet(ArchivesConstants.EMP_BAD_RECORD+index).build();
						excelWriter.write(list,writeSheet);
						index++;
						i = i + CommonConstants.EXCEL_EXPORT_LIMIT;
					}
					if (Common.isNotNull(list)){
						list.clear();
					}
				}
				excelWriter.finish();
			}else {
				WriteSheet writeSheet = EasyExcel.writerSheet(ArchivesConstants.EMP_BAD_RECORD+index).build();
				excelWriter.write(list,writeSheet);
				excelWriter.finish();
			}
			if (Common.isNotNull(list)){
				list.clear();
			}
			out.flush();
		}catch (Exception e){
			log.error("执行异常" ,e);
		}finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}

	private LambdaQueryWrapper buildQueryWrapper(ContractAlertSearchVo entity){
		LambdaQueryWrapper<TEmpContractAlert> wrapper = Wrappers.lambdaQuery();
		if (ArrayUtil.isNotEmpty(entity.getCreateTimes())) {
			wrapper.ge(TEmpContractAlert::getCreateTime, entity.getCreateTimes()[0])
					.le(TEmpContractAlert::getCreateTime,
							entity.getCreateTimes()[1]);
		}
		if (Common.isNotNull(entity.getEmpName())){
			wrapper.eq(TEmpContractAlert::getEmpName,entity.getEmpName());
		}
		if (Common.isNotNull(entity.getEmpIdcard())){
			wrapper.eq(TEmpContractAlert::getEmpIdcard,entity.getEmpIdcard());
		}
		if (Common.isNotNull(entity.getProject())){
			wrapper.eq(TEmpContractAlert::getProject,entity.getProject());
		}
		if (Common.isNotNull(entity.getProjectNo())){
			wrapper.eq(TEmpContractAlert::getProjectNo,entity.getProjectNo());
		}
		if (Common.isNotNull(entity.getEmpType())){
			wrapper.eq(TEmpContractAlert::getEmpType,entity.getEmpType());
		}
		if (Common.isNotNull(entity.getContractType())){
			wrapper.eq(TEmpContractAlert::getContractType,entity.getContractType());
		}
		if (Common.isNotNull(entity.getContractTerm())){
			wrapper.eq(TEmpContractAlert::getContractTerm,entity.getContractTerm());
		}
		if (Common.isNotNull(entity.getFileProvince())){
			wrapper.eq(TEmpContractAlert::getFileProvince,entity.getFileProvince());
		}
		if (Common.isNotNull(entity.getFileCity())){
			wrapper.eq(TEmpContractAlert::getFileCity,entity.getFileCity());
		}
		if (Common.isNotNull(entity.getFileTown())){
			wrapper.eq(TEmpContractAlert::getFileTown,entity.getFileTown());
		}

		if (Common.isNotNull(entity.getAlertPerson())){
			wrapper.eq(TEmpContractAlert::getAlertPerson,entity.getAlertPerson());
		}
		if (Common.isNotNull(entity.getDueFlag())){
			wrapper.eq(TEmpContractAlert::getDueFlag,entity.getDueFlag());
		}
		if (Common.isNotNull(entity.getHandleStatus())){
			wrapper.eq(TEmpContractAlert::getHandleStatus,entity.getHandleStatus());
		}
		return wrapper;
	}
	/**
	 * 定时任务生成合同续签代码信息
	 * @return R<List>
	 * @Author FXJ
	 * @Date 2022-07-4
	 **/
	@Override
	public R<Boolean> taskCreateContractAlert() {
		baseMapper.truncate();
		// 获取合同为在档、员工类型为“派遣”、“外包”、最近一次合同审核通过、过期或离过期还有3个月的数据
		List<TEmployeeContractInfo> alertList = contractInfoMapper.selectList(Wrappers.<TEmployeeContractInfo>query()
				.lambda().eq(TEmployeeContractInfo::getAuditStatus,CommonConstants.TWO_STRING)
				.isNotNull(TEmployeeContractInfo::getAuditTimeLast)
				.eq(TEmployeeContractInfo::getWorkFlag,CommonConstants.ZERO_STRING)
				.ge(TEmployeeContractInfo::getAuditTimeLast,DateUtil.dateIncreaseByMonth(DateUtil.getCurrentDateTime(),CommonConstants.THREE_INT_NEGATE))
				.eq(TEmployeeContractInfo::getDeleteFlag,CommonConstants.ZERO_STRING));
		// 获取所有未审核通过的合同数据
		List<TEmployeeContractInfo> notAccessList = contractInfoMapper.selectList(Wrappers.<TEmployeeContractInfo>query()
				.lambda().ne(TEmployeeContractInfo::getAuditStatus,CommonConstants.TWO_STRING)
				.eq(TEmployeeContractInfo::getWorkFlag,CommonConstants.ZERO_STRING)
				.eq(TEmployeeContractInfo::getDeleteFlag,CommonConstants.ZERO_STRING));
		Map<String,TEmpContractAlert> alertMap = new HashMap<>();
		if (Common.isNotNull(alertList)){
			Date nowDate = new Date();
			for (TEmployeeContractInfo contract:alertList){
				extracted(nowDate, contract,alertMap);
			}
		}
		if (Common.isNotNull(notAccessList) && Common.isNotNull(alertMap)){
			TEmpContractAlert exist;
			for (TEmployeeContractInfo contract:notAccessList){
				exist = alertMap.get(contract.getEmpIdcard());
				if (Common.isNotNull(exist)){
					exist.setHandleStatus(CommonConstants.ONE_STRING);
					alertMap.put(exist.getEmpIdcard(),exist);
				}

			}
		}
		if (Common.isNotNull(alertMap)){
			this.saveBatch(alertMap.values());
		}
		return R.ok();
	}

	private void extracted(Date nowDate,
						   TEmployeeContractInfo contract,
						   Map<String,TEmpContractAlert> alertMap) {
		TEmpContractAlert alert = alertMap.get(contract.getEmpIdcard());
		// 存在多个审核通过的数据 用最新的审核通过的合同覆盖已有的
		if (Common.isNotNull(alert) &&
				alert.getContractEnd().after(contract.getContractEnd())){
			return;
		}
		alert = new TEmpContractAlert();
		alert.setContractId(contract.getId());
		alert.setAlertPerson(contract.getCreateName());
		alert.setEmpName(contract.getEmpName());
		alert.setEmpId(contract.getEmpId());
		alert.setProject(contract.getSubjectDepart());
		alert.setProjectNo(contract.getDeptNo());
		alert.setEmpIdcard(contract.getEmpIdcard());
		alert.setContractStart(contract.getContractStart());
		alert.setContractEnd(contract.getContractEnd());
		if (Common.isNotNull(contract.getFileProvince())){
			alert.setFileProvince(Integer.toString(contract.getFileProvince()));
		}
		if (Common.isNotNull(contract.getFileCity())){
			alert.setFileCity(Integer.toString(contract.getFileCity()));
		}
		if (Common.isNotNull(contract.getFileTown())){
			alert.setFileTown(Integer.toString(contract.getFileTown()));
		}
		alert.setEmpType(contract.getEmpNatrue());
		alert.setContractType(contract.getContractName());
		alert.setContractTerm(contract.getContractType());
		if (Common.isNotNull(alert.getContractEnd())){
			if (Common.isNotNull(contract.getContractEnd()) && contract.getContractEnd().before(nowDate)){
				alert.setDueFlag(CommonConstants.ONE_STRING);
				alert.setDaysOver(DateUtil.daysBetween(nowDate,alert.getContractEnd()));
			}else {
				alert.setDaysDue(DateUtil.daysBetween(alert.getContractEnd(), nowDate));
				alert.setDueFlag(CommonConstants.ZERO_STRING);
			}
			alert.setFirstAlertTime(DateUtil.dateIncreaseByMonth(alert.getContractEnd(),CommonConstants.THREE_INT_NEGATE));
		}
		alert.setHandleStatus(CommonConstants.ZERO_STRING);
		alertMap.put(alert.getEmpIdcard(),alert);
	}
}
