<template>
  <el-image
    v-bind="imageBindProps"
    :style="imageStyle"
    :src="imageUrl"
    loading="lazy"
  />
</template>

<script setup lang="ts">
import { omit } from 'lodash-es'
import type { ImageProps } from 'element-plus'

interface ThumbnailProps
  extends Omit<Partial<ImageProps>, 'src' | 'width' | 'height' | 'style'> {
  src: string
  width?: string
  height?: string
  displayWidth?: string
  displayHeight?: string
}

type ThumbnailBindProps = Omit<
  ThumbnailProps,
  'src' | 'width' | 'height' | 'displayWidth' | 'displayHeight'
>

defineOptions({ inheritAttrs: false })

const props = withDefaults(defineProps<ThumbnailProps>(), {
  width: '45',
})

const imageBindProps = computed(
  (): Partial<ThumbnailBindProps> =>
    omit(props, ['src', 'width', 'height', 'displayWidth', 'displayHeight']),
)

const displayWidth = computed(() => {
  return props.displayWidth ?? props.width
})

const displayHeight = computed(() => {
  return props.displayHeight ?? props.height ?? displayWidth.value
})

const imageStyle = computed(() => {
  return {
    width: `${displayWidth}px`,
    height: `${displayHeight}px`,
  }
})

const imageUrl = computed(() => {
  if (props.src.includes('custom.jomalls.com')) {
    return props.src.replace(/\.(png|jpg|jpeg)$/i, `-${props.width}.$1`)
  } else if (props.src.includes('oss')) {
    return (
      props.src + `?x-oss-process=image/resize,m_fixed,w_${displayWidth.value}`
    )
  }
  return props.src
})
</script>
