<template>
  <view
    v-if="loader?.loadStatus.value == 'loading'"
    class="loader-view center"
  >
    <LoadingPage loadingText="加载中" textSize="18" />
  </view>
  <view
    v-else-if="loader?.loadStatus.value == 'error'"
    class="loader-view"
  >
    <Empty
      image="error"
      :description="loader.loadError.value"
    >
      <Height :height="20" />
      <Button type="primary" text="刷新" @click="handleRetry" />
    </Empty>
  </view> 
  <view
    v-if="showEmpty || loader?.loadStatus.value == 'nomore'"
    class="loader-view"
  >
    <Empty
      image="search"
      :description="emptyView?.text ?? '暂无数据'"
    >
      <Height :height="20" />
      <Button 
        v-if="emptyView?.button"  
        type="primary"
        :text="emptyView?.buttonText ?? '刷新'"
            @click="() => emptyView?.buttonClick ? emptyView?.buttonClick() : handleRetry()"
      />
    </Empty>
  </view>
  <image 
    v-if="lazy && !loaded"
    :lazy-load="true"
    @load="handleLoad"
    @error="handleLoad"
    src="https://mn.wenlvti.net/app_static/empty.jpg"
    style="width:0px;height:0px"
  />

  <slot />
</template>

<script setup lang="ts">
import { onMounted, ref, type PropType } from 'vue';
import type { ISimplePageContentLoader } from '../composeabe/SimplePageContentLoader';
import Empty from '@/components/feedback/Empty.vue';
import Button from '@/components/basic/Button.vue';
import LoadingPage from '@/components/display/loading/LoadingPage.vue';
import Height from '@/components/layout/space/Height.vue';

const props = defineProps({	
  loader: {
    type: Object as PropType<ISimplePageContentLoader<any, any>>,
    default: null,
  },
  lazy: {
    type: Boolean,
    default: false, 
  },
  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">
.loader-view {
  min-height: 200rpx;

  &.center {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>