<script setup lang="ts">
import { fullUrl, previewImg } from '@/utils/common'
import type { StyleValue } from 'vue'
import { ref } from 'vue'

const props = withDefaults(
  defineProps<{
    src: string[]
    imgStyle?: StyleValue
    preImg?: boolean
    mode?:
      | 'scaleToFill'
      | 'aspectFit'
      | 'aspectFill'
      | 'widthFix'
      | 'heightFix'
      | 'top'
      | 'bottom'
      | 'center'
      | 'center'
      | 'right'
      | 'top left'
      | 'top right'
      | 'bottom left'
      | 'bottom right'
    lazyLoad?: boolean
    showMenuByLongpress?: boolean
    draggable?: boolean
  }>(),
  {
    src: () => [],
    mode: 'widthFix',
    lazyLoad: false,
    showMenuByLongpress: false,
    draggable: true,
    preImg: true,
  },
)

const preImgs = (url: string) => {
  if (props.preImg) {
    previewImg(url, props.src)
  }
}

const imgHeight = ref('')
const onLoadImg = (event: UniHelper.ImageOnLoadEvent) => {
  const getSystemInfo = uni.getSystemInfoSync()
  const { windowWidth, windowHeight } = getSystemInfo
  const { width, height } = event.detail
  imgHeight.value = (parseFloat(height) * windowWidth) / parseFloat(width) + 'px'
}
</script>

<template>
  <view class="image" :style="props.imgStyle" v-if="props.src.length > 0">
    <image
      v-for="(url, index) in props.src"
      :key="index"
      :src="fullUrl(url)"
      :mode="props.mode"
      :lazy-load="props.lazyLoad"
      :show-menu-by-longpress="props.showMenuByLongpress"
      :draggable="props.draggable"
      :style="{ height: imgHeight }"
      @tap="preImgs(url)"
      @load="onLoadImg"
      class="image"
    />
  </view>
</template>

<style lang="scss">
.image {
  width: 100%;
  will-change: transform;
  height: 100%;
}
</style>
