<script lang="ts" setup>
import { useSessionStorage } from '@vueuse/core'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useMarkingData } from '@/components/marking/composables/useMarkingData'
import { getOnekeyScores, useMarkingSettings } from '@/components/marking/composables/useMarkingSettings'

interface Props {
  isLandscape?: boolean
  fullScore?: number
}

interface Emits {
  (e: 'score-selected', score: number): void
}

const props = withDefaults(defineProps<Props>(), {
  isLandscape: false,
  fullScore: 12,
})

const emit = defineEmits<Emits>()

// 获取数据和设置
const markingData = useMarkingData()
const settings = useMarkingSettings()
const { currentScore } = markingData

// 计算属性
const scoreMode = computed(() => settings.value.quickScoreMode)
const currentMode = computed({
  get: () => settings.value.scoreMode,
  set: (value) => { settings.value.scoreMode = value },
})

// 是否收起
const isCollapsed = ref(true)

// 悬浮按钮的位置 (使用 SessionStorage 持久化)
const floatingButtonPosition = ref(uni.getStorageSync('quick-score-submit-button-position') || {
  x: 0,
  y: 0,
})

watch(floatingButtonPosition, (newVal) => {
  uni.setStorageSync('quick-score-submit-button-position', newVal)
})

// 初始化悬浮按钮位置
function initFloatingButtonPosition() {
  const { windowWidth, windowHeight } = uni.getSystemInfoSync()
  const buttonSize = 48
  const margin = 16
  floatingButtonPosition.value = {
    x: windowWidth - buttonSize - margin,
    y: windowHeight - buttonSize - margin,
  }
}

// 屏幕旋转监听
function handleOrientationChange() {
  initFloatingButtonPosition()
}

onMounted(() => {
  if (floatingButtonPosition.value.x === 0 && floatingButtonPosition.value.y === 0) {
    initFloatingButtonPosition()
  }
  uni.onWindowResize(handleOrientationChange)
})

onUnmounted(() => {
  uni.offWindowResize(handleOrientationChange)
})

// 拖动状态
const isDragging = ref(false)
const dragState = ref({
  startX: 0,
  startY: 0,
  startPositionX: 0,
  startPositionY: 0,
})

/**
 * 开始拖动
 */
function handleDragStart(e: TouchEvent) {
  isDragging.value = true
  const touch = e.touches[0]
  dragState.value = {
    startX: touch.clientX,
    startY: touch.clientY,
    startPositionX: floatingButtonPosition.value.x,
    startPositionY: floatingButtonPosition.value.y,
  }
}

/**
 * 拖动中
 */
function handleDragMove(e: TouchEvent) {
  if (!isDragging.value)
    return

  const touch = e.touches[0]
  const deltaX = touch.clientX - dragState.value.startX
  const deltaY = touch.clientY - dragState.value.startY

  floatingButtonPosition.value = {
    x: dragState.value.startPositionX + deltaX,
    y: dragState.value.startPositionY + deltaY,
  }
}

/**
 * 结束拖动
 */
function handleDragEnd() {
  isDragging.value = false
}

// 显示的项目列表
const displayItems = computed(() => {
  if (scoreMode.value === 'onekey') {
    const scores = getOnekeyScores(settings.value.stepSize, props.fullScore)
    return scores.map(score => ({
      type: 'score' as const,
      value: score,
      label: score.toString(),
      action: () => selectScore(score),
      class: 'border-blue-300 bg-white text-blue-600 hover:border-blue-500 hover:bg-blue-50',
    }))
  }
  else {
    const isAdd = currentMode.value === 'add'
    return settings.value.quickScoreScores.map((step) => {
      const isActive = settings.value.quickScoreClickMode && settings.value.quickScoreClickValue === step
      return {
        type: 'button' as const,
        value: isAdd ? step : -step,
        label: isAdd ? `+${step}` : `-${step}`,
        action: () => addToScore(isAdd ? step : -step),
        class: isActive
          ? (isAdd ? 'border-green-500 bg-green-500 text-white' : 'border-red-500 bg-red-500 text-white')
          : (isAdd
              ? 'border-green-300 bg-white text-green-600 hover:border-green-500 hover:bg-green-50'
              : 'border-red-300 bg-white text-red-600 hover:border-red-500 hover:bg-red-50'),
      }
    })
  }
})

// 两列布局（展开时使用）
const twoColumnLayout = computed(() => {
  const items = displayItems.value
  const layout: Array<Array<typeof items[0]>> = []

  for (let i = 0; i < items.length; i += 2) {
    const row = [items[i], items[i + 1]].filter(Boolean)
    layout.push(row)
  }

  return layout
})

// 收起/展开功能
function toggleCollapse() {
  isCollapsed.value = !isCollapsed.value
}

// 选择分数
function selectScore(score: number) {
  if (scoreMode.value === 'onekey') {
    // 一键打分模式：直接设置分数并提交
    currentScore.value = score
    emit('score-selected', score)
    submitScore(score)
  }
  else {
    // 快捷打分模式：激活点击模式
    enableQuickScoreClickMode(score)
  }
}

// 增加分数
function addToScore(addValue: number) {
  if (scoreMode.value === 'onekey') {
    const newScore = Math.min(Math.max(currentScore.value + addValue, 0), props.fullScore)
    currentScore.value = newScore
    emit('score-selected', newScore)
    submitScore(newScore)
  }
  else {
    // 快捷打分模式：激活点击模式
    enableQuickScoreClickMode(Math.abs(addValue))
  }
}

/**
 * 启用快捷打分点击模式
 */
function enableQuickScoreClickMode(value: number) {
  // 如果已经是当前值，则关闭点击模式
  if (settings.value.quickScoreClickMode && settings.value.quickScoreClickValue === value) {
    settings.value.quickScoreClickMode = false
    settings.value.quickScoreClickValue = 0
    uni.showToast({
      title: '已关闭快捷打分点击模式',
      icon: 'none',
    })
  }
  else {
    // 启用点击模式
    settings.value.quickScoreClickMode = true
    settings.value.quickScoreClickValue = value
    const modeText = currentMode.value === 'add' ? '+' : '-'
    uni.showToast({
      title: `已启用 ${modeText}${value}分 点击模式，在图片上点击即可加分并添加文字标记`,
      icon: 'none',
    })
  }
}

// 提交分数
async function submitScore(score: number) {
  try {
    await markingData.submitRecord()
  }
  catch (error) {
    console.error('提交分数失败:', error)
    uni.showToast({
      title: '提交失败',
      icon: 'none',
    })
  }
}

// 提交当前分数
async function submitCurrentScore() {
  try {
    // 如果当前分数是-1（未打分），根据模式设置默认分数
    if (currentScore.value === -1) {
      if (currentMode.value === 'subtract') {
        // 减分模式：不打分提交就是满分
        currentScore.value = props.fullScore
      }
      else {
        // 加分模式：不打分提交就是0分
        currentScore.value = 0
      }
    }

    await markingData.submitRecord()
    uni.showToast({
      title: '提交成功',
      icon: 'success',
    })
    // 关闭快捷打分点击模式
    if (settings.value.quickScoreClickMode) {
      settings.value.quickScoreClickMode = false
      settings.value.quickScoreClickValue = 0
    }
  }
  catch (error) {
    console.error('提交分数失败:', error)
    uni.showToast({
      title: '提交失败',
      icon: 'none',
    })
  }
}
</script>

<template>
  <!-- 横屏布局 -->
  <scroll-view
    v-if="isLandscape"
    scroll-y
    scroll-x
    class="z-5 h-full flex flex-grow-0 flex-col py-8px"
    :class="(isCollapsed && scoreMode === 'onekey') || scoreMode === 'quick' ? 'w-60px min-w-60px px-4px' : 'w-120px min-w-120px px-8px'"
  >
    <div class="flex flex-1 flex-col gap-4px">
      <!-- 收起时：一列布局 -->
      <template v-if="isCollapsed || scoreMode === 'quick'">
        <div
          v-for="item in displayItems"
          :key="item.label"
          class="h-32px flex cursor-pointer select-none items-center justify-center border-2 rounded-4px text-12px font-medium transition-all active:scale-95"
          :class="item.class"
          @click="item.action"
        >
          {{ item.label }}
        </div>
      </template>

      <!-- 展开时：两列布局 -->
      <template v-else>
        <div
          v-for="(row, index) in twoColumnLayout"
          :key="index"
          class="flex gap-4px"
        >
          <div
            v-for="item in row"
            :key="item.label"
            class="h-40px flex flex-1 cursor-pointer select-none items-center justify-center border rounded-lg text-14px font-bold shadow-sm transition-all active:scale-95"
            :class="item.class"
            @click="item.action"
          >
            {{ item.label }}
          </div>
          <!-- 补齐空位（奇数个时） -->
          <div v-if="row.length === 1" class="flex-1" />
        </div>
      </template>

      <!-- 收起/展开按钮 - 仅在一键打分模式显示 -->
      <div
        v-if="scoreMode === 'onekey'"
        class="mb-40px mt-6px h-40px flex flex-shrink-0 cursor-pointer items-center justify-center border border-blue-100 rounded-lg bg-blue-50 transition-all active:scale-95"
        @click="toggleCollapse"
      >
        <div
          class="size-16px text-blue-500 transition-transform"
          :class="!isCollapsed ? 'i-carbon-chevron-right' : 'i-carbon-chevron-left'"
        />
      </div>
    </div>

    <!-- 快捷打分模式切换 -->
    <div v-if="scoreMode === 'quick'" class="mt-12px flex flex-col gap-8px">
      <div
        class="h-40px flex cursor-pointer items-center justify-center border rounded-lg text-12px font-bold shadow-sm transition-all"
        :class="currentMode === 'add' ? 'border-green-500 bg-green-500 text-white ring-2 ring-green-200' : 'border-slate-200 bg-white text-slate-600 hover:bg-slate-50'"
        @click="currentMode = 'add'"
      >
        加分
      </div>
      <div
        class="h-40px flex cursor-pointer items-center justify-center border rounded-lg text-12px font-bold shadow-sm transition-all"
        :class="currentMode === 'subtract' ? 'border-red-500 bg-red-500 text-white ring-2 ring-red-200' : 'border-slate-200 bg-white text-slate-600 hover:bg-slate-50'"
        @click="currentMode = 'subtract'"
      >
        减分
      </div>
    </div>
  </scroll-view>

  <!-- 竖屏布局 -->
  <scroll-view
    v-else
    scroll-y
    scroll-x
    class="z-5 h-full flex flex-grow-0 flex-col py-16rpx"
    :class="(isCollapsed && scoreMode === 'onekey') || scoreMode === 'quick' ? 'w-100rpx min-w-100rpx px-8rpx' : 'w-160rpx min-w-160rpx px-12rpx'"
  >
    <div class="flex flex-1 flex-col gap-8rpx">
      <!-- 收起时：一列布局 -->
      <template v-if="isCollapsed || scoreMode === 'quick'">
        <div
          v-for="item in displayItems"
          :key="item.label"
          class="h-64rpx flex cursor-pointer select-none items-center justify-center border-2 rounded-8rpx text-24rpx font-medium transition-all active:scale-95"
          :class="item.class"
          @click="item.action"
        >
          {{ item.label }}
        </div>
      </template>

      <!-- 展开时：两列布局 -->
      <template v-else>
        <div
          v-for="(row, index) in twoColumnLayout"
          :key="index"
          class="flex gap-8rpx"
        >
          <div
            v-for="item in row"
            :key="item.label"
            class="h-80rpx flex flex-1 cursor-pointer select-none items-center justify-center border rounded-16rpx text-28rpx font-bold shadow-sm transition-all active:scale-95"
            :class="item.class"
            @click="item.action"
          >
            {{ item.label }}
          </div>
          <!-- 补齐空位（奇数个时） -->
          <div v-if="row.length === 1" class="flex-1" />
        </div>
      </template>

      <!-- 收起/展开按钮 - 仅在一键打分模式显示 -->
      <div
        v-if="scoreMode === 'onekey'"
        class="mb-40px mt-12rpx h-80rpx flex flex-shrink-0 cursor-pointer items-center justify-center border border-blue-100 rounded-16rpx bg-blue-50 transition-all active:scale-95"
        @click="toggleCollapse"
      >
        <div
          class="size-32rpx text-blue-500 transition-transform"
          :class="!isCollapsed ? 'i-carbon-chevron-right' : 'i-carbon-chevron-left'"
        />
      </div>
    </div>

    <!-- 快捷打分模式切换 -->
    <div v-if="scoreMode === 'quick'" class="mt-16rpx flex flex-col gap-12rpx">
      <div
        class="h-80rpx flex cursor-pointer items-center justify-center border rounded-16rpx text-26rpx font-bold shadow-sm transition-all"
        :class="currentMode === 'add' ? 'border-green-500 bg-green-500 text-white ring-2 ring-green-200' : 'border-slate-200 bg-white text-slate-600 hover:bg-slate-50'"
        @click="currentMode = 'add'"
      >
        加分
      </div>
      <div
        class="h-80rpx flex cursor-pointer items-center justify-center border rounded-16rpx text-26rpx font-bold shadow-sm transition-all"
        :class="currentMode === 'subtract' ? 'border-red-500 bg-red-500 text-white ring-2 ring-red-200' : 'border-slate-200 bg-white text-slate-600 hover:bg-slate-50'"
        @click="currentMode = 'subtract'"
      >
        减分
      </div>
    </div>
  </scroll-view>

  <!-- 快捷打分模式的悬浮提交按钮 -->
  <div
    v-if="scoreMode === 'quick'"
    class="fixed z-10 size-48px flex select-none items-center justify-center border-2 border-blue-500 rounded-full bg-blue-500 text-14px text-white shadow-xl transition-transform lg:size-56px active:scale-95"
    :class="{
      'cursor-move': isDragging,
      'cursor-pointer': !isDragging,
    }"
    :style="{
      left: `${floatingButtonPosition.x}px`,
      top: `${floatingButtonPosition.y}px`,
      touchAction: 'none',
    }"
    @touchstart.stop="handleDragStart"
    @touchmove.stop="handleDragMove"
    @touchend.stop="handleDragEnd"
    @click.stop="!isDragging && submitCurrentScore()"
  >
    提交
  </div>
</template>
