package com.yida.data.common.core.utils;

import com.alibaba.excel.EasyExcel;
import com.yida.data.common.core.exception.FebsException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

@Slf4j
public class ExcelUtil {

    public static Workbook readExcel(InputStream inputStream, String suffix) throws IOException {
        Workbook workbook = null;
        if ("xls".equals(suffix)) {
            workbook = new HSSFWorkbook(inputStream);
        } else if ("xlsx".equals(suffix)) {
            workbook = new XSSFWorkbook(inputStream);
        }
        return workbook;
    }

    public static Workbook readExcel(File file, String suffix) throws IOException {
        return readExcel(new FileInputStream(file), suffix);
    }

    public static List<Map<Integer, Cell>> readData(Sheet sheet, Integer startRow) {
        Integer maxRow = sheet.getLastRowNum();
        List<Map<Integer, Cell>> res = new ArrayList<>();
        for (int i = startRow; i <= maxRow; i++) {
            Row row = sheet.getRow(i);
            Map<Integer, Cell> rowData = new HashMap<>();
            Integer cellNum = 0;
            if (row != null) {
                for (int j = 0; j <= row.getLastCellNum(); j++) {
                    rowData.put(j, row.getCell(j));
                }
                res.add(rowData);
            }
        }
        return res;
    }


    public static String getCellValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        String cellValue = "";
        // 以下是判断数据的类型
        switch (cell.getCellType()) {
            case NUMERIC: // 数字
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    cellValue = sdf.format(org.apache.poi.ss.usermodel.DateUtil.getJavaDate(cell.getNumericCellValue()))
                        .toString();
                } else {
                    DataFormatter dataFormatter = new DataFormatter();
                    cellValue = dataFormatter.formatCellValue(cell);
                }
                break;
            case STRING: // 字符串
                cellValue = cell.getStringCellValue();
                break;
            case BOOLEAN: // Boolean
                cellValue = cell.getBooleanCellValue() + "";
                break;
            case FORMULA: // 公式
                cellValue = cell.getCellFormula() + "";
                break;
            case BLANK: // 空值
                cellValue = "";
                break;
            case ERROR: // 故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }

    public static void export(String fileName, Class clazz, List dataList, HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            fileName =
                URLEncoder.encode(fileName, "UTF-8").replaceAll(
                    "\\+"
                    , "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), clazz).sheet("模板").doWrite(dataList);
        } catch (Exception e) {
            log.error("导出失败", e);
            throw new FebsException("导出失败");
        }
    }

    public static void export(String fileName, String suffix, Workbook workbook,
        HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            fileName =
                URLEncoder.encode(fileName, "UTF-8").replaceAll(
                    "\\+"
                    , "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + "." + suffix);
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new FebsException("导出失败");
        }
    }
}
