<template>
  <div class="app-container" id="paperContainer">
    <el-card style="margin-bottom: 10px; text-align: center">
      <el-input v-model="papername" style="width: 150px" />
      <el-button style="margin-left: 10px" type="text" @click="savePaper" :loading="isLoading">保存试卷</el-button>
      <el-button style="margin-left: 10px" type="text" @click="toQuestionList()">继续出题</el-button>
    </el-card>
    <el-card style="margin-bottom: 10px" v-for="(questionData, index) in questionList" :key="index">
      <div :class="'drag_' + index">
        <div slot="header" class="clearfix" @mouseover="showSorce(questionData, index)" @mouseout="hideSorce(questionData, index)" draggable="true" @dragstart="handleDragStart($event, questionData)" @dragover.prevent="handleDragOver($event, questionData)" @drop="handleDragEnter($event, questionData)" @dragend="handleDragEnd($event, questionData)">
          <span style="color: #000000; font-size: 14px; font-weight: bold">{{ NumberToChinese(index + 1) }}、{{ questionData.title }}(共{{
              questionData.num
            }}题;共{{ questionData.score }}分)</span>
          <span style="float: right; display: none" :id="'parent_score_' + index">
            <el-button type="text" @click="
                openParentScore = true;
                currentIndex = index;
              ">批量设置得分</el-button>
            <el-button type="text" @click="deleteType(index)">删除分类</el-button>
          </span>
        </div>
        <div v-for="(questionInfo, index2) in questionData.list" :key="index2" style="margin-bottom: 10px" @mouseover="showQuestionSorce(index, index2)" @mouseout="hideQuestionSorce(index, index2)" @dragstart="handleQuestionDragStart($event, questionInfo, index2)" @dragover.prevent="handleQuestionDragOver($event, questionInfo)" @drop="handleQuestionDragEnter($event, questionInfo, index, index2)" @dragend="handleQuestionDragEnd($event, questionInfo)" draggable="true">
          <div style="display: none" :id="'score_' + index + '_' + index2">
            <el-button type="text" @click="
                openScore = true;
                currentIndex = index;
                questionIndex = index2;
              ">设置得分</el-button>
            <el-button type="text" @click="setCurrentVal(index, index2, questionInfo)">解析</el-button>
            <el-button type="text" @click="deleteQuestion(index, index2)">删除题目</el-button>
          </div>
          <div>
            {{ index2 + 1 }}.
            <span style="color: #1890ff">题号:{{ questionInfo.id }}（{{ questionInfo.score }}分）</span><span v-html="questionInfo.title"></span>
          </div>
          <!--<div v-for="child in questionInfo.subquestions" v-html="child.title"></div>-->
        </div>
      </div>
    </el-card>

    <!-- 批量设置分数-->
    <el-dialog :visible.sync="openParentScore" width="500px" append-to-body>
      <el-form label-width="80px">
        <el-form-item label="分数" prop="parentScore">
          <el-input-number v-model.number="parentScore" :min="1" placeholder="请输入分数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setParentScore">确 定</el-button>
        <el-button @click="openParentScore = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 设置题目分数 -->
    <el-dialog :visible.sync="openScore" width="500px" append-to-body>
      <el-form label-width="80px">
        <el-form-item label="分数" prop="parentScore">
          <el-input-number v-model.number="questionScore" :min="1" placeholder="请输入分数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setScore">确 定</el-button>
        <el-button @click="openScore = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 试题篮 -->
    <el-dialog title="解析" :visible.sync="openQuestionParseDialog" width="500px" append-to-body center>
      <el-form label-width="80px">
        <el-form-item label="解析">
          <editor v-model="currentQuestionParse" :min-height="122" />
        </el-form-item>
        <el-form-item label="答案1">
          <editor v-model="currentQuestionAnswer1" :min-height="122" />
        </el-form-item>
        <el-form-item label="答案2">
          <editor v-model="currentQuestionAnswer2" :min-height="122" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setQuestionParse">确 定</el-button>
        <el-button @click="openQuestionParseDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { savePaperInfo, deleteQuestionCard } from "@/api/webApi/webQue.js";
import Editor from "@/components/Editor";
export default {
  name: "Paper",
  components: {
    Editor,
  },
  data() {
    return {
      isLoading: false,
      currentTypeIndex: 0,
      currentQuestionIndex: 0,
      currentQuestionParse: "",
      currentQuestionAnswer1: "",
      currentQuestionAnswer2: "",
      openQuestionParseDialog: false,
      openScore: false,
      questionScore: null,
      currentIndex: null,
      questionIndex: null,
      parentScore: "",
      openParentScore: false,
      papername: "试卷标题",
      questionList: [],
      chnNumChar: ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"],
      chnUnitSection: ["", "万", "亿", "万亿", "亿亿"],
      chnUnitChar: ["", "十", "百", "千"],
      qtype: [],
      jsonData: {},
      dragging: null,
      questionDragging: null,
      questionIndex2: null,
    };
  },
  mounted() {
    this.getQuestionList();
  },
  watch: {
    $route() {
      this.getQuestionList();
    },
  },
  methods: {
    setCurrentVal(index, index2, questionInfo) {
      this.openQuestionParseDialog = true;
      this.currentTypeIndex = index;
      this.currentQuestionIndex = index2;
      this.currentQuestionParse = questionInfo.parse;
      this.currentQuestionAnswer1 = questionInfo.answer1;
      this.currentQuestionAnswer2 = questionInfo.answer2;
    },
    getQuestionList() {
      this.questionList = []
      this.jsonData = JSON.parse(localStorage.getItem("paperData"))
      this.papername = this.jsonData.paperTitle || this.papername

      const source = JSON.parse(localStorage.getItem("questionList"))
      const groupedSource = source.groupBy(q => q.qtpye)
      this.questionList = groupedSource.map(g => ({
        title: g.label,
        list: g.options,
        num: g.options.length,
        score: g.options.sum(q => q.score)
      }))

      this.$nextTick(_=>this.mxGlobal.MathQueue("paperContainer"))
      console.log(this.questionList);
    },

    SectionToChinese(section) {
      var strIns = "",
        chnStr = "";
      var unitPos = 0;
      var zero = true;
      while (section > 0) {
        var v = section % 10;
        if (v === 0) {
          if (!zero) {
            zero = true;
            chnStr = this.chnNumChar[v] + chnStr;
          }
        } else {
          zero = false;
          strIns = this.chnNumChar[v];
          strIns += this.chnUnitChar[unitPos];
          chnStr = strIns + chnStr;
        }
        unitPos++;
        section = Math.floor(section / 10);
      }
      return chnStr;
    },
    NumberToChinese(num) {
      var unitPos = 0;
      var strIns = "",
        chnStr = "";
      var needZero = false;

      if (num === 0) {
        return this.chnNumChar[0];
      }

      while (num > 0) {
        var section = num % 10000;
        if (needZero) {
          chnStr = this.chnNumChar[0] + chnStr;
        }
        strIns = this.SectionToChinese(section);
        strIns +=
          section !== 0 ? this.chnUnitSection[unitPos] : this.chnUnitSection[0];
        chnStr = strIns + chnStr;
        needZero = section < 1000 && section > 0;
        num = Math.floor(num / 10000);
        unitPos++;
      }

      return chnStr;
    },
    showSorce(data, index) {
      let doc = document.getElementById("parent_score_" + index);
      doc.style.display = "block";
    },
    hideSorce(data, index) {
      let doc = document.getElementById("parent_score_" + index);
      doc.style.display = "none";
    },
    setParentScore() {
      let data = this.questionList[this.currentIndex];
      let len = data.list.length;
      data.score = len * this.parentScore;
      for (let q of data.list) {
        q.score = this.parentScore;
      }
      this.openParentScore = false;
    },
    setScore() {
      this.questionList[this.currentIndex].list[this.questionIndex].score =
        this.questionScore;
      let list = this.questionList[this.currentIndex].list;
      let score = 0;
      for (let q of list) {
        score = q.score + score;
      }

      this.questionList[this.currentIndex].score = score;
      this.openScore = false;
    },
    showQuestionSorce(pIndex, qIndex) {
      let doc = document.getElementById("score_" + pIndex + "_" + qIndex);
      doc.style.display = "block";
    },
    hideQuestionSorce(pIndex, qIndex) {
      let doc = document.getElementById("score_" + pIndex + "_" + qIndex);
      doc.style.display = "none";
    },
    deleteType(index) {
      this.questionList.splice(index, 1);
    },
    deleteQuestion(pIndex, qIndex) {
      let data = this.questionList[pIndex].list[qIndex];
      this.questionList[pIndex].list.splice(qIndex, 1);
      this.questionList[pIndex].num--;
      this.questionList[pIndex].score =
        this.questionList[pIndex].score - data.score;
    },
    toQuestionList() {
      this.$router.push("/question-center/generatingPaperCenter");
    },
    savePaper() {
      let list = [];
      let index = 1;
      let remark = ''
      for (let item of this.questionList) {
        remark += item.title + "(" + item.score + ")分；"
        for (let item1 of item.list) {
          let data = {
            questionId: item1.id,
            seq: index,
            score: item1.score,
            knowledgeId: item1.knowledgeId,
            knowledgeName: item1.knowledgeName,
            answer1: item1.answer1,
            answer2: item1.answer2,
            parse: item1.parse,
          };
          index++;
          list.push(data);
        }
      }
      let param = {
        subjectid: this.jsonData.subjectId ? this.jsonData.subjectId : 0,
        gradeId: this.jsonData.gradeId,
        buildType: this.jsonData.buildType,
        name: this.papername,
        remark: remark,
        paperId: this.jsonData.paperId,
        paperQuestions: list,
      };
      this.isLoading = true;
      savePaperInfo(param)
        .then((response) => {
          this.msgSuccess("保存成功");
          this.isLoading = false;
          localStorage.setItem("paperData", JSON.stringify({}));
          localStorage.setItem("questionList", JSON.stringify([]));
          deleteQuestionCard().then(res => this.$router.push("/question-center/generatingPaperCenter"))
        })
        .catch((err) => {
          this.isLoading = false;
          console.log(err);
        });
    },
    setQuestionParse() {
      this.questionList[this.currentTypeIndex].list[
        this.currentQuestionIndex
      ].parse = this.currentQuestionParse;
      this.questionList[this.currentTypeIndex].list[
        this.currentQuestionIndex
      ].answer1 = this.currentQuestionAnswer1;
      this.questionList[this.currentTypeIndex].list[
        this.currentQuestionIndex
      ].answer2 = this.currentQuestionAnswer2;
      this.openQuestionParseDialog = false;
    },
    // 拖动
    handleDragStart(e, item) {
      console.log(item);
      this.dragging = item;
    },
    handleDragEnd(e, item) {
      this.dragging = null;
    },
    handleDragOver(e) {
      e.dataTransfer.dropEffect = "move"; // e.dataTransfer.dropEffect="move";//在dragenter中针对放置目标来设置!
    },
    handleDragEnter(e, item) {
      e.dataTransfer.effectAllowed = "move"; //为需要移动的元素设置dragstart事件
      if (item === this.dragging) {
        return;
      }
      const newItems = this.questionList;
      const src = newItems.indexOf(this.dragging);
      const dst = newItems.indexOf(item);

      newItems.splice(dst, 0, ...newItems.splice(src, 1));

      this.questionList = newItems;
    },
    // 拖动
    handleQuestionDragStart(e, item, index2) {
      this.questionDragging = item;
      this.questionIndex2 = index2;
    },
    handleQuestionDragEnd(e, item) {
      this.questionDragging = null;
      this.questionIndex2 = null;
    },
    handleQuestionDragOver(e) {
      e.dataTransfer.dropEffect = "move"; // e.dataTransfer.dropEffect="move";//在dragenter中针对放置目标来设置!
    },
    handleQuestionDragEnter(e, item, index, index2) {
      e.dataTransfer.effectAllowed = "move"; //为需要移动的元素设置dragstart事件
      if (item === this.questionDragging && this.questionIndex2 == index2) {
        return;
      }
      const newItems = this.questionList[index].list;
      const src = this.questionIndex2;
      const dst = index2;

      newItems.splice(dst, 0, ...newItems.splice(src, 1));

      this.questionList[index].list = newItems;
    },
  },
};
</script>
