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

import com.alibaba.excel.EasyExcel;
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.TCompleteMonitorFlagVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TCompleteMonitorInfoVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TCompleteMonitorSearchVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TCompleteMonitorVo;
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.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.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;
	}
}
