import { ref, isRef, reactive } from 'vue';
import { PageResult } from '@/api/types/common';

export default function useTable<T extends Record<string, any>>(
  apiFunc: (data: any) => Promise<PageResult<T>>,
  searchModel: Record<string, any>,
  initAutoFetch = false
) {
  const dataList = ref<T[]>([]);
  const loading = ref(false);
  const selectedRows = ref<T[]>([]);
  const pagination = reactive({
    pageNumber: 1,
    pageSize: 20,
    total: 0,
    layout: `total, ->, sizes, prev, pager, next, jumper`,
  });

  interface SortConfig {
    sortProp?: string;
    sortOrder?: 'asc' | 'desc';
  }
  const sortConfig = reactive<SortConfig>({
    sortProp: undefined,
    sortOrder: undefined,
  });
  const orderMap = {
    ascending: 'asc',
    descending: 'desc',
  };

  async function getList() {
    loading.value = true;
    const datas = {
      ...(isRef(searchModel || {}) ? searchModel.value : searchModel),
      ...sortConfig,
      pageNumber: pagination.pageNumber,
      pageSize: pagination.pageSize,
    };
    const data = await apiFunc(datas).catch(() => {});
    loading.value = false;
    if (!data) return;

    dataList.value = data.result;
    pagination.total = data.totalCount;
  }
  if (initAutoFetch) getList();

  async function toPage(page: number) {
    pagination.pageNumber = page;
    await getList();
  }

  async function pageSizeChange(size: number) {
    pagination.pageSize = size;
    await toPage(1);
  }

  function getRowIndex(index: number) {
    return pagination.pageSize * (pagination.pageNumber - 1) + index + 1;
  }

  function deletePageLastItem(len = 1) {
    let page = pagination.pageNumber || 1;
    if (dataList.value && dataList.value.length === len) {
      page = page > 1 ? page - 1 : 1;
    }
    toPage(page);
  }
  // 选择
  const handleSelectionChange = (selection: T[]) => {
    selectedRows.value = selection;
  };
  // 排序
  const handleSortChange = (data: {
    column: any;
    prop: string;
    order: SortConfig['sortOrder'];
  }) => {
    sortConfig.sortProp = data.prop || undefined;
    sortConfig.sortOrder = orderMap[data.order] || undefined;
    getList();
  };

  return {
    loading,
    dataList,
    pagination,
    selectedRows,
    getRowIndex,
    getList,
    toPage,
    pageSizeChange,
    deletePageLastItem,
    handleSelectionChange,
    handleSortChange,
  };
}
