<!-- 新建试题 -->
<template>
  <div class="page-container questionBankManagement-addPage">
    <div class="page-container-top-max-big-box">
      <p class="top-1-p">{{newData.id?'编辑试题':'添加试题'}}</p>
      <p class="top-2-p" @click="backPage()">返回</p>
      <p class="top-3-p" v-if="newData.id&&!showType" @click="resetButton()">重置</p>
      <p class="top-4-p" v-if="!showType" @click="submitButton()">保存</p>
    </div>
    <div class="content-box scrollbar-box">
      <el-form class="add-form-box" :model="newData" ref="form" label-width="100px" :rules="rules">
        <div class="top-content-box">
          <div class="flex-content-box">
            <el-form-item label="是否共享" prop="shareStatus">
              <el-switch
                :active-value="1"
                :inactive-value="0"
                v-model="newData.shareStatus"
                active-color="#0183FB"
                inactive-color="#AAAAAA">
              </el-switch>
              <span style="margin-left:15px;line-height:40px;color:#999;">{{newData.shareStatus==1?'共享开启，全校所有学院单位都可见':'不共享，仅本学院单位及上级都可见'}}</span>
            </el-form-item>
            <el-form-item label="试题类型" prop="questionType" label-width="100px">
              <el-select v-model="newData.questionType" @change="answersScreening()" placeholder="试题类型" style="width: 160px">
                <el-option
                  v-for="dict in optionListA"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="难度" prop="difficulty" label-width="70px">
              <el-select v-model="newData.difficulty" placeholder="难度" style="width: 160px">
                <el-option
                  v-for="dict in optionListC"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="知识点" prop="knowledgePointIds" label-width="85px">
              <el-cascader
                style="width: 220px"
                v-model="newData.knowledgePointIds"
                :options="optionListB"
                :props="{
                multiple:true,
                emitPath:false,
                checkStrictly: true,
                value: 'id',
                label: 'knowledgePointName',
                children: 'children',
              }"
                :show-all-levels="false"
                filterable
                placeholder="知识点"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="试题分类" prop="disciplineTypeId" label-width="95px">
              <el-select :disabled="showType" v-model="newData.disciplineTypeId" placeholder="试题分类" style="width:220px;">
                <el-option
                  v-for="item in optionListD"
                  :key="item.id"
                  :label="item.disciplineName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="title-content-box">
          <p></p>
          <p>题干</p>
          <p></p>
        </div>
        <div class="editor-form-box">
          <el-form-item label="" prop="questionContent" label-width="0">
            <tinymce-container
              v-model="newData.questionContent"
              :height="300"
              :max-length="500"
              :upload-url="editorUploadUrl"
              :upload-headers="editorUploadHeaders"
            />
          </el-form-item>
        </div>
        <div class="title-content-box" v-if="newData.questionType == 1 || newData.questionType == 2">
          <p></p>
          <p>选项</p>
          <p></p>
        </div>
        <div class="max-big-for-box" v-if="newData.questionType == 1 || newData.questionType == 2">
          <p class="position-p" @click="addItem()">添加选项</p>
          <div class="for-editor-form-box"
               v-for="(item,index) in newData.options" :index="index"
               @dragstart="onBigDragStart($event, index)"
               @dragover.prevent="onBigDragOver($event, index)"
               @drop="onBigDrop($event, index)"
               @dragend="onDragEnd"
          >
            <p class="index-p">{{getLetter(index)}}</p>
            <div class="min-editor-form-box">
              <el-form-item label="" label-width="0">
                <tinymce-container
                  v-model="item.optionContent"
                  :height="300"
                  :max-length="500"
                  :upload-url="editorUploadUrl"
                  :upload-headers="editorUploadHeaders"
                />
              </el-form-item>
            </div>
            <div class="editor-right-button-box">
              <p class="el-icon-delete-solid" v-if="newData.options[4]" @click="delItem(index)"></p>
              <p class="el-icon-rank" draggable="true"></p>
            </div>
          </div>
        </div>
        <div class="title-content-box" v-if="newData.questionType">
          <p></p>
          <p>答案</p>
          <p></p>
        </div>
        <div class="answers-content-box" v-if="newData.questionType == 1 || newData.questionType == 2">
          <div class="for-answers-box" @click="checkAnswersButton(index)" v-for="(item,index) in newData.data7" :key="index" :class="item.checkItemType?'check-for-answers-box':''">
            <p :class="item.checkItemType?'el-icon-circle-check':''"></p>
            <p>{{getLetter(index)}}</p>
          </div>
        </div>
        <div class="answers-content-box" v-if="newData.questionType == 3">
          <div class="for-answers-box" @click="checkAnswersButton(index)" v-for="(item,index) in newData.data8" :key="index" :class="item.checkItemType?'check-for-answers-box':''">
            <p :class="item.checkItemType?'el-icon-circle-check':''"></p>
            <p>{{item.checkType=='Y'?'对':'错'}}</p>
          </div>
        </div>
        <div class="title-content-box">
          <p></p>
          <p>解析</p>
          <p></p>
        </div>
        <div class="editor-form-box">
          <el-form-item label="" prop="analysis" label-width="0">
            <tinymce-container
              v-model="newData.analysis"
              :height="300"
              :max-length="500"
              :upload-url="editorUploadUrl"
              :upload-headers="editorUploadHeaders"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
  //import { getDicts } from "@/api/commonality/noPermission";
  //import { systemUserSelect } from "@/api/commonality/permission";
  import {
    examElKnowledgePointTreeList,examElQuestionBankDetail,
    examElQuestionBankAdd,examElQuestionBankEdit,examElDisciplineTypeList,
  } from "@/api/safetyEducationExaminationNew/index";
  import TinymceContainer from "@/components/tinymceContainer/index.vue";
  import { getToken } from "@/utils/auth";
  export default {
    name: 'addPage',
    components: { TinymceContainer },
    props: {
      propsData: {}
    },
    data() {
      return {
        optionListA:[{value:1,label:'单选'},{value:2,label:'多选'},{value:3,label:'判断'}],
        optionListB:[],
        optionListC:[{value:1,label:'简单'},{value:2,label:'一般'},{value:3,label:'较难'},{value:4,label:'极难'}],
        optionListD:[],
        newData: {
          questionType:null,
          knowledgePointIds:[],
          disciplineTypeId:null,
          shareStatus:1,
          difficulty:null,
          questionContent:"",
          options:[{optionContent:''},{optionContent:''},{optionContent:''},{optionContent:''}],
          data7:[{checkItemType:false},{checkItemType:false},{checkItemType:false},{checkItemType:false}],
          data8:[{checkType:'Y',checkItemType:false},{checkType:'N',checkItemType:false}],
          analysis:"",
        },
        // 编辑器图片/附件上传接口，按需修改
        editorUploadUrl: this.uploadUrl(),
        editorUploadHeaders: {
          Authorization:getToken(),
        },
        rules:{
          questionType: [
            { required: true, message: "请选择试题类型", trigger: "blur" },
            { required: true, message: "请选择试题类型", validator: this.spaceJudgment, trigger: "blur" }
          ],
          knowledgePointIds: [
            { required: true, message: "请选择知识点", trigger: "blur" },
            { required: true, message: "请选择知识点", validator: this.spaceJudgment, trigger: "blur" }
          ],
          disciplineTypeId: [
            { required: true, message: "请选择试题分类", trigger: "blur" },
            { required: true, message: "请选择试题分类", validator: this.spaceJudgment, trigger: "blur" }
          ],
          difficulty: [
            { required: true, message: "请选择难度", trigger: "blur" },
            { required: true, message: "请选择难度", validator: this.spaceJudgment, trigger: "blur" }
          ],
        },
        //详情查看
        showType:false,
      }
    },
    watch: {
      'newData.knowledgePointIds': {
        handler(newVal, oldVal) {
          // 假设最多只能选 2 个
          if (newVal && newVal.length > 10) {
            this.msgError('最多选择10个知识点')
            // 将值回退到上一次的状态
            this.newData.knowledgePointIds = oldVal;
          }
        },
        deep: true, // 关键：必须开启深度监听
        immediate: false, // 初始化时不触发，防止默认值超限误报
      }
    },
    created() {

    },
    mounted() {
      if(this.propsData.id){
        this.examElQuestionBankDetail();
      }
      this.examElKnowledgePointTreeList();
      this.examElDisciplineTypeList();
    },
    methods: {
      examElQuestionBankDetail(){
        examElQuestionBankDetail({id:this.propsData.id}).then(response => {
          let obj = {
            id:this.propsData.id,
            questionType:response.data.questionType,
            knowledgePointIds:response.data.knowledgePointIds,
            disciplineTypeId:response.data.disciplineTypeId,
            shareStatus:response.data.shareStatus,
            difficulty:response.data.difficulty,
            questionContent:response.data.questionContent,
            analysis:response.data.analysis,
            options:[],
            data7:[],
            data8:[{checkType:'Y',checkItemType:false},{checkType:'N',checkItemType:false}],
          }
          if(response.data.questionType == 1 || response.data.questionType == 2){
            for (let i=0;i<response.data.options.length;i++){
              obj.options.push({optionContent:response.data.options[i].optionContent})
              obj.data7.push({checkItemType:false})
            }
            if(response.data.questionType == 1){
              console.log('this.getNumber(response.data.correctAnswer)',obj.options[this.getNumber(response.data.correctAnswer)])
              obj.data7[this.getNumber(response.data.correctAnswer)].checkItemType = true;
            }else  if (response.data.questionType == 2){
              let answerList = response.data.correctAnswer.split(',');
              for(let i=0;i<answerList.length;i++){
                obj.data7[this.getNumber(answerList[i])].checkItemType = true;
              }
            }
          }else if(response.data.questionType == 3){
            for (let i=0;i<obj.data8.length;i++){
              if(obj.data8[i].checkType == response.data.correctAnswer){
                obj.data8[i].checkItemType = true
              }
            }
          }
          this.$set(this,'newData',obj);
        });
      },
      // 返回按钮
      backPage() {
        this.$parent.tableButton(6)
      },
      resetButton(){
        let self = this;
        this.$confirm('是否确认重置?', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
        }).then(() => {
          self.examElQuestionBankDetail();
        }).catch(() => {});
      },
      // 提交按钮
      submitButton() {
        let self = this;
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(!self.newData.questionContent){
              self.msgError('请输入题干')
              return
            }
            if(this.newData.questionType == 1 ||this.newData.questionType == 2){
              for(let i=0;i<self.newData.options.length;i++){
                if(!self.newData.options[i].optionContent){
                  self.msgError('第'+(i+1)+'个选项没有填写内容.')
                  return
                }
              }
              let num = 0;
              for(let i=0;i<self.newData.data7.length;i++){
                if(self.newData.data7[i].checkItemType){
                  num++
                }
              }
              if(num == 0){
                self.msgError('没有选择答案.')
                return
              }
            }else if(this.newData.questionType == 3){
              let num = 0;
              for(let i=0;i<self.newData.data8.length;i++){
                if(self.newData.data8[i].checkItemType){
                  num++
                }
              }
              if(num == 0){
                self.msgError('没有选择答案.')
                return
              }
            }
            this.$confirm('是否确认保存?', "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(function() {
            }).then(() => {
              self.dataIntegration();
            }).catch(() => {});
          }
        })
      },
      dataIntegration(){
        let self = this;
        let obj ={
          questionContent:this.newData.questionContent,
          questionType:this.newData.questionType,
          knowledgePointIds:this.newData.knowledgePointIds,
          disciplineTypeId:this.newData.disciplineTypeId,
          difficulty:this.newData.difficulty,
          correctAnswer:'',
          analysis:this.newData.analysis,
          shareStatus:this.newData.shareStatus,
          options:[],
        }
        if(obj.questionType == 1 || obj.questionType == 2){
          for(let i=0;i<self.newData.options.length;i++){
            obj.options.push(
              {
                optionTag:self.getLetter(i),
                optionContent:self.newData.options[i].optionContent,
                sortOrder:i,
              }
            )
          }
          let correctAnswer = [];
          for (let i=0;i<self.newData.data7.length;i++){
            if(self.newData.data7[i].checkItemType){
              correctAnswer.push(self.getLetter(i))
            }
          }
          obj.correctAnswer = correctAnswer+'';
        }else if(obj.questionType == 3){
          for (let i=0;i<self.newData.data8.length;i++){
            if(self.newData.data8[i].checkItemType){
              obj.correctAnswer = self.newData.data8[i].checkType;
            }
          }
        }
        if(this.newData.id){
          obj.id = this.newData.id;
          this.examElQuestionBankEdit(obj);
        }else{
          this.examElQuestionBankAdd(obj);
        }
      },
      examElQuestionBankAdd(obj){
        examElQuestionBankAdd(obj).then(response => {
          this.msgSuccess(response.message);
          this.$parent.tableButton(6);
        });
      },
      examElQuestionBankEdit(obj){
        examElQuestionBankEdit(obj).then(response => {
          this.msgSuccess(response.message);
          this.$parent.tableButton(6);
        });
      },
      //添加选项
      addItem(){
        let self = this;
        if(this.newData.options[7]){
          this.msgError('已达到数量上限,最多8个选项.')
          return
        }
        this.$confirm('确认添加新选项?', "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
        }).then(() => {
          self.newData.options.push({optionContent:''});
          self.newData.data7.push({checkItemType:false});
        }).catch(() => {});
      },
      //删除选项
      delItem(index){
        let self = this;
        this.$confirm('确认删除 '+this.getLetter(index)+' 选项?', "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
        }).then(() => {
          self.newData.options.splice(index,1);
          self.newData.data7.splice(index,1);
        }).catch(() => {});
      },
      //答案选中
      checkAnswersButton(index){
        let self = this;
        if(this.newData.questionType == 1){
          if(self.newData.data7[index].checkItemType){
            this.$set(self.newData.data7[index],'checkItemType',false);
          }else{
            for(let i=0;i<self.newData.data7.length;i++){
              self.newData.data7[i].checkItemType = false;
            }
            this.$set(self.newData.data7[index],'checkItemType',true);
          }
        }else if(this.newData.questionType == 2){
          this.$set(self.newData.data7[index],'checkItemType',!self.newData.data7[index].checkItemType);
        }else if(this.newData.questionType == 3){
          if(self.newData.data8[index].checkItemType){
            this.$set(self.newData.data8[index],'checkItemType',false);
          }else{
            for(let i=0;i<self.newData.data8.length;i++){
              self.newData.data8[i].checkItemType = false;
            }
            this.$set(self.newData.data8[index],'checkItemType',true);
          }
        }
      },
      //答案筛选器
      answersScreening(){
        let self = this;
        if(this.newData.questionType == 1){
          let num = 0;
          let index = null;
          for(let i=0;i<self.newData.data7.length;i++){
            if(self.newData.data7[i].checkItemType && num == 0){
              num++
              index = i;
            }
          }
          if (num != 0){
            for(let i=0;i<self.newData.data7.length;i++){
              self.newData.data7[i].checkItemType = false;
            }
            this.$set(self.newData.data7[index],'checkItemType',true);
          }
        }
      },

      // ========== 大项拖拽逻辑 ==========
      onBigDragStart(e, index) {
        this.dragInfo = { type: 'big', bigIndex: index, smallIndex: null };
        //拖拽优化相关
        const rowEl = e.target.closest('.for-editor-form-box');
        if (rowEl) {
          rowEl.classList.add('dragging');
          e.dataTransfer.setDragImage(rowEl, 1373, 95);
        }
        // 给拖拽中的元素加个样式
        // e.target.classList.add('dragging');
      },
      onBigDragOver(e, index) {
        // 只有当拖拽的是大项时才允许放置
        if (this.dragInfo.type === 'big') {
          e.currentTarget.classList.add('drag-over');
        }
      },
      onBigDrop(e, targetIndex) {
        if (this.dragInfo.type !== 'big') return;
        const sourceIndex = this.dragInfo.bigIndex;
        if (sourceIndex === targetIndex) return;

        // 核心：交换数组元素
        const movedItem = this.newData.options.splice(sourceIndex, 1)[0];
        this.newData.options.splice(targetIndex, 0, movedItem);
        const movedItem2 = this.newData.data7.splice(sourceIndex, 1)[0];
        this.newData.data7.splice(targetIndex, 0, movedItem2);
      },
      // 拖拽结束，清理样式
      onDragEnd(e) {
        //拖拽优化相关
        const rowEl = e.target.closest('.for-editor-form-box');
        if (rowEl) {
          rowEl.classList.remove('dragging');
        }
        // e.target.classList.remove('dragging');
        document.querySelectorAll('.drag-over').forEach(el => el.classList.remove('drag-over'));
        this.dragInfo = { type: null, bigIndex: null, smallIndex: null };
      },
      //知识点
      examElKnowledgePointTreeList(){
        examElKnowledgePointTreeList({}).then(response => {
          const list = response.data || [];
          this.formatTreeData(list);
          this.$set(this, 'optionListB', list);
        });
      },
      //查询全部专业类别
      examElDisciplineTypeList() {
        examElDisciplineTypeList({}).then(response => {
          this.$set(this, 'optionListD', response.data)
        })
      },
      /** 将下标转换为字母*/
      getLetter(index) {
        if (typeof index !== 'number' || index < 0 || index >= 26) {
          return '其他';
        }
        return String.fromCharCode(65 + index);
      },
      /** 将字母转下标 */
      getNumber(letter) {
        if (typeof letter !== 'string' || !letter) {
          return -1;
        }
        const code = letter.toUpperCase().charCodeAt(0);
        if (code >= 65 && code <= 90) {
          return code - 65;
        }
        return -1;
      }
    },
  }
</script>

<style scoped lang="scss">
  .questionBankManagement-addPage {
    .content-box {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 20px;
      .top-content-box{
        .flex-content-box{
          display: flex;

        }
      }
      .title-content-box{
        display: flex;
        height:40px;
        overflow: hidden;
        margin:40px 40px;
        p:nth-child(1){
          flex:1;
          height:2px;
          background-color: #999;
          margin-top:19px;
        }
        p:nth-child(2){
          line-height:40px;
          color:#333;
          margin:0 20px;
          font-size:16px;
        }
        p:nth-child(3){
          flex:1;
          height:2px;
          background-color: #999;
          margin-top:19px;
        }
      }
      .max-big-for-box{
        position: relative;
        .position-p{
          position: absolute;
          top:0;
          right:40px;
          width:100px;
          line-height:40px;
          border-radius:4px;
          text-align: center;
          color:#fff;
          background-color: #0183FA;
          cursor: pointer;
        }
        .for-editor-form-box{
          display: flex;
          margin:0 40px;
          .index-p{
            margin:0 10px 0 20px;
            font-size:16px;
            background-color: #0183FA;
            color:#fff;
            width:40px;
            height:40px;
            line-height:40px;
            text-align: center;
            border-radius:4px;
          }
          .min-editor-form-box{
            flex:1;

          }
          .editor-right-button-box{
            width:120px;
            display: flex;
            margin-top:80px;
            p{
              font-size:30px;
              cursor: pointer;
              margin-left:25px;
            }
            .el-icon-delete-solid{
              color:#D81E06;
            }
            .el-icon-rank{
              color:#999;
            }
          }
        }
      }
      .editor-form-box{
        margin:0 40px;
      }
      .answers-content-box{
        display: flex;
        margin:0 60px;
        .for-answers-box{
          display: flex;
          border: 1px solid #999;
          height:40px;
          border-radius:4px;
          margin-right:20px;
          cursor: pointer;
          p:nth-child(1){
            width:16px;
            height:16px;
            border-radius:50%;
            border:1px solid #999;
            margin:11px 0 0 14px;
          }
          p:nth-child(2){
            line-height:38px;
            color:#999;
            text-align: center;
            width:40px;
            font-size:16px;
            margin-right:10px;
          }
        }
        .check-for-answers-box{
          border: 1px solid #0183FA;
          p:nth-child(1){
            margin:10px 0 0 14px;
            border:none;
            background-color: #fff;
            color:#0183FA;
            font-size:18px;
          }
          p:nth-child(2){
            color:#0183FA;
          }
        }
      }
    }
    .drag-handle {
      cursor: move;
      user-select: none; /* 防止拖拽时选中文字 */
    }
    .dragging {
      opacity: 0.5;
      background-color: #f5f7fa;
    }
    .drag-over {
      /*border-top: 2px solid #409EFF !important; !* 放置位置的指示线 *!*/
    }
  }
</style>
