<template>
  <div :style="styleMap?.mainStyle" class="w-full h-full relative">
    <ImageBg :src="styleMap?.mainStyle?.imageSrc" :imageStyle="styleMap?.mainStyle?.imageStyle" />
    <div class="w-full h-full absolute left-0 top-0 z-0 flex items-center justify-center">
      <ImageBg
        :src="src || defaultImg"
        :image-style="styleMap?.mainStyle?.image"
        :image-props="{ height: '100%', width: '100%' }"
      />
    </div>

    <div
      class="absolute left-0 top-0 z-0 w-full h-full flex items-center justify-center overflow-hidden z-1 whitespace-pre!"
      :style="textStyle"
    >
      {{ resolvedText.text }}
    </div>
  </div>
</template>

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

const props = defineProps<{
  width: number
  height: number
  text?: string
  styles: any
  state?: string
  image: string
  pressedImage: string
  selectedImage: string
  selectedPressedImage: string
  scale?: number
  antiAliasing?: boolean
}>()

const src = ref('')
const projectStore = useProjectStore()
const { resolveText, getTextStyle } = useLanguage()
const resolvedText = computed(() => resolveText(props.text))
const textStyle = getTextStyle(() => undefined, () => props.text)

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

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
      const result = await getImageByPath(basePath + imagePath)
      src.value = result?.src!
    } else {
      src.value = ''
    }
  }
)
</script>

<style scoped></style>
