<template>
  <image
    :src="lazyLoad ? placeholderSrc : realSrc"
    :mode="mode"
    :class="['lazy-image', { 'loaded': isLoaded }]"
    @load="onLoad"
    @error="onError"
    @click="onClick"
  />
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';

interface Props {
  src: string;
  mode?: string;
  placeholder?: string;
  lazyLoad?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'aspectFill',
  placeholder: '',
  lazyLoad: true,
});

const emit = defineEmits<{
  load: [event: any];
  error: [event: any];
  click: [event: any];
}>();

const isLoaded = ref(false);
const realSrc = ref('');
const placeholderSrc = props.placeholder || '/static/placeholder.png';

// 监听 src 变化
watch(() => props.src, (newVal) => {
  if (newVal && props.lazyLoad) {
    // 使用 uni-app 的懒加载
    realSrc.value = newVal;
  } else if (newVal) {
    realSrc.value = newVal;
  }
}, { immediate: true });

function onLoad(event: any) {
  isLoaded.value = true;
  emit('load', event);
}

function onError(event: any) {
  console.error('[LazyImage] 图片加载失败:', props.src);
  emit('error', event);
}

function onClick(event: any) {
  emit('click', event);
}
</script>

<style scoped>
.lazy-image {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.lazy-image.loaded {
  opacity: 1;
}
</style>
