<template>
  <div class="image-container flex justify-center items-center">
    <n-image ref="lazyRef" class="lazy__img" :src="url"  @load="handleLoad" @error="handleError">
      <template #placeholder>
        <img width="400" :src="loading" alt="loading" />
      </template>
      <template #error>
        <img :src="errorImg" alt="error" />
      </template>
    </n-image>
  </div>
</template>

<script setup lang="ts">
import { inject, onMounted, ref, toRefs } from "vue";
import loadError from "../assets/loadError.png";
import loadingImg from "../assets/loading.gif";
const props = defineProps({
  previewIcon: {
    type: String,
    default: "",
  },
  url: {
    type: String,
    default: "",
  },
  loading: {
    type: String,
    default: loadingImg,
  },
  errorImg: {
    type: String,
    default: loadError,
  }
});
const { url, loading, errorImg } = toRefs(props);

const imgLoaded = inject("imgLoaded") as () => void;
const lazyRef = ref<any>(null);

const handleLoad = () => {
  imgLoaded();
};

const handleError = () => {
  // 可以在这里添加错误处理逻辑
};

onMounted(() => {
  if (lazyRef.value) {
    imgLoaded();
  }
});
</script>

<style scoped>
:deep(.n-image img) {
  width: 100%;
  height: auto;
  /* object-fit: cover; */
}

.lazy__img img[alt="loading"],
.lazy__img img[alt="error"] {
  width: 80px;
  height: 80px;
  padding: 1em;
  margin: 0 auto;
  display: block;
}
</style>
