<script lang="ts" setup>
import type { TableInstance } from "element-plus";
import type { PropType } from "vue";
interface Emits {
  (e: "expand-change", row: any, expandedRows: any[]): void;
}
const emit = defineEmits<Emits>();
defineProps({
  data: {
    type: Array as PropType<any[]>,
  },
  total: {
    type: Number,
    required: true,
  },
  updatePage: {
    type: Function,
    required: true,
  },
  // 由父组件按实际视口计算的可用高度（px）。传了则优先生效。
  containerHeight: {
    type: Number,
    default: 0,
  },
  // 表头等区域换行导致高度变化时的额外偏移量（px）
  extraOffset: {
    type: Number,
    default: 0,
  },
  // 新增：透传给 el-table 的展开行 key 列表
  expandRowKeys: {
    type: Array as PropType<(string | number)[]>,
    default: () => [],
  },
  // 新增：行数据的唯一标识字段名
  rowKey: {
    type: String,
    default: "id",
  },
});
const page = defineModel<number>("page");
const pageSize = defineModel<number>("pageSize");

// 获取 el-table 实例引用
const tableRef = ref<TableInstance>();

// 暴露方法和属性给父组件
defineExpose({
  tableRef,
  // 封装 toggleRowExpansion 方便调用
  toggleRowExpansion: (row: any, expanded?: boolean) => {
    if (tableRef.value) {
      tableRef.value.toggleRowExpansion(row, expanded);
    }
  },
  // 暴露 sort/change 等其他可能需要的方法
  clearSort: () => tableRef.value?.clearSort(),
  clearFilter: () => tableRef.value?.clearFilter(),
});
</script>
<template>
  <div
    :style="{
      display: 'flex',
      flexDirection: 'column',
      height:
        containerHeight && containerHeight > 0 ? `${containerHeight}px` : `calc(100vh - ${157 + (extraOffset || 0)}px)`,
      overflow: 'hidden',
    }"
  >
    <div style="flex: 1; overflow: hidden">
      <el-table
        ref="tableRef"
        :data="data"
        stripe
        style="width: 100%"
        height="100%"
        :row-key="rowKey"
        :expand-row-keys="expandRowKeys as any"
        @expand-change="(row, expandedRows) => emit('expand-change', row, expandedRows)"
      >
        <slot name="columns"></slot>
      </el-table>
    </div>
    <div style="padding-top: 10px">
      <ElPagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        background
        layout="prev, pager, next, jumper, total, sizes"
        :total="total"
        @update:current-page="() => updatePage()"
        @update:page-size="() => updatePage()"
      />
    </div>
  </div>
</template>

<style scoped>
:deep(.el-table) {
  font-size: 13px;
}

:deep(.el-table th.el-table__cell) {
  font-weight: 600;
  background-color: var(--el-fill-color-light);
}

:deep(.el-pagination) {
  justify-content: flex-end;
}

:deep(.el-pagination.is-background .el-pager li) {
  font-weight: 500;
}

:deep(.el-table__expand-icon) {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  transition: all 0.2s ease;
}

:deep(.el-table__expand-icon:hover) {
  color: var(--el-color-primary);
}

:deep(.el-table__expand-icon--expanded) {
  transform: rotate(90deg);
}
</style>
