import { ref, reactive, watch, isRef } from 'vue';

// options参数示例：
// {
//   pageSize: 20,
//   params: ref({ a: 1, b: 2 }),
//   fetchDataHandle: () => {},
// }
export default function useFetchTable(apiFn, options = {}, immediately = true) {
  let pagination = reactive({
    pageNumber: 1,
    pageSize: options?.pageSize || 10,
    total: 0,
  });
  //tdesign的分页器组件的onChange方法，涵盖了页码的change和pageSize的change 两者的监听
  const onChange = (pageInfo) => {
    pagination.Size = pageInfo.pageSize;
    pagination.pageNumber = pageInfo.current;
  };
  const onPageSizeChange = (size) => {
    pagination.pageSize = size;
    pagination.pageNumber = 1;
  };

  const loading = ref(false);
  const tableData = ref([]);
  const fetchData = async () => {
    loading.value = true;
    try {
      let params = {
        pageNumber: pagination.pageNumber,
        pageSize: pagination.pageSize,
        ...((isRef(options.params) ? options.params?.value : options.params) ||
          {}),
      };
      let res = await apiFn(params);
      //下方代码 后续根据实际接口返回字段进行修改
      let list = Array.isArray(res.records) ? res.records : [];
      tableData.value = list;
      pagination.total = res.total;
      loading.value = false;

      options.fetchDataHandle && options.fetchDataHandle();
    } catch (err) {
      console.warn('分页请求错误：', err);
    }
  };

  const search = () => {
    if (pagination.pageNumber === 1) {
      fetchData();
    } else {
      pagination.pageNumber = 1;
    }
  };

  if (immediately) {
    //默认立即执行一次分页请求，如果不想如此，可以将第三个参数immediately传false
    fetchData();
  }
  watch(
    () => pagination.pageNumber,
    () => {
      fetchData();
    }
  );
  watch(
    () => pagination.pageSize,
    () => {
      search();
    }
  );

  return {
    loading,
    pagination,
    tableData,
    fetchData,
    search,
    onChange,
    onPageSizeChange,
  };
}
