import { ref, ComputedRef, unref, computed, watch } from 'vue';
import type { BaseTableProps } from '../types';

// 设置table中的loading
export function useLoading(props: ComputedRef<BaseTableProps>) {
  const loadingRef = ref(unref(props).loading);

  // 监听是否有数据-取消加载
  watch(() => unref(props).loading, (newVal: Recordable) => {
    if (newVal) {
      setLoading(true)
    } else {
      setLoading(false)
    }
  })

  // 改变加载状态
  watch(
    () => unref(props).loading,
    (loading) => {
      loadingRef.value = loading;
    },
  );

  // 获取加载状态
  const getLoading = computed(() => unref(loadingRef));

  // 设置加载状态
  function setLoading(loading: boolean) {
    loadingRef.value = loading;
  }

  return { getLoading, setLoading };
}
