<template>
  <div
    ref="wrapperRef"
    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 }"
  >
    <img v-bind="imageProps" class="absolute z-0" :src="getImgSrc" />
    <img
      v-bind="imageProps"
      ref="imgRef"
      class="absolute z-1"
      :src="getImgSrc"
      :style="shadowImageStyle"
    />
  </div>
</template>

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

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

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

const wrapperSize = useElementSize(wrapperRef)
const imgSize = useElementSize(imgRef)

// 图片覆盖色样式
const shadowImageStyle = computed((): CSSProperties => {
  const color = props.imageStyle?.backgroundColor
  const offsetX = wrapperSize.width.value / 2 + imgSize.width.value / 2
  return {
    height: 'inherit',
    maxWidth: `${wrapperSize.width.value}px`,
    maxHeight: `${wrapperSize.height.value}px`,
    filter: `drop-shadow(${offsetX}px 0px 0 ${color || 'transparent'})`,
    left: `-${imgSize.width.value}px`
  }
})

// 图片地址
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>
