import { computed, ref } from 'vue';
import { $http } from 'boot/axios';

export function useDataManager(props, pagination, table, filter) {
  const rowsData = ref([]);
  const asyncProps = ref({});

  async function getList() {
    const CurrentPage = pagination.value.page;

    //防止传0什么都不查
    const PageSize =
      pagination.value.rowsPerPage == 0
        ? 999999999
        : pagination.value.rowsPerPage;

    const model = {
      CurrentPage,
      PageSize,
      Query: filter.value,
    };
    table.value.loading = true;
    try {
      const res = await $http.post(props.getListURL, model);
      if (res) {
        rowsData.value = res.Data;
        pagination.value.rowsNumber = res.lCount;
        table.value.loading = false;
      }
    } catch (error) {
      console.log(error);
    }
  }

  async function asyncRequest(options) {
    if (!options) {
      options = asyncProps.value;
    }

    const { page, rowsPerPage, sortBy, descending } = options.pagination;

    pagination.value.page = page;
    pagination.value.rowsPerPage = rowsPerPage;
    pagination.value.sortBy = sortBy;
    pagination.value.descending = descending;
    await getList();
  }

  /**
   * On définie les données pour la table
   */
  const rows = computed(() => {
    if (table.value.rows) {
      return table.value.rows;
    }
    return rowsData.value;
  });

  return {
    rows,
    getList,
    asyncRequest,
  };
}
