package com.chinaweal.aiccs.aiccs.punishment.util;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class ExcelIePortUtils {

    /**
     * 读取某个 sheet 的 Excel
     *
     * @param excel 文件
     * @param rowModel 实体类映射，继承 BaseRowModel 类
     * @param sheetNo sheet 的序号 从1开始
     * @param headLineNum 表头行数，默认为1
     * @return Excel 数据 list
     */
    public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo, int headLineNum) {
        ExcelListener excelListener = new ExcelListener();
        ExcelReader reader = getReader(excel, excelListener);
        if (reader == null) {
            return null;
        }
        reader.read(new Sheet(sheetNo, headLineNum, rowModel.getClass()));
        return excelListener.getDatas();
    }

    public static ExcelListener getExcelListener(MultipartFile excel, BaseRowModel rowModel, int sheetNo, int headLineNum) {
        ExcelListener excelListener = new ExcelListener();
        ExcelReader reader = getReader(excel, excelListener);
        if (reader == null) {
            return null;
        }
        reader.read(new Sheet(sheetNo, headLineNum, rowModel.getClass()));
        return excelListener;
    }


    /**
     * 返回 ExcelReader
     *
     * @param excel 需要解析的 Excel 文件
     * @param excelListener new ExcelListener()
     */
    private static ExcelReader getReader(MultipartFile excel, ExcelListener excelListener) {
//        String filename = excel.getOriginalFilename();
//        if (filename == null || (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx"))) {
//            throw new Exception("文件格式错误！");
//        }
        InputStream inputStream;
        try {
            inputStream = new BufferedInputStream(excel.getInputStream());
            return new ExcelReader(inputStream, null, excelListener, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String download(URL url, String name, HttpServletResponse response) {
        HttpURLConnection connection = null;
        InputStream in = null;
        BufferedOutputStream output = null;
        BufferedInputStream input = null;
        String result = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/msexcel; charset=UTF-8");
            connection.connect();
            in = connection.getInputStream();
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/msexcel;charset=GBK");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(name.getBytes(), "ISO8859-1"));
            output = new BufferedOutputStream(response.getOutputStream());
            input = new BufferedInputStream(in);
            int n = -1;
            byte[] buffer = new byte[6 * 1024];
            while ((n = input.read(buffer, 0, 6144)) > -1) {
                output.write(buffer, 0, n);
            }
            response.flushBuffer();// 不可少
            result = "success";
            in.close();
            output.flush(); // 不可少
            output.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
            result = "fail";
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (input != null) {
                    input.close();
                }
                if (output != null) {
                    output.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
