<template>
  <div class="edit-tool">
    <template v-for="(item, index) in items" :key="index">
      <Button v-if="item.type === 'addText'" :data-element="item.dataElement" class="operate" :class="{ active: activeTool === 'addText' }" @click="changeActiveTool('addText')" :title="$t(item.title)">
        <AddText />{{ $t(item.title) }}
      </Button>
      <Button v-else-if="item.type === 'addImage'" :data-element="item.dataElement" class="operate" :class="{ active: activeTool === 'addImage' }" @click="changeActiveTool('addImage')" title="Add Image">
        <AddImage />{{ $t(item.title) }}<input v-if="isMobileDevice" type="file" id="editorImageInput" accept=".png, .jpg, .jpeg" style="display: none;" @change="handleFile" name="editor">
      </Button>
      <div v-else-if="item.type === 'divider'" :data-element="item.dataElement" class="divider pc"></div>
      <Button v-else-if="item.type === 'undo'" :data-element="item.dataElement" class="history" id="undo" :class="{ disabled: !undoListLength }" :title="$t(item.title)" @click="reset('undo')">
        <EditBack />
      </Button>
      <Button v-else-if="item.type === 'redo'" :data-element="item.dataElement" class="history" id="redo" :class="{ disabled: !redoListLength }" :title="$t(item.title)" @click="reset('redo')">
        <EditGo />
      </Button>
    </template>
  </div>
</template>

<script setup>
import { computed, h, ref, onMounted, onUnmounted } from 'vue'
import { useViewerStore } from '@/stores/modules/viewer'
import { useDocumentStore } from '@/stores/modules/document'
import MessageError from '@/assets/icons/icon-message-error.svg'
import { isMobileDevice } from '@/helpers/device'

import core from '@/core'
const { switchTool, switchAnnotationEditorMode, resetOperate } = core

defineProps(['items'])

const useDocument = useDocumentStore()
const useViewer = useViewerStore()

const activeTool = computed(() => useDocument.getActiveTool)
const currentPage = computed(() => useViewer.getCurrentPage)

const undoListLength = ref(0)
const redoListLength = ref(0)
const isListening = ref(true)

const changeActiveTool = (tool) => {
  useDocument.setToolState(tool)

  useViewer.toggleActiveHand(false)
  switchTool(0)
  
  switchAnnotationEditorMode(0)

  if (activeTool.value === 'addImage' && isMobileDevice) {
    document.getElementById('editorImageInput').click()
  }
}

const handleFile = (e) => {
  const file = e.target.files[0]
  if (!file) return
  
  if (file.size > 2 * 1024 * 1024) {
    window.$message.error(instance.$t('editorPanel.maximum'), {
      duration: 3000,
      icon: () => h('img', { src: MessageError })
    })
    e.target.value = ''
    return
  }

  const reader = new FileReader()
  reader.onload = function (e) {
    const image = new Image()
    image.onload = function () {
      const data = {
        imageBase64: e.target.result,
        width: image.width,
        height: image.height,
        pageNum: currentPage.value
      }
      core.addEditorImage(data)
    }
    image.onerror = function (error) {
      console.log(error)
    }
    image.src = e.target.result
  }
  reader.onerror = function (error) {
    console.log(error)
  }
  reader.readAsDataURL(file)
}

const reset = (operation) => {
  resetOperate({
    operation,
    pageNumber: currentPage.value
  })
}

const changeListLength = (data) => {
  undoListLength.value = data.undoListLength
  redoListLength.value = data.redoListLength
}
core.addEvent('changeOperateList', changeListLength)

// 监听键盘事件
const handleKeyDown = (event) => {
  if (!isListening.value) return // 如果不需要监听则直接返回

  const key = event.key.toLowerCase()

  // 检查撤销（Ctrl/Cmd + Z）
  if ((event.ctrlKey || event.metaKey) && key === 'z' && !event.shiftKey) {
    undoListLength.value && reset('undo') // 执行撤销操作
  }

  // 检查重做（Ctrl + Y/Cmd + Shift + Z）
  if ((event.ctrlKey && key === 'y') || (event.metaKey && event.shiftKey && key === 'z')) {
    redoListLength.value && reset('redo') // 执行重做操作
  }
}

// 组件挂载时开始监听
onMounted(() => {
  document.addEventListener('keydown', handleKeyDown)
})

// 组件卸载时移除监听
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown)
  isListening.value = false // 确保不再监听
})

</script>

<style lang="scss" scoped>
.edit-tool {
  display: flex;
  align-items: center;
  .operate {
    width: 120px;
    display: flex;
    align-items: center;
    font-family: Helvetica;
    font-size: 12px;
    font-weight: 400;
    line-height: 16px;
    margin-right: 0px;
    svg {
      margin-right: 8px;
    }
  }
  .divider {
    margin-left: 8px;
  }
}
</style>

