<template>
  <el-container class="default-body">
    <el-header>
      <back-box class="detailBack">
        <template slot="title">
          <span class="default-title">
            {{ isViewer && !isWrong ? "详情" : type == 1 ? paperType == 1 ? "修改课件" : "修改试卷" : "修改答案" }}</span>
        </template>
      </back-box>
    </el-header>
    <el-main style="margin-top: 20px !important">
      <div class="content">
        <template v-if="type == 1">
          <p class="tips" v-if="paperModifyLog.modifiedTime">
            <i class="fa fa-bell-o"></i>
            {{
              `${paperModifyLog.modifiedTime} ${paperModifyLog.realName}`
            }}老师修改了答案
          </p>
        </template>
        <div class="answer-title" :class="type == 1 ? 't-left' : ''">
          <p class="name-box">
            <span>试卷名称：</span>
            <el-input :disabled="isViewer && !isWrong" class="ipt-name" v-model="form.title"></el-input>
          </p>
          <p class="name-box">
            <span>分享范围：</span>
            <el-radio :disabled="isViewer && !isWrong" class="name-radio" v-model="form.sharingType"
              :label="0">任课班级分享</el-radio>
            <el-radio :disabled="isViewer && !isWrong" class="name-radio" @click.native="_selectClassSharingType"
              v-model="form.sharingType" :label="1">自定义分享班级</el-radio>
          </p>
        </div>
        <div class="question-box">
          <div class="question-content">
            <div v-if="paperType == 1" class="courseware-title sub-questions">
              <div class="qs-num">题号</div>
              <div class="qs-stem">题干</div>
              <div class="qs-type">题型</div>
              <div class="qs-score">分数</div>
              <div class="qs-partScore">漏选得分</div>
              <div class="qs-options">选项设置</div>
              <div v-if="!isViewer" class="qs-oprations">操作</div>
            </div>
            <div>
              <div class="question-contents" v-for="(question, index) in questionList">
                <div :class="paperType != 1 ? 'bigQuestion' : ''">
                  <div class="bigQuestionTitle" v-if="paperType != 1">
                    {{ question.questionTitle }}
                    (共{{ question.subQuestions.filter(subQuestion => subQuestion &&
                      subQuestion.questionIndex && subQuestion.questionType).length }}小题，
                    共{{ question.score }}分)
                  </div>
                  <div v-if="paperType == 2 && index == 0" class="courseware-title sub-questions">
                    <div class="qs-num">题号</div>
                    <div class="qs-stem">题干</div>
                    <div class="qs-type">题型</div>
                    <div class="qs-score">分数</div>
                    <div class="qs-partScore">漏选得分</div>
                    <div class="qs-options">选项设置</div>
                    <div v-if="!isViewer" class="qs-oprations">操作</div>
                  </div>

                  <div class="courseware-content sub-questions" v-if="subQuestion &&
                    subQuestion.questionIndex && subQuestion.questionType && question.subQuestions"
                    v-for="(subQuestion, subIndex) in question.subQuestions">
                    <div class="qs-num">{{ subQuestion.questionIndex }}</div>
                    <div class="qs-stem">
                      <iframe style="height: 100% !important" class="screenshot" :src="subQuestion.screenshot"></iframe>
                    </div>
                    <div class="qs-type">
                      <el-select :disabled="isViewer" v-model="subQuestion.questionType">
                        <el-option v-for="item in questionOption" :key="item.Key" :label="item.Text"
                          :value="item.Key" />
                      </el-select>
                    </div>
                    <div class="qs-score">
                      <el-input-number :disabled="isViewer && !isWrong" class="number-ipt" size="medium" :min="1"
                        :max="200" :precision="2" :step="1" v-model="subQuestion.score" label="单题分值" />
                    </div>
                    <div class="qs-partScore">
                      <p v-if="subQuestion.questionType != 3">------</p>
                      <el-input-number :disabled="isViewer && !isWrong" class="number-ipt" v-else size="medium" :min="0" :precision="2"
                        :max="subQuestion.score" :step="0.5" v-model="subQuestion.partScore" label="漏选得分" />
                    </div>
                    <div class="qs-options">
                      <p v-if="subQuestion.questionType == 5">--</p>
                      <p v-if="subQuestion.questionType == 4" class="answer-box">
                        <span class="answer-s" v-if="!isViewer"
                          :class="subQuestion.correctAnswer == 1 ? 'answer-active' : ''"
                          @click="subQuestion.correctAnswer = 1">✓</span>
                        <span class="answer-s" v-if="!isViewer"
                          :class="subQuestion.correctAnswer == 2 ? 'answer-active' : ''"
                          @click="subQuestion.correctAnswer = 2">✗</span>
                        <span class="answer-s" v-if="isViewer"
                          :class="subQuestion.correctAnswer == 1 ? 'answer-active' : ''">✓</span>
                        <span class="answer-s" v-if="isViewer"
                          :class="subQuestion.correctAnswer == 2 ? 'answer-active' : ''">✗</span>
                      </p>
                      <p v-if="subQuestion.questionType == 3" class="answer-box">
                        <template :disabled="isViewer" v-for="option in subQuestion.answerOptions.split(',')">
                          <span v-if="option && !isViewer" class="answer-s"
                            :class="subQuestion.correctAnswer.includes(option) ? 'answer-active' : ''" :key="option"
                            @click="changAnswer(subQuestion, option)">{{ option }}</span>
                          <span v-if="option && isViewer" class="answer-s"
                            :class="subQuestion.correctAnswer.includes(option) ? 'answer-active' : ''" :key="option">{{
                              option }}</span>
                        </template>
                        <span class="answer-s answer-opration" v-if="!isViewer"
                          @click="openStem(subQuestion, 4, index, subIndex)">+</span>
                        <span class="answer-s answer-opration" v-if="!isViewer"
                          @click="openStem(subQuestion, 5, index, subIndex)">-</span>
                      </p>
                      <p v-if="subQuestion.questionType == 2" class="answer-box">
                        <template :disabled="isViewer" v-for="option in subQuestion.answerOptions.split(',')">
                          <span class="answer-s" v-if="option && !isViewer"
                            :class="subQuestion.correctAnswer == option ? 'answer-active' : ''" :key="option"
                            @click="subQuestion.correctAnswer = option">{{ option }}</span>
                          <span v-if="option && isViewer" class="answer-s"
                            :class="subQuestion.correctAnswer.includes(option) ? 'answer-active' : ''" :key="option">{{
                              option }}</span>
                        </template>
                        <span class="answer-s answer-opration" v-if="!isViewer"
                          @click="openStem(subQuestion, 4, index, subIndex)">+</span>
                        <span class="answer-s answer-opration" v-if="!isViewer"
                          @click="openStem(subQuestion, 5, index, subIndex)">-</span>
                      </p>
                    </div>
                    <div class="qs-oprations" v-if="!isViewer">
                      <div class="qs-set">
                        <el-button class="icon-tickets" type="text"
                          @click="openStem(subQuestion, 1, index, subIndex)">题干</el-button>
                      </div>
                      <div class="qs-set">
                        <el-button class="icon-tickets" type="text"
                          @click="openStem(subQuestion, 2, index, subIndex)">解析</el-button>
                      </div>
                      <div class="qs-set">
                        <el-button type="text" @click="openKnowledge(subQuestion, index, subIndex)">知识点</el-button>
                      </div>
                      <div class="qs-set">
                        <el-popconfirm @confirm="_deleteDetermineQ(subIndex, index)" title="这是一小题确定删除吗？">
                          <!-- <el-button style="color:red; " type="text" slot="reference">删除</el-button> -->
                        </el-popconfirm>
                      </div>
                    </div>
                  </div>
                  <div v-if="!question.subQuestions" class="courseware-content sub-questions">
                    <div class="qs-num">{{ question.questionIndex }}</div>
                    <div class="qs-stem">
                      <iframe style="height: 100% !important" class="screenshot" :src="question.screenshot"></iframe>
                    </div>
                    <div class="qs-type">
                      <el-select v-model="question.questionType">
                        <el-option :disabled="isViewer" v-for="item in questionOption" :key="item.Key"
                          :label="item.Text" :value="item.Key" />
                      </el-select>
                    </div>
                    <div class="qs-score">
                      <el-input-number :disabled="isViewer && !isWrong" class="number-ipt" size="medium" :min="1"
                        :max="200" :precision="2" :step="1" v-model="question.score" label="单题分值" />
                    </div>
                    <div class="qs-partScore">
                      <p v-if="question.questionType != 3">------</p>
                      <el-input-number :disabled="isViewer && !isWrong" class="number-ipt" v-else size="medium" :min="0" :precision="2"
                        :max="question.score" :step="0.5" v-model="question.partScore" label="漏选得分" />
                    </div>
                    <div class="qs-options">
                      <p v-if="question.questionType == 5">--</p>
                      <p v-if="question.questionType == 4" class="answer-box">
                        <span class="answer-s" :class="question.correctAnswer == 1 ? 'answer-active' : ''
                          " @click="question.correctAnswer = 1">✓</span>
                        <span class="answer-s" :class="question.correctAnswer == 2 ? 'answer-active' : ''
                          " @click="question.correctAnswer = 2">✗</span>
                      </p>
                      <p v-if="question.questionType == 3" class="answer-box">
                        <template v-for="option in question.answerOptions.split(',')">
                          <span v-if="option" class="answer-s" :class="question.correctAnswer.includes(option)
                            ? 'answer-active'
                            : ''
                            " :key="option" @click="changAnswer(question, option)">{{ option }}</span>
                        </template>
                        <span class="answer-s answer-opration" v-if="!isViewer"
                          @click="openStem(question, 4, index, 0)">+</span>
                        <span class="answer-s answer-opration" v-if="!isViewer"
                          @click="openStem(question, 4, index, 0)">-</span>
                      </p>
                      <p v-if="question.questionType == 2" class="answer-box">
                        <template v-for="option in question.answerOptions.split(',')">
                          <span class="answer-s" v-if="option" :class="question.correctAnswer == option
                            ? 'answer-active'
                            : ''
                            " :key="option" @click="question.correctAnswer = option">{{ option }}</span>
                        </template>
                        <span class="answer-s answer-opration" v-if="!isViewer"
                          @click="openStem(question, 4, index, 0)">+</span>
                        <span class="answer-s answer-opration" v-if="!isViewer"
                          @click="openStem(question, 5, index, 0)">-</span>
                      </p>
                    </div>
                    <div class="qs-oprations">
                      <div class="qs-set">
                        <el-button class="icon-tickets" type="text"
                          @click="openStem(question, 1, index, 0)">题干</el-button>
                      </div>
                      <div class="qs-set">
                        <el-button class="icon-tickets" type="text"
                          @click="openStem(question, 2, index, 0)">解析</el-button>
                      </div>
                      <div class="qs-set">
                        <el-button type="text" @click="openKnowledge(question, index, 0)">知识点</el-button>
                      </div>
                      <div class="qs-set">
                        <el-popconfirm @confirm="_deleteDetermineQ(0, index)" title="这是一小题确定删除吗？">
                          <!-- <el-button style="color:red" type="text" slot="reference">删除</el-button> -->
                        </el-popconfirm>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <el-dialog title="选择班级分享" :visible.sync="classSharingType" width="800" :close-on-click-modal="false"
          :append-to-body="true">
          <div :key="classSharingType">
            <div class="row-subfix">
              <div>
                <span class="line-subfix">年级：</span>
                <span class="line-value">{{ gradeName }}</span>
              </div>
            </div>
            <div v-if="gradeClass.length >= 1" class="row-subfix"
              style="margin-top: 20px;margin-bottom: 20px;overflow: auto">
              <span class="line-subfix" style="float: left;">班级：</span>
              <div
                style="float: left;background:rgb(245,247,250);padding:15px 10px;width: calc(100% - 80px);border-radius:5px;">
                <span class="line-value" style="min-height: 300px;border-radius: 4px; background: rgb(247,247,250);">
                  <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                  <div>
                    <el-checkbox @change="handleCheckedClassChange" v-model="item.isChecked" :key="index"
                      v-for="(item, index) in gradeClass" :label="item.id">
                      {{ item.className }}
                    </el-checkbox>
                  </div>
                </span>
              </div>
            </div>
          </div>
          <div slot="footer">
            <el-button type="info" :size="'small'" @click="classSharingType = false">取消</el-button>
            <el-button type="primary" :size="'small'" @click="_checkedClass">确定</el-button>
          </div>
        </el-dialog>
        <el-dialog :close-on-click-modal="false" title="批量设置答案" :visible.sync="diaSetAns" width="400"
          :modal-append-to-body="false" :append-to-body="true">
          <div class="qs-options set-questions">
            <p class="dia-tips">
              请点击选项按钮设置答案,多选题题目之间用“,”隔开，若添加5道题：“AC,AD,BD,AC,CD”
            </p>
            <p>{{ setSubPro(formAns.qusType) }}：</p>
            <p class="ipt">
              <el-input ref="formAnsIpt" v-if="formAns.qusType == 2 || formAns.qusType == 3"
                v-model="formAns.answerList" @keydown.native="keydownAnswer($event, formAns.qusType)"
                @input="setAllAnswer($event, formAns.qusType)"></el-input>
              <el-input v-if="formAns.qusType == 4" v-model="formAns.answerList" readonly=""></el-input>
            </p>
            <p class="answer-box">
              <template v-if="formAns.qusType == 4">
                <span class="answer-s answer-active" @click="
                  formAns.answerList.length < formAns.subNum
                    ? (formAns.answerList += '✓')
                    : ''
                  ">✓</span>
                <span class="answer-s answer-active" @click="
                  formAns.answerList.length < formAns.subNum
                    ? (formAns.answerList += '✗')
                    : ''
                  ">✗</span>
              </template>
              <template v-if="formAns.qusType == 3">
                <span class="answer-s answer-active" v-for="option in formAns.answerOptions.split(',')" :key="option"
                  @click="setMultiple(formAns, option)">{{ option }}</span>
                <span class="answer-s answer-active" @click="setMultiple(formAns, ',')">,</span>
              </template>
              <template v-if="formAns.qusType == 2">
                <span class="answer-s answer-active" v-for="option in formAns.answerOptions.split(',')" :key="option"
                  @click="
                    formAns.answerList.length < formAns.subNum
                      ? (formAns.answerList += option)
                      : ''
                    ">{{ option }}</span>
              </template>
              <span class="answer-s delButton" @click="formAns.answerList = formAns.answerList.slice(0, -1)">x</span>
              <span class="answer-s ac" @click="formAns.answerList = ''">ac</span>
            </p>
          </div>
          <div class="dialog-footer" slot="footer">
            <el-button @click="saveFormAns">确 定</el-button>
            <el-button @click="diaSetAns = false">取 消</el-button>
          </div>
        </el-dialog>
        <el-dialog :close-on-click-modal="false" :title="stem.type == 1 ? '上传题干' : '上传题目解析'" :visible.sync="dialogStem"
          v-if="dialogStem" width="800px" :append-to-body="true">
          <div class="upload-box">
            <div v-loading="iframeLoading">
              <template v-if="stem.type == 1">
                <iframe ref="screenshot" class="screenshot" v-if="stem.screenshot" :src="stem.screenshot"
                  @load="iframeLoading = false"></iframe>
              </template>
              <template v-else>
                <iframe ref="screenshot" class="screenshot" v-if="stem.answerScreenshot" :src="stem.answerScreenshot"
                  @load="iframeLoading = false"></iframe>
              </template>
            </div>
            <el-upload class="upload-demo" :action="uploadUrl" :limit="1" :on-success="upSuccess" :on-error="upError"
              accept="image/*">
              <el-button size="small" type="primary">选择照片</el-button>
            </el-upload>
          </div>
          <div slot="footer">
            <el-button @click="dialogStem = false">确定</el-button>
          </div>
        </el-dialog>
        <el-dialog :append-to-body="true" :close-on-click-modal="false" title="知识点" :visible.sync="dialogKnowledge"
          width="60%">
          <knowledgePoints :key="dialogKnowledge" @opration="knowledgeOpration" :sectionName="stem.sectionName"
            :subjectName="stem.subjectName" :knowledges="stem.knowledge" />
        </el-dialog>
      </div>
      <div class="content-fi">
        <el-button type="info" @click="linkBack">取消</el-button>
        <el-button v-if="!isViewer || isWrong" class="green-el-button" @click="save">保存</el-button>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import { deepClone, checkAnswer } from "utils";
import conf from "@/config/index";
export default {
  data() {
    return {
      role: "",
      title: "",
      classSharingType: false,
      gradeName: "",
      checkAll: false,
      checkedClass: [],
      gradeClass: [],
      subjectName: "",
      isViewer: false,
      isWrong: false,
      isIndeterminate: true,
      type: 1, //1:答题卡 2:即时测报表题目列表 3:课时题目列表
      questionList: [],
      paperType: 1, //1 备题（随堂问） /2 组卷,
      classId: -1,
      //题型选项
      questionOption: [
        { Key: 2, Text: "单选题" },
        { Key: 3, Text: "多选题" },
        { Key: 4, Text: "判断题" },
        { Key: 5, Text: "主观题" },
      ],
      classSharingType: false,
      optionValues: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],
      //答题卡详情
      form: {
        examType: 2, //考试类型：0-未知/1-随堂问/2-即时测/3-xx考
        title: "",
        tag: "",
        subjectId: "",
        examsDuration: 90,
        sharingType: -1,
        sectionName: "",
        gradeName: "",
        share: 1,
        questionList: [],
      },
      paperModifyLog: {
        realName: "",
        modifiedTime: "",
      },
      diaSetAns: false,
      formAns: {
        listIndex: 0, //大题位置
        endIndex: 0, //相同题目最后一位题目的questionIndex
        index: 0,
        qusType: "", //题目类型
        subNum: 0, //数量
        answerOptions: [], //答案选项
        answerList: "", //答案列表-字符串
      },
      //v1.5
      dialogStem: false, //截图开关
      dialogKnowledge: false, //知识点开关
      // knowledgeList: { ...knowledgeList },
      classList: [],
      stem: {
        type: 1,
        index: 0, //大题位置
        indexs: 0, //小题位置
        screenshot: "", //题干图片地址
        answerScreenshot: "", //题目解析图片地址
        knowledge: [], //知识点
      },
      gradeClassList: [], //学段列表
      // uploadUrl: "/file/uploadImgToHtml",
      iframeLoading: false,
      examType: 2,
    };
  },
  computed: {
    allScore: function () {
      let score = 0;
      this.questionList?.map((item) => {
        if (item.subQuestions) {
          score += item.subQuestions.reduce((a, b) => {
            return a + (Number(b.score) || 0);
          }, 0);
        } else {
          score += item.score || 0;
        }
      }, 0);
      return Number(score).toFixed(2);
    },
    uploadUrl: function () {
      var requestUrl = '';

      var ogrinUrl = '/file/uploadImgToHtml';

      var baseUrl = conf.baseURL;

      if (baseUrl == '/' && ogrinUrl.indexOf('/') == 0) {
        requestUrl = ogrinUrl;
      }
      else {
        requestUrl = baseUrl + ogrinUrl
      }

      return requestUrl;
    }
  },
  created() {
    this.role =
      this.$store.getters.info.showRole ||
      this.$store.getters.info.permissions[0].role;
    this.type = this.$route.query.type || 1;
    this.examType = this.$route.query.examType || 2;
    this.paperType = this.$route.query.paperType || 2;
    this.isViewer = this.$route.query.isViewer || false;
    this.classId = this.$route.query.classId || -1;
    this.gradeName = this.$route.query.gradeName || "";
    this.subjectName = this.$route.query.subjectName || "";
    this.form.title = this.$route.query.title || "";
    this._QueryDetail();
    this._GradeList();
  },
  methods: {
    // 知识点
    openKnowledge(obj, index, indexs) {
      this.stem.index = index;
      this.stem.indexs = indexs;
      this.stem.knowledge = obj.knowledge;
      if (this.form.gradeName && this.form.subjectName) {
        var matchClass = this.gradeClassList.find((item) => {
          if (this.form.gradeName == item.gradeName) {
            return item.sectionName;
          }
        });
        this.stem.sectionName = matchClass?.sectionName ?? "";
        this.stem.subjectName = this.form.subjectName ?? "";
      }
      this.dialogKnowledge = true;
    },
    knowledgeOpration(target) {
      if (target.opration == 'confirm') {
        this.form.questionList[this.stem.index].
          subQuestions[this.stem.indexs].knowledge = target.knowledges.join(",");
        this.dialogKnowledge = false;
      }
      else {
        this.dialogKnowledge = false;
      }
    },
    _checkedClass() {
      this.checkedClass = this.gradeClass.filter(item => item.isChecked).map(imap => imap.id);
      this.classSharingType = false;
    },
    handleCheckAllChange(val) {
      this.gradeClass.forEach(item => {
        item.isChecked = val;
      })
      this.isIndeterminate = false;
    },
    handleCheckedClassChange() {
      var value = this.gradeClass.filter(item => item.isChecked);
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.gradeClass.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.gradeClass.length;
    },
    async _selectClassSharingType() {

      if (this.isViewer && !this.isWrong) return;

      this.gradeClass = [];

      this.classSharingType = true;

      var classResponse = await this.$request.tClassFromGrade(this.classId, this.form.subjectName);

      if (classResponse.status != 0) {
        this.$message.error(classResponse.info);
        return;
      }

      this.gradeClass = [...classResponse.data.map(item => {
        return {
          isChecked: this.checkedClass.includes(item.id),
          id: item.id,
          className: item.className
        }
      })];

      this.checkAll = this.checkedClass.length === this.gradeClass.length;
    },
    // v1.5
    //上传截图
    openStem(obj, type, index, indexs) {
      this.iframeLoading = true;
      this.stem.type = type;
      this.stem.index = index;
      this.stem.indexs = indexs;
      if (type == 1) {
        if (!obj.screenshot || obj.screenshot == "") {
          this.iframeLoading = false;
        }
        this.stem.screenshot = obj.screenshot || "";
        this.stem.answerScreenshot = "";
        // return;
      } else if (type == 3) {
      } else if (type == 4) {
        var current = this.questionList[index].subQuestions[indexs];
        var currentOps = current.answerOptions.split(",");
        if (currentOps.length >= this.optionValues.length) return;
        current.answerOptions += "," + this.optionValues[currentOps.length];
        return;
      } else if (type == 5) {
        var current = this.questionList[index].subQuestions[indexs];
        var currentOps = current.answerOptions.split(",");
        if (currentOps.length < 3) return;
        current.answerOptions = currentOps
          .splice(0, currentOps.length - 1)
          .join(",");
        return;
      } else {
        if (!obj.answerScreenshot || obj.answerScreenshot == "") {
          this.iframeLoading = false;
        }
        this.stem.answerScreenshot = obj.answerScreenshot || "";
        this.stem.screenshot = "";
      }
      this.dialogStem = true;
    },
    //图片上传成功
    upSuccess(res, file) {
      if (res && res.status == 0) {
        if (this.stem.type == 1) {
          this.stem.screenshot = res.data.url;
          if (this.questionList[0]?.subQuestions) {
            this.questionList[this.stem.index].subQuestions[
              this.stem.indexs
            ].screenshot = this.stem.screenshot;
          } else {
            this.questionList[this.stem.index].screenshot =
              this.stem.screenshot;
          }
        } else {
          this.stem.answerScreenshot = res.data.url;
          if (this.questionList[0]?.subQuestions) {
            this.questionList[this.stem.index].subQuestions[
              this.stem.indexs
            ].answerScreenshot = this.stem.answerScreenshot;
          } else {
            this.questionList[this.stem.index].answerScreenshot =
              this.stem.answerScreenshot;
          }
        }

        this.$message.success("上传成功");
      } else {
        this.$message.error(res.info);
      }
    },
    async _GradeList() {
      let fetchClassList =
        this.role == "ROLE_PERSONAL"
          ? this.$request.pClassList
          : this.$request.fetchClassList;

      const { data, status, info } = await fetchClassList();
      if (status == 0) {
        this.gradeClassList = data.list;
      } else {
        this.$message.error(info);
      }
    },
    upError(res) {
      this.$message.error("上传失败");
    },

    //end

    linkBack() {
      this.$router.go(-1);
    },
    setSubPro(type) {
      let tit;
      switch (type) {
        case 2:
          tit = "单选题";
          break;
        case 3:
          tit = "多选题";
          break;
        case 4:
          tit = "判断题";
          break;
        case 5:
          tit = "主观题";
          break;
      }
      return tit;
    },
    _deleteDetermineQ(subIndex, index) {
      if (this.questionList[index].subQuestions) {
        this.questionList[index].subQuestions.splice(subIndex, 1);
        if (this.questionList[index].subQuestions?.length == 0) {
          this.questionList.splice(index, 1);
        }
      } else {
        this.questionList.splice(index, 1);
      }
    },
    setBigNum(num) {
      let txt = "";
      let bigNum = [
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        "七",
        "八",
        "九",
        "十",
        "十一",
        "十二",
        "十三",
        "十四",
        "十五",
        "十六",
        "十七",
        "十八",
        "十九",
        "二十",
      ];
      txt = bigNum[num];

      return txt;
    },
    //计算题号
    setNum(index, indexs, sub) {
      let lengths = 0; //所在大题之前的所有小题数量
      let subIndex = 0; //所在大题的位置
      for (let i = 0; i < index; i++) {
        let subArr = this.questionList[i].subQuestions.filter((item) => {
          return !!item.questionType;
        });
        lengths += subArr.length;
      }
      for (let i = 0; i < indexs; i++) {
        if (!!this.questionList[index].subQuestions[i].questionType) {
          subIndex += 1;
        }
      }
      return lengths + subIndex + 1;
    },
    setScore(question) {
      let score = question.subQuestions.reduce((a, b) => {
        return a + (b.score || 0);
      }, 0);
      return Number(score).toFixed(2);
    },
    //设置多选答案
    changAnswer(sub, option) {
      let str = new RegExp(option, "g");
      if (sub.correctAnswer?.includes(option)) {
        sub.correctAnswer = sub.correctAnswer.replace(str, "");
      } else {
        let arrs = (sub.correctAnswer && sub.correctAnswer.split("")) || [];
        arrs.push(option);
        sub.correctAnswer = arrs.sort().join("");
      }
    },
    keydownAnswer(event, type) {
      let answerA = "ABCDEFG";
      let answer_a = "abcdefg";
      answerA = answerA.substring(0, this.formAns.subNum);
      answer_a = answer_a.substring(0, this.formAns.subNum);
      answerA += answer_a;
      answerA = type == 2 ? answerA : answerA + ",";
      if (
        event.key == "Meta" ||
        event.key == "CapsLock" ||
        event.key == "Shift" ||
        event.key == "Enter" ||
        event.key == "Alt" ||
        event.key == "Backspace" ||
        event.key == "Delete" ||
        event.key == "ArrowUp" ||
        event.key == "ArrowDown" ||
        event.key == "ArrowLeft" ||
        event.key == "v" ||
        event.key == "V" ||
        event.key == "ArrowRight"
      )
        return;
      if (!answerA.includes(event.key)) {
        event.returnValue = "";
      }
    },
    setAllAnswer(event, type) {
      let str = this.formAns.answerList;
      let str2 = checkAnswer(
        str,
        type,
        this.formAns.answerOptions.split(",").length,
        this.formAns.subNum
      );
      this.formAns.answerList = str2;
    },
    setAnswer(type, ans) {
      let txt = "";
      if (type == 2) {
        txt = ans;
      } else if (type == 3) {
        txt = ans + ",";
      } else if (type == 4) {
        txt = ans == 1 ? "✓" : ans == 2 ? "✗" : "";
      }
      return txt;
    },
    insertTxtAndSetcursor(answerList, str) {
      let element = this.$refs.formAnsIpt.$el.children[0]; // 获取到指定标签
      let startPos = element.selectionStart; // 获取光标开始的位置
      if (startPos === undefined) {
        // 如果没有光标位置 不操作
        return answerList;
      } else {
        return {
          text:
            answerList.substring(0, startPos) +
            str +
            answerList.substring(startPos), // 将文本插入
          startPos: startPos + str.length,
        };
      }
    },
    //多选答案设置
    setMultiple(obj, answer) {
      let resault = this.insertTxtAndSetcursor(obj.answerList || "", answer);
      obj.answerList = resault.text;
      let str = obj.answerList;
      let str2 = checkAnswer(
        str,
        3,
        obj.answerOptions.split(",").length,
        obj.subNum
      );
      obj.answerList = str2;
      this.$refs.formAnsIpt.$el.children[0].focus();
      this.$refs.formAnsIpt.$el.children[0].selectionStart = resault.startPos;
    },
    //初始化要修改的答案
    setFormAns(indexs, index) {
      let answerList = "";
      if (this.questionList[0]?.subQuestions) {
        this.formAns = { ...this.questionList[index].subQuestions[indexs] };
        this.formAns.listIndex = index;
        let startIndex = indexs - this.formAns.subNum; //批量设置大难开始位置
        this.questionList[index].subQuestions.map((item, subIdx) => {
          if (subIdx >= startIndex && subIdx < indexs) {
            answerList += this.setAnswer(item.questionType, item.correctAnswer);
            if (item.qusType == 3) {
              answerList = answerList.slice(0, -1);
            }
          }
        });
      } else {
        this.formAns = { ...this.questionList[indexs] };
        let startIndex = indexs - this.formAns.subNum; //批量设置开始位置
        this.formAns.answerList = [];
        this.formAns.listIndex = indexs;
        this.questionList.map((item, subIdx) => {
          if (subIdx >= startIndex && subIdx < indexs) {
            answerList += this.setAnswer(item.questionType, item.correctAnswer);
            if (item.qusType == 3) {
              answerList = answerList.slice(0, -1);
            }
          }
        });
      }
      this.formAns.answerList = answerList;
      this.diaSetAns = true;
    },
    saveFormAns() {
      //批量修改答案
      let EndIndex;
      let subNum = this.formAns.subNum - 1;
      if (this.questionList[0]?.subQuestions) {
        this.questionList[this.formAns.listIndex].subQuestions.some(
          (item, index) => {
            if (this.formAns.endIndex == item.questionIndex) {
              EndIndex = index;
            }
            return this.formAns.endIndex == item.questionIndex;
          }
        );
      } else {
        this.questionList.some((item, index) => {
          if (this.formAns.endIndex == item.questionIndex) {
            EndIndex = index;
          }
          return this.formAns.endIndex == item.questionIndex;
        });
      }

      for (let i = 0; i <= subNum; i++) {
        let correctAnswer = "";
        if (this.formAns.qusType == 2) {
          correctAnswer = this.formAns.answerList[subNum - i] || "";
        } else if (this.formAns.qusType == 3) {
          correctAnswer = this.formAns.answerList.split(",")[subNum - i] || "";
        } else if (this.formAns.qusType == 4) {
          correctAnswer =
            this.formAns.answerList[subNum - i] == "✓"
              ? 1
              : this.formAns.answerList[subNum - i] == "✗"
                ? 2
                : "";
        }
        if (this.questionList[0]?.subQuestions) {
          this.questionList[this.formAns.listIndex].subQuestions[
            EndIndex - i
          ].correctAnswer = correctAnswer;
        } else {
          this.questionList[EndIndex - i].correctAnswer = correctAnswer;
        }
      }
      this.diaSetAns = false;
    },
    async save() {

      for (let i = 0; i < this.questionList.length; i++) {
        if (this.questionList[0]?.subQuestions) {
          for (let j = 0; j < this.questionList[i].subQuestions.length; j++) {
            if (this.questionList[i].subQuestions[j].qusType) {
              this.questionList[i].subQuestions.splice(j, 1);
            }
          }
        } else {
          if (this.questionList[i].qusType) {
            this.questionList.splice(i, 1);
            i--;
          }
        }
      }
      let questionList = this.questionList.map((item) => {
        item.score = null;
        // item.questionId = "";
        // item.questionIndex = "";
        return item;
      });
      //更新答题卡
      let modifyPaper, params;
      if (this.type == 1) {
        modifyPaper =
          this.role == "ROLE_PERSONAL"
            ? this.$request.pModifyPaper
            : this.$request.pModifyPaperNew;
        params = {
          classIds: this.checkedClass,
          sharingType: this.form.sharingType,
          paperId: this.$route.query.paperId,
          questionList: questionList,
        };
        console.log(params)
      } else if (this.type == 2) {
        modifyPaper =
          this.role == "ROLE_PERSONAL"
            ? this.$request.pSetExamAnswer
            : this.$request.setExamAnswer;
        params = {
          examId: this.$route.query.paperId,
          questionList: questionList,
        };
      } else {
        modifyPaper =
          this.role == "ROLE_PERSONAL"
            ? this.$request.pSetPeriodAnswer
            : this.$request.setPeriodAnswer;
        params = {
          periodId: this.$route.query.paperId,
          questionList: questionList,
        };
      }
      const { data, status, info } = await modifyPaper({
        title: this.form.title,
        ...params,
      });
      if (status == 0) {
        if (this.paperType == 1) {
          this.$router.push({
            path: "/askPreparationQuestions",
          });
        }
        else {
          this.$router.push({
            path: "/testPaper",
          });
        }
      } else {
        this.$message.error(info);
      }
    },
    async _QueryDetail() {
      //查询详情
      let detail;
      if (this.role == "ROLE_PERSONAL") {
        detail =
          this.type == 1
            ? this.$request.pPaperDetail
            : this.type == 2
              ? this.$request.pExamQuestionList
              : this.$request.pPeriodQuestionList;
      } else {
        detail =
          this.type == 1
            ? this.$request.fetchPaperDetail
            : this.type == 2
              ? this.$request.examQuestionList
              : this.$request.periodQuestionList;
      }
      let params =
        this.type == 1
          ? { paperId: this.$route.query.paperId }
          : this.type == 2
            ? { examId: this.$route.query.paperId }
            : {
              periodId: this.$route.query.paperId,
            };
      const { data, status, info } = await detail(params);
      if (status == 0) {
        let questionList;
        if (this.type == 1) {
          //修改答案信息
          this.paperModifyLog = {
            ...this.paperModifyLog,
            ...this.form.paperModifyLog,
          };
          this.form = deepClone(data);

          questionList = this.form.questionList.map((item) => {
            if (item.subQuestions) {
              item.subQuestions.map((subQuestion) => {
                subQuestion.questionType == 2 || subQuestion.questionType == 3
                  ? (subQuestion.answerOptions =
                    subQuestion.answerOptions || "A,B,C,D")
                  : "";
                subQuestion.correctAnswer = subQuestion.correctAnswer || "";
              });
            } else {
              item.questionType == 2 || item.questionType == 3
                ? (item.answerOptions = item.answerOptions || "A,B,C,D")
                : "";
              item.correctAnswer = item.correctAnswer || "";
            }
            return item;
          });


        } else {
          questionList = data.list.sort((a, b) => {
            return a.questionIndex - b.questionIndex;
          });
        }
        if (data.tag == "错题复习" && this.isViewer == false) {
          this.isViewer = true;
          this.isWrong = true;
        }
        this.questionList = questionList;
        this.formateQuestion();
        this.checkedClass = data.classList?.map(item => item.classId);
      } else {
        this.$message.error(info);
      }
    },
    formateQuestion() {
      let arr = this.questionList;
      if (arr[0]?.subQuestions) {
        this.questionList = arr.map((item) => {
          let types = [{}];
          let addndex = 0;
          item.subQuestions.map((sub, index) => {
            if (!!sub.questionType) {
              if (
                sub.questionType == types[addndex].qusType &&
                sub.questionType != 5
              ) {
                //同类型批量答案+1
                types[addndex].subNum += 1;
                if (
                  types[addndex].answerOptions.length < sub.answerOptions.length
                ) {
                  types[addndex].answerOptions = sub.answerOptions;
                }
                types[addndex].answerList += this.setAnswer(
                  sub.questionType,
                  sub.correctAnswer
                );
                if (index == item.subQuestions.length - 1) {
                  //循环最后类型数量大于等于5，保存批量答案
                  if (types[addndex].subNum && types[addndex].subNum >= 5) {
                    types[addndex].endIndex = sub.questionIndex;
                    types[addndex].index = index;
                  }
                }
              } else {
                if (types[addndex].subNum && types[addndex].subNum >= 5) {
                  //不同类型时如果原有类型数量大于等于5，保存批量答案
                  types[addndex].endIndex =
                    item.subQuestions[index - 1].questionIndex;
                  types[addndex].index = index - 1;
                  addndex += 1;
                  types[addndex] = {};
                }
                //不同类型初始化批量答案
                types[addndex].qusType = sub.questionType;
                types[addndex].subNum = 1;
                types[addndex].answerOptions = sub.answerOptions;
                types[addndex].answerList = this.setAnswer(
                  sub.questionType,
                  sub.correctAnswer
                );
              }
            }
          });
          for (let i = 0; i < types.length; i++) {
            if (types[i].qusType == 3) {
              types[i].answerList = types[i].answerList.slice(0, -1);
            }
            if (types[i].subNum >= 5) {
              item.subQuestions.splice(
                types[i].index + i + 1,
                0,
                deepClone(types[i])
              );
            }
          }
          return item;
        });
      } else {
        let types = [{}];
        let addndex = 0;
        this.questionList = arr.map((sub, index) => {
          if (!!sub.questionType) {
            if (
              sub.questionType == types[addndex].qusType &&
              sub.questionType != 5
            ) {
              //同类型批量答案+1
              types[addndex].subNum += 1;
              //最大选项
              if (
                types[addndex].answerOptions.length < sub.answerOptions.length
              ) {
                types[addndex].answerOptions = sub.answerOptions;
              }
              types[addndex].answerList += this.setAnswer(
                sub.questionType,
                sub.correctAnswer
              );

              if (index == arr.length - 1) {
                //循环最后类型数量大于等于5，保存批量答案
                if (types[addndex].subNum && types[addndex].subNum >= 5) {
                  types[addndex].endIndex = sub.questionIndex;
                  types[addndex].index = index;
                }
              }
            } else {
              if (types[addndex].subNum && types[addndex].subNum >= 5) {
                //不同类型时如果原有类型数量大于等于5，保存批量答案
                types[addndex].endIndex =
                  this.questionList[index - 1].questionIndex;
                types[addndex].index = index - 1;
                addndex += 1;
                types[addndex] = {};
              }
              //不同类型初始化批量答案
              types[addndex].qusType = sub.questionType;
              types[addndex].subNum = 1;
              types[addndex].answerOptions = sub.answerOptions;
              types[addndex].answerList = this.setAnswer(
                sub.questionType,
                sub.correctAnswer
              );
            }
          }
          return sub;
        });
        for (let i = 0; i < types.length; i++) {
          if (types[i].qusType == 3) {
            types[i].answerList = types[i].answerList.slice(0, -1);
          }
          if (types[i].subNum >= 5) {
            this.questionList.splice(
              types[i].index + i + 1,
              0,
              deepClone(types[i])
            );
          }
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.line-value {
  color: black;
}

.question-contents {

  .el-input__inner,
  .el-input,
  .el-select,
  .el-input-number__decrease,
  .el-input-number__increase {
    background: white !important;
  }
}

.screenshot-box {
  width: 600px;
}

.screenshot {
  width: 100%;
  box-shadow: none;
  border: none;
  height: 400px;
}

.screenshot-img {
  display: block;
  width: auto;
  max-width: 100%;
  margin: 0 auto;
  margin-bottom: 10px;
}
</style>
<style lang="scss" scoped>
.content-fi {
  padding-top: 12px;
  width: 200px;
  margin: 0px auto;
}

.content {
  * {
    font-size: 14px;
    font-weight: 400;
  }

  height: calc(100% - 60px);
  overflow-y: auto;
  width: 100%;
  box-sizing: border-box;
  padding: 0px 20px;

  .ml-20 {
    margin-left: 20px;
  }

  .btn-box {
    width: 120px;
    background-color: Red !important;
    // width: calc(100% - 240px);
    // position: fixed;
    // right: 40px;
    // bottom: 20px;
    // padding: 10px 0 5px;
    // background: #fff;
    // text-align: center;
    // margin-left: 140px;
    // z-index: 10;
  }

  .tips {
    height: 48px;
    line-height: 48px;
    padding: 0 16px;
    border: 1px solid #fac7cc;
    background-color: #ffebec;
    font-size: 14px;
    color: #fd9795;
    margin: 10px 0 20px 0;

    .fa-bell-o {
      font-size: 18px;
      margin-right: 5px;
    }
  }
}

.answer-title {
  text-align: center;
  font-size: 20px;
  color: #333;
  font-weight: 700;
  padding-top: 20px;
  padding-bottom: 10px;

  &.t-left {
    text-align: left;
  }

  .totals {
    font-size: 16px;
    color: #666;
    font-weight: normal;
  }

  .name-box {
    display: flex;
    white-space: nowrap;
    align-items: center;
    margin-bottom: 20px;
    font-weight: normal;

    :deep(.el-input__inner) {
      color: #333;
      font-weight: 700;
    }

    .name-radio {
      line-height: 1;
    }
  }
}

.question-title {
  line-height: 40px;

  .ipt {
    width: 300px;
    margin: 0 16px 0 10px;

    :deep(.el-input__inner) {
      border-radius: 20px;
      border-color: #667ffd;
      background: rgba($color: #667ffd, $alpha: 0.05);
    }
  }

  .delete {
    margin-right: 8px;
  }

  .title-txt {
    margin-right: 20px;
    font-size: 16px;
    font-weight: 700;
  }
}

.question-box {
  margin-bottom: 20px;

  .screenshot-box {
    width: 100%;
    border: 1px solid #e2e2e2;
    margin-bottom: 20px;

    .screenshot-img {
      margin: 0;
    }
  }
}

.set-ans-btn {
  width: 100%;
  padding: 10px 0 10px 630px;
  box-sizing: border-box;
  border-bottom: 1px solid #e2e2e2;
  border-right: 1px solid #e2e2e2;
}

.el-input-number {
  width: 140px;
}

.delete {
  margin-left: 8px;
}

.questions-ul {
  border-left: 1px solid #e2e2e2;
  border-top: 1px solid #e2e2e2;
  margin: 12px 0;
}

.questions-ul2 {
  margin: 0;
  border-top: none;

  &:nth-child(1) {
    border-top: 1px solid #e2e2e2;
  }
}

.courseware-content {
  background-color: rgb(245, 247, 250);
  margin-top: 10px;
  height: 80px;
  border-radius: 5px;
  padding: 5px 0px;
}

.sub-questions {
  width: 100%;
  display: flex;
  // border-bottom: 1px solid #e2e2e2;

  &>div {
    .answer-active {
      background: rgba(65, 204, 149, 1);
      color: white;
    }

    min-height: 40px;
    padding: 5px;
    flex-shrink: 0;
    // border-right: 1px solid #e2e2e2;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .qs-num {
    width: 80px;
  }

  .qs-stem {
    width: 400px;
  }

  .qs-type {
    width: 130px;
  }

  .qs-score,
  .qs-partScore {
    width: 160px;

    .el-input-number__decrease,
    .el-input-number__increase {
      background: white !important;
    }
  }

  .qs-set {
    display: inline-block;
    padding: 0px 5px;
  }

  .qs-oprations {
    width: 160px;
  }

  .qs-options {
    flex: 1;
  }

  // .qs-options2 {
  //   text-align: left;
  //   justify-content: flex-start;
  //   // padding-left: 20px;
  // }

  .answer-s {
    cursor: pointer;
    margin-right: 2px;
    margin-bottom: 5px;
    background-color: white;
  }

  .answer-opration {
    background-color: rgb(107, 126, 245);
    color: white;
    font-size: 22px;
    line-height: 1;
    height: 32px;
    width: 32px;
    line-height: 30px;
    border-radius: 32px;
  }

  :deep(.el-select) {
    // .el-input__inner {
    //   border-radius: 20px;
    //   border-color: #667ffd;
    //   width: 150px;
    //   height: 32px;
    //   line-height: 32px;
    //   background: rgba($color: #667ffd, $alpha: 0.05);
    // }

    .el-input__icon {
      line-height: 32px;
    }
  }
}

.set-questions {
  .answer-box {
    .answer-s {
      cursor: pointer;
      user-select: none;

      &:first-of-type {
        margin-left: 0;
      }
    }
  }
}

.upload-box {
  .upload-demo {
    text-align: center;
  }

  .stem-pic {
    display: block;
    margin: 0 auto 20px;
    max-width: 100%;
    max-height: 200px;
    object-fit: cover;
  }
}

.row-subfix {
  margin-bottom: 10px;
}

.bigQuestion {
  padding: 20px;
  box-shadow: 0px 1px 4px 0px rgba(21, 34, 50, 0.08);
  border: 1px solid #ebeef5;
  border-radius: 5px;
  margin-top: 10px;

  .bigQuestionTitle {
    font-size: 16px;
    font-weight: bold;
  }
}
</style>
