<script lang="ts" setup>
import { computed, ref } from 'vue'
import { useMarkingData } from '@/components/marking/composables/useMarkingData'
import { getSelectedOnekeyScores, 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(false)

// 显示的项目列表
const displayItems = computed(() => {
  if (scoreMode.value === 'onekey') {
    // 一键打分：根据当前满分和用户选择动态获取分数
    const selectedScores = getSelectedOnekeyScores(
      settings.value.stepSize,
      props.fullScore,
      settings.value.onekeyScoreSelections,
    )

    return selectedScores.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 {
    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>
  <div
    class="absolute right-2 top-2 z-10 flex flex-col gap-2px"
    :class="{
      'space-y-4px bottom-50px top-120px overflow-auto': !isLandscape,
      'h-[calc(100vh-120px)] overflow-auto': isLandscape && isCollapsed,
      'h-[calc(100vh-80px)] overflow-auto': isLandscape && !isCollapsed,
    }"
  >
    <!-- 按钮内容 - 始终展示 -->
    <div class="flex flex-col gap-2px">
      <!-- 收起时：一列布局 -->
      <template v-if="isCollapsed">
        <div
          v-for="item in displayItems"
          :key="item.label"
          class="flex cursor-pointer items-center justify-center border-2 rounded-8px transition-all active:scale-95"
          :class="[
            item.class,
            scoreMode === 'onekey' ? 'size-48rpx lg:size-12' : 'h-48rpx w-80rpx lg:h-12 lg:w-20',
          ]"
          @click="item.action"
        >
          <text
            class="font-medium"
            :class="scoreMode === 'onekey' ? 'text-18rpx lg:text-base' : 'text-14rpx lg:text-sm'"
          >
            {{ item.label }}
          </text>
        </div>
      </template>

      <!-- 展开时：两列布局 -->
      <template v-else>
        <div
          v-for="(row, index) in twoColumnLayout"
          :key="index"
          class="flex gap-2px"
        >
          <div
            v-for="item in row"
            :key="item.label"
            class="flex cursor-pointer items-center justify-center border-2 rounded-8px transition-all active:scale-95"
            :class="[
              item.class,
              scoreMode === 'onekey' ? 'size-48rpx lg:size-12' : 'h-48rpx w-80rpx lg:h-12 lg:w-20',
            ]"
            @click="item.action"
          >
            <text
              class="font-medium"
              :class="scoreMode === 'onekey' ? 'text-18rpx lg:text-base' : 'text-14rpx lg:text-sm'"
            >
              {{ item.label }}
            </text>
          </div>
          <!-- 补齐空位（奇数个时） -->
          <div
            v-if="row.length === 1"
            :class="scoreMode === 'onekey' ? 'size-48rpx lg:size-12' : 'h-48rpx w-80rpx lg:h-12 lg:w-20'"
          />
        </div>
      </template>
    </div>

    <!-- 收起/展开按钮 - 始终显示 -->
    <div
      class="flex cursor-pointer items-center justify-center border-2 border-blue-200 rounded-8px bg-blue-50 transition-all active:scale-95"
      :class="isLandscape ? 'size-48rpx lg:size-12' : 'size-10'"
      @click="toggleCollapse"
    >
      <div
        class="text-blue-500 transition-transform"
        :class="isCollapsed ? 'i-carbon-chevron-left' : 'i-carbon-chevron-right'"
      />
    </div>

    <!-- 快捷打分模式切换 -->
    <div v-if="scoreMode === 'quick'" class="mt-16px flex flex-col gap-8rpx">
      <div
        class="flex flex-1 cursor-pointer items-center justify-center border rounded-16px py-8rpx transition-all"
        :class="currentMode === 'add' ? 'border-green-500 bg-green-50 text-green-600' : 'border-gray-300 bg-white text-gray-600'"
        @click="currentMode = 'add'"
      >
        <text class="text-12px">加分模式</text>
      </div>
      <div
        class="flex flex-1 cursor-pointer items-center justify-center border rounded-16px py-8rpx transition-all"
        :class="currentMode === 'subtract' ? 'border-red-500 bg-red-50 text-red-600' : 'border-gray-300 bg-white text-gray-600'"
        @click="currentMode = 'subtract'"
      >
        <text class="text-12px">减分模式</text>
      </div>

      <!-- 快捷打分提交按钮 -->
      <div
        class="mt-8rpx flex cursor-pointer items-center justify-center border-2 border-blue-500 rounded-16px bg-blue-500 py-12rpx transition-all active:scale-95"
        @click="submitCurrentScore"
      >
        <text class="text-14px text-white font-medium">提交分数</text>
      </div>
    </div>
  </div>
</template>
