<template>
  <div 
    class="editable-element-text" 
    :class="{ 'lock': elementInfo.lock }"
    :style="{
      top: elementInfo.top + 'px',
      left: elementInfo.left + 'px',
      width: elementInfo.width + 'px',
      height: elementInfo.height + 'px',
    }"
  >
    <div
      class="rotate-wrapper"
      :style="{ transform: `rotate(${elementInfo.rotate}deg)` }"
    >
      <div 
        class="element-content"
        ref="elementRef"
        :style="{
          width: elementInfo.vertical ? 'auto' : elementInfo.width + 'px',
          height: elementInfo.vertical ? elementInfo.height + 'px' : 'auto',
          background: elementInfo.fill,
          opacity: elementInfo.opacity,
          textShadow: shadowStyle,
          lineHeight: elementInfo.lineHeight,
          letterSpacing: (elementInfo.wordSpace || 0) + 'px',
          color: elementInfo.defaultColor,
          fontFamily: elementInfo.defaultFontName,
          writingMode: elementInfo.vertical ? 'vertical-rl' : 'horizontal-tb',
          WebkitTextStroke: elementInfo.stroke ? elementInfo.stroke:''
        }"
        :class="{'clip-box':elementInfo.clip}"
        
        v-contextmenu="contextmenus"
        @mousedown="$event => handleSelectElement($event)"
        @touchstart="$event => handleSelectElement($event)"
      >
        <div class="full-lock" v-if="fullLockVisible<2" @click="hideLockHandler"></div>
        <ElementOutline
          :width="elementInfo.width"
          :height="elementInfo.height"
          :outline="elementInfo.outline"
        />
        <ProsemirrorEditor
          :class="{'text-static':elementInfo.clip,'text':!elementInfo.clip}"
          :elementId="elementInfo.id"
          :defaultColor="elementInfo.defaultColor"
          :defaultFontName="elementInfo.defaultFontName"
          :editable="!elementInfo.lock"
          :value="elementInfo.content"
          :style="{
            '--paragraphSpace': `${elementInfo.paragraphSpace === undefined ? 5 : elementInfo.paragraphSpace}px`,
          }"
          @update="value => updateContent(value)"
          @mousedown="$event => handleSelectElement($event, false)"
          ref="editorRef"
        />

        <!-- 当字号过大且行高较小时，会出现文字高度溢出的情况，导致拖拽区域无法被选中，因此添加了以下节点避免该情况111 -->
        <template v-show="!activeGroupElementId">
          <div class="drag-handler top" @dblclick="setEditorHandler"></div>
          <div class="drag-handler bottom" @dblclick="setEditorHandler"></div>
        </template>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, onUnmounted, ref, watch, inject } from 'vue'
import { storeToRefs } from 'pinia'
import { debounce } from 'lodash'
import { useMainStore, useSlidesStore } from '@/store'
import type { PPTTextElement } from '@/types/slides'
import type { ContextmenuItem } from '@/components/Contextmenu/types'
import useElementShadow from '@/views/components/element/hooks/useElementShadow'
import useHistorySnapshot from '@/hooks/useHistorySnapshot'

import ElementOutline from '@/views/components/element/ElementOutline.vue'
import ProsemirrorEditor from '@/views/components/element/ProsemirrorEditor.vue'
import { ToolbarStates } from '@/types/toolbar'
import { injectKeyTemplate } from '@/types/injectKey'


const props = defineProps<{
  elementInfo: PPTTextElement
  selectElement: (e: MouseEvent | TouchEvent, element: PPTTextElement, canMove?: boolean) => void
  contextmenus: () => ContextmenuItem[] | null
}>()

const mainStore = useMainStore()
const slidesStore = useSlidesStore()
const { handleElementId, isScaling, activeGroupElementId } = storeToRefs(mainStore)

const { addHistorySnapshot } = useHistorySnapshot()

const elementRef = ref<HTMLElement>()
const editorRef = ref()

const shadow = computed(() => props.elementInfo.shadow)
const { shadowStyle } = useElementShadow(shadow)
const fullLockVisible = ref(0)
const searchData = ref({} as any)
searchData.value = inject(injectKeyTemplate)

const handleSelectElement = (e: MouseEvent | TouchEvent, canMove = true) => {
  if(e.button && e.button== 1) return
  if (props.elementInfo.lock) return
  e.stopPropagation()
  //console.log('触发选中元素：',props.elementInfo.defaultFontName)
  editorRef.value?.setClick()
  // if(!searchData.value.isTeamManage) mainStore.setToolbarState(ToolbarStates.EL_NORMALDATA)
  props.selectElement(e, props.elementInfo, canMove)
}

// 监听文本元素的尺寸变化，当高度变化时，更新高度到vuex
// 如果高度变化时正处在缩放操作中，则等待缩放操作结束后再更新
const realHeightCache = ref(-1)
const realWidthCache = ref(-1)

watch(isScaling, () => {
  if (handleElementId.value !== props.elementInfo.id) return

  if (!isScaling.value) {
    if (!props.elementInfo.vertical && realHeightCache.value !== -1) {
      slidesStore.updateElement({
        id: props.elementInfo.id,
        props: { height: realHeightCache.value },
      })
      realHeightCache.value = -1
    }
    if (props.elementInfo.vertical && realWidthCache.value !== -1) {
      slidesStore.updateElement({
        id: props.elementInfo.id,
        props: { width: realWidthCache.value },
      })
      realWidthCache.value = -1
    }
  }
})

const hideLockHandler = ()=>{
  fullLockVisible.value++
}

const updateTextElementHeight = (entries: ResizeObserverEntry[]) => {
  const contentRect = entries[0].contentRect
  if (!elementRef.value) return

  let realHeight = contentRect.height + 20
  const realWidth = contentRect.width + 20


  if (!props.elementInfo.vertical && props.elementInfo.height !== realHeight) {
    if (!isScaling.value) {
      slidesStore.updateElement({
        id: props.elementInfo.id,
        props: { height: realHeight },
      })
    }
    else realHeightCache.value = realHeight
  }
  if (props.elementInfo.vertical && props.elementInfo.width !== realWidth) {
    if (!isScaling.value) {
      slidesStore.updateElement({
        id: props.elementInfo.id,
        props: { width: realWidth },
      })
    }
    else realWidthCache.value = realWidth
  }
}
const resizeObserver = new ResizeObserver(updateTextElementHeight)

onMounted(() => {
  if (elementRef.value) resizeObserver.observe(elementRef.value)
})
onUnmounted(() => {
  if (elementRef.value) resizeObserver.unobserve(elementRef.value)
})

const updateContent = (content: string) => {
  slidesStore.updateElement({
    id: props.elementInfo.id,
    props: { content },
  })
  
  addHistorySnapshot()
}

const setEditorHandler = ()=>{
  editorRef.value?.focus()
  editorRef.value?.selectAll()
}

const checkEmptyText = debounce(function() {
  const pureText = props.elementInfo.content.replaceAll(/<[^>]+>/g, '')
  if (!pureText) slidesStore.deleteElement(props.elementInfo.id)
}, 300, { trailing: true })

const isHandleElement = computed(() => handleElementId.value === props.elementInfo.id)
watch(isHandleElement, () => {
  if (!isHandleElement.value) {
    checkEmptyText()
    editorRef.value?.clearSelect()
    fullLockVisible.value=0
  }
})
</script>

<style lang="scss" scoped>
.editable-element-text {
  position: absolute;

  &.lock .element-content {
    cursor: url('https://im.oytour.com/trip/cusor/c7ca2e93ad449598be9ead2d132dd05b.svg'), default;
  }
}
.rotate-wrapper {
  width: 100%;
  height: 100%;
}
.element-content {
  position: relative;
  padding: 10px;
  line-height: 1.5;
  word-break: break-word;
  cursor: url('https://im.oytour.com/trip/cusor/c7ca2e93ad449598be9ead2d132dd05b.svg'), default;

  .text {
    position: relative;
  }
  .text-static {
    position: static;
  }

  ::v-deep(a) {
    cursor: text;
  }

  .full-lock{
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    cursor: url('https://im.oytour.com/trip/cusor/c7ca2e93ad449598be9ead2d132dd05b.svg'), default;
    z-index: 99;
  }
}
.drag-handler {
  height: 20px;
  position: absolute;
  left: 0;
  right: 0;
  &.top {
    top: 0;
  }
  &.bottom {
    bottom: 0;
  }
}
.clip-box{
  -webkit-background-clip: text !important;
  cursor: pointer;
}
</style>
