<template>
  <image
    v-if="!isError && imgPath"
    :src="util.checkFileUrl(imgPath)"
    :style="imgStyle"
    :class="classList"
    :mode="imgMode"
    @error="imgError"
    @load="imgLoad"
    @tap.stop="handleTap"
  />
  <image
    v-else
    :src="defImgPath"
    :style="imgStyle"
    :class="classList"
    :mode="imgMode"
    @tap.stop="handleTap"
  />
</template>

<script setup>
import util from '@/utils/util'
const props = defineProps({
  src: {
    type: String,
    default: ''
  },
  imgMode: {
    type: String,
    default: 'aspectFill'
  },
  classList: {
    type: Array,
    default: () => {
      return []
    }
  },
  imgStyle: {
    type: Object,
    default: () => {
      return {}
    }
  },
  defImgInx: {
    type: Number,
    default: 0
  },
  isPreview: {
    type: Boolean,
    default: false
  }
})

const imgPath = computed(() => {
  return props.src
})

const defImgPath = computed(() => {
  switch (props.defImgInx) {
    case 0:
      return '/static/images/def.png'
    case 1:
      return '/static/images/chat/head01.png'
    case 2:
      return '/static/images/chat/userImg.jpg'
    default:
      return '/static/images/def.png'
  }
})

const emit = defineEmits(['imgError', 'imgLoad', 'handleTap'])

const isError = ref(false)
const imgError = () => {
  isError.value = true
  emit('imgError')
}

const imgLoad = (e) => {
  emit('imgLoad', e)
}

/**
 * 若设置可预览则点击直接预览图片，否则抛出点击事件
 */
const handleTap = () => {
  if (!props.isPreview) {
    emit('handleTap')
  } else {
    const list = []
    list.push(util.checkFileUrl(imgPath.value))
    uni.previewImage({
      indicator: 'none',
      current: 0,
      urls: list
    })
  }
}
</script>

<style scoped>
image {
  will-change: transform;
  width: 100%;
  height: 100%;
}
</style>
