<template>
  <div :style="boxStyle" class="w-full h-full flex items-center justify-center">
    <ImageBg
      v-if="styleMap?.mainStyle?.imageSrc"
      :src="styleMap?.mainStyle?.imageSrc"
      :image-style="styleMap?.mainStyle?.imageStyle"
    />
    <ImageBg
      :src="src || defaultImg"
      :image-style="styleMap?.mainStyle?.image"
      :image-props="imageProps"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, watch, ref } from 'vue'
import { useProjectStore } from '@/store/modules/project'
import defaultImg from '@/assets/default.png'
import ImageBg from '../ImageBg.vue'
import { useWidgetStyle } from '../hooks/useWidgetStyle'

const props = defineProps<{
  width: number
  height: number
  image: string
  styles: any
  part?: string
  state?: string
  pivot: {
    x: number
    y: number
  }
  rotation: number
  openScale?: boolean
  scale?: number
  antiAliasing?: boolean
  id?: string
}>()

const src = ref('')
const projectStore = useProjectStore()

const styleMap = useWidgetStyle({
  widget: 'lv_image',
  props
})

const imageProps = computed(() => {
  const { openScale, scale = 256, width, height, pivot } = props
  const s = openScale ? scale / 256 : 1
  const { x = width / 2, y = height / 2 } = pivot

  return {
    width: `${width}px`,
    height: `${height}px`,
    style: {
      // 设置缩放中心
      transformOrigin: `${x}px ${y}px`,
      transform: `scale(${s})`
    }
  }
})

watch(
  () => props.image,
  async (val) => {
    if (val && projectStore.project) {
      // 加载图片
      const basePath = projectStore.projectPath
      const imagePath = projectStore.project.resources.images.find((item) => item.id === val)?.path
      src.value = `local:///${(basePath + imagePath).replaceAll('\\', '/')}`
    }
  },
  {
    immediate: true
  }
)

const boxStyle = computed(() => {
  const { width, height } = props

  return {
    ...(styleMap.value?.mainStyle || {}),
    width: `${width}px`,
    height: `${height}px`,

    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center'
  }
})
</script>
