<template>
  <div
    v-if="loader?.loadStatus.value == 'loading'"
    class="loader"
  >
    <SimpleLoading />
  </div>
  <div
    v-else-if="loader?.loadStatus.value == 'error'"
    class="error"
  >
    <h1>{{ loader.loadError.value }}</h1>
    <button @click="handleRetry">重试</button>
  </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"
  >
    <h1>{{ emptyView?.text ?? '暂无数据' }}</h1>
    <button 
      v-if="emptyView?.button"
      @click="emptyView?.buttonClick ?? handleRetry"
    >
      {{emptyView?.buttonText ?? '刷新'}}
    </button>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, type PropType } from 'vue';
import type { ILoaderCommon } from '../composeable/LoaderCommon';
import SimpleLoading from './small/SimpleLoading.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>

<style lang="scss" scoped>
.loader {
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.error, .empty {
  min-height: 200px;
  text-align: center;

  h1 {
    font-size: 0.8rem;
  }
}
</style>