<script lang="ts" setup>
import { computed, ref, watch } from 'vue'
import DragSort from '@/components/common/DragSort.vue'
import {
  getOnekeyScores,
  resetOnekeyScores,
  setOnekeyScores,
  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 screenInfo = ref({ width: 375, height: 667, isPortrait: true })
const dragLayout = computed(() => {
  const { width, height, isPortrait } = screenInfo.value
  const dialogWidth = isPortrait ? width * 0.9 : Math.min(width * 0.5, 600)
  const itemSize = 32 // 2em = 32px (假设 1em = 16px)
  const gap = 8 // 0.5em = 8px
  const buttonWidth = 80 // 重新排序按钮宽度
  const containerPadding = 16 // 1em padding
  const availableWidth = dialogWidth - containerPadding * 2 - buttonWidth - gap
  const columns = Math.floor((availableWidth + gap) / (itemSize + gap))

  return {
    columns: Math.max(columns, 3),
    itemSize,
    containerWidth: availableWidth,
  }
})

// 获取屏幕信息
function updateScreenInfo() {
  uni.getSystemInfo({
    success: (res) => {
      screenInfo.value = {
        width: res.windowWidth,
        height: res.windowHeight,
        isPortrait: res.windowHeight > res.windowWidth,
      }
    },
  })
}

// 初始化屏幕信息
updateScreenInfo()

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

// 配置项
const settings = useMarkingSettings()

// 初始值保存
const initialSettings = ref({
  quickScoreMode: '',
  stepSize: 0,
  quickScoreScores: [] as number[],
  onekeyScores: [] as number[],
})

// 监听弹窗打开，保存初始值
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    updateScreenInfo()
    initialSettings.value = {
      quickScoreMode: settings.value.quickScoreMode,
      stepSize: settings.value.stepSize,
      quickScoreScores: [...settings.value.quickScoreScores],
      onekeyScores: [...getOnekeyScores(settings.value.stepSize, props.fullScore)],
    }
  }
})

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

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

// 生成所有可能的分数（用于选择）
function generateAllScores(stepSize: number, fullScore: number): number[] {
  const scores: number[] = []
  for (let i = 0; i <= fullScore; i += stepSize) {
    scores.push(i)
  }
  return scores
}

// 常用给分选项 - 根据当前选项卡动态计算
const commonScores = computed(() => {
  if (activeTab.value === 'onekey') {
    return generateAllScores(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 getOnekeyScores(settings.value.stepSize, props.fullScore)
  }
  else {
    return settings.value.quickScoreScores
  }
})

// 排序后的分数（拖拽用）
const draggableScores = ref<number[]>([])

// 同步 draggableScores
watch(selectedCommonScores, (newScores) => {
  draggableScores.value = [...newScores]
}, { immediate: true })

// 更新拖拽排序
function updateDraggableOrder(newOrder: number[]) {
  draggableScores.value = newOrder
  if (activeTab.value === 'quick') {
    settings.value.quickScoreScores = newOrder
  }
  else {
    setOnekeyScores(settings.value.stepSize, props.fullScore, newOrder)
  }
}

// 处理拖拽变化
function handleDragChange(newList: number[]) {
  updateDraggableOrder(newList)
}

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

// 切换常用给分选择
function toggleCommonScore(score: number) {
  if (activeTab.value === 'onekey') {
    const current = getOnekeyScores(settings.value.stepSize, props.fullScore)
    const index = current.indexOf(score)
    if (index > -1) {
      current.splice(index, 1)
    }
    else {
      current.push(score)
    }
    setOnekeyScores(settings.value.stepSize, props.fullScore, current)
  }
  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() {
  const sortedScores = [...selectedCommonScores.value].sort((a, b) => a - b)
  if (activeTab.value === 'onekey') {
    setOnekeyScores(settings.value.stepSize, props.fullScore, sortedScores)
  }
  else {
    settings.value.quickScoreScores = sortedScores
  }
}

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

// 取消 - 恢复初始值
function cancel() {
  settings.value.quickScoreMode = initialSettings.value.quickScoreMode
  settings.value.stepSize = initialSettings.value.stepSize
  settings.value.quickScoreScores = [...initialSettings.value.quickScoreScores]
  setOnekeyScores(settings.value.stepSize, props.fullScore, initialSettings.value.onekeyScores)
  close()
}

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

function resetOnekeyScoreScores() {
  resetOnekeyScores(settings.value.stepSize, props.fullScore)
  draggableScores.value = [...getOnekeyScores(settings.value.stepSize, props.fullScore)]
}

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

<template>
  <wd-popup
    v-model="visible"
    position="center"
    :close-on-click-modal="false"
    custom-class="score-settings-popup"
  >
    <view class="max-h-90vh overflow-auto root-container">
      <view class="w-full rounded-2 bg-white p-0.75em">
        <!-- 标题栏 -->
        <view class="mb-0.75em flex items-center justify-between">
          <text class="text-1.125em text-gray-900 font-medium">打分设置</text>
          <wd-icon
            name="close"
            size="1.25em"
            class="cursor-pointer text-gray-600"
            @click="cancel"
          />
        </view>

        <!-- 一键打分 / 快捷打分 切换 -->
        <view class="mb-0.75em flex rounded-1 bg-gray-100 p-0.25em">
          <view
            class="flex-1 cursor-pointer rounded-1 py-0.5em text-center text-0.875em text-gray-600 transition-all"
            :class="activeTab === 'onekey' ? 'bg-white text-blue-500 shadow-sm' : ''"
            @click="activeTab = 'onekey'"
          >
            一键打分
          </view>
          <view
            class="flex-1 cursor-pointer rounded-1 py-0.5em text-center text-0.875em text-gray-600 transition-all"
            :class="activeTab === 'quick' ? 'bg-white text-blue-500 shadow-sm' : ''"
            @click="activeTab = 'quick'"
          >
            快捷打分
            <wd-icon name="question" size="0.875em" class="ml-0.25em text-blue-500" />
          </view>
        </view>

        <!-- 快捷打分设置 -->
        <view v-if="activeTab === 'quick'">
          <!-- 设置加分/扣分步长 -->
          <view class="mb-0.75em">
            <view class="mb-0.375em flex items-center justify-between">
              <text class="text-0.875em text-gray-700">设置加分/扣分步长</text>
              <wd-button
                type="info"
                size="small"
                plain
                class="reset-btn"
                @click="resetQuickScoreScores"
              >
                恢复默认
              </wd-button>
            </view>
            <view class="mb-0.375em">
              <view class="flex flex-wrap gap-0.5em">
                <view
                  v-for="step in stepOptions"
                  :key="step"
                  class="h-2em w-2.5em flex cursor-pointer items-center justify-center border border-gray-300 rounded-1 bg-white text-0.875em text-gray-700 transition-all"
                  :class="settings.quickScoreScores.includes(step) ? 'bg-blue-500! text-white! border-blue-500!' : ''"
                  @click="toggleCommonScore(step)"
                >
                  {{ step }}
                </view>
                <view
                  v-if="!showCustomStepInput"
                  class="h-2em w-2.5em flex cursor-pointer items-center justify-center border border-gray-300 rounded-1 bg-white text-0.875em text-gray-700 transition-all"
                  :class="!canAddMoreSteps ? 'opacity-50 cursor-not-allowed' : ''"
                  @click="showCustomInput"
                >
                  +
                </view>
                <!-- 自定义步长输入 -->
                <view v-else class="flex items-center gap-0.25em">
                  <input
                    v-model="customStepValue"
                    type="number"
                    step="0.5"
                    min="0.5"
                    :max="fullScore"
                    placeholder="0.5"
                    class="h-2em w-3.75em border border-gray-300 rounded-1 px-0.5em text-center text-0.75em"
                  >
                  <view
                    class="h-1.5em w-1.5em flex cursor-pointer items-center justify-center border border-blue-200 rounded-1 bg-blue-50 text-0.875em text-green-500 transition-all active:bg-green-100"
                    @click="addCustomStep"
                  >
                    ✓
                  </view>
                  <view
                    class="h-1.5em w-1.5em flex cursor-pointer items-center justify-center border border-red-200 rounded-1 bg-red-50 text-0.875em text-red-500 transition-all active:bg-red-100"
                    @click="cancelCustomInput"
                  >
                    ✕
                  </view>
                </view>
              </view>
            </view>
            <text class="mt-0.375em block text-0.75em text-gray-500">
              注：新增步长只能为0.5的整数倍，且不可与现有重复，不要超出满分
            </text>
          </view>

          <!-- 给分排序 -->
          <view class="mb-0.75em">
            <view class="mb-0.375em flex items-center justify-between">
              <text class="text-0.875em text-gray-700">给分排序</text>
              <wd-button
                type="error"
                size="small"
                plain
                class="reset-btn"
                @click="resetSortOrder"
              >
                重新排序
              </wd-button>
            </view>
            <DragSort
              :list="draggableScores"
              :columns="dragLayout.columns"
              :item-size="dragLayout.itemSize"
              :gap="8"
              @change="handleDragChange"
            >
              <template #item="{ item }">
                <view class="h-full w-full flex items-center justify-center rounded-full bg-blue-500 text-0.75em text-white font-medium">
                  {{ item }}
                </view>
              </template>
            </DragSort>
          </view>
        </view>

        <!-- 一键打分设置 -->
        <view v-if="activeTab === 'onekey'">
          <!-- 设置步长 -->
          <view class="mb-0.75em">
            <view class="mb-0.375em flex items-center justify-between">
              <text class="text-0.875em text-gray-700">设置步长</text>
              <wd-button
                type="info"
                size="small"
                plain
                class="reset-btn"
                @click="resetOnekeyScoreScores"
              >
                恢复默认
              </wd-button>
            </view>
            <view class="mb-0.375em">
              <view class="flex flex-wrap gap-0.5em">
                <view
                  v-for="step in stepOptions"
                  :key="step"
                  class="h-2em w-2.5em flex cursor-pointer items-center justify-center border border-gray-300 rounded-1 bg-white text-0.875em text-gray-700 transition-all"
                  :class="settings.stepSize === step ? 'bg-blue-500! text-white! border-blue-500!' : ''"
                  @click="selectStepSize(step)"
                >
                  {{ step }}
                </view>
              </view>
            </view>
          </view>

          <!-- 常用给分 -->
          <view class="mb-0.75em">
            <text class="text-0.875em text-gray-700">常用给分</text>
            <view class="mb-0.375em mt-0.375em">
              <view class="flex flex-wrap gap-0.5em">
                <view
                  v-for="score in commonScores"
                  :key="score"
                  class="h-2em w-2.5em flex cursor-pointer items-center justify-center border border-gray-300 rounded-1 bg-white text-0.875em text-gray-700 transition-all"
                  :class="selectedCommonScores.includes(score) ? 'bg-blue-500! text-white! border-blue-500!' : ''"
                  @click="toggleCommonScore(score)"
                >
                  {{ score }}
                </view>
              </view>
            </view>
          </view>

          <!-- 给分排序 -->
          <view class="mb-0.75em">
            <view class="mb-0.375em flex items-center justify-between">
              <text class="text-0.875em text-gray-700">给分排序</text>
              <wd-button
                type="error"
                size="small"
                plain
                class="reset-btn"
                @click="resetSortOrder"
              >
                重新排序
              </wd-button>
            </view>
            <DragSort
              :list="draggableScores"
              :columns="dragLayout.columns"
              :item-size="dragLayout.itemSize"
              :gap="8"
              @change="handleDragChange"
            >
              <template #item="{ item }">
                <view class="h-full w-full flex items-center justify-center rounded-full bg-blue-500 text-0.75em text-white font-medium">
                  {{ item }}
                </view>
              </template>
            </DragSort>
          </view>
        </view>

        <!-- 确定按钮 -->
        <view class="mt-1em">
          <wd-button
            type="primary"
            round
            block
            class="confirm-button"
            @click="confirm"
          >
            确定
          </wd-button>
        </view>
      </view>
    </view>
  </wd-popup>
</template>

<style lang="scss">
.score-settings-popup {
  /* 竖屏（高>宽）占90%，横屏占50%或最大600px */
  @media (orientation: portrait) {
    width: 90vw;
  }
  @media (orientation: landscape) {
    width: min(50vw, 600px);
  }
}

/* 根容器设置 font-size，1rem 最大 16px */
.root-container {
  font-size: min(16px, calc(100vw / 23.4375)); /* 375px 屏幕下 1rem = 16px */

  /* 竖屏适配：当高度大于宽度时，限制最大宽度 */
  @media (orientation: portrait) {
    font-size: min(16px, calc(100vw / 25));
  }
}

/* 重置按钮样式 */
:deep(.reset-btn) {
  padding: 0em 0.75em !important;
  font-size: 0.65em !important;
  height: auto !important;
}

/* 确认按钮样式 */
:deep(.confirm-button) {
  height: 2.5em !important;
  font-size: 1em !important;
}
</style>
