/*
 *    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.TEmpFamily;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmpContractAlertMapper;
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.archives.vo.FamilySearchVO;
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.ExcelUtil;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;
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.ArrayList;
import java.util.List;

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

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