<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"
      :selectable="isRowSelectable"
    />
    <el-table-column prop="mainTitle" label="大题名称" width="120" />
    <el-table-column prop="mainNumber" label="大题号" width="80" />
    <el-table-column prop="subNumber" label="小题号" width="80" />
    <el-table-column prop="totalScore" label="满分" width="80" />
    <el-table-column prop="intervalScore" label="间隔分" width="80" />
    <el-table-column prop="selectiveIndex" label="选做题分组" width="100">
      <template #default="scope">
        {{ scope.row.selectiveIndex }}-
        {{ dictFilter.optionalScorePolicy(scope.row.scorePolicy) }}
      </template>
    </el-table-column>
    <el-table-column prop="selectivePart" label="选做题区" width="100">
      <template #default="scope">
        {{ scope.row.selectiveIndex }} - {{ scope.row.selectivePart }}
      </template>
    </el-table-column>
  </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,
    OptionalRulePart,
  } from '@/api/types/subject';
  import useLoading from '@/hooks/loading';
  import { dictFilter } from '@/utils/filter';

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

  interface Props {
    modelValue: number[];
    subjectCode: string;
    currentStep: number;
    selectedParts: OptionalRulePart[];
  }

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

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

  // 获取已被其他步骤选择的试题ID
  const getSelectedQuestionIds = () => {
    const selectedIds: number[] = [];
    props.selectedParts.forEach((part) => {
      selectedIds.push(...part.mainNumbers);
    });
    return selectedIds;
  };

  // 判断行是否可选择
  const isRowSelectable = (row: OptionalQuestionItem) => {
    const alreadySelectedIds = getSelectedQuestionIds();
    return !alreadySelectedIds.includes(row.id);
  };

  // 设置已选中的行，TODO:注意排除被其他选做题方案选中的题
  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.subjectCode) return;

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

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

  // 处理选择变化
  const handleSelectionChange = (selection: OptionalQuestionItem[]) => {
    const selectedIds = selection.map((item) => item.id);
    const alreadySelectedIds = getSelectedQuestionIds();

    // 过滤掉已被其他步骤选择的试题
    const validSelectedIds = selectedIds.filter(
      (id) => !alreadySelectedIds.includes(id)
    );

    emit('update:modelValue', validSelectedIds);
  };

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

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

  defineExpose({
    validate,
  });

  onMounted(() => {
    getList();
  });
</script>
