package com.diagbot.facade;

import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.diagbot.dto.*;
import com.diagbot.entity.SysHospitalSet;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.util.*;
import com.diagbot.vo.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 控制台（医生）统计相关API
 * @author: zhanghang
 * @time: 2020/6/18 10:41
 */
@Component
public class ConsoleExportFacade {

    @Autowired
    private ConsoleFacade consoleFacade;
    @Autowired
    private BehospitalInfoFacade behospitalInfoFacade;
    @Autowired
    private SysHospitalSetFacade sysHospitalSetFacade;
    @Autowired
    private FilterFacade filterFacade;
    @Autowired
    private ConsoleByDoctorFacade consoleByDoctorFacade;

    /**
     * 病案首页合格率占比
     *
     * @param filterOrderVO
     * @return
     */
    public void homePageLevelExport(HttpServletResponse response, FilterOrderVO filterOrderVO) {
        List<HomePageNumDTO> res = consoleFacade.homePageLevelStatistics(filterOrderVO);
        String fileName = "病案首页合格率占比.xls";
        ExcelUtils.exportExcel(res, null, "sheet1", HomePageNumDTO.class, fileName, response, 12.8f);
    }

    /**
     * 病案首页合格率占比-湘雅
     *
     * @param filterOrderXYPageVO
     * @return
     */
    public void homePageLevelXYExport(HttpServletResponse response, FilterOrderXYPageVO filterOrderXYPageVO) {
        filterOrderXYPageVO.setCurrent(1L);
        filterOrderXYPageVO.setSize(Long.MAX_VALUE);
        filterOrderXYPageVO.setSearchCount(false);
        IPage<HomePageNumXYDTO> res = consoleFacade.homePageLevelStatisticsXY(filterOrderXYPageVO);
        String fileName = "病案首页合格率占比.xls";
        ExcelUtils.exportExcel(res.getRecords(), null, "sheet1", HomePageNumXYDTO.class, fileName, response, 12.8f);
    }

    /**
     * 条目缺陷占比（内页）
     *
     * @param filterPageVO
     * @return
     */
    public void entryGroupByEntryExport(HttpServletResponse response, FilterPageVO filterPageVO) {
        filterPageVO.setCurrent(1L);
        filterPageVO.setSize(Long.MAX_VALUE);
        filterPageVO.setSearchCount(false);
        IPage<EntryNumDTO> page = consoleFacade.entryGroupByEntryInnerPage(filterPageVO);
        String fileName = "条目缺陷占比.xls";
        ExcelUtils.exportExcel(page.getRecords(), null, "sheet1", EntryNumDTO.class, fileName, response, 12.8f);
    }

    /**
     * 稽查统计导出（首页）
     *
     * @param filterVO
     * @return
     */
    public void medicalCheckExport(HttpServletResponse response, FilterMedicalCheckVO filterVO) {
        filterVO.setCurrent(1L);
        filterVO.setSize(Long.MAX_VALUE);
        filterVO.setSearchCount(false);
        String fileName = null;
        if ("1".equals(filterVO.getIsPlacefile())) {
            fileName = "终末病历稽查表.xls";
        } else {
            fileName = "运行病历稽查表.xls";
        }
        List<MedicalCheckExportDTO> records = consoleFacade.medicalCheckExport(filterVO);
        ExcelUtils.exportExcel(records, null, "sheet1", MedicalCheckExportDTO.class, fileName, response, 15.8f);
    }

    /**
     * 各科室缺陷占比（组合）
     *
     * @param filterOrderVO
     * @return
     */
    public void levelExport(HttpServletResponse response, FilterOrderVO filterOrderVO) {
        List<LevelStatisticsDTO> records = consoleFacade.levelStatisticsStr(filterOrderVO);
        String fileName = "各科室缺陷占比.xls";
        ExcelUtils.exportExcel(records, null, "sheet1", LevelStatisticsDTO.class, fileName, response, 12.8f);
    }

    /**
     * 各科室缺陷占比（组合）-台州-导出
     *
     * @param filterOrderVO
     * @return
     */
    public void levelExport_TZ(HttpServletResponse response, FilterOrderVO filterOrderVO) {
        List<LevelStatisticsTZDTO> records = consoleFacade.levelStatisticsByDeptStr_TZ(filterOrderVO);
        String fileName = "各科室缺陷占比-台州.xls";
        ExcelUtils.exportExcel(records, null, "sheet1", LevelStatisticsTZDTO.class, fileName, response, 12.8f);
    }

    /**
     * 按科室统计平均住院天数导出
     *
     * @param filterPageByAverageVO
     * @return
     */
    public void getAverageDayNumExport(HttpServletResponse response, FilterPageByAverageVO filterPageByAverageVO) {
        filterPageByAverageVO.setCurrent(1L);
        filterPageByAverageVO.setSize(Long.MAX_VALUE);
        filterPageByAverageVO.setSearchCount(false);
        IPage<AverageStatisticsDTO> page = consoleFacade.getAverageDayNumPage(filterPageByAverageVO);
        String fileName = " 按科室统计平均住院天数.xls";

        if (filterPageByAverageVO.getType() == 2) {
            ExcelUtils.exportExcel(page.getRecords(), null, "sheet1", AverageStatisticsDTO.class, fileName, response, 12.8f);
        }
        if (filterPageByAverageVO.getType() == 1) {
            List<AverageStatisticsMonthDTO> list = BeanUtil.listCopyTo(page.getRecords(), AverageStatisticsMonthDTO.class);
            ExcelUtils.exportExcel(list, null, "sheet1", AverageStatisticsMonthDTO.class, fileName, response, 12.8f);
        }

    }

    /**
     * 按科室统计平均住院费用导出
     *
     * @param filterPageByAverageVO
     * @return
     */
    public void getAverageFeeExport(HttpServletResponse response, FilterPageByAverageVO filterPageByAverageVO) {
        filterPageByAverageVO.setCurrent(1L);
        filterPageByAverageVO.setSize(Long.MAX_VALUE);
        filterPageByAverageVO.setSearchCount(false);
        IPage<AverageStatisticsFeeDTO> page = consoleFacade.getAverageFeePage(filterPageByAverageVO);
        String fileName = " 按科室统计平均住院费用.xls";

        if (filterPageByAverageVO.getType() == 2) {
            ExcelUtils.exportExcel(page.getRecords(), null, "sheet1", AverageStatisticsFeeDTO.class, fileName, response, 12.8f);
        }
        if (filterPageByAverageVO.getType() == 1) {
            List<AverageStatisticsFeeMonthDTO> list = BeanUtil.listCopyTo(page.getRecords(), AverageStatisticsFeeMonthDTO.class);
            ExcelUtils.exportExcel(list, null, "sheet1", AverageStatisticsFeeMonthDTO.class, fileName, response, 12.8f);
        }
    }

    /**
     * 各科室甲级病历占比排行导出
     *
     * @param filterPageVO
     * @return
     */
    public void levelPercentGroupByDeptExport(HttpServletResponse response, FilterPageVO filterPageVO) {
        filterPageVO.setCurrent(1L);
        filterPageVO.setSize(Long.MAX_VALUE);
        filterPageVO.setSearchCount(false);
        IPage<QcResultPercentDTO> page = consoleFacade.levelPercentGroupByDeptPage(filterPageVO);
        String fileName = " 各科室甲级病历占比排行.xls";
        ExcelUtils.exportExcel(page.getRecords(), null, "sheet1", QcResultPercentDTO.class, fileName, response, 12.8f);
    }

    /**
     * 缺陷详情导出
     *
     * @param filterPageVO
     * @return
     */
    public void entryCountGroupByEntryExport(HttpServletResponse response, FilterPageVO filterPageVO) {
        filterPageVO.setCurrent(1L);
        filterPageVO.setSize(Long.MAX_VALUE);
        filterPageVO.setSearchCount(false);
        IPage<EntryNumGroupDTO> page = consoleFacade.entryCountGroupByEntryPage(filterPageVO);
        String fileName = "缺陷详情.xls";
        ExcelUtils.exportExcel(page.getRecords(), null, "sheet1", EntryNumGroupDTO.class, fileName, response, 12.8f);
    }

    /**
     * 缺陷详情导出-湘雅
     *
     * @param filterPageVO
     * @return
     */
    public void entryCountGroupXYByEntryExport(HttpServletResponse response, FilterPageXYVO filterPageVO) {
        filterPageVO.setCurrent(1L);
        filterPageVO.setSize(Long.MAX_VALUE);
        filterPageVO.setSearchCount(false);
        IPage<EntryNumGroupDTO> page = consoleFacade.entryCountGroupXYByEntryPage(filterPageVO);
        String fileName = "缺陷详情.xls";
        ExcelUtils.exportExcel(page.getRecords(), null, "sheet1", EntryNumGroupDTO.class, fileName, response, 12.8f);
    }


    /**
     * 各模块缺陷占比导出
     *
     * @param filterPageVO
     * @return
     */
    public void entryCountGroupByCaseExport(HttpServletResponse response, FilterPageVO filterPageVO) {
        filterPageVO.setCurrent(1L);
        filterPageVO.setSize(Long.MAX_VALUE);
        filterPageVO.setSearchCount(false);
        IPage<NumDTO> page = consoleFacade.entryCountGroupByCasePage(filterPageVO);
        String fileName = "缺陷详情.xls";
        ExcelUtils.exportExcel(page.getRecords(), null, "sheet1", NumDTO.class, fileName, response, 12.8f);
    }

    /**
     * 关键条目缺陷占比统计
     *
     * @param entryStatisticsVO
     * @return
     */
    public void entryStatisticsExport(HttpServletResponse response, EntryStatisticsVO entryStatisticsVO) {
        List<EntryStatisticsDTO> records = consoleFacade.entryStatistics(entryStatisticsVO);
        String fileName = "关键条目缺陷占比统计.xls";
        ExcelUtils.exportExcel(records, null, "sheet1", EntryStatisticsDTO.class, fileName, response, 12.8f);
    }

    /**
     * 缺陷详情质控评分页导出
     *
     * @param qcResultShortPageVO
     * @return
     */
    public void qcResultShortPageExport(HttpServletResponse response, QcResultShortPageVO qcResultShortPageVO) {
        String hospitalId = SysUserUtils.getCurrentHospitalID();
        qcResultShortPageVO.setHospitalId(hospitalId);
        if (StringUtil.isNotBlank(qcResultShortPageVO.getDeptName())
                && qcResultShortPageVO.getDeptName().equals("全部")) {
            qcResultShortPageVO.setDeptName("");
        }
        Date startDate = qcResultShortPageVO.getStartDate();
        Date endDate = qcResultShortPageVO.getEndDate();
        //时间间隔90天
        long interval = 90 * 24l * 60l * 60l * 1000l;
        if (endDate.getTime() < startDate.getTime()) {
            throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
        }
        if (endDate.getTime() - startDate.getTime() > interval) {
            throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于90天");
        }

        qcResultShortPageVO.setCurrent(1L);
        qcResultShortPageVO.setSize(Long.MAX_VALUE);
        qcResultShortPageVO.setSearchCount(false);
        List<ExportExcelDTO> record = behospitalInfoFacade.qcResultShortPageExport(qcResultShortPageVO);
        String fileName = "缺陷详情质控评分页.xls";
        ExcelUtils.exportExcelUser(record, null, "sheet1", ExportExcelDTO.class, fileName, response);
    }

    /**
     * 缺陷详情质控评分页导出-湘雅
     *
     * @param qcResultShortPageVO
     * @return
     */
    public void qcResultShortXYPageExport(HttpServletResponse response, QcResultShortXYPageVO qcResultShortPageVO) {
        String hospitalId = SysUserUtils.getCurrentHospitalID();
        qcResultShortPageVO.setHospitalId(hospitalId);
        if (StringUtil.isNotBlank(qcResultShortPageVO.getDeptName())
                && qcResultShortPageVO.getDeptName().equals("全部")) {
            qcResultShortPageVO.setDeptName("");
        }
        Date startDate = qcResultShortPageVO.getStartDate();
        Date endDate = qcResultShortPageVO.getEndDate();
        //时间间隔90天
        long interval = 90 * 24l * 60l * 60l * 1000l;
        if (endDate.getTime() < startDate.getTime()) {
            throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
        }
        if (endDate.getTime() - startDate.getTime() > interval) {
            throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于90天");
        }

        qcResultShortPageVO.setCurrent(1L);
        qcResultShortPageVO.setSize(Long.MAX_VALUE);
        qcResultShortPageVO.setSearchCount(false);
        List<ExportExcelDTO> record = behospitalInfoFacade.getBaseMapper().qcResultShortXYPageExport(qcResultShortPageVO);
        String fileName = "缺陷详情质控评分页.xls";
        ExcelUtils.exportExcelUser(record, null, "sheet1", ExportExcelDTO.class, fileName, response);
    }

    /**
     * 出院人数统计导出
     *
     * @param qcResultShortPageVO
     * @return
     */
    public void leaveHosMrPageExport(HttpServletResponse response, QcResultShortPageVO qcResultShortPageVO) {
        String hospitalId = SysUserUtils.getCurrentHospitalID();
        qcResultShortPageVO.setHospitalId(hospitalId);
        if (StringUtil.isNotBlank(qcResultShortPageVO.getDeptName())
                && qcResultShortPageVO.getDeptName().equals("全部")) {
            qcResultShortPageVO.setDeptName("");
        }
        Date startDate = qcResultShortPageVO.getStartDate();
        Date endDate = qcResultShortPageVO.getEndDate();
        //时间间隔7天
        long interval_7 = 7 * 24 * 60 * 60 * 1000;
        long interval_90 = 90 * 24 * 60 * 60 * 1000l;

        if ("1".equals(qcResultShortPageVO.getRadioCheck())) {
            //时间间隔7天
            if (endDate.getTime() < startDate.getTime()) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
            }
            if (endDate.getTime() - startDate.getTime() > interval_7) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于7天");
            }
        } else {
            //时间间隔90天
            if (endDate.getTime() < startDate.getTime()) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
            }
            if (endDate.getTime() - startDate.getTime() > interval_90) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于90天");
            }
        }

        qcResultShortPageVO.setCurrent(1L);
        qcResultShortPageVO.setSize(Long.MAX_VALUE);
        qcResultShortPageVO.setSearchCount(false);
        List<ExportExcelDTO> records = behospitalInfoFacade.leaveHosMRPageExport(qcResultShortPageVO);
        List<ExportWideExcelDTO> resWide = new ArrayList<ExportWideExcelDTO>();
        if ("2".equals(qcResultShortPageVO.getRadioCheck())) {
            resWide = transList(records, resWide);
        }
        String fileName = "出院人数统计.xls";
        if ("1".equals(qcResultShortPageVO.getRadioCheck())) {
            ExcelUtils.exportExcelUser(records, null, "sheet1", ExportExcelDTO.class, fileName, response);
        }
        if ("2".equals(qcResultShortPageVO.getRadioCheck())) {
            ExcelUtils.exportExcelUser(resWide, null, "sheet1", ExportWideExcelDTO.class, fileName, response);
        }
    }

    public List<ExportWideExcelDTO> transList(List<ExportExcelDTO> res, List<ExportWideExcelDTO> resWide) {
        if (ListUtil.isNotEmpty(res)) {
            res.forEach(exportExcelDTO -> {
                ExportWideExcelDTO exportWideExcelDTO = new ExportWideExcelDTO();
                exportWideExcelDTO.setAvgScore(exportExcelDTO.getAvgScore());
                exportWideExcelDTO.setBehDeptName(exportExcelDTO.getBehDeptName());
                List<ExportExcelBehospitalDTO> excelBehospitalDTOS = exportExcelDTO.getExcelBehospitalDTOS();
                List<ExportExcelWideBehospitalDTO> exportExcelWideBehospitalDTOs = new ArrayList<>();
                excelBehospitalDTOS.forEach(exportExcelBehospitalDTO -> {
                    ExportExcelWideBehospitalDTO exportExcelWideBehospitalDTO = new ExportExcelWideBehospitalDTO();
                    exportExcelWideBehospitalDTO.setDoctorName(exportExcelBehospitalDTO.getDoctorName());
                    exportExcelWideBehospitalDTO.setBehospitalCode(exportExcelBehospitalDTO.getBehospitalCode());
                    exportExcelWideBehospitalDTO.setBehospitalDate(exportExcelBehospitalDTO.getBehospitalDate());
                    exportExcelWideBehospitalDTO.setLeaveHospitalDate(exportExcelBehospitalDTO.getLeaveHospitalDate());
                    exportExcelWideBehospitalDTO.setPatName(exportExcelBehospitalDTO.getPatName());
                    exportExcelWideBehospitalDTO.setScore(exportExcelBehospitalDTO.getScore());
                    exportExcelWideBehospitalDTO.setScoreBn(exportExcelBehospitalDTO.getScoreBn());
                    exportExcelWideBehospitalDTOs.add(exportExcelWideBehospitalDTO);
                });
                exportWideExcelDTO.setExcelBehospitalDTOS(exportExcelWideBehospitalDTOs);
                resWide.add(exportWideExcelDTO);
            });
        }
        return resWide;
    }

    /**
     * 质控核查统计导出
     *
     * @param filterOrderVO
     * @return
     */
    public void qcCheckStatisticsExport(HttpServletResponse response, FilterOrderVO filterOrderVO) {
        List<HomePageImproveDTO> records = consoleFacade.qcCheckStatistics(filterOrderVO);
        String fileName = "质控核查统计.xls";
        ExcelUtils.exportExcel(records, null, "sheet1", HomePageImproveDTO.class, fileName, response, 12.8f);
    }

    /**
     * 未整改病历详情页导出
     *
     * @param qcResultShortPageVO
     * @return
     */
    public void unModifyMRPageExport(HttpServletResponse response, QcResultShortPageVO qcResultShortPageVO) {
        String hospitalId = SysUserUtils.getCurrentHospitalID();
        qcResultShortPageVO.setHospitalId(hospitalId);
        if (StringUtil.isNotBlank(qcResultShortPageVO.getDeptName())
                && qcResultShortPageVO.getDeptName().equals("全部")) {
            qcResultShortPageVO.setDeptName("");
        }
        Date startDate = qcResultShortPageVO.getStartDate();
        Date endDate = qcResultShortPageVO.getEndDate();
        //时间间隔7天
        long interval = 90 * 24l * 60l * 60l * 1000l;
        if (endDate.getTime() < startDate.getTime()) {
            throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
        }
        if (endDate.getTime() - startDate.getTime() > interval) {
            throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于90天");
        }

        qcResultShortPageVO.setCurrent(1L);
        qcResultShortPageVO.setSize(Long.MAX_VALUE);
        qcResultShortPageVO.setSearchCount(false);
        List<ExportExcelDTO> records = behospitalInfoFacade.unModifyMRPageExport(qcResultShortPageVO);
        String fileName = "未整改病历详情页.xls";
        ExcelUtils.exportExcelUser(records, null, "sheet1", ExportExcelDTO.class, fileName, response);
    }

    /**
     * 病案首页不合格/合格数
     *
     * @param qcResultShortPageVO
     * @return
     */
    public void badLevelPagePageExport(HttpServletResponse response, QcResultShortPageVO qcResultShortPageVO) {
        String hospitalId = SysUserUtils.getCurrentHospitalID();
        qcResultShortPageVO.setHospitalId(hospitalId);
        if (StringUtil.isNotBlank(qcResultShortPageVO.getDeptName())
                && qcResultShortPageVO.getDeptName().equals("全部")) {
            qcResultShortPageVO.setDeptName("");
        }
        Date startDate = qcResultShortPageVO.getStartDate();
        Date endDate = qcResultShortPageVO.getEndDate();
        //时间间隔7天
        long interval_7 = 7 * 24 * 60 * 60 * 1000;
        long interval_90 = 90 * 24 * 60 * 60 * 1000l;

        if ("1".equals(qcResultShortPageVO.getRadioCheck())) {
            //时间间隔7天
            if (endDate.getTime() < startDate.getTime()) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
            }
            if (endDate.getTime() - startDate.getTime() > interval_7) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于7天");
            }
        } else {
            //时间间隔90天
            if (endDate.getTime() < startDate.getTime()) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
            }
            if (endDate.getTime() - startDate.getTime() > interval_90) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于90天");
            }
        }

        qcResultShortPageVO.setCurrent(1L);
        qcResultShortPageVO.setSize(Long.MAX_VALUE);
        qcResultShortPageVO.setSearchCount(false);
        List<ExportExcelDTO> records = behospitalInfoFacade.badLevelPagePageExport(qcResultShortPageVO);
        List<ExportWideExcelDTO> resWide = new ArrayList<ExportWideExcelDTO>();
        if ("2".equals(qcResultShortPageVO.getRadioCheck())) {
            resWide = transList(records, resWide);
        }
        String fileName = null;
        if ("不合格数".equals(qcResultShortPageVO.getTitleName())) {
            fileName = "病案首页不合格数病历详情页.xls";
        } else {
            fileName = "病案首页合格数病历详情页.xls";
        }
        if ("1".equals(qcResultShortPageVO.getRadioCheck())) {
            ExcelUtils.exportExcelUser(records, null, "sheet1", ExportExcelDTO.class, fileName, response);
        }
        if ("2".equals(qcResultShortPageVO.getRadioCheck())) {
            ExcelUtils.exportExcelUser(resWide, null, "sheet1", ExportWideExcelDTO.class, fileName, response);
        }
    }

    /**
     * 病案首页不合格/合格数-XY
     *
     * @param qcResultShortPageVO
     * @return
     */
    public void badLevelPageXYExport(HttpServletResponse response, QcResultShortXYPageVO qcResultShortPageVO) {
        String hospitalId = SysUserUtils.getCurrentHospitalID();
        qcResultShortPageVO.setHospitalId(hospitalId);
        if (StringUtil.isNotBlank(qcResultShortPageVO.getDeptName())
                && qcResultShortPageVO.getDeptName().equals("全部")) {
            qcResultShortPageVO.setDeptName("");
        }
        Date startDate = qcResultShortPageVO.getStartDate();
        Date endDate = qcResultShortPageVO.getEndDate();
        //时间间隔7天
        long interval_7 = 7 * 24 * 60 * 60 * 1000;
        long interval_90 = 90 * 24 * 60 * 60 * 1000l;

        if ("1".equals(qcResultShortPageVO.getRadioCheck())) {
            //时间间隔7天
            if (endDate.getTime() < startDate.getTime()) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
            }
            if (endDate.getTime() - startDate.getTime() > interval_7) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于7天");
            }
        } else {
            //时间间隔90天
            if (endDate.getTime() < startDate.getTime()) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
            }
            if (endDate.getTime() - startDate.getTime() > interval_90) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于90天");
            }
        }

        qcResultShortPageVO.setCurrent(1L);
        qcResultShortPageVO.setSize(Long.MAX_VALUE);
        qcResultShortPageVO.setSearchCount(false);
        List<ExportExcelDTO> records = behospitalInfoFacade.getBaseMapper().badLevelPageXYExport(qcResultShortPageVO);
        List<ExportWideExcelDTO> resWide = new ArrayList<ExportWideExcelDTO>();
        if ("2".equals(qcResultShortPageVO.getRadioCheck())) {
            resWide = transList(records, resWide);
        }
        String fileName = null;
        if ("不合格数".equals(qcResultShortPageVO.getTitleName())) {
            fileName = "病案首页不合格数病历详情页.xls";
        } else {
            fileName = "病案首页合格数病历详情页.xls";
        }
        if ("1".equals(qcResultShortPageVO.getRadioCheck())) {
            ExcelUtils.exportExcelUser(records, null, "sheet1", ExportExcelDTO.class, fileName, response);
        }
        if ("2".equals(qcResultShortPageVO.getRadioCheck())) {
            ExcelUtils.exportExcelUser(resWide, null, "sheet1", ExportWideExcelDTO.class, fileName, response);
        }
    }

    /**
     * 未整改病历统计导出
     *
     * @param response
     * @param filterUnModifyMRVO
     */
    public void unModifyMRStatisticsExport(HttpServletResponse response, FilterUnModifyMRVO filterUnModifyMRVO) {
        filterFacade.filterUnModifyMRVOSet(filterUnModifyMRVO);
        List<ExcelExportEntity> colList = Lists.newLinkedList();
        ExcelExportEntity deptNameCol = new ExcelExportEntity("科室", "deptName");
        deptNameCol.setWidth(50);
        colList.add(deptNameCol);

        QueryWrapper<SysHospitalSet> hospitalSetQueryWrapper = new QueryWrapper<>();
        hospitalSetQueryWrapper.eq("is_deleted", 'N')
                .eq("hospital_id", filterUnModifyMRVO.getHospitalId())
                .eq("code", "unmodify_mr_entry");
        SysHospitalSet hospitalSet = sysHospitalSetFacade.getOne(hospitalSetQueryWrapper);
        //缺陷条目未维护
        if (hospitalSet == null || StringUtil.isBlank(hospitalSet.getValue())) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "未整改病历条目未设置");
        }

        List<String> columnSet = Arrays.asList(hospitalSet.getValue().split(","));
        for (String valueStr : columnSet) {
            if (StringUtil.isBlank(valueStr)) {
                continue;
            }
            String[] keyValue = valueStr.split("--");
            if (keyValue != null || keyValue.length > 1) {
                ExcelExportEntity entryCol = new ExcelExportEntity(keyValue[1], "entry_" + keyValue[0] + "_num");
                entryCol.setWidth(20);
                colList.add(entryCol);
            }
        }
        UnModifyMRDTO unModifyMRDTO = consoleFacade.unModifyMRStatistics(filterUnModifyMRVO);
        List<Object> data = Lists.newLinkedList();
        if (unModifyMRDTO != null && ListUtil.isNotEmpty(unModifyMRDTO.getData())) {
            data = unModifyMRDTO.getData();
        }
        String fileName = "未整改病历统计.xls";
        ExcelUtils.exportExcelDynamicCol(colList, data, null, "sheet1", fileName, response);
    }

    /**
     * 31天再入院统计导出
     *
     * @param reBeHosPageVO
     * @return
     */
    public void reHos31DaysPageExport(HttpServletResponse response, ReBeHosPageVO reBeHosPageVO) {
        reBeHosPageVO.setSearchCount(false);
        reBeHosPageVO.setFlag(1);
        IPage<ReBeHosDTO> page = consoleFacade.reHos31DaysPage(reBeHosPageVO);
        List<ReBeHosDTO> records = page.getRecords();
        String fileName = "31天再入院统计详情.xls";
        ExcelUtils.exportExcel(records, null, "sheet1", ReBeHosDTO.class, fileName, response);
    }

    /**
     * 病案首页改善率质控评分页导出
     *
     * @param qcResultShortPageVO
     * @return
     */
    public void hmImproveMRPageExport(HttpServletResponse response, QcResultShortPageVO qcResultShortPageVO) {
        String hospitalId = SysUserUtils.getCurrentHospitalID();
        qcResultShortPageVO.setHospitalId(hospitalId);
        if (StringUtil.isNotBlank(qcResultShortPageVO.getDeptName())
                && qcResultShortPageVO.getDeptName().equals("全部")) {
            qcResultShortPageVO.setDeptName("");
        }
        Date startDate = qcResultShortPageVO.getStartDate();
        Date endDate = qcResultShortPageVO.getEndDate();
        //时间间隔7天
        long interval_7 = 7 * 24 * 60 * 60 * 1000;
        long interval_90 = 90 * 24 * 60 * 60 * 1000l;

        if ("1".equals(qcResultShortPageVO.getRadioCheck())) {
            //时间间隔7天
            if (endDate.getTime() < startDate.getTime()) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
            }
            if (endDate.getTime() - startDate.getTime() > interval_7) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于7天");
            }
        } else {
            //时间间隔90天
            if (endDate.getTime() < startDate.getTime()) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
            }
            if (endDate.getTime() - startDate.getTime() > interval_90) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于90天");
            }
        }

        qcResultShortPageVO.setCurrent(1L);
        qcResultShortPageVO.setSize(Long.MAX_VALUE);
        qcResultShortPageVO.setSearchCount(false);
        List<ExportExcelDTO> records = behospitalInfoFacade.hmImproveMRPageExport(qcResultShortPageVO);
        List<ExportWideExcelDTO> resWide = new ArrayList<ExportWideExcelDTO>();
        if ("2".equals(qcResultShortPageVO.getRadioCheck())) {
            resWide = transList(records, resWide);
        }
        String fileName = "病案首页改善率评分病历导出.xls";
        if ("1".equals(qcResultShortPageVO.getRadioCheck())) {
            ExcelUtils.exportExcelUser(records, null, "sheet1", ExportExcelDTO.class, fileName, response);
        }
        if ("2".equals(qcResultShortPageVO.getRadioCheck())) {
            ExcelUtils.exportExcelUser(resWide, null, "sheet1", ExportWideExcelDTO.class, fileName, response);
        }
    }

    /**
     * 质控核查质控评分页导出
     *
     * @param qcResultShortPageVO
     * @return
     */
    public void qcCheckMRPageExport(HttpServletResponse response, QcResultShortPageVO qcResultShortPageVO) {
        String hospitalId = SysUserUtils.getCurrentHospitalID();
        qcResultShortPageVO.setHospitalId(hospitalId);
        if (StringUtil.isNotBlank(qcResultShortPageVO.getDeptName())
                && qcResultShortPageVO.getDeptName().equals("全部")) {
            qcResultShortPageVO.setDeptName("");
        }
        Date startDate = qcResultShortPageVO.getStartDate();
        Date endDate = qcResultShortPageVO.getEndDate();

        //时间间隔7天
        long interval_7 = 7 * 24 * 60 * 60 * 1000;
        long interval_90 = 90 * 24 * 60 * 60 * 1000l;

        if ("1".equals(qcResultShortPageVO.getRadioCheck())) {
            //时间间隔7天
            if (endDate.getTime() < startDate.getTime()) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
            }
            if (endDate.getTime() - startDate.getTime() > interval_7) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于7天");
            }
        } else {
            //时间间隔90天
            if (endDate.getTime() < startDate.getTime()) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
            }
            if (endDate.getTime() - startDate.getTime() > interval_90) {
                throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于90天");
            }
        }

        qcResultShortPageVO.setCurrent(1L);
        qcResultShortPageVO.setSize(Long.MAX_VALUE);
        qcResultShortPageVO.setSearchCount(false);
        List<ExportExcelDTO> records = behospitalInfoFacade.qcCheckMRPageExport(qcResultShortPageVO);
        List<ExportWideExcelDTO> resWide = new ArrayList<ExportWideExcelDTO>();
        if ("2".equals(qcResultShortPageVO.getRadioCheck())) {
            resWide = transList(records, resWide);
        }
        String fileName = "质控核查病历导出.xls";
        if ("1".equals(qcResultShortPageVO.getRadioCheck())) {
            ExcelUtils.exportExcelUser(records, null, "sheet1", ExportExcelDTO.class, fileName, response);
        }
        if ("2".equals(qcResultShortPageVO.getRadioCheck())) {
            ExcelUtils.exportExcelUser(resWide, null, "sheet1", ExportWideExcelDTO.class, fileName, response);
        }
    }


    /**
     * 病历质控报表分页导出
     *
     * @param behospitalPageVO
     * @return
     */
    public void qualityControlExport(HttpServletResponse response, BehospitalPageVO behospitalPageVO) {
        String hospitalId = SysUserUtils.getCurrentHospitalID();
        behospitalPageVO.setHospitalId(Long.valueOf(hospitalId));

        Date startDate = behospitalPageVO.getLeaveHosDateStart();
        Date endDate = behospitalPageVO.getLeaveHosDateEnd();
        //时间间隔30天
        long interval = 30 * 24l * 60l * 60l * 1000l;
        if (endDate.getTime() < startDate.getTime()) {
            throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
        }
        if (endDate.getTime() - startDate.getTime() > interval) {
            throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于30天");
        }

        behospitalPageVO.setCurrent(1L);
        behospitalPageVO.setSize(Long.MAX_VALUE);
        behospitalPageVO.setSearchCount(false);
        //  orderMethod(behospitalPageVO);

        IPage<QualityControlDTO> page = consoleFacade.getQualityControlExport(behospitalPageVO);
        List<QualityControlDTO> records = page.getRecords();

        String fileName = "病历质控报表详情页.xls";
        ExcelUtils.exportExcel(records, "病历质控报表", "sheet1", QualityControlDTO.class, fileName, response, 26.8f);
    }

    static void orderMethod(BehospitalPageVO behospitalPageVO) {
        List orders = behospitalPageVO.getOrders();
        Boolean flag = false;
        List<OrderItem> itemList = new ArrayList<>();
        for (Object order : orders) {
            ObjectMapper objectMapper = new ObjectMapper();
            OrderItem orderName = objectMapper.convertValue(order, OrderItem.class);
            itemList.add(orderName);
            if (!orderName.getColumn().equals("deptName")) {
                flag = true;
            }
        }
        //科室作为第一升序排列，传入排序随后 配合excel注解属性mergeVertical处理科室合并
        if (flag) {
            OrderItem orderItem = new OrderItem();
            orderItem.setAsc(true);
            orderItem.setColumn("deptName");
            itemList.add(orderItem);
            Collections.reverse(itemList);
            behospitalPageVO.setOrders(itemList);
        }

    }

    ;

    /**
     * 医生质控平均分页面统计-导出
     *
     * @param response
     * @param doctorAverageStatisticsVO
     * @Return void
     */
    public void doctorAverageStatisticsExport(HttpServletResponse response, DoctorAverageStatisticsVO doctorAverageStatisticsVO) {
        //1.查询
        doctorAverageStatisticsVO.setSize(9999999);
        IPage<DoctorAverageStatisticsDTO> page = consoleByDoctorFacade.doctorAverageStatistics(doctorAverageStatisticsVO);
        //2.列表拷贝
        List<ExportDoctorAverageStatisticsDTO> records = BeanUtil.listCopyTo(page.getRecords(), ExportDoctorAverageStatisticsDTO.class);
        //3.导出
        String fileName = "医生质控平均分.xls";
        ExcelUtils.exportExcel(records, null, "sheet1", ExportDoctorAverageStatisticsDTO.class, fileName, response);
    }

    /**
     * 医生质控平均分-患者列表（等级）-导出
     *
     * @param response
     * @param exportDoctorAverageLevelVO
     * @Return void
     */
    public void doctorAverageLevelExport(HttpServletResponse response, ExportDoctorAverageLevelVO exportDoctorAverageLevelVO) {
        String hospitalId = SysUserUtils.getCurrentHospitalID();
        exportDoctorAverageLevelVO.setHospitalId(Long.parseLong(hospitalId));
        //时间设置
        exportQcresultVOSet(exportDoctorAverageLevelVO);
        List<ExportDoctorAverageLevel_7DTO> res = behospitalInfoFacade.getBaseMapper().doctorAverageLevelExport(exportDoctorAverageLevelVO);
        List<ExportDoctorAverageLevel_90DTO> resWide = new ArrayList<>();
        if ("2".equals(exportDoctorAverageLevelVO.getRadioCheck())) {
            resWide = doctorAveragetransList(res, resWide);
        }
        String fileName = "抽查住院病历质量情况.xls";
        response.setContentType("text/html;charset=UTF-8");
        if ("1".equals(exportDoctorAverageLevelVO.getRadioCheck())) {
            ExcelUtils.exportExcelUser(res, null, "sheet1", ExportDoctorAverageLevel_7DTO.class, fileName, response);
        }
        if ("2".equals(exportDoctorAverageLevelVO.getRadioCheck())) {
            ExcelUtils.exportExcelUser(resWide, null, "sheet1", ExportDoctorAverageLevel_90DTO.class, fileName, response);
        }
    }

    public List<ExportDoctorAverageLevel_90DTO> doctorAveragetransList(List<ExportDoctorAverageLevel_7DTO> res, List<ExportDoctorAverageLevel_90DTO> resWide) {
        if (ListUtil.isNotEmpty(res)) {
            res.forEach(exportExcelDTO -> {
                ExportDoctorAverageLevel_90DTO exportWideExcelDTO = new ExportDoctorAverageLevel_90DTO();
                exportWideExcelDTO.setAvgScore(exportExcelDTO.getAvgScore());
                exportWideExcelDTO.setBehDeptName(exportExcelDTO.getBehDeptName());
                List<ExportBehospital_7DTO> excelBehospitalDTOS = exportExcelDTO.getExcelBehospitalDTOS();
                List<ExportBehospital_90DTO> exportExcelWideBehospitalDTOs = new ArrayList<>();
                excelBehospitalDTOS.forEach(exportExcelBehospitalDTO -> {
                    ExportBehospital_90DTO exportBehospital_90DTO = new ExportBehospital_90DTO();
                    exportBehospital_90DTO.setDoctorName(exportExcelBehospitalDTO.getDoctorName());
                    exportBehospital_90DTO.setBehospitalCode(exportExcelBehospitalDTO.getBehospitalCode());
                    exportBehospital_90DTO.setBehospitalDate(exportExcelBehospitalDTO.getBehospitalDate());
                    exportBehospital_90DTO.setLeaveHospitalDate(exportExcelBehospitalDTO.getLeaveHospitalDate());
                    exportBehospital_90DTO.setPatName(exportExcelBehospitalDTO.getPatName());
                    exportBehospital_90DTO.setScore(exportExcelBehospitalDTO.getScore());
                    exportBehospital_90DTO.setScoreBn(exportExcelBehospitalDTO.getScoreBn());
                    exportExcelWideBehospitalDTOs.add(exportBehospital_90DTO);
                });
                exportWideExcelDTO.setExcelBehospitalDTOS(exportExcelWideBehospitalDTOs);
                resWide.add(exportWideExcelDTO);
            });
        }
        return resWide;
    }

    private void exportQcresultVOSet(ExportDoctorAverageLevelVO doctorAverageLevelVO) {
        //入参验证
        long interval_7 = 7 * 24 * 60 * 60 * 1000;
        long interval_90 = 90 * 24 * 60 * 60 * 1000l;
        //入院时间
        if (null != doctorAverageLevelVO && null != doctorAverageLevelVO.getBehosDateStart() && null != doctorAverageLevelVO.getBehosDateEnd()) {
            Date startDate = doctorAverageLevelVO.getBehosDateStart();
            Date endDate = doctorAverageLevelVO.getBehosDateEnd();
            if ("1".equals(doctorAverageLevelVO.getRadioCheck())) {
                //时间间隔7天
                if (endDate.getTime() < startDate.getTime()) {
                    throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
                }
                if (endDate.getTime() - startDate.getTime() > interval_7) {
                    throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于7天");
                }
            } else {
                //时间间隔90天
                if (endDate.getTime() < startDate.getTime()) {
                    throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
                }
                if (endDate.getTime() - startDate.getTime() > interval_90) {
                    throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于90天");
                }
            }
            doctorAverageLevelVO.setBehosDateStart(DateUtil.getFirstTimeOfDay(doctorAverageLevelVO.getBehosDateStart()));
            doctorAverageLevelVO.setBehosDateEnd(DateUtil.getFirstTimeOfDay(DateUtil.addDay(doctorAverageLevelVO.getBehosDateEnd(), 1)));
        }
        //出院时间
        if (null != doctorAverageLevelVO && null != doctorAverageLevelVO.getLeaveHosDateStart() && null != doctorAverageLevelVO.getLeaveHosDateEnd()) {
            Date startDate = doctorAverageLevelVO.getLeaveHosDateStart();
            Date endDate = doctorAverageLevelVO.getLeaveHosDateEnd();
            if ("1".equals(doctorAverageLevelVO.getRadioCheck())) {
                //时间间隔7天
                if (endDate.getTime() < startDate.getTime()) {
                    throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
                }
                if (endDate.getTime() - startDate.getTime() > interval_7) {
                    throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于7天");
                }
            } else {
                //时间间隔90天
                if (endDate.getTime() < startDate.getTime()) {
                    throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
                }
                if (endDate.getTime() - startDate.getTime() > interval_90) {
                    throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于90天");
                }
            }
            doctorAverageLevelVO.setLeaveHosDateStart(DateUtil.getFirstTimeOfDay(doctorAverageLevelVO.getLeaveHosDateStart()));
            doctorAverageLevelVO.setLeaveHosDateEnd(DateUtil.getFirstTimeOfDay(DateUtil.addDay(doctorAverageLevelVO.getLeaveHosDateEnd(), 1)));
        }
    }

    /**
     * 医生质控缺陷列表-导出
     *
     * @param response
     * @param getDetailListPageVO
     * @Return void
     */
    public void getDoctorDetailPageExport(HttpServletResponse response, GetDoctorDetailPageVO getDetailListPageVO) {
        //1.查询
        getDetailListPageVO.setSize(Long.MAX_VALUE);
        IPage<GetDoctorDetailPageDTO> doctorDetailPage = consoleByDoctorFacade.getDoctorDetailPage(getDetailListPageVO);
        //2.列表拷贝
        List<ExportGetDoctorDetailPageDTO> records = BeanUtil.listCopyTo(doctorDetailPage.getRecords(), ExportGetDoctorDetailPageDTO.class);
        //3.导出
        String fileName = "医生缺陷列表.xls";
        response.setContentType("text/html;charset=UTF-8");
        ExcelUtils.exportExcelUser(records, null, "sheet1", ExportGetDoctorDetailPageDTO.class, fileName, response);
    }

    /**
     * 缺陷数量对应的病历-导出
     *
     * @param response
     * @param getDetailRecordListPageVO
     * @Return void
     */
    public void getDetailRecordListPageExport(HttpServletResponse response, GetDetailRecordListPageVO getDetailRecordListPageVO) {
        String hospitalId = SysUserUtils.getCurrentHospitalID();
        getDetailRecordListPageVO.setHospitalId(hospitalId);
        if (StringUtil.isNotBlank(getDetailRecordListPageVO.getDeptName())
                && getDetailRecordListPageVO.getDeptName().equals("全部")) {
            getDetailRecordListPageVO.setDeptName("");
        }
        Date startDate = getDetailRecordListPageVO.getStartDate();
        Date endDate = getDetailRecordListPageVO.getEndDate();
        //时间间隔90天
        long interval = 90 * 24l * 60l * 60l * 1000l;
        if (endDate.getTime() < startDate.getTime()) {
            throw new CommonException(CommonErrorCode.PARAM_ERROR, "截止时间不能小于起始时间");
        }
        if (endDate.getTime() - startDate.getTime() > interval) {
            throw new CommonException(CommonErrorCode.PARAM_ERROR, "统计区间不能大于90天");
        }
        getDetailRecordListPageVO.setSize(Long.MAX_VALUE);
        //1.查询
        List<ExportExcelDTO> detailRecordListExport = consoleByDoctorFacade.getDetailRecordListExport(getDetailRecordListPageVO);
        String fileName = "缺陷病历信息.xls";
        response.setContentType("text/html;charset=UTF-8");
        ExcelUtils.exportExcelUser(detailRecordListExport, null, "sheet1", ExportExcelDTO.class, fileName, response);
    }
}
