package com.ruoyi.project.training.elearn.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.sems.domain.TSpecdevYlgd;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.training.elearn.domain.TElQuAnswer;
import com.ruoyi.project.training.spec.domain.vo.TStPlanImportVO;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
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.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.training.elearn.domain.TElQu;
import com.ruoyi.project.training.elearn.service.ITElQuService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 试题Controller
 *
 * @author ssy
 * @date 2024-05-28
 */
@RestController
@RequestMapping("/elearn/qu")
public class TElQuController extends BaseController {
    @Autowired
    private ITElQuService tElQuService;

    /**
     * 查询试题列表
     */
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody TElQu tElQu) {
        startPage();
        List<TElQu> list = tElQuService.selectTElQuList(tElQu);
        return getDataTable(list);
    }

    /**
     * 导出试题列表
     */
    @Log(title = "试题", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TElQu tElQu) {
        List<TElQu> list = tElQuService.selectTElQuList(tElQu);
        ExcelUtil<TElQu> util = new ExcelUtil<TElQu>(TElQu.class);
        return util.exportExcel(list, "qu");
    }

    /**
     * 获取试题详细信息
     */
    @GetMapping(value = "/{quId}")
    public AjaxResult getInfo(@PathVariable("quId") Long quId) {
        return AjaxResult.success(tElQuService.selectTElQuById(quId));
    }

    /**
     * 试题图片上传
     */
    @Log(title = "试题图片上传", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 获取年份
            int year = currentDate.getYear();
            // 获取月份
            int month = currentDate.getMonthValue();
            String dir = "/elearn/" + year;
            String avatar = FileUploadUtils.upload(RuoYiConfig.getFilePath(dir), file);
            return AjaxResult.success(avatar);
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * 新增试题
     */
    @Log(title = "试题", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TElQu tElQu) {
        return toAjax(tElQuService.insertTElQu(tElQu));
    }

    /**
     * 修改试题
     */
    @Log(title = "试题", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TElQu tElQu) {
        return toAjax(tElQuService.updateTElQu(tElQu));
    }

    /**
     * 删除试题
     */
    @Log(title = "试题", businessType = BusinessType.DELETE)
    @DeleteMapping("/{quIds}")
    public AjaxResult remove(@PathVariable Long[] quIds) {
        return toAjax(tElQuService.deleteTElQuByIds(quIds));
    }

    /**
     * 导入题目
     *
     * @param file          用户上传的文件
     * @param updateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param repoIds       题库id
     * @return
     * @throws Exception
     */
    @PostMapping("/importData2")
    public AjaxResult importData2(MultipartFile file, boolean updateSupport, String repoIds) throws Exception {
        logger.info("xzst-------------------");
        if (StringUtils.isEmpty(repoIds)) {
            return AjaxResult.error("未选择题库");
        }
        List<String> repos = Arrays.asList(repoIds.split(",").clone());


        FileInputStream fis = (FileInputStream) file.getInputStream();
        HWPFDocument document = new HWPFDocument(fis);

        WordExtractor extractor = new WordExtractor(document);
        String[] paragraphs = extractor.getParagraphText();
        // 正则表达式匹配选项
        Pattern pattern = Pattern.compile("\\[T\\](.*?)A、");
        TElQu qu = new TElQu();
        String quStr = "";
        for (String para : paragraphs) {
            logger.info(para);
            String text = para.trim();

            if (text.startsWith("[T]") || text.startsWith("@[T]")) {
                char thirdFromEnd = text.charAt(text.length() - 3);
                logger.info(String.valueOf(thirdFromEnd));
                if ("2".equals(String.valueOf(thirdFromEnd))) { //单选题
                    qu = new TElQu();
                    qu.setQuType(1l);
                } else if ("7".equals(String.valueOf(thirdFromEnd))) {//多选题
                    qu = new TElQu();
                    qu.setQuType(2l);
                } else if ("1".equals(String.valueOf(thirdFromEnd))) {//判断选题
                    qu = new TElQu();
                    qu.setQuType(3l);
                } else {
                    qu.setQuType(-1l);
                }
                quStr = "[T]";

            } else if (text.endsWith("[D/]")) {
                quStr = quStr + text;
                if (qu.getQuType() == 1l) {
                    Matcher matcher = pattern.matcher(quStr);

                    if (matcher.find()) {
                        String content = matcher.group(1);
                        System.out.println("从[T]到A、之间的内容是: " + content);
                        qu.setContent(content);
                    } else {
                        System.out.println("未找到匹配的内容");
                    }
                    //答案
                    Pattern patternA = Pattern.compile("A、(.*?)B、");
                    Matcher matcherA = patternA.matcher(quStr);
                    TElQuAnswer answerA = new TElQuAnswer();
                    answerA.setIsRight(0l);
                    TElQuAnswer answerB = new TElQuAnswer();
                    answerB.setIsRight(0l);
                    TElQuAnswer answerC = new TElQuAnswer();
                    answerC.setIsRight(0l);
                    TElQuAnswer answerD = new TElQuAnswer();
                    answerD.setIsRight(0l);
                    if (matcherA.find()) {
                        String content = matcherA.group(1);
                        System.out.println("从A、到B、之间的内容是: " + content);
                        answerA.setContent(content);
                    } else {
                        System.out.println("未找到匹配的内容");
                    }

                    Pattern patternB = Pattern.compile("B、(.*?)C、");
                    Matcher matcherB = patternB.matcher(quStr);
                    if (matcherB.find()) {
                        String content = matcherB.group(1);
                        answerB.setContent(content);
                    } else {
                        System.out.println("未找到匹配的内容");
                    }

                    Pattern patternC = Pattern.compile("C、(.*?)D、");
                    Matcher matcherC = patternC.matcher(quStr);
                    if (matcherC.find()) {
                        String content = matcherC.group(1);
                        answerC.setContent(content);
                    } else {
                        System.out.println("未找到匹配的内容");
                    }

                    Pattern patternD = Pattern.compile("D、(.*?)(?=\\[T/\\])");
                    Matcher matcherD = patternD.matcher(quStr);
                    if (matcherD.find()) {
                        String content = matcherD.group(1);
                        answerD.setContent(content);
                    } else {
                        System.out.println("未找到匹配的内容");
                    }
                    Pattern patternR = Pattern.compile("\\[D\\](.*?)(?=\\[D/\\])");
                    Matcher matcherR = patternR.matcher(quStr);
                    if (matcherR.find()) {
                        String res = matcherR.group(1);
                        System.out.println("从[D]到[D/]之间的内容是: " + res);
                        if ("A".equals(res)) {
                            answerA.setIsRight(1l);
                        } else if ("B".equals(res)) {
                            answerB.setIsRight(1l);
                        } else if ("C".equals(res)) {
                            answerC.setIsRight(1l);
                        } else if ("D".equals(res)) {
                            answerD.setIsRight(1l);
                        }
                    }
                    List<TElQuAnswer> answerList = new ArrayList<>();
                    answerList.add(answerA);
                    answerList.add(answerB);
                    answerList.add(answerC);
                    answerList.add(answerD);
                    qu.setAnswerList(answerList);
                    qu.setRepoIds(repos);
                    logger.info(JSON.toJSONString(qu));
                    tElQuService.insertTElQu(qu);
                    quStr = "";
                } else if (qu.getQuType() == 2l) {
                    Matcher matcher = pattern.matcher(quStr);

                    if (matcher.find()) {
                        String content = matcher.group(1);
                        System.out.println("从[T]到A、之间的内容是: " + content);
                        qu.setContent(content);
                    } else {
                        System.out.println("未找到匹配的内容");
                    }
                    //答案
                    Pattern patternA = Pattern.compile("A、(.*?)B、");
                    Matcher matcherA = patternA.matcher(quStr);
                    TElQuAnswer answerA = new TElQuAnswer();
                    answerA.setIsRight(0l);
                    TElQuAnswer answerB = new TElQuAnswer();
                    answerB.setIsRight(0l);
                    TElQuAnswer answerC = new TElQuAnswer();
                    answerC.setIsRight(0l);
                    TElQuAnswer answerD = new TElQuAnswer();
                    answerD.setIsRight(0l);
                    if (matcherA.find()) {
                        String content = matcherA.group(1);
                        System.out.println("从A、到B、之间的内容是: " + content);
                        answerA.setContent(content);
                    } else {
                        System.out.println("未找到匹配的内容");
                    }

                    Pattern patternB = Pattern.compile("B、(.*?)C、");
                    Matcher matcherB = patternB.matcher(quStr);
                    if (matcherB.find()) {
                        String content = matcherB.group(1);
                        answerB.setContent(content);
                    } else {
                        System.out.println("未找到匹配的内容");
                    }

                    Pattern patternC = Pattern.compile("C、(.*?)D、");
                    Matcher matcherC = patternC.matcher(quStr);
                    if (matcherC.find()) {
                        String content = matcherC.group(1);
                        answerC.setContent(content);
                    } else {
                        System.out.println("未找到匹配的内容");
                    }

                    Pattern patternD = Pattern.compile("D、(.*?)(?=\\[T/\\])");
                    Matcher matcherD = patternD.matcher(quStr);
                    if (matcherD.find()) {
                        String content = matcherD.group(1);
                        answerD.setContent(content);
                    } else {
                        System.out.println("未找到匹配的内容");
                    }
                    Pattern patternR = Pattern.compile("\\[D\\](.*?)(?=\\[D/\\])");
                    Matcher matcherR = patternR.matcher(quStr);
                    if (matcherR.find()) {
                        String res = matcherR.group(1);
                        System.out.println("从[D]到[D/]之间的内容是: " + res);
                        List<String> resList = Arrays.asList(res.split(","));
                        if (resList.contains("A")) {
                            answerA.setIsRight(1l);
                        }
                        if (resList.contains("B")) {
                            answerB.setIsRight(1l);
                        }
                        if (resList.contains("C")) {
                            answerC.setIsRight(1l);
                        }
                        if (resList.contains("D")) {
                            answerD.setIsRight(1l);
                        }
                    }
                    List<TElQuAnswer> answerList = new ArrayList<>();
                    answerList.add(answerA);
                    answerList.add(answerB);
                    answerList.add(answerC);
                    answerList.add(answerD);
                    qu.setAnswerList(answerList);
                    qu.setRepoIds(repos);
                    logger.info(JSON.toJSONString(qu));
                    tElQuService.insertTElQu(qu);
                    quStr = "";
                } else if (qu.getQuType() == 3l) {
                    // 正则表达式匹配选项
                    Pattern patternQ = Pattern.compile("\\[T\\](.*?)(?=\\[T/\\])");
                    Matcher matcher = patternQ.matcher(quStr);

                    if (matcher.find()) {
                        String content = matcher.group(1);
                        System.out.println("从[T]到A、之间的内容是: " + content);
                        qu.setContent(content);
                    } else {
                        System.out.println("未找到匹配的内容");
                    }
                    TElQuAnswer answerA = new TElQuAnswer();
                    answerA.setIsRight(0l);
                    answerA.setContent("正确");
                    TElQuAnswer answerB = new TElQuAnswer();
                    answerB.setIsRight(0l);
                    answerB.setContent("错误");
                    Pattern patternR = Pattern.compile("\\[D\\](.*?)(?=\\[D/\\])");
                    Matcher matcherR = patternR.matcher(quStr);
                    if (matcherR.find()) {
                        String res = matcherR.group(1);
                        System.out.println("从[D]到[D/]之间的内容是: " + res);
                        if ("√".equals(res)) {
                            answerA.setIsRight(1l);
                        } else {
                            answerB.setIsRight(1l);
                        }
                    }
                    List<TElQuAnswer> answerList = new ArrayList<>();
                    answerList.add(answerA);
                    answerList.add(answerB);
                    qu.setAnswerList(answerList);
                    qu.setRepoIds(repos);
                    logger.info(JSON.toJSONString(qu));
                    tElQuService.insertTElQu(qu);
                    quStr = "";
                }

            } else if (text.startsWith("正确答案")) {
                if (qu.getQuType() != -1) {
                    qu.setAnalysis(text);
                    tElQuService.updateTElQu(qu);
                }
            } else {
                quStr = quStr + text;
            }
        }

        return AjaxResult.success();
    }

    /**
     * 导入题目
     *
     * @param file          用户上传的文件
     * @param updateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param repoIds       题库id
     * @return
     * @throws Exception
     */
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, String repoIds) throws Exception {
        logger.info("xzst-------------------");
        if (StringUtils.isEmpty(repoIds)) {
            return AjaxResult.error("未选择题库");
        }
        List<String> repos = Arrays.asList(repoIds.split(",").clone());


        FileInputStream fis = (FileInputStream) file.getInputStream();
        XWPFDocument document = new XWPFDocument(fis);

        List<XWPFParagraph> paragraphs = document.getParagraphs();
        // 正则表达式匹配选项
        Pattern pattern = Pattern.compile("\\[T\\](.*?)A、");
        TElQu qu = new TElQu();
        String quStr = "";
        String anStr = "";
        for (XWPFParagraph para : paragraphs) {
            logger.info(para.getParagraphText());
            String text = para.getParagraphText().trim();
            if (text.startsWith("[多选]")) {
                qu.setQuType(2l);
                quStr = text.replaceAll("\\[多选\\]", "");
            } else if (text.startsWith("[单选]")) {
                qu.setQuType(1l);
                quStr = text.replaceAll("\\[单选\\]", "");
            } else if (text.startsWith("[判断]")) {
                qu.setQuType(3l);
                quStr = text.replaceAll("\\[判断\\]", "");
            } else if (text.startsWith("[判断]")) {
                qu.setQuType(3l);
                quStr = text.replaceAll("\\[判断\\]", "");
            } else if (text.startsWith("A.")) {
                qu.setContent(quStr);
                quStr = text;

            } else if (text.startsWith("[D]")) {
                if (qu.getQuType() == 3) { //判断题题目
                    qu.setContent(quStr);

                    TElQuAnswer answerA = new TElQuAnswer();
                    answerA.setIsRight(0l);
                    answerA.setContent("正确");
                    TElQuAnswer answerB = new TElQuAnswer();
                    answerB.setIsRight(0l);
                    answerB.setContent("错误");
                    if (text.contains("对")) {
                        answerA.setIsRight(1l);
                    } else {
                        answerB.setIsRight(1l);
                    }
                    // 插入判断题
                    List<TElQuAnswer> answerList = new ArrayList<>();
                    answerList.add(answerA);
                    answerList.add(answerB);
                    qu.setAnswerList(answerList);
                    qu.setRepoIds(repos);
                    logger.info(JSON.toJSONString(qu));
                    tElQuService.insertTElQu(qu);
                    quStr = "";
                } else { // 单选多选
                    //答案
                    quStr = quStr + text;

                    TElQuAnswer answerA = new TElQuAnswer();
                    answerA.setIsRight(0l);
                    TElQuAnswer answerB = new TElQuAnswer();
                    answerB.setIsRight(0l);
                    TElQuAnswer answerC = new TElQuAnswer();
                    answerC.setIsRight(0l);
                    TElQuAnswer answerD = new TElQuAnswer();
                    answerD.setIsRight(0l);
                    TElQuAnswer answerE = new TElQuAnswer();
                    answerE.setIsRight(0l);

                    Pattern patternA = Pattern.compile("A\\.(.*?)B\\.");
                    Matcher matcherA = patternA.matcher(quStr);
                    if (matcherA.find()) {
                        String content = matcherA.group(1);
                        System.out.println("从A、到B、之间的内容是: " + content);
                        answerA.setContent(content);
                    } else {
                        System.out.println("未找到匹配的内容");
                    }

                    Pattern patternB = Pattern.compile("B\\.(.*?)C\\.");
                    Matcher matcherB = patternB.matcher(quStr);
                    if (matcherB.find()) {
                        String content = matcherB.group(1);
                        System.out.println("从B、到C、之间的内容是: " + content);
                        answerB.setContent(content);
                    } else {
                        System.out.println("未找到匹配的内容");
                    }
                    if (quStr.contains("D.")) { //有D选项
                        Pattern patternC = Pattern.compile("C\\.(.*?)D\\.");
                        Matcher matcherC = patternC.matcher(quStr);
                        if (matcherC.find()) {
                            String content = matcherC.group(1);
                            System.out.println("从C、到D、之间的内容是: " + content);
                            answerC.setContent(content);
                        } else {
                            System.out.println("未找到匹配的内容");
                        }

                        Pattern patternD = Pattern.compile("D\\.(.*?)(?=\\[D])");
                        Matcher matcherD = patternD.matcher(quStr);
                        if (matcherD.find()) {
                            String content = matcherD.group(1);
                            System.out.println("从D、到[D]、之间的内容是: " + content);
                            answerD.setContent(content);
                        } else {
                            System.out.println("未找到匹配的内容");
                        }

                    }
                    if (quStr.contains("E.")) { //有E选项
                        Pattern patternC = Pattern.compile("C\\.(.*?)D\\.");
                        Matcher matcherC = patternC.matcher(quStr);
                        if (matcherC.find()) {
                            String content = matcherC.group(1);
                            System.out.println("从C、到D、之间的内容是: " + content);
                            answerC.setContent(content);
                        } else {
                            System.out.println("未找到匹配的内容");
                        }
                        Pattern patternD = Pattern.compile("D\\.(.*?)E\\.");
                        Matcher matcherD = patternD.matcher(quStr);
                        if (matcherD.find()) {
                            String content = matcherD.group(1);
                            System.out.println("从D、到E、之间的内容是: " + content);
                            answerD.setContent(content);
                        } else {
                            System.out.println("未找到匹配的内容");
                        }

                        Pattern patternE = Pattern.compile("E\\.(.*?)(?=\\[D])");
                        Matcher matcherE = patternE.matcher(quStr);
                        if (matcherE.find()) {
                            String content = matcherE.group(1);
                            System.out.println("从E、到[D]、之间的内容是: " + content);
                            answerE.setContent(content);
                        } else {
                            System.out.println("未找到匹配的内容");
                        }
                    }
                    if (!quStr.contains("D.")) {//无D选项
                        Pattern patternC = Pattern.compile("C\\.(.*?)(?=\\[D])");
                        Matcher matcherC = patternC.matcher(quStr);
                        if (matcherC.find()) {
                            String content = matcherC.group(1);
                            System.out.println("从C、到D、之间的内容是: " + content);
                            answerC.setContent(content);
                        } else {
                            System.out.println("未找到匹配的内容");
                        }
                    }
                    anStr = text.replaceAll("\\[D\\]", "").replaceAll("\\[/D\\]", "");
                    System.out.println("匹配答案：" + anStr);
                    if (anStr.contains("A")) {
                        answerA.setIsRight(1l);
                    }
                    if (anStr.contains("B")) {
                        answerB.setIsRight(1l);
                    }
                    if (anStr.contains("C")) {
                        answerC.setIsRight(1l);
                    }
                    if (anStr.contains("D")) {
                        answerD.setIsRight(1l);
                    }
                    if (anStr.contains("E")) {
                        answerE.setIsRight(1l);
                    }
                    List<TElQuAnswer> answerList = new ArrayList<>();
                    answerList.add(answerA);
                    answerList.add(answerB);
                    answerList.add(answerC);
                    if (quStr.contains("D.")) { //有D选项
                        answerList.add(answerD);
                        if (quStr.contains("E.")) { //有D选项
                            answerList.add(answerE);

                        }
                    }
                    qu.setAnswerList(answerList);
                    qu.setRepoIds(repos);
                    logger.info(JSON.toJSONString(qu));
                    tElQuService.insertTElQu(qu);
                    quStr = "";

                }
            } else {
                quStr = quStr + text;
            }

        }

        return AjaxResult.success();
    }

    /**
     * 导入题目
     *
     * @param file          用户上传的文件
     * @param updateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param repoIds       题库id
     * @return
     * @throws Exception
     */
    @PostMapping("/importDataExcel")
    public AjaxResult importDataExcel(MultipartFile file, boolean updateSupport, String repoIds) throws Exception {
        List<String> repos = Arrays.asList(repoIds.split(",").clone());
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        int rowNum = sheet.getPhysicalNumberOfRows();
        logger.info("总行数：" + rowNum);
        List<TElQu> list = new ArrayList<TElQu>();
        //报错行数统计
        List<Integer> failRow = new ArrayList<Integer>();
        AtomicInteger failNumber = new AtomicInteger();
        AtomicInteger successNumber = new AtomicInteger();
        AtomicInteger failNum = new AtomicInteger();

        for (int i = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TElQu qu = new TElQu();
                List<TElQuAnswer> answerList = new ArrayList<>();
                String[] options = null;
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    String cellValue = ExcelUtils.getCellValue(cell).trim();
                    logger.info("cellValue:" + cellValue);
                    if (j == 0) {
                        //题型
                        if ("单选题".equals(cellValue)) {
                            qu.setQuType(1l);
                        } else if ("多选题".equals(cellValue)) {
                            qu.setQuType(2l);
                        } else if ("判断题".equals(cellValue)) {
                            qu.setQuType(3l);
                        } else {
                            break;
                        }
                    } else if (j == 1) {
                        cellValue = replaceSubSup(cellValue);
                        qu.setContent(cellValue);
                    } else if (j == 2) {
                        cellValue = replaceSubSup(cellValue);
                        if (qu.getQuType() != 3) {
                            options = cellValue.split(";");
                        }
                    } else if (j == 3) {
                        if (qu.getQuType() != 3) { //选择
                            /*if (options.length == 4) { //ABCD
                                TElQuAnswer answerA = new TElQuAnswer();
                                answerA.setIsRight(0l);
                                answerA.setContent(options[0]);
                                TElQuAnswer answerB = new TElQuAnswer();
                                answerB.setIsRight(0l);
                                answerB.setContent(options[1]);
                                TElQuAnswer answerC = new TElQuAnswer();
                                answerC.setIsRight(0l);
                                answerC.setContent(options[2]);
                                TElQuAnswer answerD = new TElQuAnswer();
                                answerD.setIsRight(0l);
                                answerD.setContent(options[3]);
                                if (cellValue.contains("A")) {
                                    answerA.setIsRight(1l);
                                }
                                if (cellValue.contains("B")) {
                                    answerB.setIsRight(1l);
                                }
                                if (cellValue.contains("C")) {
                                    answerC.setIsRight(1l);
                                }
                                if (cellValue.contains("D")) {
                                    answerD.setIsRight(1l);
                                }
                                answerList.add(answerA);
                                answerList.add(answerB);
                                answerList.add(answerC);
                                answerList.add(answerD);
                            } else if (options.length == 5) { //ABCDE
                                TElQuAnswer answerA = new TElQuAnswer();
                                answerA.setIsRight(0l);
                                answerA.setContent(options[0]);
                                TElQuAnswer answerB = new TElQuAnswer();
                                answerB.setIsRight(0l);
                                answerB.setContent(options[1]);
                                TElQuAnswer answerC = new TElQuAnswer();
                                answerC.setIsRight(0l);
                                answerC.setContent(options[2]);
                                TElQuAnswer answerD = new TElQuAnswer();
                                answerD.setIsRight(0l);
                                answerD.setContent(options[3]);
                                TElQuAnswer answerE = new TElQuAnswer();
                                answerE.setIsRight(0l);
                                answerE.setContent(options[4]);
                                if (cellValue.contains("A")) {
                                    answerA.setIsRight(1l);
                                }
                                if (cellValue.contains("B")) {
                                    answerB.setIsRight(1l);
                                }
                                if (cellValue.contains("C")) {
                                    answerC.setIsRight(1l);
                                }
                                if (cellValue.contains("D")) {
                                    answerD.setIsRight(1l);
                                }
                                if (cellValue.contains("E")) {
                                    answerE.setIsRight(1l);
                                }
                                answerList.add(answerA);
                                answerList.add(answerB);
                                answerList.add(answerC);
                                answerList.add(answerD);
                                answerList.add(answerE);
                            } else if (options.length == 3) { //ABC
                                TElQuAnswer answerA = new TElQuAnswer();
                                answerA.setIsRight(0l);
                                answerA.setContent(options[0]);
                                TElQuAnswer answerB = new TElQuAnswer();
                                answerB.setIsRight(0l);
                                answerB.setContent(options[1]);
                                TElQuAnswer answerC = new TElQuAnswer();
                                answerC.setIsRight(0l);
                                answerC.setContent(options[2]);

                                if (cellValue.contains("A")) {
                                    answerA.setIsRight(1l);
                                }
                                if (cellValue.contains("B")) {
                                    answerB.setIsRight(1l);
                                }
                                if (cellValue.contains("C")) {
                                    answerC.setIsRight(1l);
                                }

                                answerList.add(answerA);
                                answerList.add(answerB);
                                answerList.add(answerC);
                            }*/
                            // 假设 options 是一个包含选项内容的数组，cellValue 是一个包含正确答案的字符串
                            char[] labels = {'A', 'B', 'C', 'D', 'E', 'F', 'J', 'H', 'I', 'J', 'K'};  // 可以扩展更多的选项
                            for (int c = 0; c < options.length && c < labels.length; c++) {
                                TElQuAnswer answer = new TElQuAnswer();
                                answer.setIsRight(0L);
                                answer.setContent(options[c]);

                                // 检查 cellValue 中是否包含对应的字母标识，设置正确答案
                                if (cellValue.contains(String.valueOf(labels[c]))) {
                                    answer.setIsRight(1L);
                                }

                                // 将答案添加到列表中
                                answerList.add(answer);
                            }

                        } else if (qu.getQuType() == 3) { //判断
                            TElQuAnswer answerA = new TElQuAnswer();
                            answerA.setIsRight(0l);
                            answerA.setContent("正确");
                            TElQuAnswer answerB = new TElQuAnswer();
                            answerB.setIsRight(0l);
                            answerB.setContent("错误");
                            if (cellValue.contains("A")) {
                                answerA.setIsRight(1l);
                            }
                            if (cellValue.contains("B")) {
                                answerB.setIsRight(1l);
                            }
                            answerList.add(answerA);
                            answerList.add(answerB);
                        }
                        // 最终insert
                        qu.setAnswerList(answerList);
                        qu.setRepoIds(repos);
                        logger.info(JSON.toJSONString(qu));
                        list.add(qu);
//                        tElQuService.insertTElQuBatch(qu , i);
                    }
                }
            } catch (Exception e) {
                failNumber.getAndIncrement();
                TElQu qu = new TElQu();
                list.add(qu);
                logger.error("e:" + JSON.toJSONString(e));
            }
        }
        //线程池
        ExecutorService executorService = Executors.newFixedThreadPool(30);
        final CountDownLatch latch = new CountDownLatch(list.size()); //相同线程数量的计数
        for (TElQu t : list
        ) {
            executorService.execute(() -> {
                // -- 业务模块
                failNum.getAndIncrement();
                try {
                    tElQuService.insertTElQu(t);
                    successNumber.getAndIncrement();
                } catch (Exception e) {
                    failNumber.getAndIncrement();
                    logger.info("e:" + e);
                    failRow.add(failNum.get() + 1);
                } finally {
                    latch.countDown(); //线程计数
                }
            });
        }
        try {
            latch.await(); //线程计数完毕后继续执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        logger.info("successNumber:" + String.valueOf(successNumber));
        logger.info("failNumber:" + String.valueOf(failNumber));
        logger.info("failRow:" + String.valueOf(failRow));
        logger.info("总行数：" + rowNum);
        logger.info("Row:" + list.size());
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }

    // 通用方法：替换 <sub> 和 <sup> 标签
    public String replaceSubSup(String input) {

        // 映射用于将字符替换为对应的 Unicode 上标或下标
        Map<Character, String> subMap = new HashMap<>();
        Map<Character, String> supMap = new HashMap<>();
        // 下标映射：支持 0-9 和小写字母a
        subMap.put('0', "\u2080");
        subMap.put('1', "\u2081");
        subMap.put('2', "\u2082");
        subMap.put('3', "\u2083");
        subMap.put('4', "\u2084");
        subMap.put('5', "\u2085");
        subMap.put('6', "\u2086");
        subMap.put('7', "\u2087");
        subMap.put('8', "\u2088");
        subMap.put('9', "\u2089");
        subMap.put('a', "\u2090");
        subMap.put('b', "\u2091");
        subMap.put('c', "\u2092");
        subMap.put('d', "\u2093");
        subMap.put('e', "\u2094");
        subMap.put('g', "\u2095");
        subMap.put('h', "\u2096");
        subMap.put('k', "\u2097");
        subMap.put('l', "\u2098");
        subMap.put('m', "\u2099");
        subMap.put('n', "\u209A");
        subMap.put('o', "\u209B");
        subMap.put('p', "\u209C");


        // 上标映射：支持 0-9
        supMap.put('0', "\u2070");
        supMap.put('1', "\u00B9");
        supMap.put('2', "\u00B2");
        supMap.put('3', "\u00B3");
        supMap.put('4', "\u2074");
        supMap.put('5', "\u2075");
        supMap.put('6', "\u2076");
        supMap.put('7', "\u2077");
        supMap.put('8', "\u2078");
        supMap.put('9', "\u2079");
        supMap.put('+', "\u207A");
        supMap.put('-', "\u207B");

        int iterationCount = 0;
        // 替换 <sub> 标签
        while (input.contains("<sub>") && iterationCount < 500) {
            int startIndex = input.indexOf("<sub>");
            int endIndex = input.indexOf("</sub>");

            if (startIndex != -1 && endIndex != -1) {
                String subContent = input.substring(startIndex + 5, endIndex);  // 获取 <sub> 中的内容
                StringBuilder replacedSubContent = new StringBuilder();

                // 遍历 <sub> 中的字符，替换成下标字符
                for (char c : subContent.toCharArray()) {
                    if (subMap.containsKey(c)) {
                        replacedSubContent.append(subMap.get(c));  // 替换为下标字符
                    } else {
                        replacedSubContent.append(c);  // 保留原字符
                    }
                }

                // 替换原来的 <sub> 标签为处理后的字符
                input = input.substring(0, startIndex) + replacedSubContent + input.substring(endIndex + 6);
                logger.info("处理结果：" + input);
            }
            iterationCount++;
        }

        // 替换 <sup> 或 <SUP> 标签
        while (input.contains("<sup>") && iterationCount < 500) {
            int startIndex = input.indexOf("<sup>") != -1 ? input.indexOf("<sup>") : input.indexOf("<SUP>");
            int endIndex = input.indexOf("</sup>") != -1 ? input.indexOf("</sup>") : input.indexOf("</SUP>");

            if (startIndex != -1 && endIndex != -1) {
                String supContent = input.substring(startIndex + 5, endIndex);  // 获取 <sup> 中的内容
                StringBuilder replacedSupContent = new StringBuilder();

                // 遍历 <sup> 中的字符，替换成上标字符
                for (char c : supContent.toCharArray()) {
                    if (supMap.containsKey(c)) {
                        replacedSupContent.append(supMap.get(c));  // 替换为上标字符
                    } else {
                        replacedSupContent.append(c);  // 保留原字符
                    }
                }

                // 替换原来的 <sup> 标签为处理后的字符
                input = input.substring(0, startIndex) + replacedSupContent + input.substring(endIndex + 6);
                logger.info("处理结果：" + input);
            }
            iterationCount++;
        }
        logger.info("处理结果：" + input);
        return input;
    }
}
