<template>
  <div class="theme-visual">
    <!-- 顶部操作栏 -->
    <div class="theme-toolbar">
      <div class="toolbar-left">
        <span class="toolbar-title">🎨 可视化主题</span>
        <span class="toolbar-sub">选择或自定义商城配色方案</span>
      </div>
      <div class="toolbar-right">
        <el-button @click="resetTheme" :disabled="currentThemeId==='icy_blue'">恢复默认</el-button>
        <el-button type="primary" :loading="saving" @click="saveTheme">💾 保存主题</el-button>
      </div>
    </div>

    <div class="theme-body">
      <!-- 左侧：预设主题列表 -->
      <div class="preset-panel">
        <div class="panel-section-title">预设主题</div>
        <div class="preset-list">
          <div v-for="p in presets" :key="p.id" class="preset-card" :class="{ active: currentThemeId === p.id }" @click="applyPreset(p)">
            <div class="preset-preview">
              <div class="pp-header" :style="{ background: p.colors.headerBg }"></div>
              <div class="pp-body">
                <div class="pp-bar">
                  <div class="pp-tab" :style="{ color: p.colors.tabbarActive }">🏠</div>
                  <div class="pp-tab inactive">📍</div>
                  <div class="pp-tab inactive">🛒</div>
                  <div class="pp-tab inactive">👤</div>
                </div>
              </div>
            </div>
            <div class="preset-name">{{ p.name }}</div>
            <div class="preset-desc">{{ p.desc }}</div>
          </div>
        </div>

        <el-divider />
        <div class="panel-section-title">自定义主题</div>
        <el-button class="custom-btn" @click="openCustomDialog" :icon="Edit">自由配色</el-button>
      </div>

      <!-- 中间：手机预览 -->
      <div class="preview-panel">
        <div class="preview-label">实时预览</div>
        <div class="phone-frame-wrapper">
          <div class="phone-frame" :style="{ background: themeColors.pageBg }">
            <!-- 状态栏 -->
            <div class="pf-statusbar" :style="{ background: currentThemeColors.headerBg, color: themeColors.headerText }">
              <span>9:41</span>
              <span style="font-size:10px">🔋 100%</span>
            </div>
            <!-- 首页头部 -->
            <div class="pf-header" :style="{ background: currentThemeColors.headerBg, color: themeColors.headerText }">
              <div class="pf-header-top">
                <span class="pf-brand">LiteMall</span>
                <span class="pf-icons">🔔</span>
              </div>
              <!-- 搜索栏 -->
              <div class="pf-search" :style="{ boxShadow: `0 2px 8px ${themeColors.shadow}` }">
                <span class="pf-search-icon">🔍</span>
                <span class="pf-search-text" :style="{ color: themeColors.secondaryText }">搜索商品</span>
              </div>
            </div>
            <!-- 轮播占位 -->
            <div class="pf-swiper" :style="{ background: themeColors.pageBg }">
              <div class="pf-swiper-inner" :style="{ background: `linear-gradient(135deg, ${themeColors.primary}, ${themeColors.primaryLight})`, color: themeColors.headerText }">
                LiteMall 优选
              </div>
            </div>
            <!-- 导航网格 -->
            <div class="pf-grid" :style="{ background: themeColors.cardBg }">
              <div v-for="i in 4" :key="i" class="pf-grid-item">
                <div class="pf-grid-icon" :style="{ background: themeColors.buttonPrimary + '15', color: themeColors.primary }">
                  {{ ['🔥','🎫','📦','👤'][i-1] }}
                </div>
                <div class="pf-grid-label" :style="{ color: themeColors.bodyText }">{{ ['限时秒杀','领优惠券','全部分类','我的'][i-1] }}</div>
              </div>
            </div>
            <!-- 标题栏 -->
            <div class="pf-section-header">
              <span class="pf-section-title" :style="{ color: themeColors.titleText }">推荐商品</span>
              <span class="pf-section-more" :style="{ color: themeColors.secondaryText }">更多 ›</span>
            </div>
            <!-- 商品卡片 -->
            <div class="pf-products" :style="{ background: themeColors.pageBg }">
              <div v-for="i in 2" :key="i" class="pf-product-card" :style="{ background: themeColors.cardBg }">
                <div class="pf-prod-img" :style="{ background: themeColors.pageBg }"></div>
                <div class="pf-prod-info">
                  <div class="pf-prod-name" :style="{ color: themeColors.bodyText }">商品名称</div>
                  <div class="pf-prod-price" :style="{ color: themeColors.priceColor }">¥{{ i === 1 ? '29' : '59' }}.00</div>
                </div>
              </div>
            </div>
            <!-- 底部tab -->
            <div class="pf-tabbar" :style="{ background: themeColors.tabbarBg }">
              <div v-for="(tab, i) in ['🏠','📍','🛒','👤']" :key="i" class="pf-tab" :style="{ color: i === 0 ? themeColors.tabbarActive : themeColors.tabbarInactive }">
                <div class="pf-tab-icon">{{ tab }}</div>
                <div class="pf-tab-label">{{ ['首页','分类','购物车','我的'][i] }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：颜色编辑 -->
      <div class="color-panel">
        <div class="panel-section-title">颜色配置</div>
        <div class="color-groups">
          <!-- 品牌色 -->
          <div class="color-group">
            <div class="color-group-title">🎯 品牌色</div>
            <div class="color-items">
              <div class="color-item">
                <label>主色</label>
                <div class="color-input-row">
                  <el-color-picker v-model="themeColors.primary" size="small" @change="onColorChange" />
                  <el-input v-model="themeColors.primary" size="small" class="color-value" maxlength="7" @input="onColorChange" />
                </div>
              </div>
              <div class="color-item">
                <label>辅色</label>
                <div class="color-input-row">
                  <el-color-picker v-model="themeColors.primaryLight" size="small" @change="onColorChange" />
                  <el-input v-model="themeColors.primaryLight" size="small" class="color-value" maxlength="7" @input="onColorChange" />
                </div>
              </div>
              <div class="color-item">
                <label>主按钮</label>
                <div class="color-input-row">
                  <el-color-picker v-model="themeColors.buttonPrimary" size="small" @change="onColorChange" />
                  <el-input v-model="themeColors.buttonPrimary" size="small" class="color-value" maxlength="7" @input="onColorChange" />
                </div>
              </div>
            </div>
          </div>

          <!-- 页面 -->
          <div class="color-group">
            <div class="color-group-title">📄 页面</div>
            <div class="color-items">
              <div class="color-item">
                <label>页面背景</label>
                <el-color-picker v-model="themeColors.pageBg" size="small" @change="onColorChange" />
              </div>
              <div class="color-item">
                <label>卡片背景</label>
                <el-color-picker v-model="themeColors.cardBg" size="small" @change="onColorChange" />
              </div>
            </div>
          </div>

          <!-- 头部 -->
          <div class="color-group">
            <div class="color-group-title">🏠 导航栏</div>
            <div class="color-items">
              <div class="color-item">
                <label>导航背景</label>
                <el-select v-model="headerBgType" size="small" style="width:100%;margin-bottom:6px" @change="onColorChange">
                  <el-option label="渐变" value="gradient" />
                  <el-option label="纯色" value="solid" />
                </el-select>
                <div v-if="headerBgType==='solid'">
                  <el-color-picker v-model="themeColors.headerBgSolid" size="small" @change="onColorChange" style="width:100%" />
                </div>
                <div v-else class="gradient-row">
                  <el-color-picker v-model="gradientStart" size="small" @change="onColorChange" />
                  <span style="color:#999;font-size:12px">→</span>
                  <el-color-picker v-model="gradientEnd" size="small" @change="onColorChange" />
                </div>
              </div>
              <div class="color-item">
                <label>导航文字</label>
                <el-color-picker v-model="themeColors.headerText" size="small" @change="onColorChange" />
              </div>
            </div>
          </div>

          <!-- 底部导航 -->
          <div class="color-group">
            <div class="color-group-title">📱 底部导航</div>
            <div class="color-items">
              <div class="color-item">
                <label>激活色</label>
                <el-color-picker v-model="themeColors.tabbarActive" size="small" @change="onColorChange" />
              </div>
              <div class="color-item">
                <label>未激活色</label>
                <el-color-picker v-model="themeColors.tabbarInactive" size="small" @change="onColorChange" />
              </div>
              <div class="color-item">
                <label>背景色</label>
                <el-color-picker v-model="themeColors.tabbarBg" size="small" @change="onColorChange" />
              </div>
            </div>
          </div>

          <!-- 价格/标签 -->
          <div class="color-group">
            <div class="color-group-title">💰 价格与标签</div>
            <div class="color-items">
              <div class="color-item">
                <label>价格色</label>
                <el-color-picker v-model="themeColors.priceColor" size="small" @change="onColorChange" />
              </div>
              <div class="color-item">
                <label>标签色</label>
                <el-color-picker v-model="themeColors.tagColor" size="small" @change="onColorChange" />
              </div>
            </div>
          </div>

          <!-- 文字 -->
          <div class="color-group">
            <div class="color-group-title">🔤 文字</div>
            <div class="color-items">
              <div class="color-item">
                <label>标题</label>
                <el-color-picker v-model="themeColors.titleText" size="small" @change="onColorChange" />
              </div>
              <div class="color-item">
                <label>正文</label>
                <el-color-picker v-model="themeColors.bodyText" size="small" @change="onColorChange" />
              </div>
              <div class="color-item">
                <label>辅助文字</label>
                <el-color-picker v-model="themeColors.secondaryText" size="small" @change="onColorChange" />
              </div>
            </div>
          </div>

          <!-- 边框 -->
          <div class="color-group">
            <div class="color-group-title">➖ 边框</div>
            <div class="color-items">
              <div class="color-item">
                <label>边框色</label>
                <el-color-picker v-model="themeColors.borderColor" size="small" @change="onColorChange" />
              </div>
              <div class="color-item">
                <label>阴影</label>
                <el-color-picker v-model="themeColors.shadow" size="small" show-alpha @change="onColorChange" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 自定义主题弹窗 -->
    <el-dialog v-model="showCustom" title="自定义主题" width="500px">
      <el-form label-width="90px" size="small">
        <el-form-item label="主题名称">
          <el-input v-model="customName" placeholder="如：我的专属主题" />
        </el-form-item>
        <el-form-item label="主色">
          <el-color-picker v-model="customPrimary" @change="previewCustom" />
        </el-form-item>
        <el-form-item label="辅色">
          <el-color-picker v-model="customLight" @change="previewCustom" />
        </el-form-item>
        <div class="custom-preview">
          <div class="cp-header" :style="{ background: `linear-gradient(135deg, ${customPrimary}, ${customLight})` }">
            <span>预览头部</span>
          </div>
          <div class="cp-button-row">
            <div class="cp-btn" :style="{ background: customPrimary }">主按钮</div>
            <div class="cp-btn outline" :style="{ borderColor: customPrimary, color: customPrimary }">次要按钮</div>
          </div>
          <div class="cp-price" :style="{ color: '#e84393' }">¥ 29.90</div>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="showCustom=false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="saveCustom">保存自定义主题</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import axios from 'axios'

const API = axios.create({ baseURL: '/api/admin' })
API.interceptors.request.use(c => { c.headers.Authorization = 'Bearer ' + localStorage.getItem('admin_token'); return c })
// 主题API（不在/api/admin下，是独立的/api/theme路由）
const themeAPI = axios.create({ baseURL: '/api' })
themeAPI.interceptors.request.use(c => { c.headers.Authorization = 'Bearer ' + localStorage.getItem('admin_token'); return c })

const saving = ref(false)
const presets = ref([])
const currentThemeId = ref('icy_blue')
const currentThemeName = ref('冰蓝')
const showCustom = ref(false)
const customName = ref('我的主题')
const customPrimary = ref('#7C5BF7')
const customLight = ref('#A78BFA')

// 渐变色控制
const headerBgType = ref('gradient')
const gradientStart = ref('#4A7CF7')
const gradientEnd = ref('#7C9FFF')

// 实时编辑的颜色值
const themeColors = reactive({
  primary: '#4A7CF7',
  primaryLight: '#7C9FFF',
  pageBg: '#f5f7fa',
  cardBg: '#ffffff',
  headerBg: 'linear-gradient(135deg, #4A7CF7, #7C9FFF)',
  headerBgSolid: '#4A7CF7',
  headerText: '#ffffff',
  tabbarActive: '#4A7CF7',
  tabbarInactive: '#999999',
  tabbarBg: '#ffffff',
  priceColor: '#ee0a24',
  tagColor: '#ee0a24',
  tagText: '#ffffff',
  buttonPrimary: '#4A7CF7',
  buttonText: '#ffffff',
  titleText: '#1a1a2e',
  bodyText: '#333333',
  secondaryText: '#999999',
  borderColor: '#eeeeee',
  shadow: 'rgba(74,124,247,0.2)'
})

// 计算当前主题颜色用于预览
const currentThemeColors = computed(() => {
  let bg = themeColors.headerBg
  if (headerBgType.value === 'solid') {
    bg = themeColors.headerBgSolid
  } else {
    bg = `linear-gradient(135deg, ${gradientStart.value}, ${gradientEnd.value})`
  }
  return { ...themeColors, headerBg: bg }
})

// 加载预设
async function loadPresets() {
  try {
    const r = await themeAPI.get('/theme/presets')
    presets.value = r.data.data || []
  } catch {}
}

// 加载当前主题
async function loadCurrent() {
  try {
    const r = await themeAPI.get('/theme/current')
    const data = r.data.data
    if (data) {
      currentThemeId.value = data.themeId || 'icy_blue'
      currentThemeName.value = data.name || '冰蓝'
      if (data.colors) {
        Object.assign(themeColors, data.colors)
        // 尝试解析渐变
        const bg = data.colors.headerBg || ''
        const gradMatch = bg.match(/gradient\(135deg,\s*(#[^,]+),\s*(#[^)]+)\)/)
        if (gradMatch) {
          headerBgType.value = 'gradient'
          gradientStart.value = gradMatch[1]
          gradientEnd.value = gradMatch[2]
        } else {
          headerBgType.value = 'solid'
          themeColors.headerBgSolid = data.colors.headerBg || themeColors.primary
        }
      }
    }
  } catch {}
}

// 应用预设
function applyPreset(p) {
  currentThemeId.value = p.id
  currentThemeName.value = p.name
  Object.assign(themeColors, p.colors)
  // 解析渐变色
  const bg = p.colors.headerBg || ''
  const gradMatch = bg.match(/gradient\(135deg,\s*(#[^,]+),\s*(#[^)]+)\)/)
  if (gradMatch) {
    headerBgType.value = 'gradient'
    gradientStart.value = gradMatch[1]
    gradientEnd.value = gradMatch[2]
  } else {
    headerBgType.value = 'solid'
    themeColors.headerBgSolid = p.colors.headerBg || themeColors.primary
  }
  ElMessage.info(`已应用「${p.name}」主题`)
}

// 颜色变更时同步更新渐变
function onColorChange() {
  if (headerBgType.value === 'gradient') {
    themeColors.headerBg = `linear-gradient(135deg, ${gradientStart.value}, ${gradientEnd.value})`
  } else {
    themeColors.headerBg = themeColors.headerBgSolid
  }
}

// 保存主题
async function saveTheme() {
  saving.value = true
  try {
    // 将当前编辑的颜色合成完整配置
    const colors = { ...themeColors }
    if (headerBgType.value === 'gradient') {
      colors.headerBg = `linear-gradient(135deg, ${gradientStart.value}, ${gradientEnd.value})`
    } else {
      colors.headerBg = themeColors.headerBgSolid
    }
    
    if (currentThemeId.value && !currentThemeId.value.startsWith('custom')) {
      // 预设主题，直接应用
      await themeAPI.put('/theme/apply', {
        themeId: currentThemeId.value
      })
    } else {
      // 自定义颜色，保存到自定义主题表并应用
      const saveRes = await themeAPI.post('/theme/custom', {
        name: currentThemeName.value || '自定义',
        colors
      })
      if (saveRes.data.code === 0 || saveRes.data.code === 200) {
        const newId = saveRes.data.data.id
        await themeAPI.put('/theme/apply', { themeId: 'custom_' + newId })
      }
    }
    ElMessage.success('主题已保存并生效 ✓')
  } catch (e) {
    ElMessage.error('保存失败')
  }
  saving.value = false
}

// 恢复默认
async function resetTheme() {
  const icy = presets.value.find(p => p.id === 'icy_blue')
  if (icy) applyPreset(icy)
  await saveTheme()
}

// 自定义弹窗
function openCustomDialog() {
  customName.value = '我的主题'
  customPrimary.value = themeColors.primary
  customLight.value = themeColors.primaryLight
  showCustom.value = true
}

function previewCustom() {}

async function saveCustom() {
  saving.value = true
  try {
    const colors = { ...themeColors }
    colors.primary = customPrimary.value
    colors.primaryLight = customLight.value
    colors.buttonPrimary = customPrimary.value
    colors.headerBg = `linear-gradient(135deg, ${customPrimary.value}, ${customLight.value})`
    colors.tabbarActive = customPrimary.value
    colors.shadow = (customPrimary.value.startsWith('#') ? 
    hexToRgba(customPrimary.value, 0.2) : 
    customPrimary.value.replace(')', ',0.2)').replace('rgb', 'rgba'))
    
    // 保存到自定义主题表
    const saveRes = await themeAPI.post('/theme/custom', {
      name: customName.value,
      colors
    })
    
    if (saveRes.data.code === 0 || saveRes.data.code === 200) {
      // 应用该主题
      const newId = saveRes.data.data.id
      await themeAPI.put('/theme/apply', { themeId: 'custom_' + newId })
      
      // 更新预览
      currentThemeId.value = 'custom_' + newId
      currentThemeName.value = customName.value
      Object.assign(themeColors, colors)
      headerBgType.value = 'gradient'
      gradientStart.value = customPrimary.value
      gradientEnd.value = customLight.value
      
      ElMessage.success('自定义主题已保存并应用 ✓')
      showCustom.value = false
    } else {
      ElMessage.error(saveRes.data.message || '保存失败')
    }
  } catch (e) {
    ElMessage.error('保存失败')
  }
  saving.value = false
}

function hexToRgba(hex, alpha) {
  if (!hex || !hex.startsWith('#')) return 'rgba(124,91,247,0.2)'
  const r = parseInt(hex.slice(1, 3), 16)
  const g = parseInt(hex.slice(3, 5), 16)
  const b = parseInt(hex.slice(5, 7), 16)
  return `rgba(${r},${g},${b},${alpha})`
}

onMounted(() => {
  loadPresets()
  loadCurrent()
})
</script>

<style scoped>
.theme-visual{max-width:1400px}
.theme-toolbar{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;padding:12px 16px;background:#fff;border-radius:8px;box-shadow:0 1px 3px rgba(0,0,0,.04)}
.toolbar-left{display:flex;align-items:center;gap:12px}
.toolbar-title{font-size:18px;font-weight:700;color:#1a1a2e}
.toolbar-sub{font-size:13px;color:#999}

.theme-body{display:flex;gap:16px;min-height:calc(100vh - 200px)}

/* 预设面板 */
.preset-panel{width:240px;flex-shrink:0;background:#fff;border-radius:8px;padding:16px;box-shadow:0 1px 3px rgba(0,0,0,.04);overflow-y:auto}
.panel-section-title{font-size:14px;font-weight:600;color:#333;margin-bottom:12px}
.preset-list{display:flex;flex-direction:column;gap:12px}
.preset-card{padding:12px;border-radius:10px;border:2px solid #eee;cursor:pointer;transition:all .2s}
.preset-card:hover{border-color:#d0d0d0;background:#fafafa}
.preset-card.active{border-color:#409eff;background:#ecf5ff}
.preset-preview{height:80px;border-radius:6px;overflow:hidden;margin-bottom:8px;border:1px solid #eee}
.pp-header{height:24px}
.pp-body{height:56px;background:#f8f8f8;display:flex;align-items:flex-end;padding:4px}
.pp-bar{display:flex;width:100%;justify-content:space-around}
.pp-tab{font-size:16px}.pp-tab.inactive{opacity:.4}
.preset-name{font-size:14px;font-weight:600;color:#333}
.preset-desc{font-size:11px;color:#999;margin-top:2px}
.custom-btn{width:100%}

/* 预览面板 */
.preview-panel{flex:1;display:flex;flex-direction:column;align-items:center;background:#fff;border-radius:8px;padding:16px;box-shadow:0 1px 3px rgba(0,0,0,.04)}
.preview-label{font-size:13px;color:#999;margin-bottom:12px}
.phone-frame-wrapper{flex:1;display:flex;align-items:flex-start}
.phone-frame{width:375px;border-radius:24px;overflow:hidden;box-shadow:0 8px 32px rgba(0,0,0,.12);flex-shrink:0}
.pf-statusbar{display:flex;justify-content:space-between;padding:6px 16px;font-size:11px;font-weight:600}
.pf-header{padding:8px 14px 16px}
.pf-header-top{display:flex;justify-content:space-between;align-items:center;margin-bottom:8px}
.pf-brand{font-size:18px;font-weight:800;letter-spacing:-.5px}
.pf-icons{font-size:16px}
.pf-search{display:flex;align-items:center;gap:6px;background:rgba(255,255,255,.95);border-radius:20px;padding:8px 14px;font-size:13px}
.pf-search-icon{font-size:14px}
.pf-search-text{font-size:13px}
.pf-swiper{padding:0 14px 14px;margin-top:8px}
.pf-swiper-inner{height:120px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:16px;font-weight:600}
.pf-grid{display:grid;grid-template-columns:repeat(4,1fr);padding:14px;text-align:center;gap:4px}
.pf-grid-item{cursor:default}
.pf-grid-icon{width:40px;height:40px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px;margin:0 auto 4px}
.pf-grid-label{font-size:11px;font-weight:500}
.pf-section-header{display:flex;justify-content:space-between;padding:8px 14px 4px}
.pf-section-title{font-size:15px;font-weight:700}
.pf-section-more{font-size:11px}
.pf-products{display:flex;gap:10px;padding:10px 14px 14px}
.pf-product-card{flex:1;border-radius:8px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,.06)}
.pf-prod-img{height:100px;border-radius:4px;margin:6px}
.pf-prod-info{padding:4px 8px 8px}
.pf-prod-name{font-size:11px;line-height:1.3;margin-bottom:4px}
.pf-prod-price{font-size:14px;font-weight:700}
.pf-tabbar{display:flex;padding:6px 0 10px;border-top:none}
.pf-tab{flex:1;text-align:center;font-size:10px}
.pf-tab-icon{font-size:18px;margin-bottom:2px}
.pf-tab-label{font-size:10px}

/* 颜色编辑面板 */
.color-panel{width:300px;flex-shrink:0;background:#fff;border-radius:8px;padding:16px;box-shadow:0 1px 3px rgba(0,0,0,.04);overflow-y:auto;max-height:calc(100vh - 200px)}
.color-group{margin-bottom:20px;padding-bottom:16px;border-bottom:1px solid #f0f0f0}
.color-group:last-child{border-bottom:none;margin-bottom:0}
.color-group-title{font-size:13px;font-weight:600;color:#555;margin-bottom:10px}
.color-items{display:flex;flex-direction:column;gap:10px}
.color-item label{display:block;font-size:12px;color:#888;margin-bottom:4px}
.color-input-row{display:flex;align-items:center;gap:8px}
.color-value{width:90px}
.gradient-row{display:flex;align-items:center;gap:6px}
.custom-preview{padding:12px;background:#f8f8f8;border-radius:8px;margin-top:8px}
.cp-header{padding:12px;border-radius:6px;color:#fff;font-weight:600;text-align:center;margin-bottom:8px}
.cp-button-row{display:flex;gap:8px;margin-bottom:8px}
.cp-btn{flex:1;text-align:center;padding:6px;border-radius:6px;color:#fff;font-size:13px}
.cp-btn.outline{background:transparent;border:1px solid}
.cp-price{font-size:20px;font-weight:700;text-align:center}
</style>