<!-- 备题 -->
<template>
  <div ref="content" class="content-box">
    <back-box>
      <template slot="title">
        <span>导入课件</span>
      </template>
    </back-box>
    <div class="content">

      <el-dialog :close-on-click-modal="false" title="选择班级分享" :visible.sync="classSharingType" width="800"
        :modal-append-to-body="false" :append-to-body="true">
        <div>
          <el-row class="row-subfix">
            <div class="row-line">
              <span class="line-subfix">年级：</span>
              <span class="line-value">{{ gradeName }}</span>
            </div>
          </el-row>
          <el-row class="row-subfix" style="margin-top: 20px;">
            <span class="line-subfix" style="float: left;">班级：</span>
            <div class="row-line" 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 :indeterminate="isIndeterminate" v-model="checkAll"
                  @change="handleCheckAllChange">全选</el-checkbox>
                <el-checkbox-group v-model="checkedClass" style="margin-top: 15px;" @change="handleCheckedClassChange">
                  <el-checkbox v-for="(item, index) in shareClass" :label="item.id" :key="item.id">{{
        item.className }}</el-checkbox>
                </el-checkbox-group>
              </span>
            </div>
          </el-row>
        </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-steps :active="step" finish-status="success" simple style="margin: 20px 0">
        <el-step title="基础信息" icon="el-icon-edit"></el-step>
        <el-step title="题目编辑" icon="el-icon-tickets"></el-step>
        <el-step title="课件预览" icon="el-icon-edit-outline"></el-step>
      </el-steps>
      <div v-show="step == 0">
        <el-form ref="forms" :model="form" :rules="formRules" label-width="140px">
          <el-form-item label="课件名称：" prop="title">
            <el-input class="sel2" type="text" placeholder="请输入答题卡名称" v-model.trim="form.title" maxlength="50" size="45"
              show-word-limit>
            </el-input>
          </el-form-item>
          <el-form-item v-if="role != 'ROLE_PERSONAL'" label="年级：" prop="gradeName">
            <el-select class="sel" v-model="form.gradeName" placeholder="" @change="changeGrade">
              <el-option v-for="item in gradeList" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="科目：" prop="subjectName">
            <el-select class="sel" v-model="form.subjectName" placeholder="">
              <el-option v-for="item in subjectList" :key="item.value" :label="item.label" :value="item.value">{{
        item.label
      }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="role != 'ROLE_PERSONAL'" label="分享范围：" prop="sharingType">
            <el-radio-group v-model="form.sharingType">
              <el-radio :label="0">任课班级分享</el-radio>
              <el-radio class="name-radio" @click.native="_selectClassSharingType" v-model="form.sharingType"
                :label="1">自定义分享班级</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="btn-box">
          <el-button type="danger" plain round @click="linkBack">取消</el-button>
          <el-button type="primary" round @click="setStep1">下一步</el-button>
        </div>
      </div>
      <div v-show="step == 1">
        <div class="answer-title">
          <p class="name">{{ form.title }}</p>
        </div>
        <div class="question-box">
          <ul class="questions-ul">
            <li class="sub-questions">
              <div class="qs-num">题号</div>
              <div class="qs-type">题型</div>
              <div class="qs-score">分数</div>
              <div class="qs-partScore">漏选得分</div>
              <div class="qs-options qs-options2">选项设置</div>
              <div class="qs-upload">题干</div>
              <div class="qs-upload">题目解析</div>
              <div class="qs-upload"  >知识点</div>
              <div class="qs-set">操作</div>
            </li>
          </ul>
          <template v-for="(question, index) in form.questionList">
            <ul class="questions-ul">
              <template v-if="!question.subQuestions">
                <li>
                  <p class="set-ans-btn" v-if="question.qusType && question.subNum && question.subNum > 4
        ">
                    <el-button type="primary" @click="setFormAns(index)">批量设置答案</el-button>
                  </p>
                  <div v-else class="sub-questions">
                    <div class="qs-num">{{ question.questionIndex }}</div>
                    <div class="qs-type">
                      <el-select v-model="question.questionType" placeholder="选择题目类型"
                        @change="changeSubQuestions($event, question)">
                        <el-option v-for="options in questionOptions" :key="options.value" :label="options.label"
                          :value="options.value"></el-option>
                      </el-select>
                    </div>
                    <div class="qs-score">
                      <el-input-number class="number-ipt" size="medium" :min="1" :max="200" :precision="2"
                        v-model="question.score" label="单题分值"></el-input-number>
                    </div>
                    <div class="qs-partScore">
                      <p v-if="question.questionType != 3">--</p>
                      <el-input-number class="number-ipt" v-else size="medium" :min="0" :precision="2"
                        :max="question.score" :step="0.5" v-model="question.partScore" label="漏选得分"></el-input-number>
                    </div>
                    <div class="qs-options qs-options2">
                      <p v-if="question.questionType == 5">--</p>
                      <p v-if="question.questionType == 4" class="answer-box">
                        <span class="answer-s" :class="question.correctAnswer == 1 ? 'active' : ''"
                          @click="question.correctAnswer = 1">✓</span>
                        <span class="answer-s" :class="question.correctAnswer == 2 ? 'active' : ''"
                          @click="question.correctAnswer = 2">✗</span>
                      </p>
                      <p v-if="question.questionType == 3" class="answer-box">
                        <span class="answer-s" v-for="option in question.answerOptions?.split(',')" :class="question.correctAnswer?.includes(option)
        ? 'active'
        : ''
        " :key="option" @click="changAnswer(question, option)">{{ option }}</span>
                      </p>
                      <p v-if="question.questionType == 2" class="answer-box">
                        <span class="answer-s" v-for="option in question.answerOptions?.split(',')" :class="question.correctAnswer == option ? 'active' : ''
        " :key="option" @click="question.correctAnswer = option">{{ option }}</span>
                      </p>
                      <p v-if="question.questionType == 3 ||
        question.questionType == 2
        " class="answer-box answer-box2">
                        <el-button size="mini" type="primary" icon="el-icon-plus" circle
                          @click="addOptions(question)"></el-button>
                        <el-button size="mini" type="primary" icon="el-icon-minus" round circle
                          @click="removeOptions(question)"></el-button>
                      </p>
                    </div>

                    <div class="qs-upload">
                      <el-button class="icon-tickets" type="primary" circle size="mini" icon="el-icon-tickets"
                        @click="openStem(question, 1, index)"></el-button>
                    </div>
                    <div class="qs-upload">
                      <el-button class="icon-tickets" type="primary" circle size="mini" icon="el-icon-tickets"
                        @click="openStem(question, 2, index)"></el-button>
                    </div>
                    <div class="qs-upload"  >
                      <el-button type="primary" circle size="mini" icon="el-icon-price-tag"
                        @click="openKnowledge(question, index)"></el-button>
                    </div>
                    <div class="qs-set">
                      <el-popconfirm title="确定删除这道题吗？" @confirm="delTabData(index)">
                        <el-button slot="reference" class="delete" type="danger" size="mini" circle
                          icon="el-icon-delete"></el-button>
                      </el-popconfirm>
                    </div>
                  </div>
                </li>
              </template>
              <template v-else>
                <li v-for="(subQuestions, indexs) in question.subQuestions" :key="indexs">
                  <p class="set-ans-btn" v-if="subQuestions.qusType &&
        subQuestions.subNum &&
        subQuestions.subNum > 4
        ">
                    <el-button type="primary" @click="setFormAns(index, indexs)">批量设置答案</el-button>
                  </p>
                  <div v-else class="sub-questions">
                    <div class="qs-num">
                      {{ setNum(index, indexs, subQuestions) }}
                    </div>
                    <div class="qs-type">
                      <el-select v-model="subQuestions.questionType" placeholder="选择题目类型"
                        @change="changeSubQuestions($event, subQuestions)">
                        <el-option v-for="options in questionOptions" :key="options.value" :label="options.label"
                          :value="options.value"></el-option>
                      </el-select>
                    </div>
                    <div class="qs-score">
                      <el-input-number class="number-ipt" size="medium" :min="1" :max="200" :precision="2"
                        v-model="subQuestions.score" label="单题分值"></el-input-number>
                    </div>
                    <div class="qs-partScore">
                      <p v-if="subQuestions.questionType != 3">--</p>
                      <el-input-number class="number-ipt" v-else size="medium" :min="0" :precision="2"
                        :max="subQuestions.score" :step="0.5" v-model="subQuestions.partScore"
                        label="漏选得分"></el-input-number>
                    </div>
                    <div class="qs-options qs-options2">
                      <p v-if="subQuestions.questionType == 5">--</p>
                      <p v-if="subQuestions.questionType == 4" class="answer-box">
                        <span class="answer-s" :class="subQuestions.correctAnswer == 1 ? 'active' : ''
        " @click="subQuestions.correctAnswer = 1">✓</span>
                        <span class="answer-s" :class="subQuestions.correctAnswer == 2 ? 'active' : ''
        " @click="subQuestions.correctAnswer = 2">✗</span>
                      </p>
                      <p v-if="subQuestions.questionType == 3" class="answer-box">
                        <span class="answer-s" v-for="option in subQuestions.answerOptions?.split(
        ','
      )" :class="subQuestions.correctAnswer?.includes(option)
        ? 'active'
        : ''
        " :key="option" @click="changAnswer(subQuestions, option)">{{ option }}</span>
                      </p>
                      <p v-if="subQuestions.questionType == 2" class="answer-box">
                        <span class="answer-s" v-for="option in subQuestions.answerOptions?.split(
        ','
      )" :class="subQuestions.correctAnswer == option ? 'active' : ''
        " :key="option" @click="subQuestions.correctAnswer = option">{{ option }}</span>
                      </p>
                      <p v-if="subQuestions.questionType == 3 ||
        subQuestions.questionType == 2
        " class="answer-box answer-box2">
                        <el-button size="mini" type="primary" icon="el-icon-plus" circle
                          @click="addOptions(subQuestions)"></el-button>
                        <el-button size="mini" type="primary" icon="el-icon-minus" round circle
                          @click="removeOptions(subQuestions)"></el-button>
                      </p>
                    </div>

                    <div class="qs-upload">
                      <el-button class="icon-tickets" type="primary" circle size="mini" icon="el-icon-tickets"
                        @click="openStem(subQuestions, 1, index, indexs)"></el-button>
                    </div>
                    <div class="qs-upload">
                      <el-button class="icon-tickets" type="primary" circle size="mini" icon="el-icon-tickets"
                        @click="openStem(subQuestions, 2, index, indexs)"></el-button>
                    </div>
                    <div class="qs-upload"  >
                      <el-button type="primary" circle size="mini" icon="el-icon-price-tag"
                        @click="openKnowledge(subQuestions, index, indexs)"></el-button>
                    </div>
                    <div class="qs-set">
                      <el-popconfirm title="确定删除这道题吗？" @confirm="delTabData(index, indexs)">
                        <el-button slot="reference" class="delete" type="danger" size="mini" circle
                          icon="el-icon-delete"></el-button>
                      </el-popconfirm>
                    </div>
                  </div>
                </li>
              </template>
            </ul>
          </template>
        </div>
        <el-dialog :close-on-click-modal="false" title="批量设置答案" :visible.sync="diaSetAns" width="400"
          :modal-append-to-body="false">
          <div class="qs-options">
            <p class="dia-tips">
              请点击选项按钮设置答案,多选题题目之间用“,”隔开，若添加5道题：“AC,AD,BD,AC,CD”
            </p>
            <p>{{ setSubPro(formAns.qusType) }}：</p>
            <p class="ipt">
              <el-input v-if="formAns.qusType == 2 || formAns.qusType == 3" ref="formAnsIpt"
                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 active" @click="
        formAns.answerList.length < formAns.subNum
          ? (formAns.answerList += '✓')
          : ''
        ">✓</span>
                <span class="answer-s active" @click="
        formAns.answerList.length < formAns.subNum
          ? (formAns.answerList += '✗')
          : ''
        ">✗</span>
              </template>
              <template v-if="formAns.qusType == 3">
                <span class="answer-s active" v-for="option in formAns.answerOptions.split(',')" :key="option"
                  @click="setMultiple(formAns, option, 2)">{{ option }}</span>
                <span class="answer-s active" @click="setMultiple(formAns, ',', 2)">,</span>
              </template>
              <template v-if="formAns.qusType == 2">
                <span class="answer-s 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>
        <div class="btn-box">
          <el-button type="danger" plain round @click="linkBack">取消</el-button>
          <el-button round @click="step = 0">上一步</el-button>
          <el-button type="primary" round @click="toStep(2)">下一步</el-button>
        </div>
        <el-dialog :close-on-click-modal="false" :modal-append-to-body="false"
          :title="stem.type == 1 ? '上传题干' : '上传题目解析'" :visible.sync="dialogStem" v-if="dialogStem" width="800px">
          <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="stem.type == 2">
                <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 :close-on-click-modal="false" :modal-append-to-body="false" title="知识点"
          :visible.sync="dialogKnowledge" width="60%"  >
          <div>
            <knowledgePoints :sectionName="stem.sectionName" :subjectName="stem.subjectName" :knowledges="stem.knowledge" @points="_points" /> 
          </div>
          <div slot="footer">
            <el-button @click="dialogKnowledge = false">取 消</el-button>
            <el-button type="primary" @click="setKnowledge">确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <div v-if="step == 2">
        <div class="answer-title">
          <p class="name">{{ form.title }}</p>
        </div>
        <div class="question-box">
          <template v-for="question in form.questionList">
            <template v-if="!question.subQuestions">
              <div class="screenshot-box" v-if="question.screenshot">
                <iframe class="screenshot" :src="question.screenshot"></iframe>
              </div>
            </template>
            <template v-else>
              <div v-for="subQuestions in question.subQuestions">
                <div class="screenshot-box" v-if="subQuestions.screenshot">
                  <iframe class="screenshot" :src="subQuestions.screenshot"></iframe>
                </div>
              </div>
            </template>
          </template>
        </div>
        <div class="btn-box">
          <el-button type="danger" plain round @click="linkBack">取消</el-button>
          <el-button round @click="toStep(1)">上一步</el-button>
          <el-button type="primary" round @click="save">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { deepClone, checkAnswer } from "utils";
import knowledgeList from "assets/js/knowledgeList.js";
import knowledgePoints from "@/components/knowledgePoints"
export default {
  components: {
    knowledgePoints
  },
  data() {
    return {
      shareClass: [],
      role: "",
      checkedClass: [],
      classSharingType: false,
      gradeName: "",
      isIndeterminate: false,
      checkAll: false,
      step: 0, //步骤
      gradeClassList: [], //年级-班级数据
      gradeList: [], //年级
      subjectList: [], //科目
      form: {
        //答题卡详情
        title: "",
        gradeName: "",
        subjectName: "",
        sharingType: 0,
        questionList: [],
      },
      formRules: {
        //答题卡验证
        title: [
          { required: true, message: "请输入答题卡名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ],
        gradeName: [{ required: true, message: "请选择年级", trigger: "blur" }],
        subjectName: [
          { required: true, message: "请选择科目", trigger: "blur" },
        ],
      },
      diaSetAns: false, //答案开关
      dialogKnowledge: false, //知识点
      dialogStem: false, //截图开关
      formAns: {
        listIndex: 0, //大题位置
        endIndex: 0, //相同题目最后一位题目的questionIndex
        index: 0, //相同题目最后一位题目的位置
        qusType: "", //题目类型
        subNum: 0, //数量
        answerOptions: [], //答案选项
        answerList: "", //答案列表-字符串
      },
      stem: {
        type: 1,
        index: 0, //大题位置
        indexs: 0, //小题位置
        screenshot: "", //题干图片地址
        answerScreenshot: "", //题目解析图片地址
        knowledge: [], //知识点
        subjectName: "",
        sectionName: "",
      },
      type: 1, //1-创建，2-复制答题卡
      questionOptions: [
        { label: "单选题", value: 2 },
        { label: "多选题", value: 3 },
        { label: "判断题", value: 4 },
        { label: "主观题", value: 5 },
      ],
      rightOptions: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],
      knowledgeList: { ...knowledgeList },
      //返回列表页参数记录
      listType: 1,
      listShare: 0,
      uploadUrl: "/file/uploadImgToHtml",
      iframeLoading: false,
      subjectName: "",
    };
  },
  // computed: {
  //   // 知识点列表 根据学段-科目筛选
  //   knowledgeData: function () {
  //     let jsons = [];
  //     if (this.form.gradeName && this.form.subjectName) {
  //       let sectionName = "";
  //       this.gradeClassList.map((item) => {
  //         if (this.form.gradeName == item.gradeName) {
  //           sectionName = item.sectionName;
  //         }
  //       });
  //       if (
  //         sectionName &&
  //         Object.keys(this.knowledgeList).includes(sectionName)
  //       ) {
  //         if (
  //           Object.keys(this.knowledgeList[sectionName]).includes(
  //             this.form.subjectName
  //           )
  //         ) {
  //           jsons = this.knowledgeList[sectionName][this.form.subjectName];
  //         }
  //       }
  //     }
  //     return jsons;
  //   },
  // },
  watch: {
    step: function () {
      this.$nextTick(function () {
        this.$refs.content.scrollTop = 0;
      });
    },
  },
  async created() {
    this.listType = this.$route.query.listType ? this.$route.query.listType : 1;
    this.listShare = this.$route.query.listShare
      ? this.$route.query.listShare
      : 0;
    this.subjectName = this.$route.query.subjectName || "";
    this.type = this.$route.query.type ? this.$route.query.type : 1;
    this.role =
      this.$store.getters.info.showRole ||
      this.$store.getters.info.permissions[0].role;
    if (this.type != 2) {
      let params =
        (this.$route.query.params && JSON.parse(this.$route.query.params)) ||
        null;
      this.form.title = params?.name;
      this.form.id = params?.id;
      this.form.sharingType = params?.sharingType || 0;
      this.formatData(params);
    }
    if (this.role != "ROLE_PERSONAL") {
      this.formRules.gradeName = [
        { required: true, message: "请选择年级", trigger: "blur" },
      ];
      await this._GradeList();
    }
    await this._QuerySubjectList(this.gradeList[0]);
    if (this.type == 2) {
      this._QueryDetail();
    }
  },
  methods: {
    _points(point) {

    },
    _checkedClass() {
      this.classSharingType = false;
    },
    handleCheckAllChange(val) {
      this.checkedClass = val ? this.shareClass?.map(item => item.id) : [];
      this.isIndeterminate = false;
    },
    handleCheckedClassChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.checkedClass.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.checkedClass.length;
    },
    async _selectClassSharingType() {
      this.classSharingType = true;
      var findGrade = this.gradeClassList.find(item => item.gradeName == this.form.gradeName);
      this.gradeName = findGrade.gradeName;
      var classResponse = await this.$request.tClassGrade(findGrade.grade, this.form.subjectName);
      if (classResponse.status != 0) {
        this.$message.error(classResponse.info);
      }
      this.shareClass = classResponse.data;
    },
    // 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 = "";
      } else {
        if (!obj.answerScreenshot || obj.answerScreenshot == "") {
          this.iframeLoading = false;
        }
        this.stem.answerScreenshot = obj.answerScreenshot || "";
        this.stem.screenshot = "";
      }

      this.dialogStem = true;
    },

    // 图片上传成功
    upSuccess(res) {
      if (res && res.status == 0) {
        if (this.stem.type == 1) {
          this.stem.screenshot = res.data.url;
          if (this.form.questionList[0]?.subQuestions) {
            this.form.questionList[this.stem.index].subQuestions[
              this.stem.indexs
            ].screenshot = this.stem.screenshot;
          } else {
            this.form.questionList[this.stem.index].screenshot =
              this.stem.screenshot;
          }
        } else {
          this.stem.answerScreenshot = res.data.url;
          if (this.form.questionList[0]?.subQuestions) {
            this.form.questionList[this.stem.index].subQuestions[
              this.stem.indexs
            ].answerScreenshot = this.stem.answerScreenshot;
          } else {
            this.form.questionList[this.stem.index].answerScreenshot =
              this.stem.answerScreenshot;
          }
        }
        this.$message.success("上传成功");
      } else {
        this.$message.error(res.info);
      }
    },

    upError(res) {
      this.$message.error("上传失败");
    },
    // 知识点
    openKnowledge(obj, index, indexs) {
      this.stem.index = index;
      this.stem.indexs = indexs;
      this.stem.knowledge = (obj.knowledge && obj.knowledge.split("#")) || [];
      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.stem.sectionName = 
      this.dialogKnowledge = true;
    },
    // 知识点
    setKnowledge() {
      this.form.questionList[this.stem.index].subQuestions[
        this.stem.indexs
      ].knowledge = this.stem.knowledge.join("#");
      this.dialogKnowledge = false;
    },

    //end
    linkBack() {
      this.$confirm(
        (this.type == 2 ? "修改复制的" : "导入的") + "课件未保存，确认退出吗？",
        "提示",
        {
          confirmButtonText: "取消",
          cancelButtonText: "确定",
          confirmButtonClass: "el-button--danger1",
          cancelButtonClass: "el-button--primary",
          showClose: false,
          roundButton: true,
          center: true,
          type: "warning",
        }
      )
        .then(() => { })
        .catch(() => {
          if (location.href.indexOf('askPreparationQuestionsAdd') >= 1) {
            this.$router.push({
              path: "/askPreparationQuestions"
            });
          }
          else if (location.href.indexOf('testPaperAdd') >= 1) {
            this.$router.push({
              path: "/testPaper"
            });
          }
          else {
            this.$router.push({
              path: "/examinationPaper",
              query: {
                type: this.listType,
                share: this.listShare,
              },
            });
          }
        });
    },
    //转换题型显示方式
    setSubPro(type) {
      let tit;
      switch (type) {
        case 2:
          tit = "单选题";
          break;
        case 3:
          tit = "多选题";
          break;
        case 4:
          tit = "判断题";
          break;
        case 5:
          tit = "主观题";
          break;
      }
      return tit;
    },
    //计算题号
    setNum(index, indexs, sub) {
      let lengths = 0; //所在大题之前的所有小题数量
      let subIndex = 0; //所在大题的位置
      for (let i = 0; i < index; i++) {
        let subArr = this.form.questionList[i].subQuestions.filter((item) => {
          return !!item.questionType;
        });
        lengths += subArr.length;
      }
      for (let i = 0; i < indexs; i++) {
        if (!!this.form.questionList[index].subQuestions[i].questionType) {
          subIndex += 1;
        }
      }
      return lengths + subIndex + 1;
    },
    //整理问题
    formateQuestion() {
      this.formatQuestionList();
      if (this.form.questionList[0]?.subQuestions) {
        this.form.questionList?.map((item) => {
          let types = [{}];
          let addIndex = 0;
          item.subQuestions?.map((sub, index) => {
            if (!!sub.questionType) {
              if (
                sub.questionType == types[addIndex].qusType &&
                sub.questionType != 5
              ) {
                //同类型批量答案+1
                types[addIndex].subNum += 1;
                if (
                  types[addIndex].answerOptions.length < sub.answerOptions.length
                ) {
                  types[addIndex].answerOptions = sub.answerOptions;
                }

                // types[addIndex].answerList += this.setAnswer(
                //   sub.questionType,
                //   sub.correctAnswer
                // );
                types[addIndex].answerList = "";
                if (index == item.subQuestions.length - 1) {
                  //循环最后类型数量大于等于5，保存批量答案
                  if (types[addIndex].subNum && types[addIndex].subNum >= 5) {
                    types[addIndex].endIndex = sub.questionIndex;
                    types[addIndex].index = index;
                  }
                }
              } else {
                if (types[addIndex].subNum && types[addIndex].subNum >= 5) {
                  //不同类型时如果原有类型数量大于等于5，保存批量答案
                  types[addIndex].endIndex =
                    item.subQuestions[index - 1].questionIndex;
                  types[addIndex].index = index - 1;
                  addIndex += 1;
                  types[addIndex] = {};
                }
                //不同类型初始化批量答案
                types[addIndex].qusType = sub.questionType;
                types[addIndex].subNum = 1;
                types[addIndex].answerOptions = sub.answerOptions;
                types[addIndex].answerList = "";
              }
            }
          });
          for (let i = 0; i < types.length; i++) {
            if (types[i].subNum >= 5) {
              item.subQuestions?.splice(
                types[i].index + i + 1,
                0,
                deepClone(types[i])
              );
            }
          }
        });
      } else {
        let types = [{}];
        let addIndex = 0;
        let questionList = [...this.form.questionList];
        this.form.questionList = questionList.map((sub, index) => {
          if (!!sub.questionType) {
            if (
              sub.questionType == types[addIndex].qusType &&
              sub.questionType != 5
            ) {
              //同类型批量答案+1
              types[addIndex].subNum += 1;
              if (
                types[addIndex].answerOptions.length < sub.answerOptions.length
              ) {
                types[addIndex].answerOptions = sub.answerOptions;
              }
              // types[addIndex].answerList += this.setAnswer(
              //   sub.questionType,
              //   sub.correctAnswer
              // );
              types[addIndex].answerList = "";
              if (index == questionList.length - 1) {
                //循环最后类型数量大于等于5，保存批量答案
                if (types[addIndex].subNum && types[addIndex].subNum >= 5) {
                  types[addIndex].endIndex = sub.questionIndex;
                  types[addIndex].index = index;
                }
              }
            } else {
              if (types[addIndex].subNum && types[addIndex].subNum >= 5) {
                //不同类型时如果原有类型数量大于等于5，保存批量答案
                types[addIndex].endIndex = questionList[index - 1].questionIndex;
                types[addIndex].index = index - 1;
                addIndex += 1;
                types[addIndex] = {};
              }
              //不同类型初始化批量答案
              types[addIndex].qusType = sub.questionType;
              types[addIndex].subNum = 1;
              types[addIndex].answerOptions = sub.answerOptions;
              types[addIndex].answerList = "";
            }
          }
          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.form.questionList.splice(
              types[i].index + i + 1,
              0,
              deepClone(types[i])
            );
          }
        }
      }
    },
    //初始化要修改的答案
    setFormAns(index, indexs) {
      let answerList = "";
      if (this.form.questionList[0]?.subQuestions) {
        this.formAns = {
          ...this.form.questionList[index].subQuestions[indexs],
        };
        this.formAns.listIndex = index;
        let startIndex = indexs - this.formAns.subNum; //批量设置大难开始位置
        this.form.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.form.questionList[index] };
        let startIndex = index - this.formAns.subNum; //批量设置开始位置
        this.formAns.answerList = [];
        this.formAns.listIndex = index;
        this.form.questionList.map((item, subIdx) => {
          if (subIdx >= startIndex && subIdx < index) {
            answerList += this.setAnswer(item.questionType, item.correctAnswer);
            if (item.qusType == 3) {
              answerList = answerList.slice(0, -1);
            }
          }
        });
      }

      this.formAns.answerList = answerList;
      this.diaSetAns = true;
    },
    insertTxtAndSetcursor(element, answerList, str) {
      let startPos = element.selectionStart; // 获取光标开始的位置
      if (startPos === undefined) {
        // 如果没有光标位置 不操作
        return answerList;
      } else {
        return {
          text:
            answerList.substring(0, startPos) +
            str +
            answerList.substring(startPos), // 将文本插入
          startPos: startPos + str.length,
        };
      }
    },
    //添加选项
    addOptions(subQuestions) {
      let length = subQuestions.answerOptions?.split(",").length || 0;
      if (length > 9) return;
      subQuestions.selectNum = length + 1;
      subQuestions.answerOptions = this.rightOptions
        .slice(0, subQuestions.selectNum)
        .join(",");
    },
    //删除选项
    removeOptions(subQuestions) {
      let length = subQuestions.answerOptions?.split(",").length || 0;
      if (length < 3) return;
      subQuestions.selectNum = length - 1;
      subQuestions.answerOptions = this.rightOptions
        .slice(0, subQuestions.selectNum)
        .join(",");
      subQuestions.correctAnswer = subQuestions.correctAnswer.slice(
        0,
        subQuestions.selectNum
      );
    },
    //多选答案设置
    setMultiple(obj, answer, type) {
      let elements =
        type == 1
          ? this.$refs["formAnsIpt2"].$el.children[0]
          : this.$refs["formAnsIpt"].$el.children[0];
      let resault = this.insertTxtAndSetcursor(
        elements,
        obj.answerList || "",
        answer
      );
      obj.answerList = resault.text;
      let str = obj.answerList;
      let str2;
      if (!!obj.answerOptions) {
        str2 = checkAnswer(
          str,
          3,
          obj.answerOptions.split(",").length,
          obj.subNum
        );
      } else {
        str2 = checkAnswer(str, 3, obj.selectNum, obj.number);
      }
      obj.answerList = str2;
      elements.focus();
      elements.selectionStart = resault.startPos;
    },
    //批量修改答案
    saveFormAns() {
      let EndIndex;
      let subNum = this.formAns.subNum - 1;
      this.form.questionList[this.formAns.listIndex].subQuestions.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
                : "";
        }
        this.form.questionList[this.formAns.listIndex].subQuestions[
          EndIndex - i
        ].correctAnswer = correctAnswer;
      }
      this.diaSetAns = false;
    },
    keydownAnswer(event, type) {
      let answerA = "ABCDEFGHIJ";
      let answer_a = "abcdefghij";

      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;
    },
    toStep(step) {
      this.formatQuestionList();
      this.step = step;
      if (step == 1) {
        this.formateQuestion();
      }
    },
    setStep1() {
      if (this.subjectList.length == 0) {
        this.$message.warning("暂无绑定年级信息，请先联系管理员设置。");
        return;
      }
      this.$refs["forms"].validate((valid) => {
        // 验证通过：保存
        if (valid) {
          this.formateQuestion();
          this.step = 1;
        } else {
          this.$message.error("数据有误，请检查！");
          return false;
        }
      });
    },

    //删除批量操作数据
    formatQuestionList() {
      for (let i = 0; i < this.form.questionList.length; i++) {
        if (this.form.questionList[0]?.subQuestions) {
          for (
            let j = 0;
            j < this.form.questionList[i].subQuestions?.length;
            j++
          ) {
            if (this.form.questionList[i].subQuestions[j]?.qusType) {
              this.form.questionList[i].subQuestions?.splice(j, 1);
            }
          }
        } else {
          if (this.form.questionList[i].qusType) {
            this.form.questionList.splice(i, 1);
            i--;
          }
        }
      }
    },
    //删除题
    delTabData(index, subIndex) {
      if (this.form.questionList[0].subQuestions) {
        this.form.questionList[index].subQuestions.splice(subIndex, 1);
      } else {
        this.form.questionList[index].splice(subIndex, 1);
      }
      this.formateQuestion();
    },
    //切换题型
    changeSubQuestions(val, subQuestions) {
      const that = this;
      subQuestions.score = 1;
      subQuestions.partScore = 0;
      subQuestions.correctAnswer = "";
      subQuestions.selectNum = 4;
      switch (val) {
        case 2:
          subQuestions.answerOptions = that.rightOptions
            .slice(0, subQuestions.selectNum)
            .join(",");
          break;
        case 3:
          subQuestions.answerOptions = that.rightOptions
            .slice(0, subQuestions.selectNum)
            .join(",");
          break;
        case 4:
          subQuestions.selectNum = 0;
          subQuestions.answerOptions = "1,2";
          break;
        case 5:
          subQuestions.selectNum = 0;
          break;
      }
      this.formateQuestion();
    },
    //设置多选答案
    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("");
      }
    },

    async save() {
      if (this.saveLoading) return;
      this.saveLoading = true;
      this.formatQuestionList();
      let formDatas = deepClone(this.form);

      formDatas.classIds = this.checkedClass.join(",");

      formDatas.questionList = formDatas.questionList.filter(item => {
        return item.subQuestions?.length >= 1;
      });

      let addPaper =
        this.role == "ROLE_PERSONAL"
          ? this.$request.pAddPaper
          : this.$request.addPaper;
      const { data, status, info } = await addPaper({
        type: 1,
        ...formDatas,
      });
      this.saveLoading = false;
      if (status == 0) {
        if (location.href.indexOf('askPreparationQuestionsAdd') >= 1) {
          this.$router.push({
            path: "/askPreparationQuestions"
          });
        }
        else if (location.href.indexOf('testPaperAdd') >= 1) {
          this.$router.push({
            path: "/testPaper"
          });
        }
        else {
          if (location.href.indexOf('askPreparationQuestionsAdd') >= 1) {
            this.$router.push({
              path: "/askPreparationQuestions"
            });
          }
          else if (location.href.indexOf('testPaperAdd') >= 1) {
            this.$router.push({
              path: "/testPaper"
            });
          }
          else {
            this.$router.push({
              path: "/examinationPaper",
              query: {
                type: this.listType,
                share: this.listShare,
              },
            });
          }
        }
      } else {
        this.$message.error(info);
      }
    },
    async changeGrade() {
      //切换年级查询科目
      this._QuerySubjectList(this.form.gradeName);
    },

    async _GradeList() {
      //查询年级列表
      // const { data, status, info } = await this.$request.fetchGradeList();
      // 查找班级

      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?.map((item) => {
          if (!this.gradeList.includes(item.gradeName)) {
            this.gradeList.push(item.gradeName);
          }
          return item;
        });
        // this.gradeList = (data.gradeNames && [...data.gradeNames]) || [];
        if (this.type != 2) {
          this.form.gradeName = this.gradeList[0];
        }
      } else {
        this.$message.error(info);
      }
    },
    async _QuerySubjectList(grade) {
      //查询科目列表
      if (!grade) {
        return;
      }
      let query = {};
      let fetchSubjectList =
        this.role == "ROLE_PERSONAL"
          ? this.$request.pSubjectList
          : this.$request.fetchSubjectList;
      if (this.role != "ROLE_PERSONAL") {
        query.gradeName = grade;
      }
      const { data, status, info } = await fetchSubjectList({ ...query });
      if (status === 0) {
        let subjectArr = [];
        this.subjectList =
          data.subjectNames?.map((item) => {
            let subName =
              this.role == "ROLE_PERSONAL" ? item.subjectName : item;
            subjectArr.push(subName);
            return {
              value: subName,
              label: subName,
            };
          }) || [];
        if (this.subjectList.length) {
          if (subjectArr.includes(this.$route.query.subjectName)) {
            this.form.subjectName = this.$route.query.subjectName;
          } else {
            this.form.subjectName = this.subjectList[0].value;
          }
        }
      } else {
        this.$message.error(info);
      }
    },
    async _QueryDetail() {
      //查询答题卡详情
      let fetchPaperDetail =
        this.role == "ROLE_PERSONAL"
          ? this.$request.pPaperDetail
          : this.$request.fetchPaperDetail;
      const { data, status, info } = await fetchPaperDetail({
        paperId: this.$route.query.paperId,
      });
      if (status == 0) {
        this.form.title = data.title + "_副本";

        this.form.examsDuration = data.examsDuration;
        if (this.role != "ROLE_PERSONAL") {
          this.form.sharingType = data.sharingType;
        }
        this.form.tagId = "";
        this.formatData(data);
      } else {
        this.$message.error(info);
      }
    },
    formatData(data) {
      if (this.subjectList.length) {
        this.subjectList.map((item) => {
          if (item.label == data.subjectName) {
            this.form.subjectName = item.value;
          }
        });
      } else {
        this.form.subjectName = "";
      }

      if (this.role != "ROLE_PERSONAL") {
        if (this.gradeList.length) {
          this.gradeList.map((item) => {
            if (item == data.gradeName) {
              this.form.gradeName = data.gradeName;
            }
          });
        } else {
          this.form.gradeName = "";
        }
      }
      this.form.questionList = data.questionList?.map((item) => {
        if (item.subQuestions) {
          let subQuestions =
            item.subQuestions?.map((items) => {
              return {
                ...items,
                selectNum: items.answerOptions?.split(",").length,
                answerOptions: items.answerOptions || "A,B,C,D",
                screenshot: items.screenshot || "",
                correctAnswer: items.correctAnswer || "",
                knowledge: items.knowledge || "",
              };
            }) || [];
          return {
            questionTitle: item.questionTitle,
            subQuestions: subQuestions,
            show: false,
          };
        } else {
          item.correctAnswer = item.correctAnswer || "";
          return {
            ...item,
          };
        }
      });
    },
  },
};
</script>
<style>
.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>
.red {
  color: #f30;
}

.qs-options {
  flex: 1;

  .ipt {
    margin-bottom: 5px;
  }

  .answer-box {
    .answer-s {
      cursor: pointer;
      user-select: none;
      margin-bottom: 10px;

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

  .answer-box2 {
    margin-bottom: 10px;
  }

  .delButton {
    text-indent: -9999999px;
    border-color: #ff6868;
    background: #ff6868 url("../../assets/images/arrow.png") no-repeat center;
    background-size: 19px;
    color: transparent;
  }

  .answer-s.ac {
    border: none;
  }

  .ac {
    border-color: #ff6868;
    background: #ff6868;
    color: #fff !important;
  }
}

.sel2 {
  width: 480px;
}

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

.content-box {
  width: 100%;
  height: 100%;
  overflow-y: auto;
}

.content {
  width: 100%;
  box-sizing: border-box;
  padding: 0 24px;

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

  .btn-box {
    text-align: right;
    margin-left: 140px;
  }
}

.dia-content {
  .dia-tit {
    font-size: 20px;
    color: #333;
    font-weight: 700;
    text-align: center;
  }

  .add-type {
    width: 100%;
    margin-bottom: 10px;

    .js-set {
      margin: 2.5px 10px 0 0;
      font-size: 14px;
    }
  }

  .add-btn {
    margin-left: 20px;
  }
}

.el-message-box {
  :deep(.el-button--default) {
    color: #fff;
  }
}

.add-box {
  display: flex;
  justify-content: center;
  align-items: center;

  .add-question {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    font-weight: bolder;
    padding: 2px;
    cursor: pointer;

    .s1 {
      margin-left: 6px;
    }

    :deep(.el-icon-plus) {
      font-size: 24px;
      font-weight: 900;
    }

    :deep(.el-button--mini.is-circle) {
      padding: 3px;
    }
  }
}

.dialog-footer {
  text-align: center;

  :deep(.el-button) {
    border-radius: 20px;
    padding: 8px 20px 7px;
    margin: 0 12px;
  }
}

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

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

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

.question-title {
  line-height: 40px;
  display: flex;
  align-items: center;
  margin-bottom: 12px;

  .m20 {
    margin: 0 20px;
  }

  .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;
  }

  .el-icon-caret-right {
    font-size: 24px;
    color: #888;
    transition: all 0.4s;
    margin-right: 12px;
    cursor: pointer;

    &.active {
      transform: rotate(90deg);
    }
  }
}

.questions-ul {
  border-left: 1px solid #e2e2e2;

  &:first-child {
    border-top: 1px solid #e2e2e2;
  }
}

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

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

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

.answer-box {
  .answer-s {
    display: inline-block;
    width: 30px;
    height: 30px;
    border: 1px solid #e2e2e2;
    border-radius: 3px;
    margin: 0 6px;
    font-size: 16px;
    color: #333;
    text-align: center;
    line-height: 30px;

    &.active {
      background: #5e78fa;
      border-color: #5e78fa;
      color: #fff;
    }
  }
}

.qs-options {
  .answer-s {
    display: inline-block;
    width: 30px;
    height: 30px;
    border: 1px solid #e2e2e2;
    border-radius: 3px;
    margin: 0 6px;
    font-size: 16px;
    color: #333;
    text-align: center;
    line-height: 30px;
    cursor: pointer;

    &.active {
      background: #5e78fa;
      border-color: #5e78fa;
      color: #fff;
    }
  }
}

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

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

  .qs-num {
    width: 70px;
  }

  .qs-type {
    width: 160px;
  }

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

  .qs-options {
    flex: 1;
  }

  .qs-upload {
    width: 60px;
  }

  .qs-set {
    width: 60px;
  }

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

    .answer-s {
      cursor: pointer;
    }
  }

  :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;
    }
  }
}

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

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