<template>
  <div>
    <el-table ref="tableRef" :data="filteredData" height="100%" border v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" :selectable="selectable"></el-table-column>
      <el-table-column label="方向名称" prop="name">
        <template #header>
          <el-input v-model="tempKeyword" placeholder="搜索专业" prefix-icon="Search" clearable @clear="handleQuery" @keyup.enter="handleQuery" />
        </template>
        <template #default="scope">
          <div class="flex items-center gap-x-2">
            <span class="font-bold">{{ scope.row.name }}</span>
            <span class="text-[#999] text-[12px]">{{ scope.row.ancestors }}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script setup>
import { getUniversityMajorList } from '@/api/front/university';
import { nextTick } from 'vue';
const props = defineProps({
  universityId: {
    type: Number,
    default: null,
  },
  expanded: {
    type: Boolean,
    default: false,
  },
  selection: {
    type: Array,
    default: () => [],
  }
});

const data = ref([]);
const selectedRows = ref([]);
const tableRef = ref(null);
const filteredData = computed(() => {
  return data.value.filter(item => item.name.includes(keyword.value));
});
const keyword = ref('');
const tempKeyword = ref('');
const loading = ref(false);

const selectable = (row) => {
  if (props.selection.length < 3) {
    return true;
  }
  const hasSelected = selectedRows.value.map(item => item.id).includes(row.id);
  return hasSelected;
}

const emit = defineEmits(['selection-change']);
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
  emit('selection-change', selection);
}
const handleQuery = () => {
  keyword.value = tempKeyword.value;
}
const getList = () => {
  loading.value = true;
  getUniversityMajorList({
    universityId: props.universityId,
  }).then(res => {
    data.value = res.data;
    nextTick(() => {
      // 恢复选中状态：根据 props.selection 中的 id 找到对应的 row 并选中
      props.selection.forEach(selectedItem => {
        const row = data.value.find(dataItem => dataItem.id === selectedItem.majorId);
        if (row) {
          tableRef.value.toggleRowSelection(row, true);
        }
      });
    });
  }).finally(() => {
    loading.value = false;
  });
}


watch(() => props.expanded, (newVal) => {
  if (newVal && data.value.length === 0) {
    getList();
  }
});
</script>
<style lang="scss" scoped>
:deep(.el-table__header) {
  .el-checkbox {
    display: none;
  }
}
</style>