<template>
  <div class="common-table">
    <el-table
      ref="tableRef"
      :data="currentPageData"
      v-bind="$attrs"
      :resizable="false"
      border
      :height="tableHeight"
    >
      <template v-for="column in columns" :key="column.prop">
        <el-table-column v-bind="column" :align="align">
          <template #default="scope">
            <slot
              :name="column.prop"
              v-bind="scope"
              :row="scope.row"
              :column="column"
            >
              {{ scope.row[column.prop] }}
            </slot>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <div class="pagination-container" v-if="showPagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="pageSizes"
        :total="total"
        layout="total, prev, pager, next, sizes, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :total-text="paginationTexts.total || '总计'"
        :size-change-text="paginationTexts.sizeChange || '条/页'"
        :jumper-text="paginationTexts.jumper || '前往'"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from "vue";

const props = defineProps({
  // 表格数据
  data: {
    type: Array,
    required: true,
    default: () => [],
  },
  // 列配置
  columns: {
    type: Array,
    required: true,
    default: () => [],
  },
  // 是否显示分页
  showPagination: {
    type: Boolean,
    default: true,
  },
  // 分页大小选项
  pageSizes: {
    type: Array,
    default: () => [10, 20, 30, 50],
  },
  // 默认每页条数
  defaultPageSize: {
    type: Number,
    default: 10,
  },
  // 分页器文字配置
  paginationTexts: {
    type: Object,
    default: () => ({
      total: "总计",
      sizeChange: "条/页",
      jumper: "前往",
    }),
  },
  total: {
    type: Number,
    default: 0,
  },
  // 表格最小高度
  minHeight: {
    type: Number,
    default: 300,
  },
  align: {
    type: String,
    default: "left",
  },
});

const emit = defineEmits([
  "update:current-page",
  "update:page-size",
  "pagination-change",
]);

// 表格引用
const tableRef = ref(null);
// 表格容器引用
const tableHeight = ref(props.minHeight);

// 计算表格高度
const calculateTableHeight = () => {
  nextTick(() => {
    if (!tableRef.value) return;
    const parentHeight = tableRef.value.$el.parentElement.offsetHeight;
    const paginationHeight = props.showPagination ? 70 : 0; // 分页器高度 + margin
    const calculatedHeight = parentHeight - paginationHeight;
    tableHeight.value = Math.max(calculatedHeight, props.minHeight);
  });
};

// 监听窗口大小变化
const handleResize = () => {
  calculateTableHeight();
};

onMounted(() => {
  calculateTableHeight();
  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
});

// 监听数据变化重新计算高度
watch(
  () => props.data,
  () => {
    nextTick(calculateTableHeight);
  },
  { deep: true }
);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(props.defaultPageSize);
const total = computed(() => props.total);

// 当前页数据
const currentPageData = computed(() => {
  if (props.showPagination) return props.data;
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return props.data.slice(start, end);
});

// 分页事件处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  emitPaginationChange();
  nextTick(calculateTableHeight);
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  emitPaginationChange();
};

// 向父组件发送分页变化事件
const emitPaginationChange = () => {
  emit("pagination-change", {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    total: total.value,
  });
  emit("update:current-page", currentPage.value);
  emit("update:page-size", pageSize.value);
};

const setCurrentPage = () => {
  currentPage.value = 1;
};

defineExpose({ setCurrentPage })

// 监听数据变化，重置分页
watch(
  () => props.data,
  () => {
    // currentPage.value = 1;
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
.common-table {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  :deep(.el-table) {
    flex: 1;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
    height: 32px; // 固定分页器高度
  }
}
</style>

<style lang="scss">
.el-table__header,
.el-table__body {
  width: 100% !important;
}

.el-table__header th { user-select: none; }

.el-table {
  // 设置表头样式
  th.el-table__cell {
    background-color: #f5f7fa !important;
    color: #606266;
    font-weight: 600;
  }
}
</style>
