<template>
  <div style="max-width: 1100px;">
    <NBreadcrumb style="margin-bottom: 16px;">
      <NBreadcrumbItem>
        <NuxtLink to="/admin/content/selector">产品选择器</NuxtLink>
      </NBreadcrumbItem>
      <NBreadcrumbItem>评分矩阵</NBreadcrumbItem>
    </NBreadcrumb>

    <NSpace justify="space-between" align="center" style="margin-bottom: 16px;">
      <div style="font-size: 20px; font-weight: 600; color: #111827;">评分矩阵</div>
      <NSpace :size="8">
        <NuxtLink to="/admin/content/selector">
          <NButton>返回</NButton>
        </NuxtLink>
        <NButton type="primary" :loading="saving" @click="handleSave">保存</NButton>
      </NSpace>
    </NSpace>

    <NSpin :show="!loaded">
      <template v-if="loaded">
        <div style="font-size: 13px; color: #6b7280; margin-bottom: 20px;">
          每个问题的每个选项对应各产品的评分（0-10），分数越高越推荐该产品。
        </div>

        <NCard
          v-for="(qScores, qId) in scoring"
          :key="qId"
          style="margin-bottom: 16px;"
        >
          <template #header>
            <span style="font-size: 14px; font-weight: 600; color: #374151;">
              {{ qId }} — {{ questionTexts[qId] || '' }}
            </span>
          </template>
          <div style="overflow-x: auto;">
            <table style="width: 100%; border-collapse: collapse; font-size: 13px;">
              <thead>
                <tr>
                  <th style="padding: 6px 8px; border: 1px solid #e5e7eb; background: #f9fafb; font-weight: 600; color: #374151; font-size: 11px; white-space: nowrap; text-align: center;">选项</th>
                  <th
                    v-for="pid in productIds"
                    :key="pid"
                    style="padding: 6px 8px; border: 1px solid #e5e7eb; background: #f9fafb; font-weight: 600; color: #374151; font-size: 11px; white-space: nowrap; text-align: center;"
                  >{{ pid }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(products, optValue) in qScores" :key="optValue">
                  <td style="padding: 6px 8px; border: 1px solid #e5e7eb; text-align: left; font-weight: 500; color: #111827; white-space: nowrap; min-width: 100px;">{{ optValue }}</td>
                  <td v-for="pid in productIds" :key="pid" style="padding: 6px 8px; border: 1px solid #e5e7eb; text-align: center;">
                    <NInputNumber
                      :value="products[pid] || 0"
                      :min="0"
                      :max="10"
                      size="small"
                      style="width: 64px;"
                      :show-button="false"
                      @update:value="val => setScore(qId, optValue, pid, Number(val || 0))"
                    />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </NCard>

        <div class="save-bar">
          <NuxtLink to="/admin/content/selector">
            <NButton>返回</NButton>
          </NuxtLink>
          <NButton type="primary" :loading="saving" @click="handleSave">保存</NButton>
        </div>
      </template>
    </NSpin>
  </div>
</template>

<script setup>
import { NButton, NCard, NSpace, NInputNumber, NSpin, NBreadcrumb, NBreadcrumbItem } from 'naive-ui'
import { useMessage } from 'naive-ui'

definePageMeta({ layout: 'admin', middleware: 'admin' })
const message = useMessage()
const { adminFetch } = useAdmin()
const fullData = ref({})
const scoring = ref({})
const questionTexts = ref({})
const productIds = ref([])
const loaded = ref(false)
const saving = ref(false)

async function load() {
  const res = await adminFetch('/api/admin/site-content?key=selector')
  fullData.value = res.data
  scoring.value = JSON.parse(JSON.stringify(res.data.scoring || {}))
  // 收集所有产品 ID
  const pids = new Set()
  for (const q of Object.values(scoring.value)) {
    for (const opts of Object.values(q)) {
      for (const pid of Object.keys(opts)) pids.add(pid)
    }
  }
  productIds.value = [...pids].sort()
  // 问题文本映射
  for (const q of (res.data.questions || [])) {
    questionTexts.value[q.id] = q.text
  }
  loaded.value = true
}

function setScore(qId, optValue, pid, val) {
  if (!scoring.value[qId][optValue]) scoring.value[qId][optValue] = {}
  if (val > 0) scoring.value[qId][optValue][pid] = val
  else delete scoring.value[qId][optValue][pid]
}

async function handleSave() {
  saving.value = true
  try {
    fullData.value.scoring = scoring.value
    await adminFetch('/api/admin/site-content', { method: 'PUT', body: { key: 'selector', data: fullData.value } })
    message.success('保存成功')
  } catch {
    message.error('保存失败')
  } finally {
    saving.value = false
  }
}

onMounted(load)
</script>

<style scoped>
.save-bar { position: sticky; bottom: 0; display: flex; justify-content: flex-end; gap: 8px; padding: 16px 0; margin-top: 24px; background: #f0f2f5; border-top: 1px solid #e5e7eb; }
</style>
