<template>
  <div class="otr-simple-table-workspace">
    <el-card shadow="never">
      <template #header>
        <div class="table-header">
          <span>{{ title }}</span>
          <slot name="header-extra" />
        </div>
      </template>

      <el-form :inline="true" class="filter-form" @submit.prevent>
        <el-form-item label="关键词">
          <el-input v-model="query.keyword" clearable :placeholder="keywordPlaceholder" @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="rows" border stripe>
        <el-table-column
          v-for="col in columns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :min-width="col.minWidth || 120"
          :width="col.width"
          show-overflow-tooltip
        />
      </el-table>

      <div class="pager">
        <el-pagination
          v-model:current-page="query.page"
          v-model:page-size="query.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="loadList"
          @current-change="loadList"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'

type TableColumn = { prop: string; label: string; minWidth?: number; width?: number }

const props = withDefaults(
  defineProps<{
    title: string
    keywordPlaceholder?: string
    columns: TableColumn[]
    fetcher: (params: Record<string, any>) => Promise<any>
  }>(),
  {
    keywordPlaceholder: '请输入关键词',
  },
)

const loading = ref(false)
const total = ref(0)
const rows = ref<any[]>([])
const query = reactive({
  page: 1,
  pageSize: 10,
  keyword: '',
})

async function loadList() {
  loading.value = true
  try {
    const res: any = await props.fetcher({ ...query })
    const result = res?.result ?? {}
    rows.value = result.records ?? result.list ?? []
    total.value = Number(result.total ?? rows.value.length ?? 0)
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  query.page = 1
  loadList()
}

function reset() {
  query.page = 1
  query.pageSize = 10
  query.keyword = ''
  loadList()
}

onMounted(() => {
  loadList()
})
</script>

<style scoped lang="scss">
.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.filter-form {
  margin-bottom: 8px;
}
.pager {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}
</style>
