<template>
  <div class="image-preview-container">
    <el-image
      :style="imageStyle"
      :src="src"
      :fit="fit"
      :preview-src-list="previewSrcList"
      :initial-index="initialIndex"
      :preview-teleported="true"
      :z-index="zIndex"
      @error="onError"
    >
      <template #error>
        <slot name="error">
          <div class="image-error">
            <el-icon><Picture /></el-icon>
            <div>图片加载失败</div>
          </div>
        </slot>
      </template>
    </el-image>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { Picture } from '@element-plus/icons-vue'

const props = defineProps({
  src: {
    type: String,
    required: true
  },
  width: {
    type: [String, Number],
    default: '100%'
  },
  height: {
    type: [String, Number],
    default: 'auto'
  },
  fit: {
    type: String,
    default: 'cover'
  },
  previewSrcList: {
    type: Array,
    default: () => []
  },
  initialIndex: {
    type: Number,
    default: 0
  },
  zIndex: {
    type: Number,
    default: 2000
  }
})

const emit = defineEmits(['error'])

const imageStyle = computed(() => {
  const width = typeof props.width === 'number' ? `${props.width}px` : props.width
  const height = typeof props.height === 'number' ? `${props.height}px` : props.height
  return {
    width,
    height
  }
})

const onError = (e) => {
  emit('error', e)
}
</script>

<style scoped>
.image-preview-container {
  display: inline-block;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #fef0f0;
  color: #f56c6c;
  font-size: 12px;
  border-radius: 4px;
}

.image-error .el-icon {
  font-size: 24px;
  margin-bottom: 5px;
}
</style>
