/*
 *    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.*;
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.mapper.TEmployeeInfoMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeProjectMapper;
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.*;
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;

	private final TEmployeeInfoMapper employeeInfoMapper;

	private final TEmployeeProjectMapper projectMapper;

	@Override
	public IPage<TEmpContractAlert> pageDiy(Page page, ContractAlertSearchVo searchVo) {
		LambdaQueryWrapper<TEmpContractAlert> wrapper = buildQueryWrapper(searchVo);
		if (Common.isNotNull(searchVo.getAuthSql())) {
			wrapper.last(searchVo.getAuthSql() + " order by CREATE_TIME desc");
		} else {
			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);
		}
		wrapper.ne(TEmpContractAlert::getId,CommonConstants.ZERO_STRING);
		if (Common.isNotNull(searchVo.getAuthSql())) {
			if (Common.isNotNull(searchVo.getAuthSql()) && searchVo.getAuthSql().contains("a.")) {
				searchVo.setAuthSql(searchVo.getAuthSql().replace("a.", " "));
			}
			wrapper.last(searchVo.getAuthSql());
		}
		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 (Common.isNotNull(searchVo.getAuthSql())) {
			if (Common.isNotNull(searchVo.getAuthSql()) && searchVo.getAuthSql().contains("a.")) {
				searchVo.setAuthSql(searchVo.getAuthSql().replace("a.", " "));
			}
			wrapper.last(searchVo.getAuthSql());
		}
		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() + CommonConstants.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){
				WriteSheet writeSheet;
				ExcelUtil<TEmpContractAlert> util;
				for (int i = 0; i <= count; ) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = listDiy(searchVo);
					if (Common.isNotNull(list)){
						util = new ExcelUtil<>(TEmpContractAlert.class);
						for (TEmpContractAlert vo:list){
							util.convertEntity(vo,null,null,null);
						}
					}
					if (Common.isNotNull(list)){
						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();
		wrapper.ne(TEmpContractAlert::getId,CommonConstants.ZERO_STRING);
		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());
		}
		if (Common.isNotNull(entity.getDaysDue())){
			wrapper.eq(TEmpContractAlert::getDaysDue,entity.getDaysDue());
		}
		return wrapper;
	}
	/**
	 * 定时任务生成合同续签代码信息
	 * @return R<List>
	 * @Author FXJ
	 * @Date 2022-07-4
	 **/
	@Override
	public R<Boolean> taskCreateContractAlert() {
		// 获取合同为在档、员工类型为“0外包”、“1派遣”、最近一次合同审核通过、过期或离过期还有3个月的数据
		List<TEmployeeContractInfo> alertList = contractInfoMapper.selectList(Wrappers.<TEmployeeContractInfo>query()
				.lambda().eq(TEmployeeContractInfo::getAuditStatus,CommonConstants.TWO_STRING)
				.isNotNull(TEmployeeContractInfo::getAuditTimeLast)
				.eq(TEmployeeContractInfo::getIsObsolete,CommonConstants.ZERO_STRING)
				.eq(TEmployeeContractInfo::getContractType,CommonConstants.ONE_STRING)
				.eq(TEmployeeContractInfo::getWorkFlag,CommonConstants.ZERO_STRING)
				.ne(TEmployeeContractInfo::getSituation,"续签 ")
				.ne(TEmployeeContractInfo::getSituation,"终止")
				.le(TEmployeeContractInfo::getContractEnd,DateUtil.dateIncreaseByDay(
						DateUtil.dateIncreaseByMonth(DateUtil.getCurrentDateTime(),
						CommonConstants.dingleDigitIntArray[3]),CommonConstants.dingleDigitIntArray[1]))
				.eq(TEmployeeContractInfo::getDeleteFlag,CommonConstants.ZERO_STRING));
		// 获取所有未审核通过的合同数据
		List<TEmployeeContractInfo> notAccessList = contractInfoMapper.selectList(Wrappers.<TEmployeeContractInfo>query().lambda()
				.and(obj->obj.eq(TEmployeeContractInfo::getAuditStatus,CommonConstants.ZERO_STRING)
						.or().eq(TEmployeeContractInfo::getAuditStatus,CommonConstants.ONE_STRING))
				.eq(TEmployeeContractInfo::getIsObsolete,CommonConstants.ZERO_STRING)
				.eq(TEmployeeContractInfo::getWorkFlag,CommonConstants.ZERO_STRING)
				.eq(TEmployeeContractInfo::getDeleteFlag,CommonConstants.ZERO_STRING));
		Map<String,TEmpContractAlert> alertMap = new HashMap<>();
		Map<String,TEmpContractAlert> existMap = new HashMap<>();
		initExistMap(existMap);
		if (Common.isNotNull(alertList)){
			Date nowDate = new Date();
			for (TEmployeeContractInfo contract:alertList){
				extracted(nowDate, contract,alertMap,existMap);
			}
		}
		if (Common.isNotNull(notAccessList) && Common.isNotNull(alertMap)){
			TEmpContractAlert exist;
			for (TEmployeeContractInfo contract:notAccessList){
				exist = alertMap.get(contract.getEmpIdcard()+CommonConstants.DOWN_LINE_STRING+contract.getDeptNo());
				if (Common.isNotNull(exist)){
					exist.setHandleStatus(CommonConstants.ONE_STRING);
					alertMap.put(contract.getEmpIdcard()+CommonConstants.DOWN_LINE_STRING+contract.getDeptNo(),exist);
				}
			}
		}
		baseMapper.truncate();
		if (Common.isNotNull(alertMap)){
			this.saveBatch(alertMap.values());
		}
		return R.ok();
	}

	private void initExistMap(Map<String, TEmpContractAlert> existMap) {
		List<TEmpContractAlert> exists = baseMapper.selectList(Wrappers.<TEmpContractAlert>query());
		if (Common.isNotNull(exists)){
			for (TEmpContractAlert alert:exists){
				existMap.put(alert.getContractId(),alert);
			}
		}
	}

	private void extracted(Date nowDate,
						   TEmployeeContractInfo contract,
						   Map<String, TEmpContractAlert> alertMap,
						   Map<String, TEmpContractAlert> existMap) {
		TEmployeeInfo employeeInfo = employeeInfoMapper.selectById(contract.getEmpId());
		if (Common.isNotNull(employeeInfo)){
			TEmployeeProject project = projectMapper.selectOne(Wrappers.<TEmployeeProject>query().lambda()
					.eq(TEmployeeProject::getEmpIdcard,employeeInfo.getEmpIdcard())
					.eq(TEmployeeProject::getDeleteFlag,CommonConstants.ZERO_STRING)
					.eq(TEmployeeProject::getDeptNo,contract.getDeptNo())
					.last(CommonConstants.LAST_ONE_SQL));
			if (Common.isNotNull(project)
					&& ((Common.isNotNull(project.getProjectStatus())
					&& project.getProjectStatus().intValue()== CommonConstants.ONE_INT)
					|| (
					!CommonConstants.ZERO_STRING.equals(project.getEmpNatrue())
							&& !CommonConstants.ONE_STRING.equals(project.getEmpNatrue())
							&& !CommonConstants.THREE_STRING.equals(project.getEmpNatrue()))
					)){
				return;
			}
		}
		TEmpContractAlert alert = alertMap.get(contract.getEmpIdcard()+CommonConstants.DOWN_LINE_STRING+contract.getDeptNo());
		// 存在多个审核通过的数据 用最新的审核通过的合同覆盖已有的
		if (Common.isNotNull(alert)
				&& Common.isNotNull(alert.getAuditTime())
				&& Common.isNotNull(contract.getAuditTimeLast())
				&& alert.getAuditTime().after(LocalDateTimeUtils.convertLDTToDate(contract.getAuditTimeLast()))){
			return;
		}
		TEmpContractAlert exist = null;
		if (Common.isNotNull(contract)){
			exist = existMap.get(contract.getId());
		}
		alert = new TEmpContractAlert();
		if (Common.isNotNull(exist) && Common.isNotNull(exist.getFirstAlertTime())){
			alert.setFirstAlertTime(exist.getFirstAlertTime());
		}else {
			alert.setFirstAlertTime(new Date());
		}
		alert.setCreateBy(contract.getCreateBy());
		alert.setCreateName(contract.getCreateName());
		alert.setContractId(contract.getId());
		alert.setAlertPerson(contract.getCreateName());
		alert.setEmpName(contract.getEmpName());
		alert.setEmpId(contract.getEmpId());
		alert.setEmpCode(contract.getEmpNo());
		alert.setDeptId(contract.getSettleDomain());
		alert.setProject(contract.getSubjectDepart());
		alert.setProjectNo(contract.getDeptNo());
		alert.setEmpIdcard(contract.getEmpIdcard());
		alert.setContractStart(contract.getContractStart());
		alert.setContractEnd(contract.getContractEnd());
		alert.setAuditTime(LocalDateTimeUtils.convertLDTToDate(contract.getAuditTimeLast()));
		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()) && DateUtil.daysBetween(alert.getContractEnd(),nowDate) > 0){
				alert.setDaysOver(DateUtil.daysBetween(alert.getContractEnd(),nowDate));
				alert.setDueFlag(CommonConstants.ONE_STRING);
				alert.setDaysDue(null);
			}else {
				alert.setDaysDue(DateUtil.daysBetween(nowDate,alert.getContractEnd()));
				alert.setDueFlag(CommonConstants.ZERO_STRING);
				alert.setDaysOver(null);
			}
		}
		alert.setHandleStatus(CommonConstants.ZERO_STRING);
		alertMap.put(alert.getEmpIdcard()+CommonConstants.DOWN_LINE_STRING+alert.getProjectNo(),alert);
	}
}
