<template>
  <div class="template-layout">
    <aside class="category-sidebar">
      <div class="sidebar-title">模板管理</div>
      <ul class="category-list">
        <li class="current-theme">
          <span>当前使用:</span>
          <el-tag type="success">{{ currentTheme }}</el-tag>
        </li>
      </ul>
    </aside>

    <main class="content-area">
      <header class="toolbar">
        <div class="toolbar-left">
          <span class="result-count">共 {{ templateList.length }} 个模板</span>
        </div>
        <div class="toolbar-right">
          <el-button type="primary" @click="fetchTemplates" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新模板
          </el-button>
        </div>
      </header>

      <el-divider></el-divider>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>加载模板中...</span>
      </div>

      <!-- 模板列表 -->
      <div v-else class="template-grid">
        <div v-for="item in templateList" :key="item.key" class="template-card" :class="{ active: item.key === currentTheme }">
          <div class="card-preview">
            <img :src="getPreviewUrl(item.preview)" alt="preview" @error="handleImageError($event)" />
            <div v-if="item.key === currentTheme" class="current-tag">
              <el-tag type="success" size="small">使用中</el-tag>
            </div>
          </div>

          <div class="card-info">
            <h4 class="title">{{ item.name }}</h4>
            <p class="description">{{ item.description }}</p>
            <div class="meta">
              <span class="version">v{{ item.version }}</span>
              <span v-if="item.author" class="author">{{ item.author }}</span>
            </div>
            <div class="card-footer">
              <el-button
                v-if="item.key !== currentTheme"
                type="primary"
                size="small"
                @click="handleUse(item)"
                :loading="switching === item.key"
              >
                启用
              </el-button>
              <el-button v-else type="info" size="small" disabled>
                当前使用
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Loading } from '@element-plus/icons-vue'
import { getThemeList, switchTheme } from '@/api/theme'
import { useAuthStore } from '@/stores/auth'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL
const authStore = useAuthStore()

// 状态
const loading = ref(false)
const switching = ref('')
const templateList = ref<any[]>([])
const currentTheme = ref('default')
const currentTid = ref<number>(0)

// 获取完整预览图URL
const getPreviewUrl = (path: string) => {
  if (!path) return ''
  if (path.startsWith('http')) return path
  return API_BASE_URL + path
}

// 获取模板列表
const fetchTemplates = async () => {
  loading.value = true
  try {
    currentTid.value = (authStore.user as any)?.tid || 0
    const res = await getThemeList({ tid: currentTid.value })
    if (res.code === 200) {
      templateList.value = res.data.list || []
      currentTheme.value = res.data.currentTheme || 'default'
    } else {
      ElMessage.error(res.msg || '获取模板列表失败')
    }
  } catch (error) {
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
}

// 切换模板
const handleUse = async (item: any) => {
  if (!currentTid.value) {
    ElMessage.error('请先选择租户')
    return
  }
  switching.value = item.key
  try {
    const res = await switchTheme({ tid: currentTid.value, theme_key: item.key })
    if (res.code === 200) {
      currentTheme.value = item.key
      ElMessage.success('切换成功')
    } else {
      ElMessage.error(res.msg || '切换失败')
    }
  } catch (error) {
    ElMessage.error('切换失败')
  } finally {
    switching.value = ''
  }
}

// 图片加载失败处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = 'https://picsum.photos/300/200?random=1'
}

// 生命周期
onMounted(() => {
  fetchTemplates()
})
</script>

<style lang="less" scoped>
.template-layout {
  display: flex;
  height: 100vh;
  background-color: #f0f2f5;

  .category-sidebar {
    width: 240px;
    background: #fff;
    border-right: 1px solid #e8e8e8;
    padding: 20px 0;

    .sidebar-title {
      padding: 0 24px 16px;
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .current-theme {
      padding: 12px 24px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 14px;
    }
  }

  .content-area {
    flex: 1;
    padding: 0 24px 24px;
    overflow-y: auto;

    .toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 64px;

      .result-count {
        color: #666;
        font-size: 14px;
      }
    }

    .loading-state {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 60px;
      color: #999;
      gap: 10px;

      .el-icon {
        font-size: 24px;
      }
    }

    .template-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 20px;
    }

    .template-card {
      background: #fff;
      border-radius: 8px;
      overflow: hidden;
      border: 2px solid #f0f0f0;
      transition: all 0.3s;

      &.active {
        border-color: #1890ff;
      }

      &:hover {
        box-shadow: 0 6px 16px rgba(0,0,0,0.12);
      }

      .card-preview {
        height: 200px;
        position: relative;
        overflow: hidden;
        background: #f5f5f5;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .current-tag {
          position: absolute;
          top: 8px;
          right: 8px;
        }
      }

      .card-info {
        padding: 16px;

        .title {
          margin: 0 0 8px 0;
          font-size: 16px;
          color: #333;
        }

        .description {
          font-size: 12px;
          color: #999;
          margin: 0 0 12px 0;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .meta {
          display: flex;
          gap: 12px;
          font-size: 12px;
          color: #999;
          margin-bottom: 12px;
        }

        .card-footer {
          display: flex;
          gap: 8px;
        }
      }
    }
  }
}
</style>
