<template>
  <div class="container-md">
    <div class="tip-box">
      为本直播间选择<strong>课程题库</strong>中的试题（也可先在题库中手动新增题目，再回到此处勾选添加）。
<!--      <el-link-->
<!--        type="primary"-->
<!--        style="margin-left: 5px;"-->
<!--        @click="handleToCourseQuestionBank"-->
<!--      >打开课程题库 &gt;&gt;</el-link>-->
    </div>

    <el-button type="primary" icon="el-icon-plus" style="margin: 20px 0;" @click="handleAddQuestion">添加试题</el-button>
    <el-table
      :data="questionLiveList"
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column
        prop="title"
        label="题干"
        show-overflow-tooltip
      />
      <el-table-column
        prop="type"
        label="题型"
        width="100"
      >
        <template slot-scope="scope">
          {{ scope.row.type === 1 ? '单选题' : scope.row.type === 2 ? '多选题' : '—' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="170"
      />
      <el-table-column
        label="操作"
        width="280"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="handleStartQuiz(scope.row)"
          >开始答题</el-button>
          <el-button
            type="text"
            size="small"
            @click="handleCloseQuiz(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="questionTotal > 0"
      :total="questionTotal"
      :page.sync="questionParams.pageNum"
      :limit.sync="questionParams.pageSize"
      @pagination="getLiveQuestionLiveList"
      style="margin-top: 20px;"
    />

    <el-dialog
      title="添加试题"
      :visible.sync="questionDialogVisible"
      width="860px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @open="onAddDialogOpen"
      @closed="onAddDialogClosed"
    >
      <el-tabs v-model="addQuestionTab">
        <el-tab-pane label="从课程题库选择" name="bank">
          <div class="dialog-toolbar">
            <el-input
              v-model="searchTitle"
              placeholder="题干关键词"
              clearable
              size="small"
              style="width: 220px; margin-right: 12px;"
              @keyup.enter.native="handleQuestionSearch"
            />
            <el-select
              v-model="optionTypeFilter"
              placeholder="题型"
              clearable
              size="small"
              style="width: 120px; margin-right: 12px;"
            >
              <el-option label="单选题" :value="1" />
              <el-option label="多选题" :value="2" />
            </el-select>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuestionSearch">搜索</el-button>
          </div>

          <el-table
            ref="questionTable"
            :data="questionList"
            style="width: 100%"
            v-loading="questionLoading"
            @selection-change="handleSelectionChange"
            @row-click="handleRowClick"
            row-key="id"
            max-height="420"
          >
            <el-table-column type="selection" width="50" align="center" reserve-selection />
            <el-table-column prop="title" label="题干" min-width="200" show-overflow-tooltip class-name="clickable-column" />
            <el-table-column prop="type" label="题型" width="90" class-name="clickable-column">
              <template slot-scope="scope">
                {{ scope.row.type === 1 ? '单选' : scope.row.type === 2 ? '多选' : '—' }}
              </template>
            </el-table-column>
            <el-table-column prop="createBy" label="创建人" width="100" show-overflow-tooltip class-name="clickable-column" />
            <el-table-column prop="createTime" label="创建时间" width="160" class-name="clickable-column" />
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getQuestionList"
            style="margin-top: 16px;"
          />
        </el-tab-pane>
        <el-tab-pane label="手动维护题库" name="manual">
          <el-alert
            title="自定义题目请先在「课程题库」中新增或编辑；保存后回到本页「从课程题库选择」勾选添加。"
            type="info"
            :closable="false"
            show-icon
            style="margin-bottom: 16px;"
          />
          <el-button type="primary" plain icon="el-icon-document" @click="handleToCourseQuestionBank">前往课程题库</el-button>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer" v-show="addQuestionTab === 'bank'">
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span class="selected-count">当前已选择 <span class="num">{{ selectedQuestions.length }}</span> 题（题目来自课程题库）</span>
          <div>
            <el-button @click="questionDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmAddQuestion">确 定</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addLiveQuestionLive,
  listLiveQuestionLive,
  listLiveQuestionOptionList,
  deleteLiveQuestionLive
} from '@/api/live/liveQuestionLive'

export default {
  name: 'LiveConfigAnswer',
  data() {
    return {
      addQuestionTab: 'bank',
      questionDialogVisible: false,
      questionLoading: false,
      questionTotal: 0,
      selectedQuestions: [],
      questionLiveList: [],
      questionList: [],
      loading: true,
      searchTitle: '',
      optionTypeFilter: null,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        type: null,
        liveId: null
      },
      questionParams: {
        pageNum: 1,
        pageSize: 10,
        liveId: null
      }
    }
  },
  created() {
    this.liveId = this.$route.params.liveId
    this.queryParams.liveId = this.liveId
    this.questionParams.liveId = this.liveId
    this.getLiveQuestionLiveList()
  },
  computed: {
    userId() {
      return this.$store.state.user.user.userId
    }
  },
  methods: {
    sendLiveQuizCmd(cmd, data) {
      const conn = this.$store.state.liveWs[this.liveId]
      if (!conn || !conn.ws || conn.ws.readyState !== WebSocket.OPEN) {
        this.$message.warning('直播 WebSocket 未连接，请从直播配置页进入并保持本页不刷新')
        return false
      }
      const payload = {
        cmd,
        liveId: Number(this.liveId),
        userId: this.userId,
        data: JSON.stringify(data || {})
      }
      conn.send(JSON.stringify(payload))
      return true
    },
    handleStartQuiz(row) {
      if (!row || row.id == null) {
        return
      }
      if (this.sendLiveQuizCmd('liveQuizStart', { relId: row.id })) {
        this.$message.success('已向直播间广播本题')
      }
    },
    handleCloseQuiz(row) {
      const data = row && row.id != null ? { relId: row.id } : {}
      if (this.sendLiveQuizCmd('liveQuizClose', data)) {
        this.$message.success('已广播结束答题')
      }
    },
    onAddDialogOpen() {
      this.addQuestionTab = 'bank'
      this.searchTitle = ''
      this.optionTypeFilter = null
      this.queryParams.pageNum = 1
      this.queryParams.title = null
      this.queryParams.type = null
      this.getQuestionList()
    },
    onAddDialogClosed() {
      this.selectedQuestions = []
      this.$nextTick(() => {
        const t = this.$refs.questionTable
        if (t && typeof t.clearSelection === 'function') {
          t.clearSelection()
        }
      })
    },
    handleQuestionSearch() {
      this.queryParams.pageNum = 1
      this.queryParams.title = this.searchTitle || null
      this.queryParams.type = this.optionTypeFilter
      this.getQuestionList()
    },
    getLiveQuestionLiveList() {
      this.loading = true
      listLiveQuestionLive(this.questionParams).then(response => {
        this.questionLiveList = response.rows || []
        this.questionTotal = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleToCourseQuestionBank() {
      this.$router.push('/course/courseQuestionBank')
    },
    handleAddQuestion() {
      this.questionDialogVisible = true
    },
    getQuestionList() {
      this.questionLoading = true
      const params = {
        ...this.queryParams,
        liveId: this.liveId
      }
      listLiveQuestionOptionList(params).then(response => {
        this.questionList = response.rows || []
        this.total = response.total || 0
        this.questionLoading = false
        this.$nextTick(() => this.syncTableSelection())
      }).catch(() => {
        this.questionLoading = false
      })
    },
    syncTableSelection() {
      const table = this.$refs.questionTable
      if (!table || !this.questionList.length) return
      const selectedIds = new Set(this.selectedQuestions.map(l => l.id))
      this.questionList.forEach(row => {
        table.toggleRowSelection(row, selectedIds.has(row.id))
      })
    },
    handleSelectionChange(selection) {
      const sel = selection || []
      const currentIds = new Set(this.questionList.map(r => r.id))
      const fromOtherPages = this.selectedQuestions.filter(q => !currentIds.has(q.id))
      const merged = [...fromOtherPages, ...sel]
      if (merged.length > 15) {
        this.$message.warning('最多一次添加 15 题')
        this.$nextTick(() => this.syncTableSelection())
        return
      }
      this.selectedQuestions = merged
    },
    confirmAddQuestion() {
      if (this.selectedQuestions.length === 0) {
        this.$message.warning('请选择要添加的试题')
        return
      }
      addLiveQuestionLive({
        liveId: this.liveId,
        questionIds: this.selectedQuestions.map(item => item.id).join(',')
      }).then(() => {
        this.$message.success('添加成功')
        this.questionDialogVisible = false
        this.getLiveQuestionLiveList()
      })
    },
    handleDelete(row) {
      if (!row || row.id == null) return
      this.$confirm('确认从本直播间移除该试题？（不会删除课程题库中的题目）', '提示', {
        type: 'warning'
      }).then(() => {
        return deleteLiveQuestionLive({ liveId: this.liveId, ids: String(row.id) })
      }).then(() => {
        this.$message.success('已移除')
        this.getLiveQuestionLiveList()
      }).catch(() => {})
    },
    handleRowClick(row, column, event) {
      if (column && column.type === 'selection') {
        return
      }
      const table = this.$refs.questionTable
      if (!table) {
        return
      }
      const isSelected = this.selectedQuestions.some(item => item.id === row.id)
      table.toggleRowSelection(row, !isSelected)
    }
  }
}
</script>

<style scoped>
.tip-box {
  line-height: 1.6;
  color: #606266;
}
.dialog-toolbar {
  margin-bottom: 12px;
}
.selected-count {
  font-size: 13px;
  color: #606266;
}
.selected-count .num {
  color: #409eff;
  font-style: italic;
  font-weight: 600;
}
</style>
