<!-- 新建试卷 -->
<template>
  <div class="page-container testPaperManagement-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" @click="submitButton()" v-if="!showType">保存</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="section-box">
          <!-- 试卷名称 -->
          <el-form-item label="试卷名称" prop="paperName" class="full-width-item">
            <el-input v-model="newData.paperName" maxLength="30" placeholder="请输入名称" :disabled="showType"/>
          </el-form-item>
          <!-- 总分数 / 及格分数 / 答题时间 -->
          <div class="flex-row-box">
            <el-form-item label="总分数" prop="totalScore">
              <div class="input-unit-box">
                <el-input-number
                  :disabled="showType"
                  class="form-input-number"
                  style="width:160px"
                  :min="0"
                  :max="9999"
                  :step="1" :precision="0" step-strictly
                  v-model="newData.totalScore"
                  :controls="false"
                >
                </el-input-number>
                <span class="unit-text">分</span>
              </div>
            </el-form-item>
            <el-form-item label="及格分数" prop="passScore">
              <div class="input-unit-box">
                <el-input-number
                  :disabled="showType"
                  class="form-input-number"
                  style="width:160px"
                  :min="0"
                  :max="9999"
                  :step="1" :precision="0" step-strictly
                  v-model="newData.passScore"
                  :controls="false"
                >
                </el-input-number>
                <span class="unit-text">分</span>
              </div>
            </el-form-item>
            <!--<el-form-item label="答题时间" prop="answerDuration">-->
              <!--<div class="input-unit-box">-->
                <!--<el-input-number-->
                  <!--:disabled="showType"-->
                  <!--class="form-input-number"-->
                  <!--style="width:160px"-->
                  <!--:min="0"-->
                  <!--:max="9999"-->
                  <!--:step="1" :precision="0" step-strictly-->
                  <!--v-model="newData.answerDuration"-->
                  <!--:controls="false"-->
                <!--&gt;-->
                <!--</el-input-number>-->
                <!--<span class="unit-text">分钟</span>-->
              <!--</div>-->
            <!--</el-form-item>-->
          </div>

          <!-- 专业类别 / 是否共享 -->
          <div class="flex-row-box">
            <el-form-item label="专业类别" prop="disciplineTypeId">
              <el-select :disabled="showType" v-model="newData.disciplineTypeId" placeholder="专业类别" style="width:200px;">
                <el-option
                  v-for="item in optionListA"
                  :key="item.id"
                  :label="item.disciplineName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否共享" prop="shareStatus">
              <el-switch
                :disabled="showType"
                v-model="newData.shareStatus"
                :active-value="1"
                :inactive-value="0"
                active-color="#0183FB"
                inactive-color="#AAAAAA"
              />
              <span class="share-tip">{{newData.shareStatus == 1 ? '共享开启，全校所有学院单位都可见' : '不共享，仅本学院单位及上级都可见'}}</span>
            </el-form-item>
          </div>
        </div>

        <!-- 分隔线 -->
        <div class="section-divider"></div>

        <!-- 第二块：组卷方式 & 知识点 -->
        <div class="section-box">
          <!-- 组卷方式 -->
          <el-form-item label="组卷方式" prop="assemblyMode">
            <el-radio-group v-model="newData.assemblyMode" :disabled="showType">
              <el-radio :label="1">固定组卷</el-radio>
              <el-radio :label="2">随机组卷</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 选择知识点 -->
          <el-form-item label="选择知识点" prop="knowledgePointId" class="knowledge-form-item">
            <!-- 统计信息条 -->
            <div class="stat-bar">
              <span>总题目数：<b>{{totalQuestionCount}}</b></span>
              <span style="margin-left:20px;">总分：<b>{{totalScore}}</b></span>
              <span style="margin-left:20px;">
                <span v-if="remainScore > 0">还需设置 <b>{{remainScore}}</b> 分的题目</span>
                <span v-if="remainScore < 0">超过总分数 <b>{{Math.abs(remainScore)}}</b> 分</span>
              </span>
            </div>

            <!-- 已选知识点标签 -->
            <div class="knowledge-tag-box">
              <el-cascader
                :disabled="showType"
                ref="knowledgeCascader"
                v-model="newData.knowledgePointId"
                :options="optionListKnowledge"
                :props="{
                  multiple :true,
                  emitPath: false,
                  checkStrictly: true,
                  value: 'id',
                  label: 'knowledgePointName',
                  children: 'children',
                }"
                :show-all-levels="false"
                filterable
                placeholder="选择知识点"
                style="width:1420px;"
                @change="onKnowledgeSelect"
              />
            </div>

            <!-- 知识点明细表格 -->
            <div class="knowledge-table" v-if="fixedKnowledgePointConfigs.length > 0">
              <div class="table-header">
                <span class="col-name">知识点</span>
                <span class="col-count">试题数量</span>
                <span class="col-score">每题分数</span>
                <span class="col-fixed">{{newData.assemblyMode==1?'固定选题':'随机选题'}}</span>
              </div>
              <div
                class="table-row"
                v-for="(item, index) in fixedKnowledgePointConfigs"
                :key="index"
                @dragstart="onBigDragStart($event, index)"
                @dragover.prevent="onBigDragOver($event, index)"
                @drop="onBigDrop($event, index)"
                @dragend="onDragEnd"
              >
                <div class="table-big-row">
                  <span class="col-name color-name">
                    <span class="roller-span" v-show="newData.assemblyMode==2"
                          @click="rollerButton(index)"
                          :class="item.rollerType?'el-icon-arrow-up':'el-icon-arrow-down'"></span>
                    {{item.name}}
                  </span>
                  <span class="col-count color-name">{{item.questionTotalCount}}</span>
                  <span class="col-score">
                    <span class="number-stepper">
                      <el-input-number
                        :disabled="showType"
                        v-if="newData.assemblyMode==1"
                        @change="calculationMaxData()"
                        class="form-input-number"
                        style="width:160px"
                        :min="0"
                        :max="9999"
                        :step="1" :precision="0" step-strictly
                        v-model="item.questionScore"
                      >
                      </el-input-number>
                    </span>
                  </span>
                  <span class="col-fixed">
                    <span class="item-num-span" v-if="newData.assemblyMode==1">{{item.questionIds.length}}</span>
                    <span class="el-icon-circle-plus" v-if="newData.assemblyMode==1&&!showType" @click="addFixed(index)"></span>
                    <span class="el-icon-rank" draggable="true" v-if="!showType"></span>
                  </span>
                </div>
                <div  v-if="newData.assemblyMode==2 && item.rollerType" class="table-min-row">
                  <span class="col-name">
                    <span class="roller-span">单选题</span>
                  </span>
                  <span class="col-count color-name">{{item.singleQuestionCount}}</span>
                  <span class="col-score">
                    <span class="number-stepper">
                      <el-input-number
                        :disabled="showType"
                        class="form-input-number"
                        @change="calculationMaxData()"
                        style="width:160px"
                        :min="0"
                        :max="9999"
                        :step="1" :precision="0" step-strictly
                        v-model="item.scoreA"
                      >
                      </el-input-number>
                    </span>
                  </span>
                  <span class="col-fixed">
                    <span class="number-stepper">
                      <el-input-number
                        :disabled="showType"
                        class="form-input-number"
                        @change="calculationMaxData()"
                        style="width:80px"
                        :min="0"
                        :max="item.singleQuestionCount"
                        :step="1" :precision="0" step-strictly
                        v-model="item.checkNumA"
                        :controls="false"
                      >
                      </el-input-number>
                    </span>
                  </span>
                </div>
                <div  v-if="newData.assemblyMode==2 && item.rollerType" class="table-min-row">
                  <span class="col-name">
                    <span class="roller-span">多选题</span>
                  </span>
                  <span class="col-count color-name">{{item.multipleQuestionCount}}</span>
                  <span class="col-score">
                    <span class="number-stepper">
                      <el-input-number
                        :disabled="showType"
                        class="form-input-number"
                        @change="calculationMaxData()"
                        style="width:160px"
                        :min="0"
                        :max="9999"
                        :step="1" :precision="0" step-strictly
                        v-model="item.scoreB"
                      >
                      </el-input-number>
                    </span>
                  </span>
                  <span class="col-fixed">
                    <span class="number-stepper">
                      <el-input-number
                        :disabled="showType"
                        class="form-input-number"
                        @change="calculationMaxData()"
                        style="width:80px"
                        :min="0"
                        :max="item.multipleQuestionCount"
                        :step="1" :precision="0" step-strictly
                        v-model="item.checkNumB"
                        :controls="false"
                      >
                      </el-input-number>
                    </span>
                  </span>
                </div>
                <div v-if="newData.assemblyMode==2 && item.rollerType" class="table-min-row">
                  <span class="col-name">
                    <span class="roller-span">判断题</span>
                  </span>
                  <span class="col-count color-name">{{item.judgeQuestionCount}}</span>
                  <span class="col-score">
                    <span class="number-stepper">
                      <el-input-number
                        :disabled="showType"
                        class="form-input-number"
                        @change="calculationMaxData()"
                        style="width:160px"
                        :min="0"
                        :max="9999"
                        :step="1" :precision="0" step-strictly
                        v-model="item.scoreC"
                      >
                      </el-input-number>
                    </span>
                  </span>
                  <span class="col-fixed">
                    <span class="number-stepper">
                      <el-input-number
                        :disabled="showType"
                        class="form-input-number"
                        @change="calculationMaxData()"
                        style="width:80px"
                        :min="0"
                        :max="item.judgeQuestionCount"
                        :step="1" :precision="0" step-strictly
                        v-model="item.checkNumC"
                        :controls="false"
                      >
                      </el-input-number>
                    </span>
                  </span>
                </div>
              </div>
            </div>
          </el-form-item>
        </div>

      </el-form>
    </div>
    <el-drawer
      size="100%"
      custom-class="testPaper-select-drawer"
      :append-to-body="true"
      :show-close="false"
      title="固定选题"
      ref="drawer"
      :visible.sync="drawer"
      direction="rtl"
    >
      <drawer-item v-if="drawer" :drawerPropsData="drawerPropsData"/>
    </el-drawer>
  </div>
</template>

<script>
  import {
    examElPaperAdd,examElPaperEdit,examElKnowledgePointTreeList,examElPaperDetail,
    examElDisciplineTypeList,examElQuestionBankKnowledgePointCount
  } from '@/api/safetyEducationExaminationNew/index'
  import drawerItem from './drawerItem.vue'
  import { accAdd,accMul } from '@/utils/calculation'

  export default {
    name: 'addPage',
    components: { drawerItem },
    props: {
      propsData: {}
    },
    data() {
      const validateData = (rule, value, callback) => {
        if (value == 0) {
          callback(new Error('总分数不能为0'))
        } else if (this.newData.passScore > value) {
          callback(new Error('总分数不能小于及格分数'))
        } else {
          callback()
        }
      }
      const validateData1 = (rule, value, callback) => {
        if (value == 0) {
          callback(new Error('及格分数不能为0'))
        } else if (this.newData.passScore > value) {
          callback(new Error('及格分数不能大于总分数'))
        } else {
          callback()
        }
      }
      const validateData2 = (rule, value, callback) => {
        if (value == 0) {
          callback(new Error('答题时间不能为0'))
        } else {
          callback()
        }
      }
      return {
        totalQuestionCount:0,
        totalScore:0,
        newData: {
          paperName: '',
          totalScore: 0,
          passScore: 0,
          // answerDuration: 0,
          disciplineTypeId: null,
          shareStatus: true,
          assemblyMode: 1,
          knowledgePointId: []
        },
        rules: {
          paperName: [
            { required: true, message: '请输入试卷名称', trigger: 'blur' }
          ],
          totalScore: [
            { required: true, message: '请输入总分数', trigger: 'blur' },
            { validator: validateData, trigger: 'blur' }
          ],
          passScore: [
            { required: true, message: '请输入及格分数', trigger: 'blur' },
            { validator: validateData1, trigger: 'blur' }
          ],
          // answerDuration: [
          //   { required: true, message: '请输入答题时间', trigger: 'blur' },
          //   { validator: validateData2, trigger: 'blur' }
          // ],
          assemblyMode: [
            { required: true, message: '请选择组卷方式', trigger: 'change' }
          ],
          knowledgePointId: [
            { required: true, message: '请选择知识点', trigger: 'change' }
          ]
        },
        optionListA: [],
        optionListKnowledge: [],
        fixedKnowledgePointConfigs: [],
        //弹窗相关
        drawer: false,
        drawerPropsData:{},
        //拖拽相关
        dragInfo: {
          type: null, // 'big' 或 'small'
          bigIndex: null,
          smallIndex: null
        },
        //预览状态
        showType:false,
      }
    },
    computed: {
      remainScore() {
        // return Math.max(0, Number(this.newData.totalScore || 0) - this.totalScore)
        return Number(this.newData.totalScore || 0) - this.totalScore
      }
    },
    watch: {
      'newData.knowledgePointId': {
        handler(newVal, oldVal) {
          // 假设最多只能选 2 个
          if (newVal && newVal.length > 10) {
            this.msgError('最多选择10个知识点')
            this.$nextTick(() => {
              // 将值回退到上一次的状态
              this.newData.knowledgePointId = oldVal;
            });
          }
        },
        deep: false,
        immediate: false
      }
    },
    mounted() {
      this.initialize()
      this.examElKnowledgePointTreeList()
      this.examElDisciplineTypeList()
    },
    methods: {
      //弹窗返回
      drawerReturnButton(){
        this.$refs.drawer.closeDrawer();
      },
      //弹窗确定
      drawerConfirmButton(obj){
        this.fixedKnowledgePointConfigs[obj.index].questionIds = [...obj.questionIds]
        this.calculationMaxData();
        this.$refs.drawer.closeDrawer();
      },
      initialize() {
        let self = this;
        if (this.propsData.id) {
          if(this.propsData.showType){
            this.$set(this,'showType',true);
          }
          examElPaperDetail({id:this.propsData.id}).then(response => {
            let obj = {
              id:this.propsData.id,
              paperName:response.data.paperName,
              totalScore:response.data.totalScore,
              passScore:response.data.passScore,
              // answerDuration:response.data.answerDuration,
              disciplineTypeId:response.data.disciplineTypeId,
              shareStatus:response.data.shareStatus,
              assemblyMode:response.data.assemblyMode,
              knowledgePointId:[],
            };
            let list = [];
            if(response.data.assemblyMode == 1){
              for(let i=0;i<response.data.fixedKnowledgePointDetails.length;i++){
                obj.knowledgePointId.push(response.data.fixedKnowledgePointDetails[i].knowledgePointId)
                list.push({
                  id: response.data.fixedKnowledgePointDetails[i].knowledgePointId,
                  name:response.data.fixedKnowledgePointDetails[i].knowledgePointName,
                  rollerType: true,
                  questionIds: response.data.fixedKnowledgePointDetails[i].questionIds,
                  questionScore: response.data.fixedKnowledgePointDetails[i].questionScore,//每题分数
                  fixedCount: response.data.fixedKnowledgePointDetails[i].questionIds.length,//选题数量
                  questionTotalCount:response.data.fixedKnowledgePointDetails[i].questionTotalCount,
                  singleQuestionCount:0,
                  multipleQuestionCount:0,
                  judgeQuestionCount:0,
                  scoreA:0,
                  checkNumA:0,
                  scoreB:0,
                  checkNumB:0,
                  scoreC:0,
                  checkNumC:0,
                })
              }
            }else if(response.data.assemblyMode == 2){
              for(let i=0;i<response.data.randomKnowledgePointDetails.length;i++){
                obj.knowledgePointId.push(response.data.randomKnowledgePointDetails[i].knowledgePointId)
                let minObj = {
                  id: response.data.randomKnowledgePointDetails[i].knowledgePointId,
                  name:response.data.randomKnowledgePointDetails[i].knowledgePointName,
                  rollerType: true,
                  questionIds: [],
                  questionScore: 0,//每题分数
                  fixedCount: 0,//选题数量
                  questionTotalCount:response.data.randomKnowledgePointDetails[i].questionTotalCount,
                  singleQuestionCount:0,
                  multipleQuestionCount:0,
                  judgeQuestionCount:0,
                  scoreA:0,
                  checkNumA:0,
                  scoreB:0,
                  checkNumB:0,
                  scoreC:0,
                  checkNumC:0,
                }
                for(let o=0;o<response.data.randomKnowledgePointDetails[i].rules.length;o++){
                  if(response.data.randomKnowledgePointDetails[i].rules[o].questionType == 1){
                    minObj.singleQuestionCount = response.data.randomKnowledgePointDetails[i].rules[o].questionTotalCount
                    minObj.scoreA = response.data.randomKnowledgePointDetails[i].rules[o].questionScore
                    minObj.checkNumA = response.data.randomKnowledgePointDetails[i].rules[o].questionCount
                  }
                  if(response.data.randomKnowledgePointDetails[i].rules[o].questionType == 2){
                    minObj.multipleQuestionCount = response.data.randomKnowledgePointDetails[i].rules[o].questionTotalCount
                    minObj.scoreB = response.data.randomKnowledgePointDetails[i].rules[o].questionScore
                    minObj.checkNumB = response.data.randomKnowledgePointDetails[i].rules[o].questionCount
                  }
                  if(response.data.randomKnowledgePointDetails[i].rules[o].questionType == 3){
                    minObj.judgeQuestionCount = response.data.randomKnowledgePointDetails[i].rules[o].questionTotalCount
                    minObj.scoreC = response.data.randomKnowledgePointDetails[i].rules[o].questionScore
                    minObj.checkNumC = response.data.randomKnowledgePointDetails[i].rules[o].questionCount
                  }
                }
                list.push(minObj);
              }
            }
            this.$set(this,'newData',obj);
            this.$set(this,'fixedKnowledgePointConfigs',list);
            this.calculationMaxData();
          })
        }
      },
      backPage() {
        this.$parent.tableButton(6)
      },
      resetButton() {
        this.initialize();
      },
      submitButton() {
        let self = this;
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(this.remainScore != 0){
              this.msgError('总分数与试题分数不一致')
              return
            }
            this.$confirm('是否确认保存?', "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(function() {
            }).then(() => {
              self.dataIntegration();
            }).catch(() => {});
          }
        })

      },
      dataIntegration(){
        let self = this;
        let obj = {
          paperName:this.newData.paperName,
          totalScore:this.newData.totalScore,
          passScore:this.newData.passScore,
          // answerDuration:this.newData.answerDuration,
          disciplineTypeId:this.newData.disciplineTypeId,
          shareStatus:this.newData.shareStatus,
          assemblyMode:this.newData.assemblyMode,
          fixedKnowledgePointConfigs:[],
          randomKnowledgePointConfigs:[],
        };
        for(let i=0;i<self.fixedKnowledgePointConfigs.length;i++){
          if(this.newData.assemblyMode == 1){
            obj.fixedKnowledgePointConfigs.push({
              knowledgePointId:self.fixedKnowledgePointConfigs[i].id,
              questionScore:self.fixedKnowledgePointConfigs[i].questionScore,
              questionIds:self.fixedKnowledgePointConfigs[i].questionIds,
            })
          }else if(this.newData.assemblyMode == 2){
            obj.randomKnowledgePointConfigs.push({
              knowledgePointId:self.fixedKnowledgePointConfigs[i].id,
              rules:[
                {
                  questionType:1,
                  questionCount:self.fixedKnowledgePointConfigs[i].checkNumA,
                  questionScore:self.fixedKnowledgePointConfigs[i].scoreA,
                },
                {
                  questionType:2,
                  questionCount:self.fixedKnowledgePointConfigs[i].checkNumB,
                  questionScore:self.fixedKnowledgePointConfigs[i].scoreB,
                },
                {
                  questionType:3,
                  questionCount:self.fixedKnowledgePointConfigs[i].checkNumC,
                  questionScore:self.fixedKnowledgePointConfigs[i].scoreC,
                },
              ],
            })
          }
        }
        if (this.newData.id){
          obj.id = this.newData.id;
          this.examElPaperEdit(obj);
        }else{
          this.examElPaperAdd(obj);
        }
      },
      examElPaperAdd(obj){
        examElPaperAdd(obj).then(response => {
          this.msgSuccess(response.message);
          this.$parent.tableButton(6);
        })
      },
      examElPaperEdit(obj){
        examElPaperEdit(obj).then(response => {
          this.msgSuccess(response.message);
          this.$parent.tableButton(6);
        })
      },
      //收起展开
      rollerButton(idnex){
        this.$set(this.fixedKnowledgePointConfigs[idnex],'rollerType',!this.fixedKnowledgePointConfigs[idnex].rollerType);
      },
      //change触发过滤知识点列表
      onKnowledgeSelect(val) {
        if (!Array.isArray(val)) return
        for (let i = this.fixedKnowledgePointConfigs.length - 1; i >= 0; i--) {
          const currentItem = this.fixedKnowledgePointConfigs[i]
          if (!val.includes(currentItem.id)) {
            this.fixedKnowledgePointConfigs.splice(i, 1)
          }
        }
        val.forEach(id => {
          const exists = this.fixedKnowledgePointConfigs.some(item => item.id === id)
          if (!exists) {
            const node = this.$refs.knowledgeCascader.getCheckedNodes()
            let name = ''
            for (let i = 0; i < node.length; i++) {
              if (id == node[i].value) {
                if(node[i].level == 2){
                  name = node[i].parent.label +'-'+ node[i].label
                }else{
                  name = node[i].label
                }
              }
            }
            if(this.fixedKnowledgePointConfigs[9]){
              return
            }
            this.examElQuestionBankKnowledgePointCount(name,id);
          }
        })
      },
      //查询知识点题目数量
      examElQuestionBankKnowledgePointCount(name,id) {
        examElQuestionBankKnowledgePointCount({knowledgePointId:id}).then(response => {
          this.fixedKnowledgePointConfigs.push({
            id: id,
            name,
            rollerType: true,
            questionIds: [],
            questionScore: 0,//每题分数
            fixedCount: 0,//选题数量
            questionTotalCount:response.data.questionTotalCount,//试题总量
            singleQuestionCount:response.data.singleQuestionCount,//单选
            multipleQuestionCount:response.data.multipleQuestionCount,//多选
            judgeQuestionCount:response.data.judgeQuestionCount,//判断
            scoreA:0,
            checkNumA:0,
            scoreB:0,
            checkNumB:0,
            scoreC:0,
            checkNumC:0,
          })
        })
      },
      addFixed(index) {
        this.$set(this,'drawerPropsData',{
          titleName:this.fixedKnowledgePointConfigs[index].name,
          knowledgePointId:this.fixedKnowledgePointConfigs[index].id,
          questionScore:this.fixedKnowledgePointConfigs[index].questionScore,
          questionIds:this.fixedKnowledgePointConfigs[index].questionIds,
          index:index
        });
        this.drawer = true
      },
      // ========== 大项拖拽逻辑 ==========
      onBigDragStart(e, index) {
        if(this.showType){
          return
        }
        this.dragInfo = { type: 'big', bigIndex: index, smallIndex: null }

        //拖拽优化相关
        const rowEl = e.target.closest('.table-row');
        if (rowEl) {
          rowEl.classList.add('dragging');
          e.dataTransfer.setDragImage(rowEl, 1177, 30);
        }
        // 给拖拽中的元素加个样式
        // e.target.classList.add('dragging')
      },
      onBigDragOver(e, index) {
        if(this.showType){
          return
        }
        // 只有当拖拽的是大项时才允许放置
        if (this.dragInfo.type === 'big') {
          e.currentTarget.classList.add('drag-over')
        }
      },
      onBigDrop(e, targetIndex) {
        if(this.showType){
          return
        }
        if (this.dragInfo.type !== 'big') return
        const sourceIndex = this.dragInfo.bigIndex
        if (sourceIndex === targetIndex) return

        // 核心：交换数组元素
        const movedItem = this.fixedKnowledgePointConfigs.splice(sourceIndex, 1)[0]
        this.fixedKnowledgePointConfigs.splice(targetIndex, 0, movedItem)
      },
      // 拖拽结束，清理样式
      onDragEnd(e) {
        if(this.showType){
          return
        }
        //拖拽优化相关
        const rowEl = e.target.closest('.table-row');
        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 }
      },
      // 辅助方法：获取当前鼠标悬停的大项索引
      getCurrentBigIndex(e) {
        if(this.showType){
          return
        }
        const minBox = e.currentTarget.closest('.for-max-box')
        return Array.from(this.$el.querySelectorAll('.for-max-box')).indexOf(minBox)
      },
      //查询全部专业类别
      examElDisciplineTypeList() {
        examElDisciplineTypeList({}).then(response => {
          this.$set(this, 'optionListA', response.data)
        })
      },
      //知识点
      examElKnowledgePointTreeList() {
        examElKnowledgePointTreeList({}).then(response => {
          const list = response.data || []
          this.formatTreeData(list)
          this.$set(this, 'optionListKnowledge', list)
        })
      },
      //计算总分总题
      calculationMaxData(){
        let self = this;
        let totalQuestionCount = 0;
        let totalScore = 0;
        for(let i=0;i<self.fixedKnowledgePointConfigs.length;i++){
          if(self.newData.assemblyMode == 1){
            //固定组卷
            totalQuestionCount = self.accAdd(totalQuestionCount,self.fixedKnowledgePointConfigs[i].questionIds.length)
            let minTotalScore = self.accMul(self.fixedKnowledgePointConfigs[i].questionScore,self.fixedKnowledgePointConfigs[i].questionIds.length);
            totalScore =  self.accAdd(totalScore,minTotalScore)
          }else if(self.newData.assemblyMode == 2){
            let numA = self.accMul(self.fixedKnowledgePointConfigs[i].scoreA,self.fixedKnowledgePointConfigs[i].checkNumA);
            let numB = self.accMul(self.fixedKnowledgePointConfigs[i].scoreB,self.fixedKnowledgePointConfigs[i].checkNumB);
            let numC = self.accMul(self.fixedKnowledgePointConfigs[i].scoreC,self.fixedKnowledgePointConfigs[i].checkNumC);
            totalScore = self.accAdd(totalScore,numA)
            totalScore = self.accAdd(totalScore,numB)
            totalScore = self.accAdd(totalScore,numC)
            totalQuestionCount = self.accAdd(totalQuestionCount,self.fixedKnowledgePointConfigs[i].checkNumA)
            totalQuestionCount = self.accAdd(totalQuestionCount,self.fixedKnowledgePointConfigs[i].checkNumB)
            totalQuestionCount = self.accAdd(totalQuestionCount,self.fixedKnowledgePointConfigs[i].checkNumC)
          }
        }
        this.$set(this,'totalQuestionCount',totalQuestionCount);
        this.$set(this,'totalScore',totalScore);
      },
      //乘法
      accMul(arg1,arg2){
        var m=0,s1=arg1.toString(),s2=arg2.toString();
        try{m+=s1.split(".")[1].length}catch(e){}
        try{m+=s2.split(".")[1].length}catch(e){}
        return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
      },
      //加法
      accAdd(arg1,arg2){
        var r1,r2,m;
        try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
        try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
        m=Math.pow(10,Math.max(r1,r2))
        return ((arg1*m+arg2*m)/m).toFixed(0);
      },
    }
  }
</script>

<style scoped lang="scss">
  .testPaperManagement-addPage {
    .content-box {
      flex: 1;
      overflow-y: auto;
      padding: 20px;
    }

    .add-form-box {
      .section-box {
        padding: 20px 0;
      }

      .section-divider {
        height: 1px;
        background: #e8e8e8;
        margin: 0 0 10px;
      }

      .full-width-item {
        ::v-deep .el-input {
          width: 100%;
        }

        ::v-deep .el-form-item__content {
          width: calc(100% - 100px);
        }
      }

      .flex-row-box {
        display: flex;
        flex-wrap: wrap;
        gap: 0 40px;
      }

      .input-unit-box {
        display: flex;
        align-items: center;

        .unit-text {
          margin-left: 8px;
          color: #333;
          white-space: nowrap;
        }
      }

      .share-tip {
        margin-left: 12px;
        color: #999;
        font-size: 13px;
      }

      /* 知识点区域 */
      .knowledge-form-item {
        ::v-deep .el-form-item__content {
          width: calc(100% - 100px);
        }
      }

      .stat-bar {
        background: #f5f5f5;
        padding: 10px 16px;
        margin-bottom: 10px;
        font-size: 14px;
        color: #333;

        b {
          color: #0183fa;
        }
      }

      .knowledge-tag-box {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        align-items: center;
        padding: 10px;
        border: 1px solid #e8e8e8;
        border-radius: 4px;
        min-height: 48px;
        margin-bottom: 16px;
      }

      .knowledge-tag {
        display: inline-flex;
        align-items: center;
        background: #e6f4ff;
        border: 1px solid #91caff;
        color: #0183fa;
        border-radius: 4px;
        padding: 4px 10px;
        font-size: 13px;

        i {
          margin-left: 6px;
          cursor: pointer;
          color: #0183fa;
          font-size: 12px;

          &:hover {
            color: #e74c3c;
          }
        }
      }

      /* 知识点明细表格 */
      .knowledge-table {
        border: 1px solid #e8e8e8;
        border-radius: 4px;
        overflow: hidden;

        .table-header {
          display: flex;
          align-items: center;
          padding: 12px 16px;

          .col-name {
            flex: 3;
          }

          .col-count {
            flex: 2;
            text-align: center;
          }

          .col-score {
            flex: 2;
            text-align: center;
          }

          .col-fixed {
            flex: 3;
            display: flex;
            align-items: center;
          }

          .color-name {
            color: #0183fa;
          }
        }

        .table-row {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: hidden;
          padding: 12px 0;

          .table-big-row {
            flex: 1;
            display: flex;
            align-items: center;
            overflow: hidden;
            /*padding: 0 16px 12px;*/
            /*border-bottom:1px solid #dedede;*/
            padding:0 16px;
            .col-name {
              flex: 3;
            }

            .col-count {
              flex: 2;
              text-align: center;
            }

            .col-score {
              flex: 2;
              text-align: center;
            }

            .col-fixed {
              flex: 3;
              display: flex;
              align-items: center;
            }

            .roller-span {
              color: #999;
              font-size: 24px;
              margin-right: 12px;
              cursor: pointer;
              display: inline-block;
            }

            .color-name {
              color: #0183fa;
            }

            .item-num-span {
              display: inline-block;
              width: 80px;
              line-height: 40px;
              border-radius: 4px;
              border: 1px solid #dedede;
              text-align: center;
            }

            .el-icon-circle-plus {
              font-size: 28px;
              color: #0183fa;
              cursor: pointer;
              margin-left: 28px;
            }

            .el-icon-rank {
              font-size: 28px;
              color: #999;
              cursor: pointer;
              margin-left: 28px;
            }
          }
          .table-min-row {
            flex: 1;
            display: flex;
            align-items: center;
            overflow: hidden;
            padding: 12px 16px 0;
            /*border-top:1px solid #dedede;*/
            .col-name {
              flex: 3;
            }

            .col-count {
              flex: 2;
              text-align: center;
            }

            .col-score {
              flex: 2;
              text-align: center;
            }

            .col-fixed {
              flex: 3;
              display: flex;
              align-items: center;
            }

            .roller-span {
              color: #333;
              font-size: 16px;
              cursor: pointer;
              margin-left:200px;
            }

            .color-name {
              color: #0183fa;
            }

            .item-num-span {
              display: inline-block;
              width: 80px;
              line-height: 40px;
              border-radius: 4px;
              border: 1px solid #dedede;
              text-align: center;
            }

            .el-icon-circle-plus {
              font-size: 28px;
              color: #0183fa;
              cursor: pointer;
              margin-left: 40px;
            }

            .el-icon-rank {
              font-size: 28px;
              color: #999;
              cursor: pointer;
              margin-left: 40px;
            }
          }
        }

        .table-header {
          background: #fafafa;
          font-weight: 600;
          font-size: 14px;
          color: #333;
          border-bottom: 1px solid #e8e8e8;
        }

        .table-row {
          border-bottom: 1px solid #f0f0f0;

          &:last-child {
            border-bottom: none;
          }
        }

        .link-text {
          color: #0183fa;
          cursor: pointer;
        }

        .number-stepper {
          display: inline-flex;
          align-items: center;
          border-radius: 4px;
          overflow: hidden;

          .stepper-btn {
            width: 32px;
            height: 36px;
            background: #f5f7fa;
            border: none;
            cursor: pointer;
            font-size: 16px;
            color: #333;

            &:hover {
              background: #e6f0fe;
            }
          }

          .stepper-val {
            min-width: 80px;
            text-align: center;
            font-size: 14px;
            padding: 0 4px;
          }
        }
      }
    }

    .drag-handle {
      cursor: move;
      user-select: none; /* 防止拖拽时选中文字 */
    }

    .dragging {
      opacity: 0.5;
      background-color: #f5f7fa;
    }

    .drag-over {
      /*border-top: 2px solid #409EFF !important; !* 放置位置的指示线 *!*/
    }
  }
</style>
<style lang="scss">
  .testPaper-select-drawer{
    .el-drawer__body{
      padding:0;
    }
    .el-drawer__header{
      margin:0;
    }
  }
</style>
