package cn.com.poc.knowledge;

import cn.com.poc.common.utils.StringUtils;
import cn.com.poc.common.utils.UUIDTool;
import cn.com.poc.knowledge.aggregate.KnowledgeService;
import cn.com.poc.knowledge.cache.KnowledgeDefaultCache;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import cn.com.yict.framemax.core.spring.SingleContextInitializer;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Document;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;

/**
 * @author alex.yao
 * @date 2025/2/6
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(initializers = SingleContextInitializer.class)
@WebAppConfiguration
public class KnowledgeServiceTest {

    @Resource
    private KnowledgeService knowledgeService;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test_default() {
        KnowledgeDefaultCache knowledgeDefaultCache = new KnowledgeDefaultCache();
        System.out.println(knowledgeDefaultCache.getDefaultKnowledgeId());
    }


    @Test
    public void test_delDocument() {
        knowledgeService.delDocument(138, 1071);
    }

    @Test
    public void test_checkQAKnowledgeDocument() {
        //1、上传文件列数超过10列，提示：上传文件内容不能超过10列
        //2、上传文件行数超过1500行，提示：上传文件内容不能超过1500行
        //3、上传文件单一行字数超过3000字，提示：上传文件内容单一行字数不能超过3000字
        //4、单格不可超1000字
        //5、文件大小不能超过10M
        try {
            File file = new File("C:\\Users\\52747\\Desktop\\1823模板.xlsx");
            // 文件大小不能超过10M
            long fileSizeInBytes = file.length();
            double fileSizeInMB = (double) fileSizeInBytes / (1024 * 1024);
            if (fileSizeInMB > 10) {
                throw new I18nMessageException("exception/upload.more.than.10m");
            }

            ExcelReader excelReader = ExcelUtil.getReader(file);
            Workbook workbook = excelReader.getWorkbook();
            Sheet sheetAt = workbook.getSheetAt(0);
            int rowNum = sheetAt.getLastRowNum() - 2;//行数
            if (rowNum > 1500) {
                throw new I18nMessageException("exception/file.rows.more.than.1500");
            }
            Row row = sheetAt.getRow(2);
            short lastCellNum = row.getLastCellNum();//列数
            if (lastCellNum > 10) {
                throw new I18nMessageException("exception/file.columns.more.than.10");
            }
            int lastRowNum = sheetAt.getLastRowNum();//最后一行索引
            for (int i = 2; i <= lastRowNum; i++) {
                row = sheetAt.getRow(i);
                //获取单元格内容
                Iterator<Cell> cellIterator = row.cellIterator();
                //每行字数不能超过3000字
                int totalWordCount = 0;
                while (cellIterator.hasNext()) {
                    Cell next = cellIterator.next();
                    if (StringUtils.isNotBlank(next.toString())) {
                        if (next.toString().length() > 1000) { // 每格字数不可超1000字
                            throw new I18nMessageException("exception/file.content.more.than.1000");
                        }
                        totalWordCount += next.toString().length();
                    }
                }
                if (totalWordCount > 3000) { //每行字数不可超3000字
                    throw new I18nMessageException("exception/file.content.more.than.3000");
                }
            }
        } catch (Exception e) {
            System.out.println("error" + e.getMessage());
        }
        System.out.println(true);
    }


    //    @Test
    public static void main(String[] args) throws IOException, InvalidFormatException {
        String markdownContent = readMarkdownFile("C:\\Users\\52747\\Desktop\\1.md");
        String htmlContent = convertMarkdownToHtml(markdownContent);
        convertHtmlToWord(htmlContent, "C:\\Users\\52747\\Desktop\\1.docx");
    }

    private static String readMarkdownFile(String filePath) {
        try {
            return new String(Files.readAllBytes(Paths.get(filePath)));
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    private static String convertMarkdownToHtml(String markdown) {
        Parser parser = Parser.builder().build();
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        Document document = parser.parse(markdown);
        return renderer.render(document);
    }

    private static void convertHtmlToWord(String html, String outputPath) throws IOException {
        FileOutputStream outputStream = new FileOutputStream(outputPath);
        ByteArrayInputStream bais = new ByteArrayInputStream(html.getBytes());//将字节数组包装到流中
        POIFSFileSystem poifs = new POIFSFileSystem();
        DirectoryEntry directory = poifs.getRoot();
        directory.createDocument("WordDocument", bais);
        poifs.writeFilesystem(outputStream);
    }
}
