package com.huimv.manage.util;

import com.huimv.manage.eartag.dao.entity.EtEarmarkEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;

/**
 * @Project : huimv.shiwan
 * @Package : com.huimv.biosafety.uface.controller
 * @Description : TODO
 * @Version : 1.0
 * @Author : ZhuoNing
 * @Create : 2020-12-25
 **/
@Component
@Slf4j
public class ExcelUtil {

    /**
     * @Method      : uploadExcelAboutUser
     * @Description : 导出excel的耳标号二维码数据
     * @Params      : [response, fileName, dataList]
     * @Return      : void
     * 
     * @Author      : ZhuoNing
     * @Date        : 2021/11/9       
     * @Time        : 14:47
     */
    public void exportEarmarkExcel(HttpServletResponse response, String fileName,String applyId, List<EtEarmarkEntity> dataList,Integer quantity) throws IOException {
        List<String> titleList = Arrays.asList("序号","耳标编号", "耳标编码号", "申请ID", "耳标二维码数据","打码状态");
        System.out.println("开始导出数据......");
        //声明输出流
        OutputStream os = null;
        //设置响应头
        setResponseHeader(response,fileName);
        try {
            //获取输出流
            os = response.getOutputStream();
            //内存中保留1000条数据，以免内存溢出，其余写入硬盘
            SXSSFWorkbook wb = new SXSSFWorkbook(quantity);
            /** 设置格式* */
            wb.setCompressTempFiles(true);
            // 设置并获取到需要的样式
            XSSFCellStyle cellStyleHeader = getAndSetXSSFCellStyleHeader(wb);
            XSSFCellStyle cellStyleOne = getAndSetXSSFCellStyleOne(wb);
            //获取该工作区的第一个sheet
            SXSSFSheet sheet1 = wb.createSheet(String.valueOf(applyId)+"-"+String.valueOf(dataList.size())+"");
            sheet1.createFreezePane(0, 1);
            // 在后面设置sheet
            setSheet(sheet1);
            int excelRow = 0;
            //创建标题行
            Row titleRow = sheet1.createRow(excelRow);
            for(int i = 0;i<titleList.size();i++){
                //创建该行下的每一列，并写入标题数据
                Cell cell = titleRow.createCell(i);
                cell.setCellValue(titleList.get(i));
                cell.setCellStyle(cellStyleHeader);
            }
            log.info("导出记录数="+dataList.size());
            //设置内容行
            if(dataList!=null && dataList.size()>0){
                //序号是从1开始的
                int count = 0;
                for(int a=0;a<dataList.size();a++){
//                    log.info("行数="+excelRow);
                    EtEarmarkEntity earmarkEntity = dataList.get(a);
                    count = 0;
                    Row dataRow = sheet1.createRow(++excelRow);
                    Cell cell0 = dataRow.createCell(count++);
                    cell0.setCellValue(excelRow);
                    cell0.setCellStyle(cellStyleOne);
                    Cell cell1 = dataRow.createCell(count++);
                    cell1.setCellValue(earmarkEntity.getEarmarkId());
                    cell1.setCellStyle(cellStyleOne);
                    Cell cell2 = dataRow.createCell(count++);
                    cell2.setCellValue(earmarkEntity.getEarmarkNumber());
                    cell2.setCellStyle(cellStyleOne);
                    Cell cell3 = dataRow.createCell(count++);
                    cell3.setCellValue(earmarkEntity.getApplyId());
                    cell3.setCellStyle(cellStyleOne);
                    Cell cell4 = dataRow.createCell(count++);
                    cell4.setCellValue(earmarkEntity.getEarmarkData());
                    cell4.setCellStyle(cellStyleOne);
                    Cell cell5 = dataRow.createCell(count++);
                    if(earmarkEntity.getSetPrintState() == null){
                        cell5.setCellValue("0");
                    }else{
                        cell5.setCellValue(earmarkEntity.getSetPrintState());
                    }
                    cell5.setCellStyle(cellStyleOne);
                }
            }
            // test
//            fos = new FileOutputStream(excelExportDestfilepath);
//            wb.write(fos);
            //将整理好的excel数据写入流中
            wb.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭输出流
                if (os != null) {
                    os.close();
                }
                System.out.println("导出完成.");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // test
    public void exportEarmarkExcel(String applyId,List<EtEarmarkEntity> dataList,Integer quantity){
        List<String> titleList = Arrays.asList("序号","耳标编号", "耳标编码号", "申请ID", "耳标二维码数据","打码状态");
        System.out.println("开始导出数据......");
        // test
        String excelExportDestfilepath = "C:\\Users\\huimv\\Desktop\\3\\abc.xlsx";
        //声明输出流
        OutputStream os = null;
        FileOutputStream fos = null;
        //设置响应头
//        setResponseHeader(response,fileName);
        try {
            //获取输出流
//            os = response.getOutputStream();
            //内存中保留1000条数据，以免内存溢出，其余写入硬盘
            SXSSFWorkbook wb = new SXSSFWorkbook(quantity);
            /** 设置格式* */
//            wb.setCompressTempFiles(true);
            // 设置并获取到需要的样式
            XSSFCellStyle cellStyleHeader = getAndSetXSSFCellStyleHeader(wb);
            XSSFCellStyle cellStyleOne = getAndSetXSSFCellStyleOne(wb);
            //获取该工作区的第一个sheet
            SXSSFSheet sheet1 = wb.createSheet(String.valueOf(applyId)+"（"+String.valueOf(dataList.size())+"）");
            sheet1.createFreezePane(0, 1);
            // 在后面设置sheet
            setSheet(sheet1);
            int excelRow = 0;
            //创建标题行
            Row titleRow = sheet1.createRow(excelRow);
            for(int i = 0;i<titleList.size();i++){
                //创建该行下的每一列，并写入标题数据
                Cell cell = titleRow.createCell(i);
                cell.setCellValue(titleList.get(i));
                cell.setCellStyle(cellStyleHeader);
            }
            //设置内容行
            if(dataList!=null && dataList.size()>0){
                //序号是从1开始的
                int count = 0;
                for(int a=0;a<dataList.size();a++){
                    EtEarmarkEntity earmarkEntity = dataList.get(a);
                    count = 0;
                    Row dataRow = sheet1.createRow(++excelRow);
                    Cell cell0 = dataRow.createCell(count++);
                    cell0.setCellValue(excelRow);
                    cell0.setCellStyle(cellStyleOne);
                    Cell cell1 = dataRow.createCell(count++);
                    cell1.setCellValue(earmarkEntity.getEarmarkId());
                    cell1.setCellStyle(cellStyleOne);
                    Cell cell2 = dataRow.createCell(count++);
                    cell2.setCellValue(earmarkEntity.getEarmarkNumber());
                    cell2.setCellStyle(cellStyleOne);
                    Cell cell3 = dataRow.createCell(count++);
                    cell3.setCellValue(earmarkEntity.getApplyId());
                    cell3.setCellStyle(cellStyleOne);
                    Cell cell4 = dataRow.createCell(count++);
                    cell4.setCellValue(earmarkEntity.getEarmarkData());
                    cell4.setCellStyle(cellStyleOne);
                    Cell cell5 = dataRow.createCell(count++);
                    if(earmarkEntity.getSetPrintState() == null){
                        cell5.setCellValue("0");
                    }else{
                        cell5.setCellValue(earmarkEntity.getSetPrintState());
                    }
                    cell5.setCellStyle(cellStyleOne);
                }
            }
            // test
            fos = new FileOutputStream(excelExportDestfilepath);
            wb.write(fos);
            //将整理好的excel数据写入流中
//            wb.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭输出流
                if (os != null) {
                    os.close();
                }
                System.out.println("导出完成.");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 获取并设置header样式
     */
    private XSSFCellStyle getAndSetXSSFCellStyleHeader(SXSSFWorkbook sxssfWorkbook) {
        XSSFCellStyle xssfCellStyle = (XSSFCellStyle) sxssfWorkbook.createCellStyle();
        Font font = sxssfWorkbook.createFont();
        // 字体大小
        font.setFontHeightInPoints((short) 13);
        // 字体粗细
//        font.setBoldweight((short) 20);
        font.setBold(true);
        // 将字体应用到样式上面
        xssfCellStyle.setFont(font);
        // 是否自动换行
        xssfCellStyle.setWrapText(false);
        // 水平居中
        xssfCellStyle.setAlignment(HorizontalAlignment.CENTER);
        // 垂直居中
        xssfCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        return xssfCellStyle;
    }
    /**
     * 获取并设置样式一
     */
    private XSSFCellStyle getAndSetXSSFCellStyleOne(SXSSFWorkbook sxssfWorkbook) {
        XSSFCellStyle xssfCellStyle = (XSSFCellStyle) sxssfWorkbook.createCellStyle();
        XSSFDataFormat format = (XSSFDataFormat)sxssfWorkbook.createDataFormat();
        // 是否自动换行
        xssfCellStyle.setWrapText(false);
        // 水平居中
        xssfCellStyle.setAlignment(HorizontalAlignment.CENTER);
        // 垂直居中
        xssfCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 前景颜色
//        xssfCellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
//        xssfCellStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex());
        // 边框
//        xssfCellStyle.setBorderBottom(BorderStyle.THIN);
//        xssfCellStyle.setBorderRight(BorderStyle.THIN);
//        xssfCellStyle.setBorderTop(BorderStyle.THIN);
//        xssfCellStyle.setBorderLeft(BorderStyle.THIN);
//        xssfCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
//        xssfCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
//        xssfCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
//        xssfCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        // 防止数字过长,excel导出后,显示为科学计数法,如:防止8615192053888被显示为8.61519E+12
        xssfCellStyle.setDataFormat(format.getFormat("0"));
        return xssfCellStyle;
    }

    /**
     * 获取并设置样式二
     */
    private XSSFCellStyle getAndSetXSSFCellStyleTwo(SXSSFWorkbook sxssfWorkbook) {
        XSSFCellStyle xssfCellStyle = (XSSFCellStyle) sxssfWorkbook.createCellStyle();
        XSSFDataFormat format = (XSSFDataFormat)sxssfWorkbook.createDataFormat();
        // 是否自动换行
        xssfCellStyle.setWrapText(false);
        // 水平居中
        xssfCellStyle.setAlignment(HorizontalAlignment.CENTER);
        // 边框
        xssfCellStyle.setBorderBottom(BorderStyle.THIN);
        xssfCellStyle.setBorderRight(BorderStyle.THIN);
        xssfCellStyle.setBorderTop(BorderStyle.THIN);
        xssfCellStyle.setBorderLeft(BorderStyle.THIN);
        xssfCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        xssfCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
        xssfCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        xssfCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        // 垂直居中
        xssfCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 防止数字过长,excel导出后,显示为科学计数法,如:防止8615192053888被显示为8.61519E+12
        xssfCellStyle.setDataFormat(format.getFormat("0"));
        return xssfCellStyle;
    }
    /**
     * 设置sheet
     */
    private void setSheet(Sheet sheet) {
        // 设置各列宽度(单位为:字符宽度的1/256)
        sheet.setColumnWidth(0, 10 * 256);
        sheet.setColumnWidth(1, 15 * 256);
        sheet.setColumnWidth(2, 20 * 256);
        sheet.setColumnWidth(3, 10 * 256);
        sheet.setColumnWidth(4, 70 * 256);
        sheet.setColumnWidth(5, 12 * 256);
    }
    /*
        设置浏览器下载响应头
     */
    private static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
//                fileName = new String(fileName.getBytes(),"ISO8859-1");
                fileName = new String(fileName.getBytes(),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
