<template>
  <div
    v-if="loader?.loadStatus.value == 'loading'"
    style="min-height: 200rpx;display: flex;justify-content: center;align-items: center;"
  >
    <a-spin tip="加载中" />
  </div>
  <div
    v-else-if="loader?.loadStatus.value == 'error'"
    style="min-height: 200rpx"
  >
    <a-empty :description="loader.loadError.value" >
      <a-button  @click="handleRetry">重试</a-button>
    </a-empty>
  </div>
  <template v-else-if="loader?.loadStatus.value == 'finished' || loader?.loadStatus.value == 'nomore'">
    <slot />
  </template>
  <div
    v-if="showEmpty || loader?.loadStatus.value == 'nomore'"
    style="min-height: 200rpx"
    class="empty"
  >
    <a-empty :description="emptyView?.text ?? '暂无数据'">
      <a-button
        v-if="emptyView?.button"
        @click="emptyView?.buttonClick ?? handleRetry"
      >
        {{emptyView?.buttonText ?? '刷新'}}
      </a-button>
    </a-empty>
  </div>
</template>

<script setup lang="ts">
import type { ILoaderCommon } from '@/composeable/LoaderCommon';
import { onMounted, ref, type PropType } from 'vue';

const props = defineProps({	
  loader: {
    type: Object as PropType<ILoaderCommon<any>>,
    default: null,
  },
  autoLoad: {
    type: Boolean,
    default: false, 
  },
  showEmpty: {
    type: Boolean,
    default: false, 
  },
  emptyView: {
    type: Object as PropType<{
      text: string,
      buttonText: string,
      button: boolean,
      buttonClick: () => void,
    }>,
    default: null,
  },
})

const loaded = ref(false);

onMounted(() => {
  loaded.value = false;
  if (props.autoLoad)
    handleLoad(); 
});

function handleRetry() {
  props.loader.loadData(undefined);
}
function handleLoad() {
  if (loaded.value) 
    return;
  loaded.value = true;
  props.loader.loadData(undefined);
}
</script>