<template>
  <div
    v-if="getImgSrc"
    class="w-full h-full absolute left-0 top-0 z-0 overflow-hidden flex items-center justify-center"
    :style="{ opacity: imageStyle?.opacity }"
    v-bind="$attrs"
  >
    <img v-bind="imageProps" ref="imgRef" class="absolute z-0" :src="getImgSrc" draggable="false" />
    <div v-if="hasCoverColor" class="absolute z-1 pointer-events-none" :style="maskStyle"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, type CSSProperties, type ImgHTMLAttributes } from 'vue'
import { useElementSize } from '@vueuse/core'
import { useProjectStore } from '@/store/modules/project'

const props = defineProps<{
  src?: string
  id?: string
  imageStyle?: CSSProperties
  imageProps?: ImgHTMLAttributes
}>()

defineOptions({
  inheritAttrs: false
})

const imgRef = ref<HTMLImageElement>()
const projectStore = useProjectStore()

const imgSize = useElementSize(imgRef)

// 图片覆盖色样式
const getCssSize = (value: unknown, fallback: number) => {
  if (value === undefined || value === null || value === '') {
    return fallback ? `${fallback}px` : undefined
  }
  return typeof value === 'number' ? `${value}px` : String(value)
}

const getStyleObject = (style: unknown): CSSProperties => {
  return style && typeof style === 'object' && !Array.isArray(style) ? (style as CSSProperties) : {}
}

const getCssUrl = (url: string) => `url("${url.replace(/"/g, '\\"')}")`

const hasCoverColor = computed(() => !!props.imageStyle?.backgroundColor)

const maskStyle = computed((): CSSProperties => {
  const imageUrl = getCssUrl(getImgSrc.value || '')
  const imagePropStyle = getStyleObject(props.imageProps?.style)

  return {
    ...imagePropStyle,
    width: getCssSize(props.imageProps?.width, imgSize.width.value),
    height: getCssSize(props.imageProps?.height, imgSize.height.value),
    backgroundColor: props.imageStyle?.backgroundColor,
    maskImage: imageUrl,
    WebkitMaskImage: imageUrl,
    maskSize: '100% 100%',
    WebkitMaskSize: '100% 100%',
    maskPosition: 'center',
    WebkitMaskPosition: 'center',
    maskRepeat: 'no-repeat',
    WebkitMaskRepeat: 'no-repeat'
  }
})

// 图片地址
const getImgSrc = computed(() => {
  const { id, src } = props
  if (src) return src
  const imgResource = projectStore.project?.resources.images.find((img) => img.id === id)
  if (!imgResource) return
  return `local:///${(projectStore.projectPath + imgResource.path).replaceAll('\\', '/')}`
})
</script>
