<template>
  <div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <!-- tab栏 -->
      <div class="tab-wrapper">
        <div class="tab-item" @click="handleTab(1)" v-if="isAdd || (isEdit && active == 1)">
          <div class="title">单选题</div>
          <div :class="{ 'bt-line': active == 1 }" />
        </div>
        <div class="tab-item" @click="handleTab(2)" v-if="isAdd || (isEdit && active == 2)">
          <div class="title">多选题</div>
          <div :class="{ 'bt-line': active == 2 }" />
        </div>
        <div class="tab-item" @click="handleTab(3)" v-if="isAdd || (isEdit && active == 3)">
          <div class="title">判断题</div>
          <div :class="{ 'bt-line': active == 3 }" />
        </div>
        <div class="tab-item" @click="handleTab(4)" v-if="isAdd || (isEdit && active == 4)">
          <div class="title">简答题</div>
          <div :class="{ 'bt-line': active == 4 }" />
        </div>
      </div>

      <div v-show="active == 1">
        <!-- 表单 -->
        <el-form :model="radioForm" ref="radioForm" size="small" label-width="80px">
          <el-form-item label="题目" prop="question" :rules="rules">
            <el-input
              type="textarea"
              v-model="radioForm.question"
              placeholder="请输入题目"
              clearable v-no-whitespace
              :rows="4"
              :maxlength="500"
              show-word-limit
              style="margin-bottom: 20px"
            />
            <!-- 上传图片 -->
            <ImageUpload
              v-model="radioForm.questionImg"
              :limit="3"
              :fileSize="2"
              :isShowTip="false"
              :topicType="'radio'"
              @input="handleImgTopic"
            />
            <span style="font-size: 12px; margin-left: 10px">支持添加图片 3 张(2M)</span>
          </el-form-item>
        </el-form>

        <div class="answer-title">答案选项：</div>
        <!-- 答案 -->
        <div class="answerList-wrapper" v-for="(item, index) in answerList" :key="index">
          <div class="answer-bg answer-item">{{ item.label }}</div>
          <div class="answer-item">
            <el-input
              class="answer-input"
              v-model="item.value"
              placeholder="请输入选项内容" v-no-whitespace
              size="small"
              maxlength="500"
            />
            <ImageUpload
              v-model="item.img"
              :limit="3"
              :fileSize="2"
              :fileType="['png', 'jpg', 'jpeg']"
              :isShowTip="false"
              :topicType="'radio' + item.label"
              @input="handleImgTopic"
            />
          </div>
          <!-- 删除 -->
          <el-button
            class="answer-item"
            type="text"
            icon="el-icon-delete"
            style="color: #e47571"
            @click="handleDelete(item)"
          >
            删除
          </el-button>
        </div>

        <!-- 正确答案: -->
        <div class="answer-title">
          <div style="margin-bottom: 10px">正确答案：</div>
          <el-radio-group v-model="radioAnswer">
            <el-radio v-for="(item, index) in answerList" :key="index" :label="item.label">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </div>

        <!-- 解析 analysis -->
        <div class="analysis">
          <div>答案解析:</div>
          <el-input
            type="textarea"
            v-model="analysis"
            placeholder="请输入解析" v-no-whitespace
            clearable
            :rows="4"
            :maxlength="500"
            show-word-limit
            style="margin: 10px 0"
          />
        </div>
        <el-row>
          <!-- 添加选项 -->
          <el-button
            type="primary"
            plain
            size="small"
            icon="el-icon-plus"
            @click="handleAddAnswer"
            style="margin-left: 40px; margin-top: 20px"
          >
            添加选项
          </el-button>
          <!-- 添加标签 -->
          <el-button
            type="primary"
            plain
            size="small"
            icon="el-icon-plus"
            @click="handleAddTag"
            style="margin-left: 20px; margin-top: 20px"
          >
            选择标签
          </el-button>
          <!-- 展示已选的-tag -->
          <el-tag
            v-for="(tag, index) in radioTag"
            :key="index"
            closable
            @close="handleClose(tag)"
            style="margin-left: 10px; margin-top: 20px"
          >
            {{ tag.labelName }}
          </el-tag>
        </el-row>
      </div>

      <div v-show="active == 2">
        <!-- 表单 -->
        <el-form :model="multipleForm" ref="multipleForm" size="small" label-width="80px">
          <el-form-item label="题目" prop="question" :rules="rules2">
            <el-input
              type="textarea"
              v-model="multipleForm.question"
              placeholder="请输入题目" v-no-whitespace
              clearable
              :rows="4"
              :maxlength="500"
              show-word-limit
              style="margin-bottom: 20px"
            />
            <!-- 上传图片 -->
            <ImageUpload
              v-model="multipleForm.questionImg"
              :limit="3"
              :fileSize="2"
              :isShowTip="false"
              :topicType="'multiple'"
              @input="handleImgTopic"
            />
            <span style="font-size: 12px; margin-left: 10px">支持添加图片 3 张(2M)</span>
          </el-form-item>
        </el-form>

        <div class="answer-title">答案选项：</div>
        <!-- 答案 -->
        <div class="answerList-wrapper answer-item" v-for="(item, index) in multipleAnswerList" :key="index">
          <div class="answer-bg answer-item">{{ item.label }}</div>
          <div class="answer-item answer-input">
            <el-input
              class="answer-input"
              v-model="item.value"
              placeholder="请输入选项内容" v-no-whitespace
              size="small"
              maxlength="500"
            />
            <ImageUpload
              v-model="item.img"
              :limit="3"
              :fileSize="2"
              :fileType="['png', 'jpg', 'jpeg']"
              :isShowTip="false"
              :topicType="'multiple' + item.label"
              @input="handleImgTopic"
            />
          </div>
          <!-- 删除 -->
          <el-button
            class="answer-item"
            type="text"
            icon="el-icon-delete"
            style="color: #e47571"
            @click="handleDelete(item)"
          >
            删除
          </el-button>
        </div>

        <!-- 正确答案: -->
        <div class="answer-title">
          <div style="margin-bottom: 10px">正确答案：</div>
          <!-- 多选框 -->
          <el-checkbox-group v-model="multipleAnswer">
            <el-checkbox v-for="(item, index) in multipleAnswerList" :key="index" :label="item.label">
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <!-- 解析 analysis -->
        <div class="analysis">
          <div>答案解析:</div>
          <el-input
            type="textarea"
            v-model="analysis2"
            placeholder="请输入解析" v-no-whitespace
            clearable
            :rows="4"
            :maxlength="500"
            show-word-limit
            style="margin: 10px 0"
          />
        </div>
        <el-row>
          <!-- 添加选项 -->
          <el-button
            type="primary"
            plain
            size="small"
            icon="el-icon-plus"
            @click="handleAddAnswer"
            style="margin-left: 40px; margin-top: 20px"
          >
            添加选项
          </el-button>
          <!-- 添加标签 -->
          <el-button
            type="primary"
            plain
            size="small"
            icon="el-icon-plus"
            @click="handleAddTag"
            style="margin-left: 20px; margin-top: 20px"
          >
            选择标签
          </el-button>
          <!-- 展示已选的-tag -->
          <el-tag
            v-for="(tag, index) in radioTag"
            :key="index"
            closable
            @close="handleClose(tag)"
            style="margin-left: 10px; margin-top: 20px"
          >
            {{ tag.labelName }}
          </el-tag>
        </el-row>
      </div>

      <div v-show="active == 3">
        <!-- 表单 -->
        <el-form :model="judgeForm" ref="judgeForm" size="small" label-width="80px">
          <el-form-item label="题目" prop="question" :rules="rules3">
            <el-input
              type="textarea"
              v-model="judgeForm.question"
              placeholder="请输入题目"
              clearable v-no-whitespace
              :rows="4"
              :maxlength="500"
              show-word-limit
              style="margin-bottom: 20px"
            />
            <ImageUpload
              v-model="judgeForm.questionImg"
              :limit="3"
              :fileSize="2"
              :isShowTip="false"
              :topicType="'judge'"
              @input="handleImgTopic"
            />
            <span style="font-size: 12px; margin-left: 10px">支持添加图片 3 张(2M)</span>
          </el-form-item>
        </el-form>

        <div class="answer-title">答案选项：</div>
        <!-- 答案 -->
        <div class="answerList-wrapper" v-for="(item, index) in judgeAnswerList" :key="index">
          <div class="answer-bg answer-item">{{ item.label }}</div>
          <div class="answer-item">
            <el-input class="answer-input" v-model="item.value" size="small" disabled  v-no-whitespace/>
          </div>
        </div>

        <!-- 正确答案: -->
        <div class="answer-title">
          <div style="margin-bottom: 10px">正确答案：</div>
          <el-radio-group v-model="judgeAnswer">
            <el-radio v-for="(item, index) in judgeAnswerList" :key="index" :label="item.label">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </div>
        <!-- 解析 analysis -->
        <div class="analysis">
          <div>答案解析:</div>
          <el-input
            type="textarea"
            v-model="analysis3"
            placeholder="请输入解析"
            clearable v-no-whitespace
            :rows="4"
            :maxlength="500"
            show-word-limit
            style="margin: 10px 0"
          />
        </div>
        <el-row>
          <!-- 添加标签 -->
          <el-button
            type="primary"
            plain
            size="small"
            icon="el-icon-plus"
            @click="handleAddTag"
            style="margin-left: 20px; margin-top: 20px"
          >
            选择标签
          </el-button>
          <!-- 展示已选的-tag -->
          <el-tag
            v-for="(tag, index) in radioTag"
            :key="index"
            closable
            @close="handleClose(tag)"
            style="margin-left: 10px; margin-top: 20px"
          >
            {{ tag.labelName }}
          </el-tag>
        </el-row>
      </div>

      <div v-show="active == 4">
        <!-- 表单 -->
        <el-form :model="shortAnswerForm" ref="shortAnswerForm" size="small" label-width="80px">
          <el-form-item label="题目" prop="question" :rules="rules4">
            <el-input
              type="textarea"
              v-model="shortAnswerForm.question"
              placeholder="请输入题目"
              clearable v-no-whitespace
              :rows="4"
              :maxlength="500"
              show-word-limit
              style="margin-bottom: 20px"
            />
            <ImageUpload v-model="shortAnswerForm.questionImg" :limit="3" :fileSize="2" :isShowTip="false" />
            <span style="font-size: 12px; margin-left: 10px">支持添加图片 3 张(2M)</span>
          </el-form-item>
        </el-form>

        <div class="answer-title">关键词：</div>
        <!-- 文本域 -->
        <el-input
          v-model="shortAnswerAnswer"
          type="textarea"
          placeholder="请输入关键词"
          clearable v-no-whitespace
          :rows="4"
          :maxlength="500"
          show-word-limit
          style="margin: 10px 40px; width: 90%"
        />
        <span style="font-size: 12px; margin-left: 40px">
          判断规则：考生答案中涉及涉及到全部关键词，为满分，涉及到部分关键词，则根据关键词占比，计算答案分值占比；
        </span>
        <div style="font-size: 12px; margin-left: 40px">例：判断题10分，共5个关键词，则每个关键词占2分；</div>

        <!-- 解析 analysis -->
        <div class="analysis">
          <div>答案解析:</div>
          <el-input
            type="textarea"
            v-model="analysis4"
            placeholder="请输入解析"
            clearable v-no-whitespace
            :rows="4"
            :maxlength="500"
            show-word-limit
            style="margin: 10px 0"
          />
        </div>
        <!-- 标签 -->
        <el-row>
          <!-- 添加标签 -->
          <el-button
            type="primary"
            plain
            size="small"
            icon="el-icon-plus"
            @click="handleAddTag"
            style="margin-left: 20px; margin-top: 20px"
          >
            选择标签
          </el-button>
          <!-- 展示已选的-tag -->
          <el-tag
            v-for="(tag, index) in radioTag"
            :key="index"
            closable
            @close="handleClose(tag)"
            style="margin-left: 10px; margin-top: 20px"
          >
            {{ tag.labelName }}
          </el-tag>
        </el-row>
      </div>

      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="handleConfirm(1)">发 布</el-button>
        <el-button v-if="!isEdit" size="mini" type="primary" @click="handleConfirm(2)">发布并继续新建</el-button>
      </span>
    </el-dialog>

    <!-- 添加标签-弹框 -->
    <el-dialog title="添加标签" :visible.sync="tagVisible" width="30%">
      <!-- 标签列表 -->
      <el-table
        :data="tagList"
        fit
        highlight-current-row
        style="width: 100%"
        @selection-change="selectionChange"
        ref="multipleTable"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column type="index" width="55" label="序号" align="center" />
        <el-table-column
          v-for="column in columns"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          align="center"
        ></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="handleTagConfirm" v-preventReClick="3000">确定</el-button>
        <el-button size="mini" @click="tagVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ImageUpload from './ImageUpload'
import {
  getLabels,
  addTopic,
  getTopicDetail,
  editTopic,
  addTopicByTask,
} from '@/api/educationalTraining/resourceAdministration'
import { lookFaceFile } from '@/utils/bonus'

export default {
  props: {
    dialogTitle: {
      type: String,
      default: '新建试题',
    },
    questionsLibraryId: {
      type: String | Number,
      default: '',
    },
    isNewExam: {
      type: Boolean,
      default: false,
    },
  },
  components: { ImageUpload },
  data() {
    return {
      questionId: '',
      dialogVisible: false,
      tagVisible: false,
      active: 1,
      imgBaseUrl: '',
      // 单选题-表单
      radioForm: {
        question: '',
        // 题目图片
        questionImg: [],
      },
      // 多选题-表单
      multipleForm: {
        question: '',
        questionImg: [],
      },
      // 判断题-表单
      judgeForm: {
        question: '',
        questionImg: [],
      },
      // 简答题-表单
      shortAnswerForm: {
        question: '',
        questionImg: [],
      },
      analysis: '', // 解析
      analysis2: '', // 解析
      analysis3: '', // 解析
      analysis4: '', // 解析
      rules: [{ required: true, message: '请输入题目', trigger: 'blur' }],
      rules2: [{ required: true, message: '请输入题目', trigger: 'blur' }],
      rules3: [{ required: true, message: '请输入题目', trigger: 'blur' }],
      rules4: [{ required: true, message: '请输入题目', trigger: 'blur' }],
      // 答案选项
      answerList: [
        { label: 'A', value: '', img: [] },
        { label: 'B', value: '', img: [] },
        { label: 'C', value: '', img: [] },
        { label: 'D', value: '', img: [] },
      ],
      // 多选-答案选项
      multipleAnswerList: [
        { label: 'A', value: '', img: [] },
        { label: 'B', value: '', img: [] },
        { label: 'C', value: '', img: [] },
        { label: 'D', value: '', img: [] },
      ],
      // 判断-答案选项
      judgeAnswerList: [
        { label: 'A', value: '对' },
        { label: 'B', value: '错' },
      ],
      // 单选-正确答案
      radioAnswer: 'A',
      // 多选-正确答案
      multipleAnswer: [],
      // 判断-正确答案
      judgeAnswer: 'A',
      // 简答-正确答案
      shortAnswerAnswer: '',
      // 标签
      radioTag: [],
      // 选中的标签
      selectedTag: [],
      // 保存的选中标签
      saveTag: [],
      // 标签列表
      tagList: [],
      // 表格头
      columns: [{ prop: 'labelName', label: '标签名称' }],
      delAnswerIds: [], // 删除的选项id
      delPictureIds: [], // 删除的图片id
      isAdd: true,
      isEdit: false,
    }
  },
  created() {
    this.imgBaseUrl = lookFaceFile()
  },
  methods: {
    // 打开弹框
    async openDialog(item) {
      console.log('🚀 ~ openDialog ~ item:', item)
      await (this.dialogVisible = true)

      // 重置表单
      this.isAdd = true
      this.isEdit = false
      this.questionId = ''
      this.$refs.radioForm.resetFields()
      this.radioForm.questionImg = []
      this.$refs.multipleForm.resetFields()
      this.multipleForm.questionImg = []
      this.$refs.judgeForm.resetFields()
      this.judgeForm.questionImg = []
      this.$refs.shortAnswerForm.resetFields()
      this.shortAnswerForm.questionImg = []
      this.radioTag = []
      this.analysis = ''
      this.analysis2 = ''
      this.analysis3 = ''
      this.analysis4 = ''
      this.delAnswerIds = []
      this.delPictureIds = []
      this.answerList = [
        { label: 'A', value: '', img: [] },
        { label: 'B', value: '', img: [] },
        { label: 'C', value: '', img: [] },
        { label: 'D', value: '', img: [] },
      ]
      this.multipleAnswerList = [
        { label: 'A', value: '', img: [] },
        { label: 'B', value: '', img: [] },
        { label: 'C', value: '', img: [] },
        { label: 'D', value: '', img: [] },
      ]
      this.radioAnswer = 'A'
      this.multipleAnswer = []
      this.judgeAnswer = 'A'
      this.shortAnswerAnswer = ''
      this.active = 1
      if (item && item.isEdit) {
        console.log('🚀 ~ item ~ 编辑:', item)
        this.isAdd = false
        this.isEdit = true
        this.questionId = item.questionId
        console.log('🚀 ~ openDialog ~ this.questionId:', this.questionId)
        this.getTopicDetail(item)
      }
    },
    // 编辑试题
    async getTopicDetail(item) {
      // 编辑
      const params = {
        questionId: item.questionId,
        questionsLibraryId: item.questionsLibraryId,
      }
      const res = await getTopicDetail(params)
      console.log('🚀 ~ openDialog ~ res-编辑试题:', res)
      // 根据题型赋值 res.data.questionType: 1单选题;2多选题;3判断题;4简答题
      this.radioTag = []
      if (res.data.labelIds && res.data.labelIds.length > 0) {
        res.data.labelIds.forEach((id, index) => {
          this.radioTag.push({ labelId: id })
          res.data.questionLabel.split(',').forEach((item, itemIndex) => {
            if (index == itemIndex) {
              this.radioTag[index].labelName = item
            }
          })
        })
        console.log('🚀 ~ getTopicDetail ~ this.radioTag:', this.radioTag)
      }
      if (res.data.questionType == 1) {
        this.active = 1
        this.analysis = res.data.analysis
        this.radioForm.question = res.data.content
        this.radioForm.questionImg = res.data.questionPictureVoList
        if (this.radioForm.questionImg && this.radioForm.questionImg.length > 0) {
          this.radioForm.questionImg.forEach(item => {
            item.url = this.imgBaseUrl + item.pictureUrl
            item.name = item.pictureUrl
          })
        }
        this.radioAnswer = res.data.correctAnswer
        this.answerList = res.data.questionAnswerVoList
        if (this.answerList && this.answerList.length > 0) {
          this.answerList.forEach(item => {
            item.label = item.options
            item.value = this.$set(item, 'value', item.answerOptions)
            item.img = item.questionPictureVoList
            item.img.forEach(item => {
              item.url = this.imgBaseUrl + item.pictureUrl
              item.name = item.pictureUrl
            })
          })
        }
        console.log('this.answerList', this.answerList)
      } else if (res.data.questionType == 2) {
        this.active = 2
        this.analysis2 = res.data.analysis
        this.multipleForm.question = res.data.content
        this.multipleForm.questionImg = res.data.questionPictureVoList
        if (this.multipleForm.questionImg && this.multipleForm.questionImg.length > 0) {
          this.multipleForm.questionImg.forEach(item => {
            item.url = this.imgBaseUrl + item.pictureUrl
            item.name = item.pictureUrl
          })
        }
        this.multipleAnswer = res.data.correctAnswer.split(',')
        this.multipleAnswerList = res.data.questionAnswerVoList
        if (this.multipleAnswerList && this.multipleAnswerList.length > 0) {
          this.multipleAnswerList.forEach(item => {
            item.label = item.options
            item.value = this.$set(item, 'value', item.answerOptions)
            item.img = item.questionPictureVoList
            item.img.forEach(item => {
              item.url = this.imgBaseUrl + item.pictureUrl
              item.name = item.pictureUrl
            })
          })
        }
      } else if (res.data.questionType == 3) {
        this.active = 3
        this.analysis3 = res.data.analysis
        this.judgeForm.question = res.data.content
        this.judgeForm.questionImg = res.data.questionPictureVoList
        if (this.judgeForm.questionImg && this.judgeForm.questionImg.length > 0) {
          this.judgeForm.questionImg.forEach(item => {
            item.url = this.imgBaseUrl + item.pictureUrl
            item.name = item.pictureUrl
          })
        }
        this.judgeAnswer = res.data.correctAnswer
      }
    },
    // tab切换
    handleTab(index) {
      this.active = index
      console.log('🚀 ~ handleTab ~ this.active:', this.active)
    },
    // 删除答案选项
    handleDelete(item) {
      console.log('🚀 ~ handleDelete ~ item:', item)
      if (this.active === 1) {
        const index = this.answerList.findIndex(v => v.label === item.label)
        this.answerList.splice(index, 1)
        // 重新设置label
        this.answerList.forEach((v, i) => {
          v.label = String.fromCharCode(65 + i)
        })
      } else if (this.active === 2) {
        const index = this.multipleAnswerList.findIndex(v => v.label === item.label)
        this.multipleAnswerList.splice(index, 1)
        // 重新设置label
        this.multipleAnswerList.forEach((v, i) => {
          v.label = String.fromCharCode(65 + i)
        })
      }
      if (item.answerId) {
        this.delAnswerIds.push(item.answerId)
      }
    },
    // 添加选项
    handleAddAnswer() {
      let label = ''
      if (this.active === 1) {
        label = String.fromCharCode(65 + this.answerList.length)
        this.answerList.push({ label, value: '', img: [] })
      } else if (this.active === 2) {
        label = String.fromCharCode(65 + this.multipleAnswerList.length)
        this.multipleAnswerList.push({ label, value: '', img: [] })
      }
    },
    // 添加标签
    handleAddTag() {
      getLabels().then(res => {
        console.log('🚀 ~ res:', res)
        console.log('🚀 ~ .selectedTag-已选标签:', this.selectedTag)
        this.tagVisible = true
        this.tagList = res.data.map(item => ({ labelName: item.labelName, labelId: item.labelId }))
        this.tagList.forEach(tag => {
          this.$refs.multipleTable.toggleRowSelection(tag, true)
          if (item.labelId === tag.labelId) {
          }
        })
        this.setDefaultSelection()
      })
    },
    // 发布并继续新建
    handleConfirm(type) {
      console.log('发布并继续新建', this.active, type)
      // 校验题目是否为空
      if (this.active === 1 && this.radioForm.question === '') {
        this.$message.error('请输入题目')
        return
      } else if (this.active === 2 && this.multipleForm.question === '') {
        this.$message.error('请输入题目')
        return
      } else if (this.active === 3 && this.judgeForm.question === '') {
        this.$message.error('请输入题目')
        return
      } else if (this.active === 4 && this.shortAnswerForm.question === '') {
        this.$message.error('请输入题目')
        return
      }
      // 多选题 至少两个选项
      if (this.active === 2 && this.multipleAnswer.length < 2) {
        this.$message.error('至少选择两个答案选项')
        return
      }
      let params = {
        questionsLibraryId: this.questionsLibraryId, // 题库id
        content: '', // 题目
        correctAnswer: '', // 正确答案
        analysis: '', // 解析
        questionType: this.active, // 题型
        isSelfBuild: this.isNewExam ? 1 : 0, // 是否自建
        labelIds: this.radioTag.map(item => item.labelId),
        questionAnswerVoList: [],
      }
      if (this.questionId) {
        params.questionId = this.questionId
        params.delAnswerIds = this.delAnswerIds
        params.delPictureIds = this.delPictureIds
      }
      let formData = new FormData()
      // type: 1单选题;2多选题;3判断题;4简答题
      if (this.active === 1) {
        formData.append('type', 1)
        // 将题目图片添加到file[]第一个
        this.radioForm.questionImg.forEach(item => {
          console.log('🚀 ~ handleConfirm ~ item:', item)
          if (!item.pictureId) {
            // 检查是否有 formData.中是否有 'topic' 这个key, 有就不添加, 没有就添加
            formData.append('type[]', 'topic')
            formData.append('file[]', item.raw)
          }
        })
        // 根据 answerList 往formData.append('type[]', 'topic')后面追加
        this.answerList.forEach((item, index) => {
          console.log('🚀 ~ handleConfirm ~ item:', item)
          if (item.img && item.img.length > 0) {
            item.img.forEach(img => {
              if (!img.pictureId) {
                formData.append('type[]', item.label)
                formData.append('file[]', img.raw)
              }
            })
          }
        })
        // 题目
        params.content = this.radioForm.question
        // 正确答案
        params.correctAnswer = this.radioAnswer
        params.analysis = this.analysis // 解析
        // 答案选项
        params.questionAnswerVoList = this.answerList.map(item => ({
          answerId: item.answerId,
          options: item.label,
          answerOptions: item.value,
        }))
        console.log('🚀 ~ handleConfirm ~ params:', params)
        formData.append('params', JSON.stringify(params))

        // 打印formData
        for (let value of formData.values()) {
          console.log('🚀 ~ value:', value)
        }

        // 未选择标签不能提交-提示
        // if (this.radioTag.length === 0) {
        //   this.$message.error('请选择标签')
        //   return
        // }

        // 发送请求
        if (this.questionId) {
          editTopic(formData).then(res => {
            console.log('🚀 ~ editTopic ~ res:', res)
            if (res.code === 200) {
              // 提示
              this.$message.success('发布成功')
              this.$emit('getList')
              if (type == 1) {
                this.dialogVisible = false
              } else {
                this.reset()
              }
            }
          })
        } else {
          if (this.isNewExam) {
            addTopicByTask(formData).then(res => {
              console.log('🚀 ~ addTopic ~ res:', res)
              if (res.code === 200) {
                // 提示
                this.$message.success('发布成功')
                this.$emit('getList', res.data)
                if (type == 1) {
                  this.dialogVisible = false
                } else {
                  this.reset()
                }
              }
            })
          } else {
            addTopic(formData).then(res => {
              console.log('🚀 ~ addTopic ~ res:', res)
              if (res.code === 200) {
                // 提示
                this.$message.success('发布成功')
                this.$emit('getList')
                if (type == 1) {
                  this.dialogVisible = false
                } else {
                  this.reset()
                }
              }
            })
          }
        }
      } else if (this.active === 2) {
        formData.append('type', 2)
        // 将题目图片添加到file[]第一个
        this.multipleForm.questionImg.forEach(item => {
          if (!item.pictureId) {
            formData.append('type[]', 'topic')
            formData.append('file[]', item.raw)
          }
        })
        // 根据 multipleAnswerList 往formData.append('type[]', 'topic')后面追加
        this.multipleAnswerList.forEach((item, index) => {
          // console.log('🚀 ~ handleConfirm ~ item:', item)
          if (item.img && item.img.length > 0) {
            item.img.forEach(img => {
              if (!img.pictureId) {
                formData.append('type[]', item.label)
                formData.append('file[]', img.raw)
              }
            })
          }
        })
        // 题目
        params.content = this.multipleForm.question
        // 正确答案
        this.multipleAnswer.sort()
        params.correctAnswer = this.multipleAnswer.join(',')
        params.analysis = this.analysis2 // 解析
        // 答案选项
        params.questionAnswerVoList = this.multipleAnswerList.map(item => ({
          answerId: item.answerId,
          options: item.label,
          answerOptions: item.value,
        }))
        console.log('🚀 ~ handleConfirm ~ params:', params)
        formData.append('params', JSON.stringify(params))

        // 打印formData
        // for (let value of formData.values()) {
        //   console.log('🚀 ~ value:', value)
        // }
        // 多选题-未选择答案不能提交-提示
        if (this.multipleAnswer.length === 0) {
          this.$message.error('请选择正确答案')
          return
        } else {
          // 发送请求
          if (this.questionId) {
            editTopic(formData).then(res => {
              if (res.code === 200) {
                // 提示
                this.$message.success('发布成功')
                this.$emit('getList')
                if (type == 1) {
                  this.dialogVisible = false
                } else {
                  this.reset()
                }
              }
            })
          } else {
            if (this.isNewExam) {
              addTopicByTask(formData).then(res => {
                console.log('🚀 ~ addTopic ~ res:', res)
                if (res.code === 200) {
                  // 提示
                  this.$message.success('发布成功')
                  this.$emit('getList', res.data)
                  if (type == 1) {
                    this.dialogVisible = false
                  } else {
                    this.reset()
                  }
                }
              })
            } else {
              addTopic(formData).then(res => {
                console.log('🚀 ~ addTopic ~ res:', res)
                if (res.code === 200) {
                  // 提示
                  this.$message.success('发布成功')
                  this.$emit('getList')
                  if (type == 1) {
                    this.dialogVisible = false
                  } else {
                    this.reset()
                  }
                }
              })
            }
          }
        }
      } else if (this.active === 3) {
        formData.append('type', 3)
        this.judgeForm.questionImg.forEach(item => {
          if (!item.pictureId) {
            formData.append('type[]', 'topic')
            formData.append('file[]', item.raw)
          }
        })
        // 题目
        params.content = this.judgeForm.question
        // 正确答案
        params.correctAnswer = this.judgeAnswer
        params.analysis = this.analysis3 // 解析
        // 答案选项
        params.questionAnswerVoList = this.judgeAnswerList.map(item => ({
          answerId: item.answerId,
          options: item.label,
          answerOptions: item.value,
        }))
        console.log('🚀 ~ handleConfirm ~ params:', params)
        formData.append('params', JSON.stringify(params))

        // 发送请求
        if (this.questionId) {
          editTopic(formData).then(res => {
            if (res.code === 200) {
              // 提示
              this.$message.success('发布成功')
              this.$emit('getList')
              if (type == 1) {
                this.dialogVisible = false
              } else {
                this.reset()
              }
            }
          })
        } else {
          if (this.isNewExam) {
            addTopicByTask(formData).then(res => {
              console.log('🚀 ~ addTopic ~ res:', res)
              if (res.code === 200) {
                // 提示
                this.$message.success('发布成功')
                this.$emit('getList', res.data)
                if (type == 1) {
                  this.dialogVisible = false
                } else {
                  this.reset()
                }
              }
            })
          } else {
            addTopic(formData).then(res => {
              console.log('🚀 ~ addTopic ~ res:', res)
              if (res.code === 200) {
                // 提示
                this.$message.success('发布成功')
                this.$emit('getList')
                if (type == 1) {
                  this.dialogVisible = false
                } else {
                  this.reset()
                }
              }
            })
          }
        }
      } else if (this.active === 4) {
        formData.append('type', 4)
      }
    },
    //
    reset() {
      // 清除解析
      this.analysis = ''
      this.analysis2 = ''
      this.analysis3 = ''
      this.analysis4 = ''
      // 清除标签
      this.radioTag = []
      // 根据active重置对应的表单数据, 不关闭弹框
      if (this.active === 1) {
        this.radioForm = {
          question: '',
          questionImg: [],
        }
        this.answerList = [
          { label: 'A', value: '', img: [] },
          { label: 'B', value: '', img: [] },
          { label: 'C', value: '', img: [] },
          { label: 'D', value: '', img: [] },
        ]
        this.radioAnswer = 'A'
      } else if (this.active === 2) {
        this.multipleForm = {
          question: '',
          questionImg: [],
        }
        this.multipleAnswerList = [
          { label: 'A', value: '', img: [] },
          { label: 'B', value: '', img: [] },
          { label: 'C', value: '', img: [] },
          { label: 'D', value: '', img: [] },
        ]
        this.multipleAnswer = []
      } else if (this.active === 3) {
        this.judgeForm = {
          question: '',
          questionImg: [],
        }
        this.judgeAnswer = 'A'
      } else if (this.active === 4) {
        this.shortAnswerForm = {
          question: '',
          questionImg: [],
        }
        this.shortAnswerAnswer = ''
      }
    },
    // 选择标签
    selectionChange(val) {
      console.log('🚀 ~ val-选择标签:', val)
      // 选择的标签数量不能超过3个, 达到3个后不可选
      if (val.length > 3) {
        this.$message.error('最多选择3个标签')
        return
      }
      this.selectedTag = val
    },
    // tag-确定
    handleTagConfirm() {
      console.log('确定')
      this.radioTag = this.selectedTag
      this.tagVisible = false
    },
    // tag-关闭
    handleClose(tag) {
      console.log('关闭', tag)
      const index = this.radioTag.findIndex(v => v.labelId === tag.labelId)
      this.radioTag.splice(index, 1)
    },
    // 题目图片
    handleImgTopic(val, type, pictureId) {
      console.log('🚀 ~ handleImgTopic ~ pictureId:', pictureId)
      // console.log('🚀 ~ handleImgTopic ~ val:', val, type)
      if (type === 'radio') {
        this.radioForm.questionImg = val
      } else if (type === 'multiple') {
        this.multipleForm.questionImg = val
      } else if (type === 'judge') {
        this.judgeForm.questionImg = val
      } else if (type === 'shortAnswer') {
        this.shortAnswerForm.questionImg = val
      } else if (type.includes('radio')) {
        const index = this.answerList.findIndex(v => v.label === type.slice(5))
        this.answerList[index].img = val
      } else if (type.includes('multiple')) {
        const index = this.multipleAnswerList.findIndex(v => v.label === type.slice(8))
        this.multipleAnswerList[index].img = val
      }
      if (pictureId) {
        this.delPictureIds.push(pictureId)
      }
      console.log('🚀 ~ handleImgTopic ~ this.delPictureIds:', this.delPictureIds)
      // console.log('🚀 ~ handleImgTopic ~ this.radioForm-单选:', this.radioForm)
      // console.log('🚀 ~ handleImgTopic ~ this.answerList-单选:', this.answerList)
      // console.log('🚀 ~ handleImgTopic ~ this.multipleAnswerList-多选:', this.multipleAnswerList)
    },
    setDefaultSelection() {
      console.log('执行了', this.radioTag)
      this.$nextTick(() => {
        console.log('🚀 ~ this.$nextTick ~ this.selectedTag-已选标签:', this.radioTag)
        this.radioTag.forEach(item => {
          this.tagList.forEach(tag => {
            if (item.labelId === tag.labelId) {
              this.$refs.multipleTable.toggleRowSelection(tag, true)
            }
          })
        })
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.tab-wrapper {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  .tab-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    .title {
      font-size: 16px;
      font-weight: bold;
    }
  }
}
.bt-line {
  width: 100%;
  height: 2px;
  background-color: #5a9cf8;
  margin-top: 10px;
}
// 答案-title
.answer-title {
  margin: 20px 40px;
  font-size: 16px;
  font-weight: bold;
}
.analysis {
  margin: 20px 40px;
  font-size: 16px;
  font-weight: bold;
}
.answerList-wrapper {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: 10px 40px;
  .answer-item {
    margin-right: 30px;
    .answer-input {
      width: 300px;
      margin-bottom: 10px;
    }
  }
}
.answer-bg {
  width: 45px;
  height: 45px;
  border-radius: 5px;
  background-color: #b9bfd3;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
}
::v-deep .el-upload--picture-card {
  width: 50px;
  height: 50px;
  font-size: 13px;
  display: flex;
  justify-content: center;
  align-items: center;
}
::v-deep .el-upload--picture-card i {
  font-size: 15px;
}
</style>
