<!--
@description: 标准资源列表页。优先使用 ProTable 自带的搜索、刷新、导出、列设置、选择和分页能力。
@supporting-files: 将返回的 types/mock/utils 模板写入 ./instances/，不要自行重写组件 API。
-->
<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import {
  Button,
  ButtonGroup,
  TableColumn,
  type TableGroupValue,
  type TableSortValue,
} from '@king-design/vue';
import {
  LayoutContent,
  ProTable,
  Status,
  TableColumnId,
  type SearchType,
  type TableHeaderProps,
} from '@ksyun-internal/versatile';
import type { PageChangeData, ResourceRow } from './instances/types';
import { resourceRows } from './instances/mock';
import {
  filterResourceRows,
  paginateResourceRows,
} from './instances/utils';

const emit = defineEmits<{
  'open-resource': [row: ResourceRow];
  'click-resource-id': [id: string];
}>();

const checkedKeys = ref<string[]>([]);
const searchKey = ref('name');
const searchValue = ref('');
const page = ref(1);
const limit = ref(20);
const refreshVersion = ref(0);
const sort = ref<TableSortValue>({});
const group = ref<TableGroupValue>({});

const params = reactive({
  page,
  limit,
  searchValue,
  refreshVersion,
});

const searches: Record<string, SearchType> = {
  name: {
    key: 'name',
    label: '资源名称',
    placeholder: '请输入资源名称',
    batchFilter: true,
  },
  id: {
    key: 'id',
    label: '资源 ID',
    placeholder: '请输入资源 ID',
    uniqueKey: true,
  },
};

const tableHeaderProps = computed<TableHeaderProps>(() => ({
  show: true,
  search: {
    show: true,
    searchGroups: [{ label: '全局搜索', groups: ['name', 'id'] }],
    searches,
  },
  toolbar: {
    show: true,
    refresh: { show: true },
    exports: {
      show: true,
      title: '导出资源',
      exportRangeList: [
        { value: 'all', label: '导出全部' },
        {
          value: 'checked',
          label: '导出已选',
          disabled: checkedKeys.value.length === 0,
          disabledText: '请先选择资源',
        },
      ],
    },
    setting: { show: true, title: '自定义列表字段' },
  },
  filter: { show: true },
}));

const pageHeaderProps = {
  title: '资源列表',
  doc: {
    indexUrl: 'https://docs.ksyun.com',
    indexEnUrl: 'https://docs.ksyun.com',
  },
};

function rowKey(row: ResourceRow): string {
  return row.id;
}

function onNameClick(row: ResourceRow): void {
  emit('open-resource', row);
}

function onIdClick(id: string): void {
  emit('click-resource-id', id);
}

function onPageChange(data: PageChangeData): void {
  page.value = data.value;
  limit.value = data.limit;
}

async function requestRows(
  requestParams: Record<string, unknown> | undefined,
): Promise<{ code: number; data: ResourceRow[]; total: number }> {
  const filtered = filterResourceRows(
    resourceRows,
    searchKey.value,
    searchValue.value,
  );
  const currentPage = Number(requestParams?.page ?? page.value);
  const currentLimit = Number(requestParams?.limit ?? limit.value);
  const result = paginateResourceRows(
    filtered,
    currentPage,
    currentLimit,
  );
  return {
    code: 200,
    ...result,
  };
}
</script>

<template>
  <LayoutContent :header-props="pageHeaderProps">
    <ProTable
      :table-header-props="tableHeaderProps"
      :row-key="rowKey"
      :request="requestRows"
      :params="params"
      :sort="sort"
      :group="group"
      :pagination="{ value: page, limit, limits: [10, 20, 50] }"
      v-model:checked-keys="checkedKeys"
      v-model:search-key="searchKey"
      v-model:search-value="searchValue"
      @refresh="refreshVersion += 1"
      @page="onPageChange"
    >
      <template #actions>
        <ButtonGroup separate>
          <Button type="primary">新建</Button>
          <Button :disabled="checkedKeys.length === 0">批量操作</Button>
        </ButtonGroup>
      </template>

      <TableColumn title="资源名称/ID" key="name" width="240">
        <template #template="[row]">
          <TableColumnId
            :name="row.name"
            :id="row.id"
            @click:name="onNameClick(row)"
            @click:id="onIdClick"
          />
        </template>
      </TableColumn>
      <TableColumn title="状态" key="status" width="120">
        <template #template="[row]">
          <Status
            :color="row.status === 'running' ? 'success' : 'disabled'"
            :text="row.statusLabel"
          />
        </template>
      </TableColumn>
      <TableColumn title="创建时间" key="createdAt" width="180" />
      <TableColumn title="操作" key="actions" width="140" fixed="right">
        <template #template>
          <Button type="link">查看</Button>
          <Button type="link">删除</Button>
        </template>
      </TableColumn>
    </ProTable>
  </LayoutContent>
</template>
