package com.yifu.cloud.plus.v1.yifu.archives.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.TCompleteMonitor;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TCompleteMonitorMapper;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TEmployeeProjectMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TCompleteMonitorService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.*;
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 lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 档案完整度监控
 *
 * @author huyc
 * @date 2024-06-17 16:08:58
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class TCompleteMonitorServiceImpl extends ServiceImpl<TCompleteMonitorMapper, TCompleteMonitor> implements TCompleteMonitorService {

	private final TEmployeeProjectMapper projectMapper;

	/**
     * 档案完整度监控简单分页查询
     * @param tCompleteMonitor 档案完整度监控
     * @return
     */
    @Override
    public IPage<TCompleteMonitor> getTCompleteMonitorPage(Page<TCompleteMonitor> page, TCompleteMonitor tCompleteMonitor){
        return baseMapper.getTCompleteMonitorPage(page,tCompleteMonitor);
    }

    /**
     * 档案完整度监控批量导出
     * @param searchVo 档案完整度监控
     * @return
     */
    @Override
    public void listExport(HttpServletResponse response, TCompleteMonitorSearchVo searchVo){
        String fileName = "档案完整度监控列表" + DateUtil.getThisTime() + ".xlsx";
        //获取要导出的列表
        List<TCompleteMonitorVo> list = new ArrayList<>();
        long count = baseMapper.getExportCount(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，然后文件流会自动关闭
            //EasyExcel.write(out, TEmpBadRecord.class).sheet("不良记录").doWrite(list);
            ExcelWriter excelWriter = EasyExcel.write(out, TCompleteMonitorVo.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 = baseMapper.getTCompleteMonitorExportList(searchVo);
                    if (Common.isNotNull(list)){
                        ExcelUtil<TCompleteMonitorVo> util = new ExcelUtil<>(TCompleteMonitorVo.class);
                        for (TCompleteMonitorVo 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 void createComlpeteMonitor() throws IllegalAccessException {
		//先删除所有的档案监控数据
		baseMapper.deleteAllMonitorInfo();
		//批量查询项目档案的是否完整状态
		List<TCompleteMonitorFlagVo> flagList = baseMapper.checkEmpProjectCompleteFlag(null);
		if (!flagList.isEmpty()) {
			List<String> projectIdList = new ArrayList<>();
			String projectId;
			for(TCompleteMonitorFlagVo flagVo : flagList) {
				boolean flag = checkObjFieldIsNull(flagVo);
				if(!flag){
					projectId = flagVo.getEmpProjectId();
					projectIdList.add(projectId);
				}
			}
			//批量更新
			if (!projectIdList.isEmpty()) {
				projectMapper.batchUpdateEmpProjectCompleteStatus(projectIdList);
			}
		}

		//查询项目维度的信息
		List<TCompleteMonitor> list = baseMapper.getAllMonitorEmpList(null);
		//查询当天新增的项目档案数据来筛选需要刷新的数据
		this.saveBatch(list);
	}

	/**
	 * 档案完整度监控简单分页查询
	 * @param deptNo 项目编码
	 * @return
	 */
	@Override
	public IPage<TCompleteMonitorInfoVo> getMonitorEmpInfoListPage(Page<TCompleteMonitorInfoVo> page, String deptNo){
		return baseMapper.getMonitorEmpInfoList(page,deptNo);
	}

	@Override
	public void updateProjectStatusByDeptNo(String deptNo) throws IllegalAccessException{

		//批量查询项目档案的是否完整状态
		List<TCompleteMonitorFlagVo> flagList = baseMapper.checkEmpProjectCompleteFlag(deptNo);
		if (!flagList.isEmpty()) {
			List<String> projectIdList = new ArrayList<>();
			String projectId;
			for(TCompleteMonitorFlagVo flagVo : flagList) {
				boolean flag = checkObjFieldIsNull(flagVo);
				if(!flag){
					projectId = flagVo.getEmpProjectId();
					projectIdList.add(projectId);
				}
			}
			//批量更新
			if (!projectIdList.isEmpty()) {
				projectMapper.batchUpdateEmpProjectCompleteStatus(projectIdList);
			}
		}

		//删除项目监控表数据
		baseMapper.deleteMonitorInfoByDeptNo(deptNo);
		//查询项目维度的信息
		List<TCompleteMonitor> list = baseMapper.getAllMonitorEmpList(deptNo);
		//查询当天新增的项目档案数据来筛选需要刷新的数据
		this.saveBatch(list);
	}

	/**
	 *
	 * @param obj 对象
//	 * @param checkField  要检查的属性集合
	 * @return  true 指定属性有为空的   false  所有属性值都不为空
	 * @throws IllegalAccessException
	 */
	public boolean checkObjFieldIsNull(Object obj) throws IllegalAccessException {
		//获取对象的类
		Class<?> aClass = obj.getClass();
		Field[] declaredFields = aClass.getDeclaredFields();
		//筛选出包含在要检查的list 并且 属性为null的字段
		for(Field field : declaredFields){
			if (null == field.get(obj)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 档案完整度监控导出全量
	 * hgw 2024-6-26 11:19:18
	 */
	@Override
	public void exportAll(HttpServletResponse response, TCompleteMonitorSearchVo searchVo) {
		String name = "档案完整度监控导出全量";
		String fileName = name + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<TMainExportAllVO> list = Lists.newArrayList();
		long count = baseMapper.getTEmpMainAllCount(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，然后文件流会自动关闭
			List<List<String>> headList = Lists.newArrayList();
			headList.add(this.getNewArrayList(new String[]{"信息是否完整","信息是否完整"}));
			headList.add(this.getNewArrayList(new String[]{"进项目时间","进项目时间"}));
			String oneTitle = "员工基本信息";
			headList.add(this.getNewArrayList(new String[]{oneTitle,"员工主码"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"员工类型"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"员工姓名"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"身份证号"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"性别"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"身份证期限"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"身份证开始日期"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"身份证截止日期"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"出生日期"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"年龄"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"婚姻状况"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"民族"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"政治面貌"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"手机号码"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"邮箱"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"户籍所在地"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"户口性质"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"档案所在地"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"档案状态"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"通信地址"}));
			oneTitle = "在项信息";
			headList.add(this.getNewArrayList(new String[]{oneTitle,"客户名称"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"项目名称"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"业务类型"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"合同类型"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"工时制"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"就职岗位"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"入职日期"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"试用期"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"标签"}));
			oneTitle = "紧急联络人";
			headList.add(this.getNewArrayList(new String[]{oneTitle,"姓名"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"与本人关系"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"联系地址"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"联系电话"}));
			oneTitle = "最高教育经历";
			headList.add(this.getNewArrayList(new String[]{oneTitle,"学校"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"专业"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"学历"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"是否大专及以上"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"最高学历"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"入学时间"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"毕业时间"}));
			oneTitle = "主要工作经历";
			headList.add(this.getNewArrayList(new String[]{oneTitle,"是否为首份工作"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"工作单位"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"工作岗位"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"开始工作日期"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"结束工作日期"}));
			oneTitle = "主要家庭成员信息";
			headList.add(this.getNewArrayList(new String[]{oneTitle,"成员姓名"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"与本人关系"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"手机号码"}));
			oneTitle = "职业资格信息";
			headList.add(this.getNewArrayList(new String[]{oneTitle,"是否有职业资格证书"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"申报年度"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"职业资格名称"}));
			oneTitle = "伤残信息";
			headList.add(this.getNewArrayList(new String[]{oneTitle,"是否曾被认定为工伤"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"是否有职业病"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"职业病名称"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"是否有传染性疾病"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"传染病名称"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"是否持有残疾人证明"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"伤残病名称"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"伤残等级"}));
			headList.add(this.getNewArrayList(new String[]{oneTitle,"是否从事过井下、高空、高温、特别繁重体力劳动以及有毒有害工种"}));
			oneTitle = "不良记录";
			headList.add(this.getNewArrayList(new String[]{oneTitle,"不良记录描述"}));
			ExcelWriter excelWriter = EasyExcelFactory.write(out).head(headList).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = baseMapper.getTEmpMainAllList(searchVo);
					if (Common.isNotNull(list)) {
						WriteSheet writeSheet = EasyExcelFactory.writerSheet(name + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcelFactory.writerSheet(name + 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);
			}
		}
	}

	/**
	 * @Description: 转化
	 * @Author: hgw
	 * @Date: 2024/6/26 11:19
	 **/
	private List<String> getNewArrayList(String[] strArr) {
		return Arrays.asList(strArr);
	}

}
