package com.njcn.poi.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2022年04月01日 20:10
 */
public class PoiUtil {

    /**
     * 根据数值返回适当文字描述
     * 比如：3.14159 - 暂无数据
     */
    public static String dealData(Double value) {
        return value == 3.14159 ? "暂无数据" : value + "%";
    }

    /**
     * excel包装数字返回的
     */
    public static String dealPOIData(Double value) {

        return " : (" + dealData(value) + ")";
    }

    /**
     * 注意：此方法下载完文件后，会删除当前文件
     *
     * @param filePath 文件绝对路径
     * @param response 响应
     */
    public static void exportFileByAbsolutePath(String filePath, HttpServletResponse response) {
        File file = new File(filePath);
        String fileName = file.getName();
        try (ServletOutputStream outputStream = response.getOutputStream(); FileInputStream fileInputStream = new FileInputStream(file)) {
            fileName = URLEncoder.encode(fileName, CharsetUtil.UTF_8);
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setContentType("application/octet-stream;charset=" + CharsetUtil.UTF_8);
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CommonResponseEnum.EXPORT_FILE_ERROR);
        }
        FileUtil.del(file);
    }


    /**
     * 按工作蒲导出文件
     *
     * @param workbook 工作蒲
     * @param fileName 文件名
     * @param response 响应
     */
    public static void exportFileByWorkbook(Workbook workbook, String fileName, HttpServletResponse response) {
        response.reset();
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            fileName = URLEncoder.encode(fileName, CharsetUtil.UTF_8);
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setContentType("application/octet-stream;charset=" + CharsetUtil.UTF_8);
            //将带*号的列变成红色
            Sheet sheetAt = workbook.getSheetAt(0);
            //获取列数
            int physicalNumberOfCells = sheetAt.getRow(0).getPhysicalNumberOfCells();
            //没有表格标题,只有表格头
            for (int i = 0; i < 2; i++) {
                //获取行
                Row row = sheetAt.getRow(i);
                if (Objects.isNull(row)) {
                    continue;
                }
                for (int j = 0; j < physicalNumberOfCells; j++) {
                    //获取单元格对象
                    Cell cell = row.getCell(j);
                    //获取单元格样式对象
                    CellStyle cellStyle = workbook.createCellStyle();
                    //获取单元格内容对象
                    Font font = workbook.createFont();
                    font.setFontHeightInPoints((short) 12);
                    //一定要装入 样式中才会生效
                    cellStyle.setFont(font);
                    //设置居中对齐
                    cellStyle.setAlignment(HorizontalAlignment.CENTER);
                    cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                    //设置单元格字体颜色
                    cell.setCellStyle(cellStyle);
                    //获取当前值
                    String stringCellValue = cell.getStringCellValue();
                    if (stringCellValue.contains("*")) {
                        // 创建一个富文本
                        XSSFRichTextString xssfRichTextString = new XSSFRichTextString(stringCellValue);
                        int startIndex = stringCellValue.indexOf("*");
                        int entIndex = stringCellValue.lastIndexOf("*");
                        if (entIndex != 0) {
                            Font font3 = workbook.createFont();
                            font3.setFontHeightInPoints((short) 12);
                            font3.setColor(Font.COLOR_NORMAL);
                            xssfRichTextString.applyFont(0, entIndex, font3);
                        }
                        //设置带*样式
                        Font font1 = workbook.createFont();
                        font1.setFontHeightInPoints((short) 12);
                        font1.setColor(Font.COLOR_RED);
                        xssfRichTextString.applyFont(startIndex, entIndex + 1, font1);
                        //其他样式
                        Font font2 = workbook.createFont();
                        font2.setFontHeightInPoints((short) 12);
                        font2.setColor(Font.COLOR_NORMAL);
                        xssfRichTextString.applyFont(entIndex + 1, stringCellValue.length(), font2);
                        cell.setCellValue(xssfRichTextString);
                    }
                }
            }
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CommonResponseEnum.EXPORT_FILE_ERROR);
        }
    }

}
