import { computed, onMounted, reactive, ref } from 'vue';
import { useRequest } from 'vue-vulcan';

interface DataListOption {
  params?: {
    [prop: string]: string | number | undefined;
  }
}

interface DataListFilters {
  page_index: number;
  [prop: string]: any;
}

interface PageModel {
  page_index: number;
  page_size?: number;
  page_count?: number;
}

const defaultOptions = {
  type: 'scroll',
  params: {}
}

export function usePagingData<T = any>(url: string, options: DataListOption = defaultOptions) {

  const loading     = ref(true);
  const error       = ref(false);
  const refresh     = ref(false);
  const listData    = ref<T[]>([]);
  const total       = ref(1);
  const filters     = reactive({ }) as DataListFilters;
  const page        = reactive({ page_index: 1 }) as PageModel;
  const finished    = computed(() => total.value <= listData.value.length);
  const empty       = computed(() => listData.value.length === 0 && !loading.value && !refresh.value);

  onMounted(() => {
    requestData()
  })

  const [, doRequest ] = useRequest<any>(url, { auto: false })
  const requestData = () => {
    doRequest({...options.params, ...filters, ...page}).then(data => {
      listData.value  = listData.value.concat(data.list);
      total.value     = parseInt(data.total, 10);
      refresh.value   = false;
    }).catch( _ => error.value = true )
  }

  const setFilter = (key: string, value: any) => {
    listData.value      = [];
    filters[key]        = value;
    page.page_index     = 1;
    requestData();
  }

  const setFresh = () => {
    page.page_index = 1;
    requestData();
  }

  const loadNextPage = () => {
    page.page_index ++;
    requestData();
  }

  return {
    loading,
    refresh,
    finished,
    empty,
    page,
    listData,
    total,
    loadNextPage,
    setFilter,
    setFresh
  }
}
