<script setup lang="ts">
import type { MarkingSubmitData } from '../../composables/useMarkingData'
import { DictCode, useDict } from '@/composables/useDict'
import { svgToDataURL } from '@/utils/dom'
import { MarkingTool } from '../../composables/renderer/useMarkingDom'
import { markingSettings as settings } from '../../composables/useMarkingSettings'

interface Props {
  canUndo?: boolean
  canRedo?: boolean
  hasMarks?: boolean
  specialMarks?: {
    excellent: boolean
    typical: boolean
    problem: boolean
  }
  isLandscape?: boolean
  currentMarkingData?: MarkingSubmitData
}

const props = withDefaults(defineProps<Props>(), {
  canUndo: false,
  canRedo: false,
  hasMarks: false,
  specialMarks: () => ({
    excellent: false,
    typical: false,
    problem: false,
  }),
  isLandscape: false,
})

const emit = defineEmits<{
  'add-correct-mark': [position: { x: number, y: number }]
  'add-wrong-mark': [position: { x: number, y: number }]
  'add-half-mark': [position: { x: number, y: number }]
  'undo': []
  'redo': []
  'clear-all': []
  'toggle-special-mark': [type: 'excellent' | 'typical' | 'problem']
}>()
const currentTool = defineModel<MarkingTool>('currentTool', { required: true })

// 收起状态
const isCollapsed = ref(uni.getStorageSync('marking-toolbar-collapsed') || false)
// 用于控制动画，只有用户主动展开时才显示动画
const shouldAnimate = ref(false)

watch(isCollapsed, (newVal) => {
  uni.setStorageSync('marking-toolbar-collapsed', newVal)
  // 只有从收起到展开时才需要动画
  if (!newVal) {
    shouldAnimate.value = true
  }
  // 收起/展开后重新计算位置，或者保持位置不变（保持 top/left 不变自然就是 anchored to top-left）
})

const { getDictOptionsComputed } = useDict()
const { options: problemTypeOptions } = getDictOptionsComputed(DictCode.SCAN_ANOMALY_STATUS)

// --- Position & Dragging Logic ---
const position = ref<{ x: number, y: number } | null>(null)
const storageKey = computed(() => `marking-toolbar-pos-${props.isLandscape ? 'landscape' : 'portrait'}`)

// 初始化或重置位置
function loadPosition() {
  const stored = uni.getStorageSync(storageKey.value)
  if (stored) {
    position.value = stored
  }
  else {
    // 如果没有存储的位置，设置默认位置为左下角
    const { windowHeight } = uni.getSystemInfoSync()
    const offset = props.isLandscape ? 12 : 48 // 与 CSS 中的 bottom/left 保持一致
    position.value = {
      x: offset,
      y: windowHeight - offset - (props.isLandscape ? 48 : 80), // 减去按钮高度
    }
  }
}

watch(() => props.isLandscape, () => {
  loadPosition()
}, { immediate: true })

// 拖拽状态
let isDragging = false
let hasMoved = false // 是否有实际移动
let startTouch = { x: 0, y: 0 }
let startPos = { x: 0, y: 0 }
let touchStartTime = 0 // 触摸开始时间

// 判断是否为点击的阈值
const CLICK_DISTANCE_THRESHOLD = 20 // 移动距离小于20px认为是点击
const CLICK_TIME_THRESHOLD = 300 // 时间小于300ms认为是点击

function onTouchStart(e: TouchEvent) {
  if (e.touches.length !== 1)
    return

  // 阻止冒泡，防止触发画布点击等
  // e.stopPropagation() // 在模板中使用 .stop

  const touch = e.touches[0]
  startTouch = { x: touch.clientX, y: touch.clientY }
  touchStartTime = Date.now()
  isDragging = true
  hasMoved = false

  if (position.value) {
    startPos = { ...position.value }
  }
  else {
    // 如果当前是默认位置（CSS定位），需要先获取当前实际位置
    // 使用 uni.createSelectorQuery 兼容小程序
    const query = uni.createSelectorQuery().in(getCurrentInstance())
    query.select('.trace-toolbar').boundingClientRect((data) => {
      const rect = data as UniApp.NodeInfo
      if (rect) {
        position.value = { x: rect.left || 0, y: rect.top || 0 }
        startPos = { x: rect.left || 0, y: rect.top || 0 }
      }
    }).exec()
  }
}

function onTouchMove(e: TouchEvent) {
  if (!isDragging || e.touches.length !== 1)
    return

  const touch = e.touches[0]
  const dx = touch.clientX - startTouch.x
  const dy = touch.clientY - startTouch.y
  const distance = Math.sqrt(dx * dx + dy * dy)

  // 如果移动距离超过阈值，标记为已移动
  if (distance > CLICK_DISTANCE_THRESHOLD) {
    hasMoved = true
  }

  // 如果起始位置还没获取到（异步Query），则跳过
  if (!position.value && dx === 0 && dy === 0)
    return

  // 简单的防抖或阈值可以加在这里，但为了流畅性直接更新
  // 如果 position 刚被 query 设置，可能在这里会突变？
  // 应该基于 startPos 更新

  // 如果 startPos 还是 0,0 且 position 也是 null (Query 还没回来)，忽略
  // 这里简化处理，假设 Query 很快或下一次 move 生效

  if (position.value) {
    const newX = startPos.x + dx
    const newY = startPos.y + dy

    // 边界限制（可选，这里暂不严格限制，允许拖到边缘）
    const { windowWidth, windowHeight } = uni.getSystemInfoSync()
    // 简单限制在屏幕内
    // position.value = {
    //   x: Math.max(0, Math.min(newX, windowWidth - 40)),
    //   y: Math.max(0, Math.min(newY, windowHeight - 40))
    // }
    position.value = { x: newX, y: newY }
  }
}

function onTouchEnd() {
  const touchDuration = Date.now() - touchStartTime

  // 判断是否为点击：移动距离短 且 时间短
  const isClick = !hasMoved && touchDuration < CLICK_TIME_THRESHOLD

  if (isDragging && position.value && !isClick) {
    // 只有在真正拖拽时才保存位置
    uni.setStorageSync(storageKey.value, position.value)
  }
  else if (isClick) {
    // 如果是点击，恢复原始位置
    position.value = startPos.x !== 0 || startPos.y !== 0 ? { ...startPos } : position.value
  }

  isDragging = false
  hasMoved = false
}

/**
 * 生成半对标记的 SVG data URL
 */
function generateHalfMarkSvg(isActive: boolean): string {
  const color = isActive ? '#ffffff' : '#eab308'
  const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
    <line x1="6" y1="12" x2="10.5" y2="16.5" stroke="${color}" stroke-width="2" stroke-linecap="round" fill="none"/>
    <line x1="10.5" y1="16.5" x2="18" y2="7.5" stroke="${color}" stroke-width="2" stroke-linecap="round" fill="none"/>
    <line x1="11.25" y1="9.38" x2="17.25" y2="15" stroke="${color}" stroke-width="2" stroke-linecap="round" fill="none"/>
  </svg>`
  return svgToDataURL(svg)
}

const halfMarkSvg = computed(() => {
  const isActive = currentTool.value === MarkingTool.HALF
  return generateHalfMarkSvg(isActive)
})

// 待放置标记的状态
const pendingMarkType = ref<'correct' | 'wrong' | 'half' | null>(null)

// 画笔提示相关
const PEN_TOOLTIP_KEY = 'marking-pen-tooltip-shown'

function showPenTooltip() {
  const hasShown = uni.getStorageSync(PEN_TOOLTIP_KEY)
  if (!hasShown) {
    uni.showModal({
      title: '温馨提示',
      content: '激活画笔时无法在图片上滚动试卷，如需滚动请再次点击画笔关闭，或者滚动图片外的区域',
      showCancel: false,
      confirmText: '知道了',
      success: () => {
        uni.setStorageSync(PEN_TOOLTIP_KEY, true)
      },
    })
  }
}

/**
 * 切换工具（支持取消激活）
 */
function switchTool(tool: MarkingTool) {
  const wasDeactivated = currentTool.value === tool
  currentTool.value = wasDeactivated ? MarkingTool.SELECT : tool
  pendingMarkType.value = null

  if (!wasDeactivated && tool === MarkingTool.PEN) {
    showPenTooltip()
  }

  settings.value.showToolOptions = currentTool.value === 'pen' || currentTool.value === 'text'
}

/**
 * 处理标记工具切换
 */
function handleMarkTool(type: 'correct' | 'wrong' | 'half') {
  const toolMap = {
    correct: MarkingTool.CORRECT,
    wrong: MarkingTool.WRONG,
    half: MarkingTool.HALF,
  }
  const tool = toolMap[type]
  currentTool.value = currentTool.value === tool ? MarkingTool.SELECT : tool
  pendingMarkType.value = null
}

/**
 * 处理图片点击
 */
function handleImageClick(position: { x: number, y: number }) {
  if (pendingMarkType.value) {
    switch (pendingMarkType.value) {
      case 'correct':
        emit('add-correct-mark', position)
        break
      case 'wrong':
        emit('add-wrong-mark', position)
        break
      case 'half':
        emit('add-half-mark', position)
        break
    }
    pendingMarkType.value = null
  }
}

/**
 * 切换特殊标记
 */
function toggleSpecialMark(type: 'excellent' | 'typical' | 'problem') {
  emit('toggle-special-mark', type)
}

function toggleCollapse() {
  isCollapsed.value = !isCollapsed.value
}

// 暴露点击处理方法给父组件
defineExpose({
  handleImageClick,
})
</script>

<template>
  <wd-root-portal>
    <div
      class="trace-toolbar fixed z-15 flex flex-col items-start transition-opacity duration-300 ease-out"
      :class="[
        !position && (isLandscape
          ? 'bottom-12px left-1/2 -translate-x-1/2 items-center'
          : 'bottom-48rpx left-12rpx items-start'), // Removed max-w-[75vw]
      ]"
      :style="position ? { left: `${position.x}px`, top: `${position.y}px` } : {}"
    >
      <!-- 收起状态 (FAB) - 可以拖拽 -->
      <div
        v-if="isCollapsed"
        class="flex cursor-pointer items-center justify-center rounded-full bg-white shadow-lg transition-all active:scale-95"
        :class="isLandscape ? 'size-48px' : 'size-80rpx'"
        @click.stop="toggleCollapse"
        @touchend.stop="onTouchEnd"
        @touchmove.stop.prevent="onTouchMove"
        @touchstart.stop="onTouchStart"
      >
        <div class="i-fluent:edit-24-regular text-blue-600" :class="isLandscape ? 'size-24px' : 'size-40rpx'" />
      </div>

      <!-- 展开状态 - 不可拖拽 -->
      <div
        v-else
        class="flex items-center rounded-full bg-white shadow-xl ring-1 ring-slate-900 ring-opacity-5 transition-all"
        :class="[
          isLandscape ? 'px-8px py-4px gap-4px' : 'pl-8rpx pr-4rpx py-8rpx gap-2rpx', // 竖屏减小内边距和间距
        ]"
      >
        <!-- 收起按钮 -->
        <div
          class="flex flex-shrink-0 cursor-pointer items-center justify-center rounded-full text-slate-400 active:scale-95 hover:bg-slate-100"
          :class="isLandscape ? 'size-32px' : 'size-48rpx'"
          @click.stop="toggleCollapse"
        >
          <!-- 竖屏尺寸减小 size-60rpx -> size-48rpx -->
          <div
            :class="[
              isLandscape ? 'i-carbon:chevron-down size-20px' : 'i-carbon:chevron-left size-32rpx', // 竖屏 icon 减小
            ]"
          />
        </div>

        <!-- 分隔线 -->
        <div class="h-4/5 w-1px flex-shrink-0 bg-slate-200" />

        <!-- 工具内容区域 (竖屏时不滚动，全显示) -->
        <!-- 移除 scroll-view，改为 div flex -->
        <div
          class="flex whitespace-nowrap"
          :class="isLandscape ? 'w-auto' : ''"
        >
          <div class="flex items-center" :class="isLandscape ? 'gap-6px' : 'gap-8rpx'">
            <!-- 标记组 -->
            <div class="flex items-center rounded-full bg-slate-50" :class="isLandscape ? 'p-4px gap-4px' : 'p-4rpx gap-4rpx'">
              <!-- 竖屏 padding/gap 减小 -->
              <wd-tooltip :content="isLandscape ? '正确' : ''" placement="top">
                <div
                  class="flex cursor-pointer items-center justify-center rounded-full transition-all active:scale-95"
                  :class="[
                    currentTool === MarkingTool.CORRECT ? 'bg-green-500 text-white shadow-md' : 'text-slate-500 hover:bg-white hover:text-green-600',
                    isLandscape ? 'size-32px' : 'size-48rpx', // 竖屏尺寸减小
                  ]"
                  @click.stop="handleMarkTool('correct')"
                >
                  <div class="i-fluent:checkmark-24-regular" :class="isLandscape ? 'size-20px' : 'size-32rpx'" />
                </div>
              </wd-tooltip>

              <wd-tooltip :content="isLandscape ? '错误' : ''" placement="top">
                <div
                  class="flex cursor-pointer items-center justify-center rounded-full transition-all active:scale-95"
                  :class="[
                    currentTool === MarkingTool.WRONG ? 'bg-red-500 text-white shadow-md' : 'text-slate-500 hover:bg-white hover:text-red-600',
                    isLandscape ? 'size-32px' : 'size-48rpx',
                  ]"
                  @click.stop="handleMarkTool('wrong')"
                >
                  <div class="i-fluent:dismiss-24-regular" :class="isLandscape ? 'size-20px' : 'size-32rpx'" />
                </div>
              </wd-tooltip>

              <wd-tooltip :content="isLandscape ? '半对' : ''" placement="top">
                <div
                  class="flex cursor-pointer items-center justify-center rounded-full transition-all active:scale-95"
                  :class="[
                    currentTool === MarkingTool.HALF ? 'bg-yellow-500 text-white shadow-md' : 'text-slate-500 hover:bg-white hover:text-yellow-600',
                    isLandscape ? 'size-32px' : 'size-48rpx',
                  ]"
                  @click.stop="handleMarkTool('half')"
                >
                  <view
                    :class="isLandscape ? 'size-20px' : 'size-32rpx'"
                    :style="{
                      backgroundImage: `url('${halfMarkSvg}')`,
                      backgroundSize: 'contain',
                      backgroundRepeat: 'no-repeat',
                      backgroundPosition: 'center',
                    }"
                  />
                </div>
              </wd-tooltip>
            </div>

            <!-- 分隔线 -->
            <div class="h-20px w-1px flex-shrink-0 bg-slate-200" />

            <!-- 绘图组 -->
            <div class="flex items-center rounded-full bg-slate-50" :class="isLandscape ? 'p-4px gap-4px' : 'p-4rpx gap-4rpx'">
              <wd-tooltip :content="isLandscape ? '画笔' : ''" placement="top">
                <div
                  class="flex cursor-pointer items-center justify-center rounded-full transition-all active:scale-95"
                  :class="[
                    currentTool === MarkingTool.PEN ? 'bg-blue-600 text-white shadow-md' : 'text-slate-500 hover:bg-white hover:text-blue-600',
                    isLandscape ? 'size-32px' : 'size-48rpx',
                  ]"
                  @click.stop="switchTool(MarkingTool.PEN)"
                >
                  <div class="i-fluent:pen-24-regular" :class="isLandscape ? 'size-20px' : 'size-32rpx'" />
                </div>
              </wd-tooltip>

              <wd-tooltip :content="isLandscape ? '文字' : ''" placement="top">
                <div
                  class="flex cursor-pointer items-center justify-center rounded-full transition-all active:scale-95"
                  :class="[
                    currentTool === MarkingTool.TEXT ? 'bg-blue-600 text-white shadow-md' : 'text-slate-500 hover:bg-white hover:text-blue-600',
                    isLandscape ? 'size-32px' : 'size-48rpx',
                  ]"
                  @click.stop="switchTool(MarkingTool.TEXT)"
                >
                  <div class="i-fluent:text-24-regular" :class="isLandscape ? 'size-20px' : 'size-32rpx'" />
                </div>
              </wd-tooltip>

              <wd-tooltip :content="isLandscape ? '擦除' : ''" placement="top">
                <div
                  class="flex cursor-pointer items-center justify-center rounded-full transition-all active:scale-95"
                  :class="[
                    currentTool === MarkingTool.ERASER ? 'bg-slate-600 text-white shadow-md' : 'text-slate-500 hover:bg-white hover:text-slate-700',
                    isLandscape ? 'size-32px' : 'size-48rpx',
                  ]"
                  @click.stop="switchTool(MarkingTool.ERASER)"
                >
                  <div class="i-fluent:eraser-24-regular" :class="isLandscape ? 'size-20px' : 'size-32rpx'" />
                </div>
              </wd-tooltip>
            </div>

            <!-- 分隔线 -->
            <div class="h-20px w-1px flex-shrink-0 bg-slate-200" />

            <!-- 特殊标记组 -->
            <div class="flex items-center" :class="isLandscape ? 'gap-6px' : 'gap-6rpx'">
              <div
                v-for="type in ['excellent', 'typical', 'problem']"
                :key="type"
                class="flex flex-shrink-0 cursor-pointer items-center justify-center rounded-full font-medium transition-all active:scale-95"
                :class="[
                  specialMarks[type as keyof typeof specialMarks]
                    ? (type === 'excellent' ? 'bg-yellow-100 text-yellow-700' : type === 'typical' ? 'bg-blue-100 text-blue-700' : 'bg-red-100 text-red-700')
                    : 'bg-slate-50 text-slate-500 hover:bg-slate-100',
                  isLandscape ? 'h-32px px-12px text-12px' : 'h-48rpx px-12rpx text-20rpx', // 竖屏减小
                ]"
                @click.stop="toggleSpecialMark(type as any)"
              >
                {{ type === 'excellent' ? '优秀' : type === 'typical' ? '典例' : '问题' }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </wd-root-portal>
</template>
