<template>
  <div
    id="editPaperApp"
    v-loading="loading"
    class="view-paper"
    element-loading-text="拼命加载中。。。"
  >
    <div class="view-header box-justify">
      <div class="header-info">
        <div class="header-info-item">
          <span>课程代码：</span>
          <span>{{ paper.course.code }}</span>
        </div>
        <div class="header-info-item">
          <span>课程名称：</span>
          <span>{{ paper.course.name }}</span>
        </div>
        <div class="header-info-item">
          <span>试卷名称：</span>
          <span>
            {{ paper.name }}
          </span>
        </div>
        <div class="header-info-item">
          <span>试卷难度：</span>
          <span>{{ paper.difficulty }}</span>
        </div>
      </div>
      <div class="header-btns">
        <el-button
          type="primary"
          plain
          icon="icon icon-share"
          @click="releasePaper(paper.id)"
          >释放</el-button
        >
        <el-button type="danger" plain icon="icon icon-back" @click="back"
          >返回</el-button
        >
      </div>
    </div>

    <div class="view-body">
      <div class="view-title">
        <h1 class="paper-title">{{ paper.course.name }}&nbsp;试卷</h1>
        <p v-if="paper.hasAudio" class="paper-title-sub">（含音频试卷）</p>
        <p class="paper-title-sub">（课程代码&nbsp;{{ paper.course.code }}）</p>
      </div>
      <div class="view-summary">
        <el-table :data="paper.paperDetails" border>
          <el-table-column prop="name" label="大题名称"> </el-table-column>
          <el-table-column prop="score" label="大题总分"> </el-table-column>
          <el-table-column prop="unitCount" label="小题数量"> </el-table-column>
          <el-table-column prop="pubCount" label="公开数量"> </el-table-column>
          <el-table-column prop="noPubCount" label="非公开数量">
          </el-table-column>
        </el-table>
      </div>
      <div class="view-seperator"></div>
      <!-- 考试说明 -->
      <div class="view-part">
        <div class="paper-question-title">考试说明</div>
        <div class="paper-question-body">
          <rich-text :text-json="paper.examRemark"></rich-text>
          <div>本试卷满分{{ paper.totalScore }}分。</div>
        </div>
      </div>
      <!-- 循环大题 -->
      <div
        v-for="(paperDetail, detailIndex) in paper.paperDetails"
        v-show="paperDetailShow(paperDetail)"
        :key="detailIndex"
        class="view-part"
        @mouseover="quesMouseOver(paperDetail.id)"
        @mouseout="quesMouseOut(paperDetail.id)"
      >
        <div class="paper-question-title">
          <span>{{ paperDetail.cnNum }}</span> <span>.</span>
          <span>{{ paperDetail.name }}</span>
          <span>
            ({{ !paperDetail.title ? "本大题" : paperDetail.title + "，" }}共{{
              paperDetail.unitCount
            }}小题，满分{{ paperDetail.score }}分)
          </span>
        </div>
        <rich-text
          class="paper-question-body"
          :text-json="paperDetail.description"
        ></rich-text>
        <div :id="paperDetail.id" class="view-part-action">
          <el-button
            v-show="showButtons[detailIndex].up"
            size="small"
            icon="el-icon-arrow-up"
            @click.stop="hideContent(detailIndex)"
          ></el-button>

          <el-button
            v-show="!showButtons[detailIndex].up"
            size="small"
            icon="el-icon-arrow-down"
            @click.stop="showContent(detailIndex)"
          ></el-button>
        </div>

        <!-- 循环小题 -->
        <div
          v-show="showQuestions[detailIndex].is_show"
          class="view-paper-questions"
        >
          <div
            v-for="(paperDetailUnit, unitIndex) in paperDetail.paperDetailUnits"
            v-show="quesShow(paperDetailUnit.id)"
            :key="unitIndex"
            class="view-quesiton"
            @mouseover="quesMouseOver(paperDetailUnit.id)"
            @mouseout="quesMouseOut(paperDetailUnit.id)"
          >
            <div class="paper-question-title">
              <span>{{ paperDetailUnit.number }}.</span>
              <rich-text
                :text-json="paperDetailUnit.question.quesBody"
              ></rich-text>
              <span> （{{ paperDetailUnit.score }}分） </span>
            </div>
            <div class="paper-question-body">
              <div
                v-for="(quesOption, optionIndex) in paperDetailUnit.question
                  .quesOptions"
                :key="optionIndex"
                class="paper-question-option"
              >
                <span>{{ optionIndex | optionOrderWordFilter }}. </span>
                <rich-text :text-json="quesOption.optionBody"></rich-text>
              </div>
            </div>
            <div :id="paperDetailUnit.id" class="view-part-action">
              <el-button
                size="small"
                type="primary"
                plain
                @click="editQues(paperDetailUnit, paperDetailUnit.question)"
                >查看
              </el-button>
            </div>
            <!-- 子题循环 -->
            <div class="view-question-subs">
              <div
                v-for="(subQuestion, subIndex) in paperDetailUnit.question
                  .subQuestions"
                v-show="quesShow(subQuestion.id)"
                :key="subIndex"
                class="view-part"
                @mouseover="
                  quesMouseOver(getSubQuesEditId(paperDetailUnit, subQuestion))
                "
                @mouseout="
                  quesMouseOut(getSubQuesEditId(paperDetailUnit, subQuestion))
                "
              >
                <div class="paper-question-title">
                  <span>{{ subQuestion.subNumber }}. </span>
                  <rich-text :text-json="subQuestion.quesBody"></rich-text>
                  <span
                    >（{{ paperDetailUnit.subScoreList[subIndex] }}分）</span
                  >
                </div>
                <div
                  v-if="paperDetailUnit.questionType != 'MATCHING_QUESTION'"
                  class="paper-question-body"
                >
                  <div
                    v-for="(
                      subQuesOption, subOptIndex
                    ) in subQuestion.quesOptions"
                    :key="subOptIndex"
                    class="paper-question-option"
                  >
                    <span>{{ subOptIndex | optionOrderWordFilter }}. </span>
                    <rich-text
                      :text-json="subQuesOption.optionBody"
                    ></rich-text>
                  </div>
                </div>
                <div
                  :id="getSubQuesEditId(paperDetailUnit, subQuestion)"
                  class="view-part-action"
                >
                  <el-button
                    size="small"
                    type="primary"
                    plain
                    @click="editQues(paperDetailUnit, subQuestion)"
                    >查看
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 试题查看 -->
    <el-dialog
      v-loading.body="dialogLoading"
      title="试题查看"
      :visible.sync="quesDialog"
      :modal="false"
      append-to-body
      custom-class="side-dialog"
      @close="closeQuesDialog"
    >
      <el-form :model="quesModel" label-position="right" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="题型">
              <el-select
                v-model="quesModel.questionType"
                :disabled="true"
                placeholder="请输入题型"
              >
                <el-option
                  v-for="item in questionTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分值">
              <el-input
                v-model="quesModel.score"
                :disabled="true"
                placeholder="分值"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="难度">
              <el-select
                v-model="quesModel.difficulty"
                placeholder="请输入难度"
                :disabled="true"
              >
                <el-option
                  v-for="item in difficultyList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公开度">
              <el-select
                v-model="quesModel.publicity"
                placeholder="请输入公开度"
                :disabled="true"
              >
                <el-option
                  v-for="item in publicityList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            v-if="quesModel.questionType == 'TEXT_ANSWER_QUESTION'"
            :span="12"
          >
            <el-form-item label="作答类型">
              <el-select v-model="quesModel.answerType" :disabled="true">
                <el-option
                  v-for="item in answerTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            v-if="quesModel.questionType && !isNested(quesModel.questionType)"
            :span="12"
          >
            <el-form-item label="时长">
              <el-input
                v-model="quesModel.control.maxAnswerTime"
                size="small"
                class="select_width"
                :disabled="true"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col
            v-if="quesModel.questionType == 'MATCHING_QUESTION'"
            :span="12"
          >
            <el-form-item label="配对类型">
              <el-select
                v-model="quesModel.quesParam.matchingType"
                :disabled="true"
              >
                <el-option
                  v-for="item in matchingTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            v-if="quesModel.questionType == 'MATCHING_QUESTION'"
            :span="12"
          >
            <el-form-item label="答题模式">
              <el-select
                v-model="quesModel.quesParam.matchingMode"
                :disabled="true"
              >
                <el-option
                  v-for="item in matchingModes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="属性列表">
          <el-tooltip
            v-for="(content, propIndex) in quesModel.quesProperties"
            :key="propIndex"
            placement="top"
          >
            <div slot="content">
              <span v-if="content.firstProperty != null"
                >一级属性：{{ content.firstProperty.name }}</span
              ><br />
              <span v-if="content.secondProperty != null"
                >二级属性：{{ content.secondProperty.name }}</span
              >
            </div>
            <span>
              <el-tag
                :key="propIndex"
                style="margin-right: 5px"
                :closable="false"
                type="primary"
                effect="dark"
              >
                {{ content.courseProperty.name }}
              </el-tag>
            </span>
          </el-tooltip>
        </el-form-item>

        <el-form-item label="题目">
          <rich-text
            class="paper-question-title"
            style="font-weight: 400; padding-top: 7px"
            :text-json="quesModel.quesBody"
          ></rich-text>
        </el-form-item>
        <el-form-item
          v-if="
            !quesModel.parentType || quesModel.parentType != 'MATCHING_QUESTION'
          "
        >
          <div
            v-for="(quesOption, optIndex) in quesModel.quesOptions"
            :key="optIndex"
            class="paper-question-option"
          >
            <span>{{ optIndex | optionOrderWordFilter }}. </span>
            <rich-text :text-json="quesOption.optionBody"></rich-text>
          </div>
        </el-form-item>
        <el-form-item v-if="!isNested(quesModel.questionType)" label="答案">
          <question-answer
            class="paper-question-body"
            style="padding-top: 6px"
            :data="quesModel"
          ></question-answer>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" plain @click="closeQuesDialog">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { QUESTION_API } from "@/constants/constants";
import { isEmptyStr, QUESTION_TYPES } from "../constants/constants";
import { mapState } from "vuex";

export default {
  name: "EditPaperApp",
  components: {},
  data() {
    return {
      hValue: "100px",
      wValue: "500px",
      display: "block",
      uploadAction: "",
      fileList: [],
      answerFileList: [],
      paperId: "",
      paperDetailId: "",
      editPaperDetailUnit: "",
      quesDialog: false,
      paperDatailDialog: false,
      paperRemarkDialog: false,
      parentView: "",
      paper: {
        course: {
          code: "",
          name: "",
        },
        examRemark: "",
      },
      loading: false,
      dialogLoading: false,
      detailLoading: false,
      uploadAudioLoading: false,
      uploadAnswerLoading: false,
      questionTypes: QUESTION_TYPES,
      questionType: "",
      quesModel: { quesProperties: [] },
      editpaperDetail: {},
      reduplicateQuestions: [],
      reduplicateGroup: [],
      reduplicateQuesColor: [],
      singleRightAnswer: "", //接收单选答案
      multipleRightAnswer: [], //接收多选答案
      options: ["正确", "错误"],
      duplicateLoading: false,
      dialogRadioFile: false,
      dialogAnswerFile: false,
      isUpload: true,
      isUploadAnswer: true,
      message: "",
      answerMessage: "",
      checkResult: false,
      checkResultAnswer: false,
      fileNameList: [],
      defaultColor: [
        "Red",
        "Blue",
        "LimeGreen",
        "GoldenRod",
        "Black",
        "BlueViolet",
        "Chocolate",
        "DarkCyan",
        "HotPink",
        "Orange",
        "IndianRed",
        "Indigo",
        "Green",
        "Aqua",
        "CadetBlue",
        "SkyBlue",
        "SlateBlue",
        "SlateGray",
        "Tomato",
        "VioletRed",
      ],
      difficultyList: [
        { label: "难", value: "难" },
        { label: "中", value: "中" },
        { label: "易", value: "易" },
      ],
      publicityList: [
        { label: "公开", value: true },
        { label: "非公开", value: false },
      ],
      answerTypes: [
        { label: "文本", value: "DIVERSIFIED_TEXT" },
        { label: "音频", value: "SINGLE_AUDIO" },
      ],
      matchingTypes: [
        { label: "填词", value: 1 },
        { label: "段落", value: 2 },
      ],
      matchingModes: [
        { label: "单用", value: 1 },
        { label: "复用", value: 2 },
      ],
      coursePropertyList: [],
      coursePropertyName: "", //课程属性名
      firstPropertyList: [], //一级属性集合
      firstPropertyId: "", //一级属性id
      secondPropertyList: [], //二级属性集合
      secondPropertyId: "", //二级属性id
      examRemark: "",
      showQuestions: [],
      showButtons: [],
    };
  },
  computed: {
    ...mapState({
      user: (state) => state.user,
    }),
    updatePorperty() {
      return false;
    },
    answer() {
      if (this.quesModel.questionType == "SINGLE_ANSWER_QUESTION") {
        return this.singleRightAnswer;
      } else if (this.quesModel.questionType == "MULTIPLE_ANSWER_QUESTION") {
        var obj = this.multipleRightAnswer;
        return obj.sort().toString();
      }
      return this.quesModel.quesAnswer;
    },
  },
  created() {
    // $("body").attr("style", "");
    document.getElementsByTagName("body")[0].style = "";
    this.paperId = this.$route.params.id;
    this.parentView = this.$route.params.parentView;
    this.initPaper();
    this.uploadAction = QUESTION_API + "/uploadRadio/" + this.paperId;
    this.uploadHeaders = {
      key: this.user.key,
      token: this.user.token,
    };
  },
  methods: {
    isNested(questionType) {
      if (
        questionType == "NESTED_ANSWER_QUESTION" ||
        questionType == "LISTENING_QUESTION" ||
        questionType == "MATCHING_QUESTION"
      ) {
        return true;
      } else {
        return false;
      }
    },
    releasePaper(paperid) {
      this.$confirm("确认释放试卷吗?", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;
        this.$http.put(QUESTION_API + "/paper_storage/release/" + paperid).then(
          () => {
            this.loading = false;
            this.$notify({
              message: "操作成功",
              type: "success",
            });
            this.back();
          },
          (response) => {
            this.loading = false;
            this.$notify({
              message: response.response.data.desc,
              type: "error",
            });
          }
        );
      });
    },

    //隐藏大题下的所有小题
    hideContent(index) {
      console.log("up");
      this.showQuestions[index].is_show = false;
      this.showButtons[index].up = false;
    },
    //展开大题下所有小题
    showContent(index) {
      console.log("down");
      this.showQuestions[index].is_show = true;
      this.showButtons[index].up = true;
    },
    quesMouseOver(index) {
      document.getElementById(index).style.visibility = "visible";
    },
    quesMouseOut(index) {
      document.getElementById(index).style.visibility = "hidden";
    },
    //初始化试卷
    initPaper() {
      const scrollPosition =
        document.documentElement.scrollTop || document.body.scrollTop;
      this.loading = true;
      this.paper = {
        course: {
          code: "",
          name: "",
        },
      };
      this.$http
        .get(QUESTION_API + "/paper/" + this.paperId)
        .then((response) => {
          this.paper = response.data;
          //将所有小题分为公开和非公开
          if (this.paper.paperDetails && this.paper.paperDetails.length > 0) {
            for (let paperDetil of this.paper.paperDetails) {
              this.showQuestions.push({ is_show: true });
              this.showButtons.push({ up: true });
              paperDetil.pubCount = 0;
              paperDetil.noPubCount = 0;
              if (
                paperDetil.paperDetailUnits &&
                paperDetil.paperDetailUnits.length > 0
              ) {
                for (let paperDetilUt of paperDetil.paperDetailUnits) {
                  if (!this.isNested(paperDetilUt.question.questionType)) {
                    //非套题
                    if (paperDetilUt.question.publicity) {
                      paperDetil.pubCount = paperDetil.pubCount + 1;
                    } else {
                      paperDetil.noPubCount = paperDetil.noPubCount + 1;
                    }
                  } else {
                    //循环所有子题
                    for (let ques of paperDetilUt.question.subQuestions) {
                      if (ques.publicity) {
                        paperDetil.pubCount = paperDetil.pubCount + 1;
                      } else {
                        paperDetil.noPubCount = paperDetil.noPubCount + 1;
                      }
                    }
                  }
                }
              }
            }
          }
          setTimeout(() => {
            document.documentElement.scrollTop = document.body.scrollTop =
              scrollPosition;
            console.log(scrollPosition);
          }, 1000);
          this.loading = false;
        });
    },
    quesShow(id) {
      if (this.reduplicateGroup.length < 1) {
        return true;
      }
      for (var i = 0, imax = this.reduplicateGroup.length; i < imax; i++) {
        if (id == this.reduplicateGroup[i]) {
          return true;
        }
      }
      return false;
    },
    //编辑题目
    editQues(paperDetailUnit, question) {
      console.log("question:", question);
      this.coursePropertyName = "";
      this.firstPropertyId = "";
      this.secondPropertyId = "";
      this.editPaperDetailUnit = paperDetailUnit;
      this.quesModel = JSON.parse(JSON.stringify(question)); //深拷贝
      this.quesModel.score = paperDetailUnit.score;
      //如果是套题下面的小题编辑 ( paperDetailUnit的类型是套题，question的类型不是套题)
      if (
        (paperDetailUnit.questionType == "NESTED_ANSWER_QUESTION" &&
          question.questionType != "NESTED_ANSWER_QUESTION") ||
        (paperDetailUnit.questionType == "LISTENING_QUESTION" &&
          question.questionType != "LISTENING_QUESTION") ||
        (paperDetailUnit.questionType == "MATCHING_QUESTION" &&
          question.questionType != "MATCHING_QUESTION")
      ) {
        for (var i = 0; i < paperDetailUnit.question.subQuestions.length; i++) {
          if (
            paperDetailUnit.question.subQuestions[i].id == this.quesModel.id
          ) {
            this.quesModel.score = paperDetailUnit.subScoreList[i];
            this.quesModel.parentType = paperDetailUnit.questionType;
            this.quesModel.optionsSelected = paperDetailUnit.optionsSelected;
            this.quesModel.parentQuesParam = paperDetailUnit.question.quesParam;
            break;
          }
        }
      }

      if (isEmptyStr(this.quesModel.answerType)) {
        this.quesModel.answerType = "DIVERSIFIED_TEXT";
      }

      this.assignAnswers(); //给singleRightAnswer或multipleRightAnswer赋值
      this.openQuesDialog();
    },
    //给singleRightAnswer和multipleRightAnswer赋值
    assignAnswers() {
      if (this.quesModel.quesOptions && this.quesModel.quesOptions.length > 0) {
        this.singleRightAnswer = "";
        this.multipleRightAnswer = [];
        for (let i = 0; i < this.quesModel.quesOptions.length; i++) {
          let option = this.quesModel.quesOptions[i];
          if (
            this.quesModel.questionType == "SINGLE_ANSWER_QUESTION" &&
            option.isCorrect == 1
          ) {
            this.singleRightAnswer = String.fromCharCode(65 + i);
          }
          if (
            this.quesModel.questionType == "MULTIPLE_ANSWER_QUESTION" &&
            option.isCorrect == 1
          ) {
            this.multipleRightAnswer.push(String.fromCharCode(65 + i));
          }
        }
      }
    },
    //打开修改试题编辑框
    openQuesDialog() {
      this.quesDialog = true;
    },
    //关闭试题编辑框
    closeQuesDialog() {
      this.quesDialog = false;
      this.quesModel = {};
    },
    //新增属性
    //在正确的option上设置isCorrect=1
    setRightAnswer() {
      if (
        !this.quesModel.quesOptions ||
        this.quesModel.quesOptions.length == 0
      ) {
        return false;
      }
      for (var i = 0; i < this.quesModel.quesOptions.length; i++) {
        var option = this.quesModel.quesOptions[i];
        var answerOrderNum = String.fromCharCode(65 + i);
        if (this.quesModel.questionType == "SINGLE_ANSWER_QUESTION") {
          option["isCorrect"] =
            answerOrderNum == this.singleRightAnswer ? 1 : 0;
        }
        if (this.quesModel.questionType == "MULTIPLE_ANSWER_QUESTION") {
          option["isCorrect"] =
            this.multipleRightAnswer.indexOf(answerOrderNum) > -1 ? 1 : 0;
        }
      }
    },
    getSubQuesEditId(paperDetailUnit, subQuestion) {
      return paperDetailUnit.question.id + "_" + subQuestion.subNumber;
    },
    //返回
    back() {
      if (sessionStorage.getItem("question_back") == "true") {
        this.$router.push({
          path: "/questions/paper_storage/0",
        });
      } else {
        this.$router.push({
          path: "/questions/paper_storage/1",
        });
      }
    },
    paperDetailShow(paperDetail) {
      if (this.reduplicateGroup.length == 0) {
        return true;
      }
      let paperDetailUnits = paperDetail.paperDetailUnits;
      for (let i = 0, imax = paperDetailUnits.length; i < imax; i++) {
        for (var j = 0, jmax = this.reduplicateGroup.length; j < jmax; j++) {
          if (paperDetailUnits[i].id == this.reduplicateGroup[j]) {
            return true;
          }
        }
      }
      return false;
    },
  },
};
</script>
