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

import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
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.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
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.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("/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();
        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();
    }
}
