<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="课程" prop="courseId">
        <el-select filterable  v-model="queryParams.courseId" placeholder="请选择课程"  clearable size="small" style="width: 100%" :value-key="'dictValue'">
          <el-option
            v-for="dict in courseList"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table border v-loading="loading" :data="list" @selection-change="handleSelectionChange" ref="videoTable" :row-key="'videoId'" :reserve-selection="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="小节名称" align="center" prop="courseVideoName" />
      <el-table-column label="视频名称" align="center" prop="videoName" />
      <el-table-column label="时长" align="center" prop="duration"/>
    </el-table>

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

    <div class="footer-button">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </div>
</template>

<script>
import { courseList } from '@/api/course/courseRedPacketLog'
import { getChooseCourseVideoList } from '@/api/course/userCourseVideo'

export default {
  name: "ChooseCourseVideoComponent",
  props: {
    videoIds: {
      type: Array,
      default: () => []
    }
  },
  activated() {
    // keep-alive 激活时恢复选中
    this.$nextTick(() => {
      this.restoreSelection()
    })
  },
  watch: {
    // videoIds 变化时重新恢复选中
    videoIds: {
      immediate: false,
      handler() {
        this.$nextTick(() => this.restoreSelection())
      }
    }
  },
  data() {
    return {
      loading: false,
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseId: null
      },
      courseList: [],
      total: 0,
      list: [],
      selected: []
    }
  },
  created() {
    courseList().then(response => {
      this.courseList = response.list;
    });
    this.handleQuery()
  },
  methods: {
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        courseId: null
      }
      this.handleQuery()
    },
    getList() {
      this.loading = true
      getChooseCourseVideoList(this.queryParams).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.loading = false
        // 列表加载后，根据传入的 videoIds 自动选中
        this.$nextTick(() => this.restoreSelection())
      })
    },
    handleSelectionChange(selection) {
      this.selected = selection
    },
    cancel() {
      this.$emit('closeChoose')
    },
    submit() {
      this.$emit('selectConfirm', this.selected)
    },
    // 恢复勾选状态
    restoreSelection() {
      const tableRef = this.$refs.videoTable
      if (!tableRef || !Array.isArray(this.list) || !Array.isArray(this.videoIds)) return
      tableRef.clearSelection()
      if (this.videoIds.length === 0) return
      const idsSet = new Set(this.videoIds)
      this.list.forEach(row => {
        if (row && idsSet.has(row.videoId)) {
          tableRef.toggleRowSelection(row, true)
        }
      })
    }
  }
}
</script>

<style scoped>
.footer-button {
  display: flex;
  justify-content: flex-end;
  margin-top: 40px;
}
</style>
