<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="
        (row) =>
          props.disabledIds.includes(
            `${row.bigQuestionNo}-${row.smallQuestionNo}`
          )
      "
    />
    <el-table-column prop="bigQuestionNo" label="大题号" width="80" />
    <el-table-column prop="smallQuestionNo" label="小题号" width="80" />
    <el-table-column prop="bigQuestionName" label="名称" min-width="120" />
    <el-table-column prop="bigQuestionNickname" label="昵称" min-width="120" />
    <el-table-column prop="fullScore" label="分数" width="80" />
    <el-table-column prop="optional" 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, onMounted, nextTick } from 'vue';
  import { ElMessage } from 'element-plus';
  import { getOptionalQuestionList } from '@/api/subject';
  import type { OptionalQuestionItem } from '@/api/types/subject';
  import type { MarkGroupUpdateParams } from '@/api/types/mark';

  import useLoading from '@/hooks/loading';

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

  interface Props {
    modelValue: MarkGroupUpdateParams['questions'];
    subjectCode: string;
    disabledIds: string[];
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: [],
    subjectCode: null,
    disabledIds: () => [],
  });

  const emit = defineEmits<{
    'update:modelValue': [value: MarkGroupUpdateParams['questions']];
  }>();

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

  // 设置已选中的行
  const setSelectedRows = () => {
    if (!tableRef.value || !props.modelValue.length) return;
    const selectedIds = props.modelValue.map(
      (item) => `${item.bigQuestionNo}-${item.smallQuestionNo}`
    );

    dataList.value.forEach((row) => {
      if (selectedIds.includes(`${row.bigQuestionNo}-${row.smallQuestionNo}`)) {
        tableRef.value.toggleRowSelection(row, true);
      }
    });
  };

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

    setLoading(true);
    try {
      // TODO:就当是获取选做题试题列表吧，后面依据实际情况修改
      const res = await getOptionalQuestionList(props.subjectCode);
      dataList.value = res || [];

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

  // 处理选择变化
  const handleSelectionChange = (selection: OptionalQuestionItem[]) => {
    const selectedQuestions = selection.map((item) => {
      return {
        bigQuestionNo: item.bigQuestionNo,
        smallQuestionNo: item.smallQuestionNo,
        intervalScore: item.intervalScore,
        arbitrationThreshold: item.arbitrationThreshold,
      };
    });
    emit('update:modelValue', selectedQuestions);
  };

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

  defineExpose({
    validate,
  });

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