import { ref } 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 pageNumber = ref(1);
  const pageSize = ref(10);
  const total = ref(0);
  const dataList = ref<T[]>();

  async function getList() {
    const datas = {
      ...searchModel,
      pageNumber: pageNumber.value,
      pageSize: pageSize.value,
    };
    const data = await apiFunc(datas);
    dataList.value = data.result;
    total.value = data.totalCount;
  }
  if (initAutoFetch) getList();

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

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

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

  function deletePageLastItem(len = 1) {
    let page = pageNumber.value || 1;
    if (dataList.value && dataList.value.length === len) {
      page = page > 1 ? page - 1 : 1;
    }
    toPage(page);
  }

  const pagination = {
    total: total.value,
    current: pageNumber.value,
    pageSize: pageSize.value,
    showTotal: true,
    showJumper: true,
    showPageSize: true,
    onChange: toPage,
    onPageSizeChange: pageSizeChange,
  };

  return {
    dataList,
    pagination,
    getRowIndex,
    getList,
    toPage,
    deletePageLastItem,
  };
}
