package com.yinlihupo.enlish.service.utils;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.yinlihupo.enlish.service.domain.dataobject.ExamWordsDO;
import com.yinlihupo.enlish.service.domain.dataobject.LessonPlansDO;
import jakarta.servlet.http.HttpServletResponse;

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class WordExportUtil {

    private static final Configure config;
    private static final Configure configLessonPlanWeekday;
    private static final Configure configLessonPlanWeekend;

    static {
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        config = Configure.builder()
                .bind("words", policy)
                .bind("words1", policy)
                .bind("words2", policy)
                .bind("answer", policy)
                .build();

        LoopRowTableRenderPolicy policyLessonPlanWeekday = new LoopRowTableRenderPolicy();
        configLessonPlanWeekday = Configure.builder()
                .bind("syncVocabList", policyLessonPlanWeekday)
                .bind("gapVocabList", policyLessonPlanWeekday)
                .bind("reviewVocabList", policyLessonPlanWeekday)
                .bind("drillRound1", policyLessonPlanWeekday)
                .bind("drillRound2", policyLessonPlanWeekday)
                .bind("drillRound3", policyLessonPlanWeekday)
                .bind("mixedDrill", policyLessonPlanWeekday)
                .bind("checkList", policyLessonPlanWeekday)
                .bind("checkListAns", policyLessonPlanWeekday)
                .bind("sentences", policyLessonPlanWeekday)
                .bind("sentencesAns", policyLessonPlanWeekday)
                .bind("words1", policy)
                .bind("words2", policy)
                .build();

        LoopRowTableRenderPolicy policyLessonPlan = new LoopRowTableRenderPolicy();
        configLessonPlanWeekend = Configure.builder()
                .bind("words1", policy)
                .bind("words2", policy)
                .build();
    }

    /**
     * 公共入口：根据数据量决定是导出单文件还是压缩包
     */
    public static void generateExamWords(List<Map<String, Object>> data, ExamWordsDO examWordsDO, HttpServletResponse response, String templateWordPath) {
        if (data == null || data.isEmpty()) {
            return;
        }

        try {
            if (data.size() == 1) {
                // 如果只有一份数据，直接导出 docx，用户体验更好
                generateExamWordsDocx(data.get(0), examWordsDO, response, templateWordPath);
            } else {
                // 如果有多份数据，打包导出
                generateExamWordsZip(data, examWordsDO, response, templateWordPath);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("导出文档失败", e);
        }
    }

    public static void generateLessonPlanDocx(Map<String, Object> map, LessonPlansDO lessonPlan, HttpServletResponse response, String templateWordPath, boolean isWeekday) throws IOException {
        String fileName = URLEncoder.encode(lessonPlan.getTitle() + ".docx", StandardCharsets.UTF_8).replaceAll("\\+", "%20");

        // 3. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);

        try (InputStream inputStream = new FileInputStream(templateWordPath)) {
            XWPFTemplate template;
            if (isWeekday) {
                template = XWPFTemplate.compile(inputStream, configLessonPlanWeekday);
            } else {
                template = XWPFTemplate.compile(inputStream, configLessonPlanWeekend);
            }
            String url = "http://english.yinlihupo.cn/#/plan/tts?planId=" + lessonPlan.getId();
            map.put("img", Pictures.ofBytes(generateQR(url), PictureType.PNG).create());
            OutputStream out = response.getOutputStream();
            template.render(map);
            template.write(out);
            template.close();
            out.flush();
        }
    }

    /**
     * 核心补充：批量渲染并打包为 ZIP
     */
    private static void generateExamWordsZip(List<Map<String, Object>> data, ExamWordsDO examWordsDO, HttpServletResponse response, String templateWordPath) throws IOException {
        // 1. 设置响应头为 ZIP
        String zipName = URLEncoder.encode("批量导出_" + examWordsDO.getTitle() + ".zip", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + zipName);

        // 2. 创建 ZipOutputStream 包装 Response 输出流
        // 使用 try-with-resources 自动关闭 zipOut
        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {

            int index = 1;
            for (Map<String, Object> itemData : data) {
                // 3. 确定压缩包内的文件名
                // 优先从 map 中获取 'fileName' 字段，否则使用默认编号
                String entryName = (String) itemData.getOrDefault("fileName",  + index);
                // 确保文件名后缀正确
                if (!entryName.endsWith(".docx")) {
                    entryName += ".docx";
                }

                // 4. 创建 ZIP 条目
                ZipEntry zipEntry = new ZipEntry(entryName);
                zipOut.putNextEntry(zipEntry);

                // 5. 加载模板并渲染
                // 注意：每次循环都需要重新读取模板流，因为 poi-tl 渲染会修改文档结构
                try (InputStream templateInputStream = new FileInputStream(templateWordPath)) {
                    XWPFTemplate template = XWPFTemplate.compile(templateInputStream, config);
                    template.render(itemData);

                    // 6. 将渲染后的文档直接写入 ZipOutputStream
                    // template.write 默认不关闭流，所以这里是安全的
                    template.write(zipOut);

                    // 显式关闭 template (释放 POI 资源)
                    template.close();
                }

                // 7. 关闭当前条目
                zipOut.closeEntry();
                index++;
            }

            // 8. 循环结束，zipOut 会在 try 块结束时自动 finish 和 close
            response.flushBuffer();
        }
    }

    /**
     * 现有的单文件导出逻辑
     */
    private static void generateExamWordsDocx(Map<String, Object> data, ExamWordsDO examWordsDO, HttpServletResponse response, String templateWordPath) throws IOException {

        String fileName = URLEncoder.encode(examWordsDO.getTitle() + ".docx", StandardCharsets.UTF_8).replaceAll("\\+", "%20");

        // 3. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);

        try (InputStream inputStream = new FileInputStream(templateWordPath)) {
            XWPFTemplate template = XWPFTemplate.compile(inputStream, config);
            OutputStream out = response.getOutputStream();
            template.render(data);
            template.write(out);
            template.close(); // 最好关闭 template
            out.flush();
        }
    }

    private static byte[] generateQR(String content) {
        int width = 300;
        int height = 300;
        String format = "png";

        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 1);

        try {
            // 1. 生成比特矩阵
            BitMatrix bitMatrix = new MultiFormatWriter().encode(
                    content,
                    BarcodeFormat.QR_CODE,
                    width,
                    height,
                    hints
            );

            // 2. 将 BitMatrix 转为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            // MatrixToImageWriter 是 Zxing 提供的工具类
            MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);

            return outputStream.toByteArray();

        } catch (WriterException | IOException e) {
            // 建议增加对 IOException 的捕获，因为涉及流操作
            throw new RuntimeException("生成二维码失败", e);
        }
    }
}
