<script setup lang="ts">
import type { MarkingSubmitData } from '../../composables/useMarkingData'
import { useSessionStorage } from '@vueuse/core'
import { DictCode, useDict } from '@/composables/useDict'
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 toolbarRef = ref<HTMLElement>()

// 收起状态
const isCollapsed = ref(uni.getStorageSync('marking-toolbar-collapsed') || false)
watch(isCollapsed, (newVal) => {
  uni.setStorageSync('marking-toolbar-collapsed', newVal)
})

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

/**
 * 将 SVG 转换为 data URL（用于小程序）
 */
function svgToDataURL(svg: string): string {
  svg = svg.replace(/data-(.*?=(['"]).*?\2)/g, '$1')
  svg = svg.replace(/xlink-href=/g, 'xlink:href=')
  svg = svg.replace(/view-box=/g, 'viewBox=')
  svg = svg.replace(/<(title|desc|defs)>[\s\S]*?<\/\1>/g, '')
  if (!/xmlns=/.test(svg))
    svg = svg.replace(/<svg/, '<svg xmlns=\'http://www.w3.org/2000/svg\'')
  svg = svg.replace(/\d+\.\d+/g, match => Number.parseFloat(Number.parseFloat(match).toFixed(2)) as any)
  svg = svg.replace(/<!--[\s\S]*?-->/g, '')
  svg = svg.replace(/\s+/g, ' ')
  svg = svg.replace(/[{}|\\^~[\]`"<>#%]/g, (match) => {
    return `%${match[0].charCodeAt(0).toString(16).toUpperCase()}`
  })
  svg = svg.replace(/'/g, '\\\'')
  return `data:image/svg+xml,${svg.trim()}`
}

/**
 * 生成半对标记的 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>
  <div
    ref="toolbarRef"
    class="fixed z-5 flex flex-col items-start transition-all duration-300 ease-out"
    :class="[
      isLandscape
        ? 'bottom-12px left-1/2 -translate-x-1/2 items-center'
        : 'bottom-48rpx left-12rpx items-start max-w-[75vw]',
    ]"
    @touchend.stop
    @touchmove.stop
    @touchstart.stop
  >
    <!-- 收起状态 (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="toggleCollapse"
    >
      <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-12rpx pr-6rpx py-10rpx gap-4rpx',
        { 'animate-fade-in-up': !isCollapsed },
      ]"
    >
      <!-- 收起按钮 -->
      <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-60rpx'"
        @click="toggleCollapse"
      >
        <div
          :class="[
            isLandscape ? 'i-carbon:chevron-down size-20px' : 'i-carbon:chevron-left size-36rpx',
          ]"
        />
      </div>

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

      <!-- 工具内容区域 (竖屏时可滚动) -->
      <scroll-view
        :scroll-x="true"
        :show-scrollbar="false"
        class="flex whitespace-nowrap"
        :class="isLandscape ? 'w-auto' : 'max-w-[65vw]'"
      >
        <div class="flex items-center" :class="isLandscape ? 'gap-6px' : 'gap-16rpx'">
          <!-- 标记组 -->
          <div class="flex items-center rounded-full bg-slate-50" :class="isLandscape ? 'p-4px gap-4px' : 'p-6rpx gap-8rpx'">
            <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-64rpx',
                ]"
                @click="handleMarkTool('correct')"
              >
                <div class="i-fluent:checkmark-24-regular" :class="isLandscape ? 'size-20px' : 'size-40rpx'" />
              </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-64rpx',
                ]"
                @click="handleMarkTool('wrong')"
              >
                <div class="i-fluent:dismiss-24-regular" :class="isLandscape ? 'size-20px' : 'size-40rpx'" />
              </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-64rpx',
                ]"
                @click="handleMarkTool('half')"
              >
                <view
                  :class="isLandscape ? 'size-20px' : 'size-40rpx'"
                  :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-6rpx gap-8rpx'">
            <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-64rpx',
                ]"
                @click="switchTool(MarkingTool.PEN)"
              >
                <div class="i-fluent:pen-24-regular" :class="isLandscape ? 'size-20px' : 'size-40rpx'" />
              </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-64rpx',
                ]"
                @click="switchTool(MarkingTool.TEXT)"
              >
                <div class="i-fluent:text-24-regular" :class="isLandscape ? 'size-20px' : 'size-40rpx'" />
              </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-64rpx',
                ]"
                @click="switchTool(MarkingTool.ERASER)"
              >
                <div class="i-fluent:eraser-24-regular" :class="isLandscape ? 'size-20px' : 'size-40rpx'" />
              </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-12rpx'">
            <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-64rpx px-20rpx text-24rpx',
              ]"
              @click="toggleSpecialMark(type as any)"
            >
              {{ type === 'excellent' ? '优秀' : type === 'typical' ? '典例' : '问题' }}
            </div>
          </div>
        </div>
      </scroll-view>
    </div>
  </div>
</template>

<style scoped>
.animate-fade-in-up {
  animation: fadeInUp 0.2s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
