<template>
  <div class="page-map">
    <div class="page-header">
      <h2>📄 主题页面</h2>
      <p class="sub">为不同页面分别指定主题，选"跟随全局"则使用主题配色中设置的主题</p>
    </div>

    <el-card shadow="never">
      <el-table :data="pageList" border style="width:100%">
        <el-table-column label="页面" width="120" align="center">
          <template #default="{row}">
            <span style="font-size:22px">{{ pageIcons[row.page_key] || '📄' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="页面名称" width="140">
          <template #default="{row}">{{ pageNames[row.page_key] || row.page_key }}</template>
        </el-table-column>
        <el-table-column label="当前主题" width="200">
          <template #default="{row}">
            <el-tag v-if="row.theme_id === 'global'" type="info">跟随全局</el-tag>
            <el-tag v-else :color="getThemeColor(row.theme_id)" style="color:#fff;border:0">{{ getThemeName(row.theme_id) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="选择主题" min-width="280">
          <template #default="{row}">
            <el-select v-model="row.theme_id" style="width:100%" @change="t=>saveMap(row,t)">
              <el-option label="🌍 跟随全局" value="global" />
              <el-option v-for="t in allThemes" :key="t.id" :label="t.name" :value="t.id">
                <span>{{ t.type === 'preset' ? '📦 ' : '✏️ ' }}{{ t.name }}</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="{row}">
            <el-button size="small" type="primary" link @click="previewPage(row)">预览</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 全局主题预览 -->
    <el-card shadow="never" style="margin-top:16px">
      <template #header>
        <span>🌍 全局主题（未单独设置的页面默认使用）</span>
        <el-tag v-if="globalTheme" style="margin-left:8px">{{ globalTheme.name }}</el-tag>
      </template>
      <div class="global-theme-bar">
        <template v-if="globalTheme">
          <div class="gt-item">
            <span class="gt-label">主色</span>
            <span class="gt-color" :style="{ background: globalTheme.colors.primary }"></span>
            <span class="gt-value">{{ globalTheme.colors.primary }}</span>
          </div>
          <div class="gt-item">
            <span class="gt-label">页面背景</span>
            <span class="gt-color" :style="{ background: globalTheme.colors.pageBg }"></span>
          </div>
          <div class="gt-item">
            <span class="gt-label">卡片背景</span>
            <span class="gt-color" :style="{ background: globalTheme.colors.cardBg, border: '1px solid #ddd' }"></span>
          </div>
        </template>
        <el-button v-if="globalTheme" size="small" @click="goThemeVisual">去修改 →</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const API = axios.create({ baseURL: '/api' })
API.interceptors.request.use(c => { c.headers.Authorization = 'Bearer ' + localStorage.getItem('admin_token'); return c })

const pageList = ref([])
const allThemes = ref([])
const globalTheme = ref(null)

const pageNames = {
  home: '首页', category: '分类页', cart: '购物车',
  user: '个人中心', product: '商品详情', order: '订单页'
}
const pageIcons = {
  home: '🏠', category: '📂', cart: '🛒',
  user: '👤', product: '📦', order: '📋'
}

async function loadData() {
  try {
    // 获取页面映射
    const [mapRes, themeRes] = await Promise.all([
      API.get('/theme/page-map'),
      API.get('/theme/my-themes')
    ])
    if (mapRes.data.code === 0 || mapRes.data.code === 200) {
      pageList.value = mapRes.data.data.list || []
      // 获取全局主题信息
      if (mapRes.data.data.globalThemeId) {
        const gtId = mapRes.data.data.globalThemeId
        const all = []
        if (themeRes.data.code === 0 || themeRes.data.code === 200) {
          const data = themeRes.data.data
          data.presets?.forEach(p => all.push({ ...p, type: 'preset' }))
          data.customs?.forEach(c => all.push({ ...c, type: 'custom' }))
          // 查找全局主题
          const found = all.find(t => t.id === gtId)
          if (found) globalTheme.value = found
        }
        allThemes.value = all
      }
    }
  } catch (e) { console.error(e) }
}

async function saveMap(row) {
  try {
    await API.put('/theme/page-map', { pageKey: row.page_key, themeId: row.theme_id })
    ElMessage.success(`${pageNames[row.page_key] || row.page_key} 主题已更新`)
  } catch { ElMessage.error('保存失败') }
}

function getThemeName(themeId) {
  if (themeId === 'global') return '跟随全局'
  const t = allThemes.value.find(t => t.id === themeId)
  return t?.name || themeId
}

function getThemeColor(themeId) {
  const t = allThemes.value.find(t => t.id === themeId)
  return t?.colors?.primary || '#409eff'
}

function previewPage(row) {
  ElMessage.info(`预览功能：/mobile/?page=${row.page_key}`)
}

function goThemeVisual() {
  router.push('/theme-visual')
}

onMounted(loadData)
</script>

<style scoped>
.page-map { padding: 20px; }
.page-header { margin-bottom: 20px; }
.page-header h2 { margin: 0 0 4px; font-size: 20px; font-weight: 600; }
.sub { color: #999; font-size: 13px; margin: 0; }
.global-theme-bar { display: flex; align-items: center; gap: 24px; }
.gt-item { display: flex; align-items: center; gap: 6px; }
.gt-label { font-size: 12px; color: #999; }
.gt-color { width: 24px; height: 24px; border-radius: 4px; display: inline-block; }
.gt-value { font-size: 11px; color: #666; font-family: monospace; }
</style>
