<template>
  <el-table
    ref="tableRef"
    v-loading="loading"
    :data="dataList"
    class="question-table"
    border
    stripe
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column prop="bigQuestionName" label="大题名称" width="120" />
    <el-table-column prop="bigQuestionNo" label="大题号" width="80" />
    <el-table-column prop="smallQuestionNo" label="小题号" width="80" />
    <el-table-column prop="fullScore" label="满分" width="80" />
    <el-table-column prop="intervalScore" label="间隔分" width="80" />
    <el-table-column
      prop="optionalQuestionGroup"
      label="选做题分组"
      width="100"
    />
    <el-table-column prop="optionalQuestionArea" label="选做题区" width="100" />
  </el-table>
</template>

<script setup lang="ts">
  import { ref, watch, onMounted, nextTick } from 'vue';
  import { ElMessage } from 'element-plus';
  import { getOptionalQuestionList } from '@/api/subject';
  import type { OptionalQuestionItem } from '@/api/types/subject';
  import useLoading from '@/hooks/loading';

  defineOptions({
    name: 'OptionalQuestionSelect',
  });

  interface Props {
    modelValue: number[];
    subjectId: number;
  }

  const props = defineProps<Props>();
  const emit = defineEmits<{
    'update:modelValue': [value: number[]];
  }>();

  const tableRef = ref();
  const dataList = ref<OptionalQuestionItem[]>([]);
  const { loading, setLoading } = useLoading();

  // 设置已选中的行
  const setSelectedRows = () => {
    if (!tableRef.value || !props.modelValue.length) return;

    dataList.value.forEach((row) => {
      if (props.modelValue.includes(row.id)) {
        tableRef.value.toggleRowSelection(row, true);
      }
    });
  };

  // 获取试题列表
  const getList = async () => {
    if (!props.subjectId) return;

    setLoading(true);
    try {
      const res = await getOptionalQuestionList(props.subjectId);
      dataList.value = res || [];

      // 设置已选中的项
      await nextTick();
      setSelectedRows();
    } catch (error) {
      dataList.value = [];
    } finally {
      setLoading(false);
    }
  };

  // 处理选择变化
  const handleSelectionChange = (selection: OptionalQuestionItem[]) => {
    const selectedIds = selection.map((item) => item.id);
    emit('update:modelValue', selectedIds);
  };

  // 监听父组件数据变化
  watch(
    () => props.modelValue,
    () => {
      nextTick(() => {
        setSelectedRows();
      });
    },
    { deep: true }
  );

  // 暴露验证方法
  const validate = () => {
    if (props.modelValue.length === 0) {
      ElMessage.warning('请至少选择一个试题');
      return Promise.reject(new Error('请至少选择一个试题'));
    }
    return Promise.resolve(true);
  };

  defineExpose({
    validate,
  });

  onMounted(() => {
    if (props.subjectId) {
      getList();
    }
  });
</script>
