<!--
@description: 带状态/类型筛选、排序、批量操作和列设置的 ProTable 列表。
-->
<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';

interface ResourceRow {
  id: string;
  name: string;
  status: 'running' | 'stopped' | 'creating';
  type: 'performance' | 'capacity';
}

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

const sourceRows: ResourceRow[] = [
  { id: 'resource-001', name: 'demo-1', status: 'running', type: 'performance' },
  { id: 'resource-002', name: 'demo-2', status: 'stopped', type: 'capacity' },
];

const checkedKeys = ref<string[]>([]);
const searchKey = ref('name');
const searchValue = ref('');
const page = ref(1);
const limit = ref(20);
const params = reactive({ page, limit, searchValue });
const sort = ref<TableSortValue>({});
const group = ref<TableGroupValue>({ status: [], type: [] });
const statusOptions = ref([
  { label: '运行中', value: 'running' },
  { label: '已关机', value: 'stopped' },
  { label: '创建中', value: 'creating' },
]);
const typeOptions = ref([
  { label: '性能型', value: 'performance' },
  { label: '容量型', value: 'capacity' },
]);

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: '导出全部' }],
    },
    setting: { show: true, title: '自定义列表字段' },
  },
  filter: { show: true },
}));

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 onSortChange(value: TableSortValue): void {
  sort.value = { ...value };
  page.value = 1;
}

function onGroupChange(value: TableGroupValue): void {
  group.value = { ...value };
  page.value = 1;
}

async function requestRows(
  requestParams: Record<string, unknown> | undefined,
  tableSort: TableSortValue | undefined,
  tableGroup: TableGroupValue | undefined,
): Promise<{ code: number; data: ResourceRow[]; total: number }> {
  const query = searchValue.value.trim().toLocaleLowerCase('zh-CN');
  const statuses = Array.isArray(tableGroup?.status) ? tableGroup.status : [];
  const types = Array.isArray(tableGroup?.type) ? tableGroup.type : [];
  const filtered = sourceRows.filter((row) => {
    const field = searchKey.value === 'id' ? row.id : row.name;
    return (
      field.toLocaleLowerCase('zh-CN').includes(query) &&
      (statuses.length === 0 || statuses.includes(row.status)) &&
      (types.length === 0 || types.includes(row.type))
    );
  });
  const sorted = tableSort?.key === 'name' && tableSort.type
    ? [...filtered].sort((left, right) =>
        left.name.localeCompare(right.name, 'zh-CN') *
        (tableSort.type === 'asc' ? 1 : -1),
      )
    : filtered;
  const currentPage = Number(requestParams?.page ?? page.value);
  const currentLimit = Number(requestParams?.limit ?? limit.value);
  const start = (currentPage - 1) * currentLimit;
  return {
    code: 200,
    data: sorted.slice(start, start + currentLimit),
    total: sorted.length,
  };
}
</script>

<template>
  <LayoutContent :header-props="{ title: '高级资源列表' }">
    <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"
      @$change:sort="onSortChange"
      @$change:group="onGroupChange"
    >
      <template #actions>
        <ButtonGroup separate>
          <Button type="primary">创建</Button>
          <Button :disabled="checkedKeys.length === 0">批量删除</Button>
        </ButtonGroup>
      </template>

      <TableColumn title="资源名称/ID" key="name" width="240" sortable>
        <template #template="[row]">
          <TableColumnId
            :name="row.name"
            :id="row.id"
            @click:name="onNameClick(row)"
            @click:id="onIdClick"
          />
        </template>
      </TableColumn>
      <TableColumn title="状态" key="status" v-model:group="statusOptions">
        <template #template="[row]">
          <Status
            :color="row.status === 'running' ? 'success' : 'disabled'"
            :text="statusOptions.find((item) => item.value === row.status)?.label"
          />
        </template>
      </TableColumn>
      <TableColumn
        title="类型"
        key="type"
        multiple
        v-model:group="typeOptions"
      />
      <TableColumn title="操作" key="actions" width="120" fixed="right">
        <template #template>
          <Button type="link">查看</Button>
        </template>
      </TableColumn>
    </ProTable>
  </LayoutContent>
</template>
