<template>
  <image
    v-if="realSrc"
    :src="realSrc"
    :mode="mode"
    :class="imgClass"
    :style="imgStyle"
    @click="onImageClick"
    @error="$emit('error', $event)"
  />
</template>

<script>
import { resolveResourceUrl, resolveResourceUrlList } from '@/utils/resourceUrl'

/**
 * 接口图片预览（对齐 ruoyi-ui/src/components/ImagePreview）
 * 相对路径自动拼接 BASE_API；H5 生产环境为当前浏览器 origin + /prod-api
 */
export default {
  name: 'ImagePreview',
  props: {
    src: {
      type: String,
      default: ''
    },
    mode: {
      type: String,
      default: 'aspectFill'
    },
    width: {
      type: [Number, String],
      default: ''
    },
    height: {
      type: [Number, String],
      default: ''
    },
    preview: {
      type: Boolean,
      default: false
    },
    imgClass: {
      type: String,
      default: ''
    }
  },
  emits: ['error', 'click'],
  computed: {
    realSrc() {
      return resolveResourceUrl(this.src)
    },
    realSrcList() {
      return resolveResourceUrlList(this.src)
    },
    imgStyle() {
      const style = {}
      if (this.width !== '' && this.width != null) {
        style.width = typeof this.width === 'string' ? this.width : `${this.width}px`
      }
      if (this.height !== '' && this.height != null) {
        style.height = typeof this.height === 'string' ? this.height : `${this.height}px`
      }
      return style
    }
  },
  methods: {
    onImageClick(e) {
      this.$emit('click', e)
      if (!this.preview || !this.realSrcList.length) {
        return
      }
      uni.previewImage({
        urls: this.realSrcList,
        current: this.realSrc
      })
    }
  }
}
</script>
