import { reactive, ref, isRef, Ref } from "vue";
import type { UnwrapRef } from "vue";
import { PageResult } from "@/ap/types/common";
import type { TablePaginationConfig } from "ant-design-vue";

export default function useTable<T extends Record<string, any>>(
  apiFunc: (data: any) => Promise<PageResult<T>>,
  searchModel: Record<string, any> | Ref,
  initAutoFetch = true
) {
  const pageNumber = ref(1);
  const pageSize = ref(10);
  const total = ref(0);
  const dataList = ref<T[]>([]);
  const loading = ref(false);

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

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

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

  function setPageSize(size: number) {
    pageSize.value = size;
  }

  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: UnwrapRef<TablePaginationConfig> = reactive({
    total,
    current: pageNumber,
    pageSize,
    showTotal: (totalCount: number) => `共${totalCount}条`,
    showQuickJumper: true,
    showSizeChanger: false,
    onChange: toPage,
  });

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