/*
 *  页面表格操作hooks
 *   tableLoading： 表格loading加载字段
 *   requestObj： 接口对象
 *   pager： 分页数据
 *   searchForm： 搜索对象
 *   tableData： 表格数据
 *   selectedRowKeys： 表格选择数据
 *
 */
import type { Pager } from '/@/api/types/pager';
import { onMounted, ref } from 'vue';
import type { Ref } from 'vue';

// T是tableData的类型，U是searchForm的类型
export function useData<T, U>(
  requestObj: { list: (params: any) => Promise<T[]> },
  searchForm: Ref<U>,
) {
  const tableLoading = ref(false);
  const pager = ref<Pager>({
    page: 1,
    pageSize: 10,
    total: 0,
  });
  const tableData: Ref<T[]> = ref([]);
  const selectedRowKeys = ref<number[]>([]);
  // const searchForm: Ref<U> = ref({} as any);
  // 初始化data数据
  const initDataList = async () => {
    try {
      tableLoading.value = true;
      const res: any = await requestObj.list({ ...pager.value, ...searchForm.value });
      pager.value.total = res.totalRecord;
      tableData.value = res.datas || [];
      tableLoading.value = false;
    } catch (e) {
      tableLoading.value = false;
      console.log(e);
    }
  };

  // 搜索
  const onSearch = () => {
    pager.value.page = 1;
    initDataList();
  };

  // 重置
  const onRset = (initSearchForm: U) => {
    pager.value.page = 1;
    searchForm.value = initSearchForm;
    initDataList();
  };

  // 分页
  const onPageChange = (page: number, size: number) => {
    pager.value.page = page;
    pager.value.pageSize = size;
    initDataList();
  };
  const onSizeChange = (_current: any, size: number) => {
    pager.value.page = 1;
    pager.value.pageSize = size;
    initDataList();
  };

  // 表格选择
  const onSelectChange = (row: number[]) => {
    selectedRowKeys.value = [...row];
  };

  onMounted(() => {
    initDataList();
  });

  return {
    initDataList,
    onSearch,
    onRset,
    onPageChange,
    onSizeChange,
    onSelectChange,
    tableLoading,
    pager,
    tableData,
    selectedRowKeys,
    searchForm,
  };
}
