<template>
  <view
    v-if="loader?.loadStatus.value == 'loading'"
    style="min-height: 200rpx;display: flex;justify-content: center;align-items: center;"
  >
    <u-loading-icon text="加载中" textSize="18" />
  </view>
  <view
    v-else-if="loader?.loadStatus.value == 'error'"
    style="min-height: 200rpx"
  >
    <u-empty
      mode="page"
      :text="loader.loadError.value"
    />
    <view style="margin-top: 20rpx">
      <u-row justify="center">
        <u-col span="3">
          <u-button text="刷新" @click="handleRetry" />
        </u-col>
      </u-row>
    </view>
  </view>
  <template v-else-if="loader?.loadStatus.value == 'finished' || loader?.loadStatus.value == 'nomore'">
    <slot />
  </template>
  <view
    v-if="showEmpty || loader?.loadStatus.value == 'nomore'"
    style="min-height: 200rpx"
  >
    <u-empty
      mode="data"
      :text="emptyView?.text ?? '暂无数据'"
    />
    <view v-if="emptyView?.button" style="margin-top: 20rpx">
      <u-row justify="center">
        <u-col span="3">
          <u-button
            :text="emptyView?.buttonText ?? '刷新'" 
            @click="() => emptyView?.buttonClick ? emptyView?.buttonClick() : handleRetry()"
          />
        </u-col>
      </u-row>
    </view>
  </view>
  <image 
    v-if="lazy && !loaded"
    :lazy-load="true"
    @load="handleLoad"
    @error="handleLoad"
    src="https://mn.wenlvti.net/uploads/20250313/46adb2f039c6f23a3e69149526eb7e61.png"
    style="width:0px;height:0px"
  />
</template>

<script setup lang="ts">
import { onMounted, ref, type PropType } from 'vue';
import type { ISimplePageContentLoader } from '../composeabe/SimplePageContentLoader';

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>