<!--
 * @Author: xiejiang
 * @Date: 2024-11-07 11:19:31
 * @LastEditors: xiejiang
 * @LastEditTime: 2024-12-11 22:37:22
 * @Description: 表格页面容器组件
-->
<template>
  <div class="h-full flex flex-col">
    <!-- 筛选区域 -->
    <PageFilters
      :filter-conditions="props.filterConditions"
      v-bind="filtersProps"
      @on-filter="handleSeach"
      @on-search="onSeachChange"
      @clear="handleClear"
    />
    <div class="mt-[12px] p-[12px] bg-white flex-1 max-h-[calc(100%-64px)] overflow-auto">
      <!-- 表格头部操作区 -->
      <div class="flex justify-between items-center">
        <div class="header-left">
          <slot name="header-left"></slot>
        </div>
        <div class="header-right">
          <div class="flex items-center justify-end gap-2">
            <t-button v-if="props.showSetting" variant="outline" @click="columnControllerVisible = true">
              <template #icon><SettingIcon /></template>列配置
            </t-button>
            <slot name="header-right"></slot>
          </div>
        </div>
      </div>

      <!-- 表格内容区 -->
      <div class="mt-[12px]">
        <t-table
          :row-key="rowKey"
          v-bind="tableProps"
          v-model:column-controller-visible="columnControllerVisible"
          :data="tableData"
          :columns="columns"
          :loading="loading"
          :max-height="tableMaxheight"
          :column-controller="columnControllerConfig"
          :pagination="computedPagination"
          @filter-change="onFilterChange"
          @page-change="onPageChange"
          @sort-change="onSortChange"
        >
          <!-- 为每一列创建动态插槽 -->
          <template v-for="col in columns" :key="col.colKey" #[soltName(col)]="{ row }">
            <template v-if="col.colKey != 'operation'">
              <t-tooltip
                :content="row[col.colKey as string]"
                placement="top"
                theme="light"
                overlay-class-name="custom-tooltip"
              >
                <div class="cell-content">{{ row[col.colKey as string] || '-' }}</div>
              </t-tooltip>
            </template>
          </template>
          <!-- 保留自定义列插槽 -->
          <template v-for="[name] in Object.entries($slots)" #[name]="scope">
            <slot :name="name" v-bind="scope" />
          </template>
        </t-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx">
import { PrimaryTableCol, TableProps } from 'tdesign-vue-next'
import { PageContainerProps, Pagination } from './interface'
import PageFilters from '../PageFilters/index.vue'
import { filterItemProp } from '../PageFilters/interface'
import { soltName } from '@/utils'

defineOptions({ name: 'PageContainer' })

// 组件 props
const props = withDefaults(
  defineProps<
    PageContainerProps & {
      rowKey?: string
      stripe?: boolean
      tableMaxheight?: string
      tableData?: any[] // 表格数据
      columns?: PrimaryTableCol[] // 表格列配置
      loading?: boolean // 加载状态
      tableProps?: Partial<TableProps> // t-table 原生属性
      filtersProps?: Record<string, any> // filters 原生属性
    }
  >(),
  {
    rowKey: 'id',
    filterConditions: () => [] as filterItemProp[],
    showTableHeader: true,
    showPagination: true,
    showSetting: false,
    stripe: true,
    loading: false,
    tableMaxheight: '550px',
    pageSizes: () => [10, 15, 30, 100],
    pagination: () => ({ page: 1, limit: 10, total: 0 }),
    tableData: () => [],
    columns: () => [],
    tableProps: () => ({ hover: true, resizable: true }),
    filtersProps: () => ({})
  }
)

// 组件事件
const emit = defineEmits<{
  'update:pagination': [pagination: Pagination]
  'filter-change': [filters: Record<string, any>]
  'search-change': [params: Record<string, any>]
  'sort-change': [sort: Record<string, any>]
  'page-change': [pageInfo: Pagination]
  clear: []
  change: [changeParams: any]
  'on-search': [params: Record<string, any>]
}>()

// 清空
const handleClear = () => {
  emit('clear')
}

// 列配置项
const columnControllerVisible = ref(false)
const columnControllerConfig = computed<TableProps['columnController']>(() => ({
  hideTriggerButton: true,
  placement: 'top-right',
  dialogProps: { preventScrollThrough: true },
  fields: props.columns.map(item => item.colKey) as string[],
  ...props.tableProps?.columnController
}))

// 使用计算属性替代
const computedPagination = computed(() => ({
  showJumper: true,
  pageSizeOptions: props.pageSizes,
  ...props.pagination
}))

// 分开管理筛选状态
const filterValue = ref<Record<string, any>>({}) // 表格列筛选
const searchValue = ref<Record<string, any>>({}) // 搜索条件

// 处理表格列筛选变化
const onFilterChange = (filters: any) => {
  filterValue.value = filters
  emit('filter-change', filters)
}

// 处理搜索条件变化
const handleSeach = (params: Record<string, any>) => {
  searchValue.value = params
  emit('search-change', params)
}

// 处理搜索条件不调用接口
const onSeachChange = (params: Record<string, any>) => {
  searchValue.value = params
  emit('on-search', params)
}

// 处理排序变化
const onSortChange: TableProps['onSortChange'] = val => {
  emit('sort-change', val)
}

// 处理分页变化
const onPageChange = (pageInfo: { current: number; pageSize: number }) => {
  emit('page-change', {
    page: pageInfo.current,
    limit: pageInfo.pageSize
  })
}
</script>

<style lang="less" scoped>
:deep(.t-pagination__jump) {
  background-color: var(--td-white) !important;
}

:deep(.t-pagination__total) {
  text-align: right;
  padding-right: 20px;
}

:deep(.t-table--hoverable) {
  tbody tr:hover {
    background-color: var(--td-brand-color-1) !important; /* 鼠标悬停时的背景色 */
  }
}

.cell-content {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
