<template>
  <div class="live-question-bank-container">
    <div class="question-bank-container">
        <div class="question-bank-header">
            <el-button
              type="primary"
              icon="el-icon-plus"
              v-hasPermi="['live:liveQuestionBank:add']"
              @click="handleAdd"
            >添加试题</el-button>
            <div class="actions">
                <el-input
                v-model="queryParams.title"
                @input="handleSearch"
                placeholder="请输入搜索内容"
                style="width: 300px;"
                />
            </div>
        </div>

        <el-table :data="questionBankList" style="width: 100%; margin-top: 20px;" v-loading="loading">
            <el-table-column prop="title" label="题干内容" width="500"></el-table-column>
            <el-table-column label="题型" width="100">
              <template slot-scope="scope">
                {{ formatType(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column prop="createBy" label="创建人"></el-table-column>
            <el-table-column prop="updateTime" label="最后更新时间"></el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
                <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  style="color: #00CC66;"
                  @click="handleEdit(scope.row)"
                >编辑</el-button>
                <el-button
                  type="text"
                  size="small"
                  style="color: #F56C6C;"
                  @click="handleDelete(scope.row)"
                >删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getQuestionBankList"
        />

        <!-- 添加试题弹窗 -->
        <el-dialog
          :title="dialogTitle"
          :visible.sync="dialogVisible"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
        >
          <el-form :model="form" ref="form" :rules="dynamicRules" label-width="80px">
            <el-form-item label="题型" prop="type">
              <el-select v-model="form.type" placeholder="请选择题型" style="width: 100%">
                <el-option
                  v-for="item in questionTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="题干" prop="title">
              <el-input
                type="textarea"
                v-model="form.title"
                placeholder="请输入题干"
                :autosize="{ minRows: 4 }"
              ></el-input>
            </el-form-item>
            <!-- 动态渲染选项 -->
            <el-form-item
              v-for="(option, index) in form.options"
              :key="index"
              :label="`选项${option.label}`"
              :prop="`options.${index}.content`"
            >
              <el-input
                type="textarea"
                v-model="option.content"
                placeholder="请输入选项内容"
                :autosize="{ minRows: 4 }"
              ></el-input>
              <div class="option-helper">
                <el-checkbox
                  v-model="option.isCorrect"
                  @change="() => handleCorrectChange(option)"
                >设为正确答案</el-checkbox>
                <el-link type="primary" style="margin-left: auto;" @click="removeOption(index)">删除</el-link>
              </div>
            </el-form-item>
            <!-- 添加选项按钮 -->
            <el-form-item>
              <el-button type="text" @click="addOption" icon="el-icon-plus">添加选项</el-button>
            </el-form-item>
            <el-form-item label="答案" prop="analysis">
              <el-input
                type="text"
                v-model="form.analysis"
                style="width: 150px"
                disabled
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm">保 存</el-button>
            <el-button
              v-if="!isEdit"
              type="success"
              @click="submitAndContinue"
            >保存并继续添加</el-button>
          </div>
        </el-dialog>
    </div>
  </div>
</template>

<script>
import { listLiveQuestionBank, addLiveQuestionBank, updateLiveQuestionBank, deleteLiveQuestionBank } from '@/api/live/liveQuestionBank'
export default {
  name: 'LiveQuestionBank',
  data() {
    return {
      total: 0,
      loading: true,
      queryParams: {
        title: null,
        pageNum: 1,
        pageSize: 10
      },
      questionBankList: [],
      dialogVisible: false,
      dialogTitle: '添加试题',
      isEdit: false,
      form: {
        id: null,
        title: '',
        type: 1,
        options: [
          { label: 'A', content: '', isCorrect: false },
          { label: 'B', content: '', isCorrect: false },
          { label: 'C', content: '', isCorrect: false },
          { label: 'D', content: '', isCorrect: false }
        ],
        analysis: ''
      },
      questionTypes: [
        { label: '单选题', value: 1 },
        { label: '多选题', value: 2 }
      ]
    }
  },
  computed: {
    dynamicRules() {
      const rules = {
        title: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        type: [{ required: true, message: '请选择题型', trigger: 'change' }],
        analysis: [{ required: true, message: '请设置正确答案', trigger: 'change' }]
      }

      // 动态添加选项验证规则
      this.form.options.forEach((_, index) => {
        rules[`options.${index}.content`] = [{ required: true, message: '请输入选项内容', trigger: 'blur' }]
      })

      return rules
    }
  },
  created() {
    this.getQuestionBankList()
  },
  watch: {
    'form.options': {
      handler(options) {
        const correctLabels = options
          .filter(option => option.isCorrect)
          .map(option => option.label)
          .join(',')
        this.form.analysis = correctLabels
      },
      deep: true
    },
    'form.type'() {
      this.handleTypeChange()
    }
  },
  methods: {
    getQuestionBankList() {
      this.loading = true;
      listLiveQuestionBank(this.queryParams).then(response => {
        this.questionBankList = response.rows
        this.total = response.total;
        this.loading = false;
      })
    },
    handleSearch() {
      this.getQuestionBankList()
    },
    handleAdd() {
      this.dialogTitle = '添加试题'
      this.isEdit = false
      this.dialogVisible = true
      this.resetForm()
    },
    handleEdit(row) {
      this.dialogTitle = '编辑试题'
      this.isEdit = true
      this.dialogVisible = true

      // 先设置基础数据
      this.form.id = row.id
      this.form.title = row.title

      // 先回显选项数据
      let options = JSON.parse(row.content)
      const answerArray = row.answer.split(',')
      this.form.options = options.map(option => ({
        label: option.label,
        content: option.content,
        isCorrect: answerArray.includes(option.label)
      }))

      // 最后设置题型和答案，因为设置题型会触发handleTypeChange
      this.form.type = row.type
      this.form.analysis = row.answer
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          this.$message({
            message: '请检查表单填写是否正确',
            type: 'warning'
          })
          return
        }

        // 验证是否有正确答案
        if (!this.form.analysis) {
          this.$message({
            message: '请设置正确答案',
            type: 'warning'
          })
          return
        }

        // 验证答案数量
        const correctCount = this.form.options.filter(option => option.isCorrect).length
        if (this.form.type === 1 && correctCount !== 1) {
          this.$message({
            message: '单选题必须设置一个正确答案',
            type: 'warning'
          })
          return
        }
        if (this.form.type === 2 && correctCount < 2) {
          this.$message({
            message: '多选题至少需要设置两个正确答案',
            type: 'warning'
          })
          return
        }

        // 构造提交的参数
        let params = {
          id: this.isEdit ? this.form.id : null,
          title: this.form.title,
          type: this.form.type,
          content: JSON.stringify(this.form.options),
          answer: this.form.analysis
        }

        // TODO: 根据isEdit判断调用添加还是更新接口
        if (this.isEdit) {
          // 调用更新接口
          updateLiveQuestionBank(params).then(response => {
            this.msgSuccess("更新成功");
            this.getQuestionBankList();
          })
        } else {
          // 调用添加接口
          addLiveQuestionBank(params).then(response => {
            this.msgSuccess("新增成功");
            this.getQuestionBankList();
          })
        }

        this.dialogVisible = false
        this.resetForm()
      })
    },
    submitAndContinue() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          this.$message({
            message: '请检查表单填写是否正确',
            type: 'warning'
          })
          return
        }

        // 验证是否有正确答案
        if (!this.form.analysis) {
          this.$message({
            message: '请设置正确答案',
            type: 'warning'
          })
          return
        }

        // 验证答案数量
        const correctCount = this.form.options.filter(option => option.isCorrect).length
        if (this.form.type === 1 && correctCount !== 1) {
          this.$message({
            message: '单选题必须设置一个正确答案',
            type: 'warning'
          })
          return
        }
        if (this.form.type === 2 && correctCount < 2) {
          this.$message({
            message: '多选题至少需要设置两个正确答案',
            type: 'warning'
          })
          return
        }

        // 构造提交的参数
        let params = {
          title: this.form.title,
          type: this.form.type,
          content: JSON.stringify(this.form.options),
          answer: this.form.analysis
        }
        // 保存逻辑
        addLiveQuestionBank(params).then(response => {
            this.msgSuccess("新增成功");
            this.getQuestionBankList();
          })
        this.resetForm()
      })
    },
    addOption() {
      if (this.form.options.length >= 6) {
        this.$message({
          message: '最多只能添加6个选项',
          type: 'warning'
        })
        return
      }
      const nextLabel = String.fromCharCode('A'.charCodeAt(0) + this.form.options.length)
      this.form.options.push({
        label: nextLabel,
        content: '',
        isCorrect: false
      })
    },
    removeOption(index) {
      if (this.form.options.length <= 2) {
        this.$message({
          message: '至少需要保持两个选项',
          type: 'warning'
        })
        return
      }
      this.form.options.splice(index, 1)
      // 重新排列选项标签
      this.form.options.forEach((option, idx) => {
        option.label = String.fromCharCode('A'.charCodeAt(0) + idx)
      })
    },
    resetForm() {
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      // 重置表单数据
      this.form = {
        id: null,
        title: '',
        type: 1,
        options: [
          { label: 'A', content: '', isCorrect: false },
          { label: 'B', content: '', isCorrect: false },
          { label: 'C', content: '', isCorrect: false },
          { label: 'D', content: '', isCorrect: false }
        ],
        analysis: ''
      }
      this.isEdit = false
    },
    handleCorrectChange(currentOption) {
      const correctCount = this.form.options.filter(option => option.isCorrect).length

      if (this.form.type === 1) { // 单选题
        // 如果当前选项被选中，则取消其他选项的选中状态
        if (currentOption.isCorrect) {
          this.form.options.forEach(option => {
            if (option !== currentOption) {
              option.isCorrect = false
            }
          })
        }
      } else { // 多选题
        // 如果取消选中会导致正确答案少于2个，阻止操作
        if (!currentOption.isCorrect && correctCount < 2) {
          currentOption.isCorrect = true
          this.$message({
            message: '多选题至少需要2个正确答案',
            type: 'warning'
          })
        }
      }
    },
    handleTypeChange() {
      // 如果是编辑状态，不重置答案
      if (!this.isEdit) {
        // 重置所有选项的正确答案状态
        this.form.options.forEach(option => {
          option.isCorrect = false
        })
        this.form.analysis = ''
      }
    },
    handleDelete(row) {
      this.$confirm('是否确认删除该试题?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteLiveQuestionBank(row.id).then(response => {
          this.msgSuccess("删除成功");
          this.getQuestionBankList();
        })
      }).catch(() => {
        // 取消删除，不做任何操作
      })
    },
    // 添加获取题型值的方法
    getQuestionTypeName(type) {
      const found = this.questionTypes.find(item => item.value === type)
      return found ? found.label : ''
    },

    // 修改表格列的显示
    formatType(row) {
      return this.getQuestionTypeName(row.type)
    }
  }
}
</script>

<style scoped>
.live-question-bank-container {
  padding: 10px 20px;
  height: calc(100vh - 84px); /* 减去头部导航的高度 */
}
.question-bank-container {
    background-color: #fff;
    padding: 10px 20px;
    border-radius: 4px;
    height: 100%;
}

.question-bank-header {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.actions {
  display: flex;
  align-items: center;
}

/* 修改表格行高 */
::v-deep .el-table td {
  padding: 12px 0;
}

/* 修改表格hover颜色 */
::v-deep .el-table tbody tr:hover > td {
  background-color: #F5F7FA;
}

.option-helper {
  display: flex;
  align-items: center;
  margin-top: 8px;
}

/* 修改弹窗样式 */
::v-deep .el-dialog {
  height: 100%;
  margin: 0 !important;
  display: flex;
  flex-direction: column;
}

::v-deep .el-dialog__body {
  flex: 1;
  padding: 30px 40px;
  overflow-y: auto;
  margin-bottom: 80px;  /* 给底部按钮预留空间 */
}

::v-deep .el-dialog__header {
  padding: 20px 40px;
  border-bottom: 1px solid #e4e7ed;
}

::v-deep .el-dialog__footer {
  padding: 20px 40px;
  border-top: 1px solid #e4e7ed;
  position: fixed;
  bottom: 0;
  width: 100%;
  background: #fff;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.12);
  z-index: 1;
}

::v-deep .el-form-item__label {
  font-weight: normal;
}

::v-deep .el-textarea__inner {
  background-color: #fff;
  resize: none;
}

.dialog-footer {
  text-align: center;
  padding-top: 10px;
}
</style>
