<script lang="ts" setup>
import { computed, ref } from 'vue'
import { VueDraggable } from 'vue-draggable-plus'
import {
  generateOnekeyScores,
  getSelectedOnekeyScores,
  updateOnekeyScoreSelection,
  useMarkingSettings,
} from '@/components/marking/composables/useMarkingSettings'

interface Props {
  modelValue: boolean
  fullScore?: number
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', data: { stepSize: number, commonScores: number[] }): void
}

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

const emit = defineEmits<Emits>()

// 弹窗显示状态
const visible = computed({
  get: () => props.modelValue,
  set: value => emit('update:modelValue', value),
})

// 配置项
const settings = useMarkingSettings()

// 当前选项卡
const activeTab = computed({
  get: () => settings.value.quickScoreMode,
  set: (value) => {
    settings.value.quickScoreMode = value
  },
})

// 步长选项
const stepOptions = [0.5, 1, 2, 3, 4, 5]

// 常用给分选项 - 根据当前选项卡动态计算
const commonScores = computed(() => {
  if (activeTab.value === 'onekey') {
    // 一键打分模式：根据步长和满分动态生成
    return generateOnekeyScores(settings.value.stepSize, props.fullScore)
  }
  else {
    // 快捷打分模式：固定的步长选项
    return [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
  }
})

// 选择步长
function selectStepSize(step: number) {
  settings.value.stepSize = step
  // 步长变化时不需要特殊处理，分数会自动重新计算
}

// 自定义步长输入
const showCustomStepInput = ref(false)
const customStepValue = ref('')

// 已选择的常用给分
const selectedCommonScores = computed(() => {
  if (activeTab.value === 'onekey') {
    // 一键打分：根据用户选择状态和当前满分动态计算
    return getSelectedOnekeyScores(
      settings.value.stepSize,
      props.fullScore,
      settings.value.onekeyScoreSelections,
    )
  }
  else {
    return settings.value.quickScoreScores
  }
})

// 排序后的分数（拖拽用）
const draggableScores = computed({
  get: () => {
    return [...selectedCommonScores.value]
  },
  set: (newOrder: number[]) => {
    if (activeTab.value === 'onekey') {
      // 一键打分：更新选择状态以反映新的排序
      // 先清除当前步长和满分的所有选择
      const currentKey = `${settings.value.stepSize}_${props.fullScore}`
      Object.keys(settings.value.onekeyScoreSelections).forEach((key) => {
        if (key.startsWith(currentKey)) {
          delete settings.value.onekeyScoreSelections[key]
        }
      })

      // 重新设置选中的分数
      newOrder.forEach((score) => {
        updateOnekeyScoreSelection(
          settings.value.stepSize,
          props.fullScore,
          score,
          true,
          settings.value.onekeyScoreSelections,
        )
      })
    }
    else {
      settings.value.quickScoreScores = newOrder
    }
  },
})

// 排序后的分数（一键打分）
const sortedScores = computed(() => {
  if (activeTab.value === 'onekey') {
    return [...selectedCommonScores.value].sort((a, b) => a - b)
  }
  return []
})

// 排序后的分数（快捷打分）
const sortedQuickScores = computed(() => {
  return [...selectedCommonScores.value].sort((a, b) => a - b)
})

// 快捷打分步长限制检查
const canAddMoreSteps = computed(() => {
  if (activeTab.value === 'quick') {
    return settings.value.quickScoreScores.length < 5
  }
  return true // 一键打分不受限制
})

// 切换常用给分选择
function toggleCommonScore(score: number) {
  if (activeTab.value === 'onekey') {
    // 一键打分：更新选择状态
    const isCurrentlySelected = selectedCommonScores.value.includes(score)
    updateOnekeyScoreSelection(
      settings.value.stepSize,
      props.fullScore,
      score,
      !isCurrentlySelected,
      settings.value.onekeyScoreSelections,
    )
  }
  else {
    const currentScores = [...settings.value.quickScoreScores]
    const index = currentScores.indexOf(score)
    if (index > -1) {
      currentScores.splice(index, 1)
    }
    else {
      // 检查快捷打分步长限制
      if (currentScores.length >= 5) {
        uni.showToast({
          title: '快捷打分最多5个步长',
          icon: 'none',
        })
        return
      }
      currentScores.push(score)
    }
    settings.value.quickScoreScores = currentScores
  }
}

// 显示自定义步长输入
function showCustomInput() {
  if (!canAddMoreSteps.value) {
    uni.showToast({
      title: '快捷打分最多5个步长',
      icon: 'none',
    })
    return
  }
  showCustomStepInput.value = true
}

// 添加自定义步长
function addCustomStep() {
  const value = Number.parseFloat(customStepValue.value)

  // 验证输入
  if (Number.isNaN(value) || value <= 0) {
    uni.showToast({
      title: '请输入有效的数值',
      icon: 'none',
    })
    return
  }

  // 验证步长规则（必须是0.5的整数倍）
  if (value % 0.5 !== 0) {
    uni.showToast({
      title: '步长必须是0.5的整数倍',
      icon: 'none',
    })
    return
  }

  // 验证不能超出满分
  if (value > props.fullScore) {
    uni.showToast({
      title: '步长不能超出满分',
      icon: 'none',
    })
    return
  }

  // 验证不能重复
  if (settings.value.quickScoreScores.includes(value)) {
    uni.showToast({
      title: '步长不能重复',
      icon: 'none',
    })
    return
  }

  // 添加步长（只有快捷打分模式支持自定义）
  const currentScores = [...settings.value.quickScoreScores, value]
  settings.value.quickScoreScores = currentScores

  // 重置输入
  customStepValue.value = ''
  showCustomStepInput.value = false
}

// 取消自定义输入
function cancelCustomInput() {
  customStepValue.value = ''
  showCustomStepInput.value = false
}

// 重新排序（从小到大）
function resetSortOrder() {
  if (activeTab.value === 'onekey') {
    // 一键打分：重新排序不需要特殊处理，因为draggableScores会自动处理
    const sortedScores = [...selectedCommonScores.value].sort((a, b) => a - b)
    draggableScores.value = sortedScores
  }
  else {
    settings.value.quickScoreScores = [...settings.value.quickScoreScores].sort((a, b) => a - b)
  }
}

// 关闭弹窗
function close() {
  visible.value = false
}

// 确认设置
function confirm() {
  emit('confirm', {
    stepSize: settings.value.stepSize,
    commonScores: selectedCommonScores.value,
  })
  close()
}

function resetOnekeyScoreScores() {
  // 清除当前步长和满分的所有选择状态，恢复默认（全选）
  const currentKey = `${settings.value.stepSize}_${props.fullScore}`
  Object.keys(settings.value.onekeyScoreSelections).forEach((key) => {
    if (key.startsWith(currentKey)) {
      delete settings.value.onekeyScoreSelections[key]
    }
  })
}

function resetQuickScoreScores() {
  settings.value.quickScoreScores = [0.5, 1, 2, 3, 4, 5]
}
</script>

<template>
  <wd-popup
    v-model="visible"
    position="center"
    :close-on-click-modal="false"
    custom-class="w-90vw max-w-400px"
  >
    <div class="rounded-16px bg-white p-24px">
      <!-- 标题栏 -->
      <!-- <div class="mb-24px flex items-center justify-between">
        <wd-icon
          name="arrow-left"
          size="20px"
          class="cursor-pointer text-gray-600"
          @click="close"
        />
        <text class="text-16px text-gray-900 font-medium">打分设置</text>
        <div class="w-20px" />
      </div> -->

      <!-- 一键打分 / 快捷打分 切换 -->
      <div class="mb-24px flex rounded-8px bg-gray-100 p-4px">
        <div
          class="flex-1 cursor-pointer rounded-6px py-8px text-center transition-all"
          :class="activeTab === 'onekey' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-600'"
          @click="activeTab = 'onekey'"
        >
          一键打分
        </div>
        <div
          class="flex-1 cursor-pointer rounded-6px py-8px text-center transition-all"
          :class="activeTab === 'quick' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-600'"
          @click="activeTab = 'quick'"
        >
          快捷打分
          <wd-icon name="question" size="14px" class="ml-4px text-blue-400" />
        </div>
      </div>

      <!-- 快捷打分设置 -->
      <div v-if="activeTab === 'quick'" class="space-y-24px">
        <!-- 设置加分/扣分步长 -->
        <div>
          <div class="mb-12px flex items-center justify-between text-14px text-gray-700">
            设置加分/扣分步长

            <wd-button
              type="info"
              size="small"
              plain
              class="!px-12px !py-4px !text-12px"
              @click="resetQuickScoreScores"
            >
              恢复默认
            </wd-button>
          </div>
          <div class="flex items-center justify-between">
            <div class="flex flex-wrap gap-8px">
              <div
                v-for="step in stepOptions"
                :key="step"
                class="h-32px w-40px flex cursor-pointer items-center justify-center border rounded-4px transition-all"
                :class="settings.quickScoreScores.includes(step)
                  ? 'bg-blue-500 text-white border-blue-500'
                  : 'bg-white text-gray-700 border-gray-300'"
                @click="toggleCommonScore(step)"
              >
                {{ step }}
              </div>
              <div
                v-if="!showCustomStepInput"
                class="h-32px w-40px flex cursor-pointer items-center justify-center border border-gray-300 rounded-4px bg-white text-gray-700 transition-all"
                :class="canAddMoreSteps ? 'hover:border-blue-300 hover:text-blue-600' : 'opacity-50 cursor-not-allowed'"
                @click="showCustomInput"
              >
                +
              </div>
              <!-- 自定义步长输入 -->
              <div v-else class="flex items-center space-x-4px">
                <input
                  v-model="customStepValue"
                  type="number"
                  step="0.5"
                  min="0.5"
                  :max="fullScore"
                  placeholder="0.5"
                  class="h-32px w-60px border border-gray-300 rounded-4px px-8px text-center text-12px"
                >
                <div
                  class="h-24px w-24px flex cursor-pointer items-center justify-center border border-green-300 rounded-4px bg-green-50 text-green-600 transition-all hover:bg-green-100"
                  @click="addCustomStep"
                >
                  ✓
                </div>
                <div
                  class="h-24px w-24px flex cursor-pointer items-center justify-center border border-red-300 rounded-4px bg-red-50 text-red-600 transition-all hover:bg-red-100"
                  @click="cancelCustomInput"
                >
                  ✕
                </div>
              </div>
            </div>
          </div>
          <div class="mt-8px text-12px text-gray-500">
            注：新增步长只能为0.5的整数倍，且不可与现有重复，不要超出满分
          </div>
        </div>

        <!-- 给分排序 -->
        <div>
          <div class="mb-12px text-14px text-gray-700">
            给分排序
          </div>
          <div class="flex items-center justify-between">
            <VueDraggable
              v-model="draggableScores"
              class="w-0 flex flex-grow flex-wrap gap-2"
            >
              <div
                v-for="score in draggableScores"
                :key="score"
                class="h-32px w-32px flex flex-shrink-0 cursor-move items-center justify-center rounded-full bg-blue-500 text-12px text-white font-medium transition-all hover:bg-blue-600"
              >
                {{ score }}
              </div>
            </VueDraggable>
            <wd-button
              type="error"
              size="small"
              plain
              class="!px-12px !py-4px !text-12px"
              @click="resetSortOrder"
            >
              重新排序
            </wd-button>
          </div>
        </div>
      </div>

      <!-- 一键打分设置 -->
      <div v-if="activeTab === 'onekey'" class="space-y-24px">
        <!-- 设置步长 -->
        <div>
          <div class="mb-12px flex items-center justify-between text-14px text-gray-700">
            设置步长
            <wd-button
              type="info"
              size="small"
              plain
              class="!px-12px !py-4px !text-12px"
              @click="resetOnekeyScoreScores"
            >
              恢复默认
            </wd-button>
          </div>
          <div class="flex items-center justify-between">
            <div class="flex space-x-8px">
              <div
                v-for="step in stepOptions"
                :key="step"
                class="h-32px w-40px flex cursor-pointer items-center justify-center border rounded-4px transition-all"
                :class="settings.stepSize === step
                  ? 'bg-blue-500 text-white border-blue-500'
                  : 'bg-white text-gray-700 border-gray-300'"
                @click="selectStepSize(step)"
              >
                {{ step }}
              </div>
            </div>
          </div>
        </div>

        <!-- 常用给分 -->
        <div>
          <div class="mb-12px text-14px text-gray-700">
            常用给分
          </div>
          <div class="flex items-center justify-between">
            <div class="flex flex-wrap gap-8px">
              <div
                v-for="score in commonScores"
                :key="score"
                class="h-32px w-32px flex cursor-pointer items-center justify-center border rounded-4px transition-all"
                :class="selectedCommonScores.includes(score)
                  ? 'bg-blue-500 text-white border-blue-500'
                  : 'bg-white text-gray-700 border-gray-300'"
                @click="toggleCommonScore(score)"
              >
                {{ score }}
              </div>
            </div>
          </div>
        </div>

        <!-- 给分排序 -->
        <div>
          <div class="mb-12px text-14px text-gray-700">
            给分排序
          </div>
          <div class="flex items-center justify-between">
            <VueDraggable
              v-model="draggableScores"
              class="w-0 flex flex-grow flex-wrap gap-2"
            >
              <div
                v-for="score in draggableScores"
                :key="score"
                class="h-32px w-32px flex flex-shrink-0 cursor-move items-center justify-center rounded-full bg-blue-500 text-12px text-white font-medium transition-all hover:bg-blue-600"
              >
                {{ score }}
              </div>
            </VueDraggable>
            <wd-button
              type="error"
              size="small"
              plain
              class="!px-12px !py-4px !text-12px"
              @click="resetSortOrder"
            >
              重新排序
            </wd-button>
          </div>
        </div>
      </div>

      <!-- 确定按钮 -->
      <div class="mt-32px">
        <wd-button
          type="primary"

          round block
          class="!h-40px !text-16px"
          @click="confirm"
        >
          确定
        </wd-button>
      </div>
    </div>
  </wd-popup>
</template>
