<template>
  <ele-page :multi-card="false">
    <ele-card :body-style="{ paddingTop: '8px' }">
      <div class="menu-template-header">
        <el-button
          type="primary"
          class="ele-btn-icon"
          :icon="Plus"
          @click="createNewTemplate"
        >
          新建整版酒单
        </el-button>
        <div class="header-info">
          <el-text type="info" size="small">
            支持 2-12 款酒的整版排版，可自由设计布局样式
          </el-text>
        </div>
      </div>

      <!-- 模板列表 -->
      <el-row :gutter="16" v-loading="loading">
        <el-col
          v-for="item in menuTemplates"
          :key="item.id"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="24"
          class="template-col"
        >
          <ele-card
            shadow="hover"
            :body-style="{ padding: 0 }"
            class="template-card-wrapper"
          >
            <el-image
              :src="item.preview"
              class="template-image"
              fit="cover"
              alt="模板预览图"
              @click="editTemplate(item)"
            />
            <div class="template-content">
              <div class="template-header">
                <div class="template-title">
                  <ele-text size="md" class="template-name">
                    {{ item.name }}
                  </ele-text>
                  <div class="template-tags">
                    <el-tag size="small" type="success">
                      {{ item.itemCount }}款酒
                    </el-tag>
                    <el-tag size="small" type="info">
                      {{ getLayoutText(item.layout) }}
                    </el-tag>
                  </div>
                </div>
                <div class="template-actions">
                  <el-button 
                    type="danger" 
                    size="small" 
                    :icon="Delete" 
                    circle 
                    @click.stop="removeTemplate(item)" 
                  />
                  <el-button 
                    type="info" 
                    size="small" 
                    :icon="DocumentCopy" 
                    circle 
                    @click.stop="copyTemplate(item)" 
                  />
                  <el-button 
                    type="primary" 
                    size="small" 
                    :icon="Edit" 
                    circle 
                    @click.stop="editTemplate(item)" 
                  />
                </div>
              </div>
              
              <div class="template-description">
                <ele-text type="placeholder" size="sm">
                  模版编码：{{ item.originalData?.uuid || item.id }}
                </ele-text>
              </div>
              
              <div class="template-footer">
                <ele-text type="placeholder" size="sm">
                  更新时间：{{ formatTime(item.updateTime, 'YYYY-MM-DD') }}
                </ele-text>
              </div>
            </div>
          </ele-card>
        </el-col>
      </el-row>

      <!-- 空状态 -->
      <el-empty
        v-if="!loading && menuTemplates.length === 0"
        description="暂无整版酒单模板"
        :image-size="120"
      >
        <el-button type="primary" @click="createNewTemplate">
          创建第一个模板
        </el-button>
      </el-empty>
    </ele-card>


  </ele-page>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Plus, Delete, DocumentCopy, Edit } from '@element-plus/icons-vue';
  import { 
    getWineMenuTemplates, 
    deleteWineMenuTemplate, 
    copyWineMenuTemplate,
    getEditorToken 
  } from '@/api/template';
  import { formatTime } from '@/utils/date-util';

  // 响应式数据
  const loading = ref(false);
  const menuTemplates = ref([]);

  // 获取模板列表
  const fetchTemplates = async () => {
    try {
      loading.value = true;
      const response = await getWineMenuTemplates();
      console.log('[fetchTemplates] API响应:', response);
      console.log('[fetchTemplates] response.data:', response?.data);
      console.log('[fetchTemplates] response.data.templates:', response?.data?.templates);
      console.log('[fetchTemplates] response.data.data:', response?.data?.data);
      console.log('[fetchTemplates] response.data.data.templates:', response?.data?.data?.templates);
      
      if (response && response.data && response.data.code === 200) {
        // 处理FastPoster返回的数据格式
        const templates = response.data.data?.templates || [];
        console.log('[fetchTemplates] 模板数据:', templates);
        
        menuTemplates.value = templates.map(item => {
          console.log('[fetchTemplates] 处理模板项:', item);
          
          // 解析模板JSON数据以获取更多信息
          let templateData = {};
          try {
            if (item.json && typeof item.json === 'string') {
              templateData = JSON.parse(item.json);
            } else if (item.json && typeof item.json === 'object') {
              templateData = item.json;
            }
            console.log('[fetchTemplates] 解析后的templateData:', templateData);
          } catch (e) {
            console.warn('解析模板JSON失败:', e, 'item.json:', item.json);
          }
          
          // 从layoutConfig中获取布局类型和酒款数量
          const layoutConfig = templateData.layoutConfig || {};
          const layoutMode = layoutConfig.mode || 'grid';
          const itemCount = layoutConfig.itemCount || templateData.itemCount || 6;
          
          const processedItem = {
            id: item.id,
            name: item.name || '未命名模板',
            layout: layoutMode,
            status: item.status !== undefined ? item.status : 1,
            preview: item.preview || 'https://oss.beerape.com/placeholder/menu-preview.jpg',
            remark: templateData.description || item.remark || '整版酒单模板',
            updateTime: item.updateTime || item.updatedAt || new Date().toISOString(),
            itemCount: itemCount,
            // 保留原始数据以备后用
            originalData: item
          };
          
          console.log('[fetchTemplates] 处理后的项:', processedItem);
          return processedItem;
        });
        
        console.log('[fetchTemplates] 处理后的模板列表:', menuTemplates.value);
      } else {
        const errorMsg = response?.data?.msg || response?.msg || response?.message || '获取模板列表失败';
        throw new Error(errorMsg);
      }
    } catch (error) {
      ElMessage.error('获取模板列表失败: ' + error.message);
      console.error('获取模板列表失败：', error);
      menuTemplates.value = [];
    } finally {
      loading.value = false;
    }
  };

  // 创建新模板 - 直接跳转到编辑器
  const createNewTemplate = async () => {
    try {
      // 获取编辑器访问令牌
      const res = await getEditorToken({
        purpose: 'create'
      });
      
      console.log('[createNewTemplate] getEditorToken返回:', res);
      if (res && res.data && res.data.code === 200 && res.data.fastPosterUrl && res.data.editorToken) {
        // 构建编辑器URL，先经过Home页面验证token，然后跳转到menu-designer
        const url = `${res.data.fastPosterUrl}?editorToken=${res.data.editorToken}&redirect=menu-designer&mode=menu`;
        console.log('[createNewTemplate] 跳转URL:', url);
        window.open(url, '_blank');
      } else {
        console.error('[createNewTemplate] 获取编辑器令牌失败:', res);
        ElMessage.error((res.data && res.data.msg) || '获取编辑器令牌失败');
      }
    } catch (error) {
      console.error('[createNewTemplate] 网络异常:', error);
      ElMessage.error(error.message || '网络异常，无法打开编辑器');
    }
  };

  // 编辑模板
  const editTemplate = async (template) => {
    try {
      // 确保传递正确的模板ID，支持uuid和id字段
      const templateId = template.originalData?.uuid || template.id;
      const posterId = template.id;
      console.log('[editTemplate] 模板数据:', template, '使用templateId:', templateId, 'posterId:', posterId);
      
      if (!templateId) {
        ElMessage.error('模板ID缺失，无法编辑');
        return;
      }
      
      // 获取编辑器访问令牌
      const res = await getEditorToken({
        templateId: templateId.toString(),
        purpose: 'edit'
      });
      
      console.log('[editTemplate] getEditorToken返回:', res);
      if (res && res.data && res.data.code === 200 && res.data.fastPosterUrl && res.data.editorToken) {
        // 构建编辑器URL，添加posterId参数以便编辑器识别
        const url = `${res.data.fastPosterUrl}?editorToken=${res.data.editorToken}&templateId=${templateId}&posterId=${posterId}&redirect=menu-designer&mode=menu`;
        console.log('[editTemplate] 跳转URL:', url);
        window.open(url, '_blank');
      } else {
        console.error('[editTemplate] 获取编辑器令牌失败:', res);
        ElMessage.error((res.data && res.data.msg) || '获取编辑器令牌失败');
      }
    } catch (error) {
      console.error('[editTemplate] 网络异常:', error);
      ElMessage.error(error.message || '网络异常，无法打开编辑器');
    }
  };

  // 复制模板
  const copyTemplate = async (template) => {
    try {
      const newName = template.name + ' (副本)';
      console.log('[copyTemplate] 复制模板:', template.id, '新名称:', newName);
      
      const response = await copyWineMenuTemplate(template.id, newName);
      console.log('[copyTemplate] 复制响应:', response);
      
      if (response && response.data && response.data.code === 200) {
        ElMessage.success('模板复制成功');
        await fetchTemplates(); // 重新获取列表
      } else {
        const errorMsg = response?.data?.msg || response?.msg || response?.message || '模板复制失败';
        throw new Error(errorMsg);
      }
    } catch (error) {
      ElMessage.error('模板复制失败: ' + error.message);
      console.error('模板复制失败：', error);
    }
  };

  // 删除模板
  const removeTemplate = async (template) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除模板"${template.name}"吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
      
      console.log('[removeTemplate] 删除模板:', template.id);
      const response = await deleteWineMenuTemplate(template.id);
      console.log('[removeTemplate] 删除响应:', response);
      
      if (response && response.data && response.data.code === 200) {
        ElMessage.success('模板删除成功');
        await fetchTemplates(); // 重新获取列表
      } else {
        const errorMsg = response?.data?.msg || response?.msg || response?.message || '模板删除失败';
        throw new Error(errorMsg);
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('模板删除失败: ' + (error.message || error));
        console.error('模板删除失败：', error);
      }
    }
  };



  // 获取布局文本
  const getLayoutText = (layout) => {
    const layoutMap = {
      grid: '网格布局',
      list: '列表布局',
      custom: '自定义布局'
    };
    return layoutMap[layout] || '未知';
  };

  // 组件挂载时获取数据
  onMounted(() => {
    fetchTemplates();
  });
</script>

<style scoped>
  .menu-template-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }

  .header-info {
    display: flex;
    align-items: center;
  }

  /* 确保所有列高度一致 */
  .template-col {
    display: flex;
    margin-bottom: 16px;
  }

  /* 确保所有卡片高度一致 */
  .template-card-wrapper {
    overflow: hidden;
    cursor: pointer;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    border: 1px solid #e6e6e6;
    border-radius: 8px;
    transition: all 0.3s ease;
  }

  .template-card-wrapper:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border-color: #d9d9d9;
  }

  :deep(.el-card__body) {
    height: 100%;
    display: flex;
    flex-direction: column;
    border: none !important;
  }

  .template-image {
    width: 100%;
    height: 200px;
    object-fit: cover;
    object-position: center;
    display: block;
    transition: transform 0.3s ease;
    flex-shrink: 0;
  }

  .template-image:hover {
    transform: scale(1.05);
  }

  .template-content {
    padding: 16px;
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 160px; /* 确保内容区域最小高度 */
  }

  .template-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
  }

  .template-title {
    flex: 1;
    min-width: 0; /* 防止flex item过度扩展 */
  }

  .template-name {
    font-weight: 500;
    color: #303133;
    line-height: 1.4;
    margin-bottom: 8px;
    display: block;
    word-break: break-word;
  }

  .template-tags {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
    align-items: center;
  }

  .template-actions {
    display: flex;
    gap: 4px;
    margin-left: 12px;
    flex-shrink: 0;
  }

  .template-description {
    margin-bottom: 12px;
    flex: 1;
    display: flex;
    align-items: flex-start;
  }

  .template-footer {
    margin-top: auto;
    padding-top: 8px;
    border-top: 1px solid #f0f0f0;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .template-image {
      height: 160px;
    }
    
    .template-header {
      flex-direction: column;
      gap: 8px;
    }
    
    .template-actions {
      margin-left: 0;
      justify-content: flex-end;
    }
  }

  @media (max-width: 480px) {
    .template-image {
      height: 120px;
    }
    
    .template-content {
      padding: 12px;
    }
  }
</style>