package com.zzsmart.qomo.kn.cost.manage.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.zzsmart.qomo.kn.cost.manage.entity.CostStandardDetail;
import org.apache.poi.ss.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class EasyExcelUtil {
    /**
     * 导出Excel文件到HTTP响应流，包含自定义表头。
     *
     * @param response HTTP响应对象
     * @param fileName 导出的文件名
     * @param head     表头信息列表
     * @param data     需要导出的数据列表
     * @param clazz    数据模型的Class类型
     * @throws IOException IO异常
     */
    public static <T> void export(HttpServletResponse response, String fileName, List<?> head, List<T> data, Class<T> clazz) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        try {
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 自定义表头样式
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = getHorizontalCellStyleStrategy();

        // 使用EasyExcel导出
        try {
            EasyExcel.write(response.getOutputStream(), clazz)
                    // 注册样式策略
                    .registerWriteHandler(horizontalCellStyleStrategy).sheet("1111").doWrite(data);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
//        FileOutputStream outputStream=  new FileOutputStream(fileName);
//        try {
//            EasyExcel.write(outputStream)
//                    // 设置自定义样式，可选
//                    .sheet("Sheet1") // 设置工作表名称
//                    .doWrite(data); // 将数据写入Excel
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println("zheli==============");
//        } finally {
////            if (excelWriter != null) {
////                excelWriter.finish();
////            }
//            if (outputStream != null) {
//                outputStream.close();
//            }

//        }
    }

    /**
     * 创建自定义的水平单元格样式策略，用于表头样式。
     *
     * @return 水平单元格样式策略
     */
    private static HorizontalCellStyleStrategy getHorizontalCellStyleStrategy() {
        // 设置表头字体样式
        WriteFont headFont = new WriteFont();
        headFont.setFontHeightInPoints((short) 12);
        headFont.setFontName("Arial");
        headFont.setBold(true);

        // 设置表头单元格样式
        WriteCellStyle headCellStyle = new WriteCellStyle();
        headCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        headCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        headCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        headCellStyle.setBorderLeft(BorderStyle.THIN);
        headCellStyle.setBorderRight(BorderStyle.THIN);
        headCellStyle.setBorderTop(BorderStyle.THIN);
        headCellStyle.setBorderBottom(BorderStyle.THIN);
        headCellStyle.setWriteFont(headFont);

        // 创建并返回水平单元格样式策略
        return new HorizontalCellStyleStrategy(headCellStyle, (List<WriteCellStyle>) null);
    }

    /**
     * 获取带有@Excel注解的属性集合
     *
     * @param clazz 实体类的Class对象
     * @return 带有@Excel注解的Field集合
     */
    public static Field[] getExcelPropertyAnnotatedFields(Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        List<Field> annotatedFields = new ArrayList<>();

        for (Field field : fields) {
            if (field.isAnnotationPresent(ExcelProperty.class)) {
                annotatedFields.add(field);
            }
        }
        return annotatedFields.toArray(new Field[0]);
    }

    /**
     * 查询类需要导出的列名
     *
     * @param clazz
     * @return
     */
    public static Set<String> getIncludeFields(Class<?> clazz) {
        Field[] excelPropertyAnnotatedFields = getExcelPropertyAnnotatedFields(CostStandardDetail.class);
        Set<String> includeColumnFiledNames = new HashSet<String>();
        for (int i = 0; i < excelPropertyAnnotatedFields.length; i++) {
            includeColumnFiledNames.add(excelPropertyAnnotatedFields[i].getName());
        }
        return includeColumnFiledNames;
    }
}
