package com.shinsoft.sto.tools;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.shinsoft.sto.model.record.ImportModel;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class ExcelExportTools {

    /**
     * 导出 Excel
     * @param response HttpServletResponse
     * @param dataList 数据列表
     * @param fileName 文件名
     * @param sheetName sheet名称
     * @param clazz 实体类类型
     */
    public <T> void exportExcel(HttpServletResponse response,
                                List<T> dataList,
                                String fileName,
                                String sheetName,
                                Class<T> clazz) throws IOException {

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString())
                .replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName + ".xlsx");

        // 写入 Excel
        EasyExcel.write(response.getOutputStream(), clazz)
                .sheet(sheetName)
                .doWrite(dataList);
    }

    /**
     * 导出到多个 Sheet
     */
    public <T> void exportExcelMultiSheet(HttpServletResponse response,
                                          List<List<T>> dataLists,
                                          String fileName,
                                          List<String> sheetNames,
                                          Class<T> clazz) throws IOException {

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString())
                .replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName + ".xlsx");

        ExcelWriter excelWriter = null;
        try {
            excelWriter = EasyExcel.write(response.getOutputStream(), clazz).build();

            for (int i = 0; i < dataLists.size(); i++) {
                WriteSheet writeSheet = EasyExcel.writerSheet(i, sheetNames.get(i))
                        .head(clazz)
                        .build();
                excelWriter.write(dataLists.get(i), writeSheet);
            }
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    /**
     * 解析Excel文件
     */
    public List<ImportModel> parseExcelFile(MultipartFile file) throws Exception {
        // 使用EasyExcel解析文件
        return EasyExcel.read(file.getInputStream())
                .head(ImportModel.class)
                .sheet()
                .doReadSync();
    }
}