/**
 * Copyright (C), 2015-2019
 * Author:   HJL
 * Date:     2019/7/19 14:40
 * Description:未归档病历列表
 */
package com.emr.controller;

import com.emr.entity.Archive_Master_Vo;
import com.emr.entity.OffsetLimitPage;
import com.emr.service.Archive_MasterService;
import com.emr.service.Emr_DictionaryService;
import com.emr.util.ThreadExcelUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/unfile")
public class unfileMedicalController {
    @Autowired
    private Archive_MasterService archiveMasterService;

    @Autowired
    private Emr_DictionaryService emrDictionaryService;

    @RequestMapping(value = "/unfileMedicals")
    public String faults(Model model) {
        return "unfileMedicalDir/unfileMedicalList";
    }

    @ResponseBody
    @RequestMapping(value = "/unfileList")
    public OffsetLimitPage unfileList(HttpServletRequest request, HttpServletResponse response, Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        OffsetLimitPage result = archiveMasterService.selectByUnfile(archiveMasterVo, offset, limit);
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/exportExcel")
    public void exportExcel(HttpServletResponse response, Archive_Master_Vo archiveMasterVo) throws Exception {
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        String[] header = {"病历清单id","住院号","住院次数","名字","性别","身份证","入院科室","入院日期","出院科室","出院日期","主管医生","状态","医生是否提交","医生","医生提交日期","护士是否提交","护士","护士提交日期","电子病历医生提交","电子病历护士提交","是否死亡"};
        String[] fileNames = {"id","inpNo","visitId","name","sex","idNo","deptAdmissionTo","admissionDateTime","deptName","dischargeDateTime","doctorInCharge","archivestate","cmtDoctor","doctorName","cmtDoctorDate","cmtNurse","nurseName","cmtNurseDate","emrDoctorCmt","emrNureCmt","deathFlag"};
        //文件名
        String fileName = "未归档病历列表" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
        //构造excel的数据
        List<Archive_Master_Vo> list = archiveMasterService.selectByUnfileAndColumn(archiveMasterVo,null,null);
        ThreadExcelUtils utils = new ThreadExcelUtils(fileName, "", header, fileNames);
        String result=utils.exportExcelToFilePath(response,utils.listConvert(list));
    }


    @RequestMapping("getImg2")
    public void getImg2(HttpServletRequest request, HttpServletResponse response, String path) throws IOException {
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(path);
            os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @ResponseBody
    @RequestMapping(value = "/exportExcel2")
    public void exportBigDataExcel(HttpServletResponse response, Archive_Master_Vo archiveMasterVo)
            throws Exception {
        // 最重要的就是使用SXSSFWorkbook，表示流的方式进行操作
        // 在内存中保持100行，超过100行将被刷新到磁盘
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        Sheet sh = wb.createSheet(); // 建立新的sheet对象
        Row row = sh.createRow(0);   // 创建第一行对象
        // -----------定义表头-----------
        Cell cel0 = row.createCell(0);
        cel0.setCellValue("病历清单id");
        Cell cel2 = row.createCell(1);
        cel2.setCellValue("住院号");
        Cell cel3 = row.createCell(2);
        cel3.setCellValue("住院次数");
        Cell cel4 = row.createCell(3);
        cel4.setCellValue("名字");
        Cell cel5 = row.createCell(4);
        cel5.setCellValue("性别");
        Cell cel6 = row.createCell(5);
        cel6.setCellValue("身份证");
        Cell cel7 = row.createCell(6);
        cel7.setCellValue("入院科室");
        Cell cel8 = row.createCell(7);
        cel8.setCellValue("入院日期");
        Cell cel9 = row.createCell(8);
        cel9.setCellValue("出院科室");
        Cell cel10 = row.createCell(9);
        cel10.setCellValue("出院日期");
        Cell cel11 = row.createCell(10);
        cel11.setCellValue("主管医生");
        Cell cel12 = row.createCell(11);
        cel12.setCellValue("状态");
        Cell cel13 = row.createCell(12);
        cel13.setCellValue("医生是否提交");
        Cell cel14 = row.createCell(13);
        cel14.setCellValue("医生");
        Cell cel15 = row.createCell(14);
        cel15.setCellValue("医生提交日期");
        Cell cel16 = row.createCell(15);
        cel16.setCellValue("护士是否提交");
        Cell cel17 = row.createCell(16);
        cel17.setCellValue("护士");
        Cell cel18 = row.createCell(17);
        cel18.setCellValue("护士提交日期");
        Cell cel19 = row.createCell(18);
        cel19.setCellValue("电子病历医生提交");
        Cell cel20 = row.createCell(19);
        cel20.setCellValue("电子病历护士提交");
        Cell cel21 = row.createCell(20);
        cel21.setCellValue("是否死亡");
        List<Archive_Master_Vo> list = new ArrayList<Archive_Master_Vo>();

        // 数据库中存储的数据行
        int page_size = 10000;
        // 求数据库中待导出数据的行数
        Integer list_count = archiveMasterService.selectCountNum(archiveMasterVo);
        System.out.println("list_count:::::"+list_count);
        // 根据行数求数据提取次数
        int export_times = list_count % page_size > 0 ? list_count / page_size
                + 1 : list_count / page_size;
        // 按次数将数据写入文件
        for (int j = 0; j < export_times; j++) {
            list = archiveMasterService.selectByUnfileAndColumn(archiveMasterVo,j + 1, page_size);
            int len = list.size() < page_size ? list.size() : page_size;
            for (int i = 0; i < len; i++) {
                Row row_value = sh.createRow(j * page_size + i + 1);
                Cell cel0_value = row_value.createCell(0);
                cel0_value.setCellValue(list.get(i).getId());
                Cell cel2_value = row_value.createCell(1);
                cel2_value.setCellValue(list.get(i).getInpNo());
                Cell cel3_value = row_value.createCell(2);
                cel3_value.setCellValue(list.get(i).getVisitId());
                Cell cel4_value = row_value.createCell(3);
                cel4_value.setCellValue(list.get(i).getName());
                Cell cel5_value = row_value.createCell(4);
                cel5_value.setCellValue(list.get(i).getSex());
                Cell cel6_value = row_value.createCell(5);
                cel6_value.setCellValue(list.get(i).getIdNo());
                Cell cel7_value = row_value.createCell(6);
                cel7_value.setCellValue(list.get(i).getDeptAdmissionTo());
                Cell cel8_value = row_value.createCell(7);
                cel8_value.setCellValue(list.get(i).getAdmissionDateTime());
                Cell cel9_value = row_value.createCell(8);
                cel9_value.setCellValue(list.get(i).getDeptName());
                Cell cel10_value = row_value.createCell(9);
                cel10_value.setCellValue(list.get(i).getDischargeDateTime());
                Cell cel11_value = row_value.createCell(10);
                cel11_value.setCellValue(list.get(i).getDoctorInCharge());
                Cell cel12_value = row_value.createCell(11);
                cel12_value.setCellValue(list.get(i).getArchivestate());
                Cell cel13_value = row_value.createCell(12);
                cel13_value.setCellValue(list.get(i).getCmtDoctor());
                Cell cel14_value = row_value.createCell(13);
                cel14_value.setCellValue(list.get(i).getDoctorName());
                Cell cel15_value = row_value.createCell(14);
                cel15_value.setCellValue(list.get(i).getCmtDoctorDate());
                Cell cel16_value = row_value.createCell(15);
                cel16_value.setCellValue(list.get(i).getCmtNurse());
                Cell cel17_value = row_value.createCell(16);
                cel17_value.setCellValue(list.get(i).getNurseName());
                Cell cel18_value = row_value.createCell(17);
                cel18_value.setCellValue(list.get(i).getCmtNurseDate());
                Cell cel19_value = row_value.createCell(18);
                cel19_value.setCellValue(list.get(i).getEmrDoctorCmt());
                Cell cel20_value = row_value.createCell(19);
                cel20_value.setCellValue(list.get(i).getEmrNureCmt());
                Cell cel21_value = row_value.createCell(20);
                cel21_value.setCellValue(list.get(i).getDeathFlag());



            }
            list.clear(); // 每次存储len行，用完了将内容清空，以便内存可重复利用
        }

        OutputStream os = response.getOutputStream();
        //导出excel建议加上重置输出流，可以不加该代码，但是如果不加必须要保证输出流中不应该在存在其他数据，否则导出会有问题
        response.reset();
        //处理乱码
        String fileName = "未归档病历列表" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xlsx";
        //attachment为以附件方式下载
        response.setContentType("application/vnd.ms-excel");
        //代码里面使用Content-Disposition来确保浏览器弹出下载对话框的时候。
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.setBufferSize(1024);
       /* File file = new File(filePath);
        if (!file.exists()) {//文件夹不存在
            file.mkdirs();//创建目录
        }*/
        //FileOutputStream fout = new FileOutputStream(new File(file, fileName));
        try {
            //wb.write(fout);
            wb.write(os);//将excel中的数据写到输出流中，用于文件的输出
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }



    }




}
 

