<template>
  <div class="box">
    <div
      v-if="loader?.loadStatus.value == 'loading'"
      class="full"
    >
      <a-spin tip="加载中" />
    </div>
    <div
      v-else-if="loader?.loadStatus.value == 'error'"
      class="full"
    >
      <a-empty :description="loader.loadError.value" >
        <a-button  @click="handleRetry">重试</a-button>
      </a-empty>
    </div>
    <slot></slot>
    <div
      v-if="showEmpty || loader?.loadStatus.value == 'nomore'"
      class="full empty"
    >
      <a-empty :description="emptyView?.text ?? '暂无数据'">
        <a-button
          v-if="emptyView?.button"
          @click="emptyView?.buttonClick ?? handleRetry"
        >
          {{emptyView?.buttonText ?? '刷新'}}
        </a-button>
      </a-empty>
    </div>
  </div>
</template>

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

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>

<style lang="scss" scoped>
.box {
  position: relative;
  min-height: 200px;
}
.full {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 10;
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>