<template>
  <MainLayout>
    <div class="template-market">
        <!-- 搜索和筛选 -->
        <el-card class="search-card">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-input
                v-model="searchQuery"
                placeholder="搜索模板..."
                clearable
                @clear="handleSearch"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
                <template #append>
                  <el-button @click="handleSearch">搜索</el-button>
                </template>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-select v-model="categoryFilter" placeholder="分类" clearable @change="handleSearch">
                <el-option label="LLM" value="llm" />
                <el-option label="数据处理" value="data_processing" />
                <el-option label="自动化" value="automation" />
                <el-option label="集成" value="integration" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="sortBy" placeholder="排序" @change="handleSearch">
                <el-option label="最新" value="created_at" />
                <el-option label="评分最高" value="rating_avg" />
                <el-option label="使用最多" value="use_count" />
                <el-option label="查看最多" value="view_count" />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-switch
                v-model="featuredOnly"
                active-text="仅精选"
                @change="handleSearch"
              />
            </el-col>
          </el-row>
        </el-card>

        <!-- 模板列表 -->
        <el-card class="templates-card">
          <template #header>
            <div class="card-header">
              <span>模板列表</span>
              <span class="total-count">共 {{ totalCount }} 个模板</span>
            </div>
          </template>

          <el-row :gutter="20" v-loading="loading">
            <el-col
              v-for="template in templates"
              :key="template.id"
              :span="6"
              style="margin-bottom: 20px;"
            >
              <el-card
                class="template-card"
                :body-style="{ padding: '10px' }"
                shadow="hover"
                @click="viewTemplate(template)"
              >
                <div class="template-thumbnail" v-if="template.thumbnail">
                  <img :src="template.thumbnail" alt="模板缩略图" />
                </div>
                <div class="template-info">
                  <h3 class="template-name">{{ template.name }}</h3>
                  <p class="template-description">{{ template.description || '无描述' }}</p>
                  <div class="template-meta">
                    <div class="template-stats">
                      <el-icon><View /></el-icon>
                      <span>{{ template.view_count }}</span>
                      <el-icon><Star /></el-icon>
                      <span>{{ template.rating_avg.toFixed(1) }}</span>
                      <el-icon><DocumentCopy /></el-icon>
                      <span>{{ template.use_count }}</span>
                    </div>
                    <div class="template-category" v-if="template.category">
                      <el-tag size="small">{{ getCategoryName(template.category) }}</el-tag>
                    </div>
                  </div>
                  <div class="template-tags" v-if="template.tags && template.tags.length > 0">
                    <el-tag
                      v-for="tag in template.tags.slice(0, 3)"
                      :key="tag"
                      size="small"
                      style="margin-right: 5px;"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                  <div class="template-actions">
                    <el-button
                      type="primary"
                      size="small"
                      @click.stop="useTemplate(template)"
                    >
                      使用
                    </el-button>
                    <el-button
                      :type="template.is_favorited ? 'warning' : 'default'"
                      size="small"
                      :icon="template.is_favorited ? Star : StarFilled"
                      @click.stop="toggleFavorite(template)"
                    >
                      {{ template.is_favorited ? '已收藏' : '收藏' }}
                    </el-button>
                    <el-rate
                      v-model="template.user_rating"
                      :max="5"
                      size="small"
                      @change="(value) => rateTemplate(template, value)"
                      @click.stop
                    />
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 分页 -->
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[12, 24, 48, 96]"
            :total="totalCount"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            style="margin-top: 20px; justify-content: center;"
        />
      </el-card>

    <!-- 分享模板对话框 -->
    <el-dialog
      v-model="showShareDialog"
      title="分享模板"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form :model="shareForm" label-width="100px">
        <el-form-item label="选择工作流" required>
          <el-select
            v-model="shareForm.workflow_id"
            placeholder="请选择要分享的工作流"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="workflow in myWorkflows"
              :key="workflow.id"
              :label="workflow.name"
              :value="workflow.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="模板名称" required>
          <el-input v-model="shareForm.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板描述">
          <el-input
            v-model="shareForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入模板描述"
          />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="shareForm.category" placeholder="请选择分类">
            <el-option label="LLM" value="llm" />
            <el-option label="数据处理" value="data_processing" />
            <el-option label="自动化" value="automation" />
            <el-option label="集成" value="integration" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-input
            v-model="tagsInput"
            placeholder="输入标签，用逗号分隔"
            @blur="handleTagsInput"
          />
          <div style="margin-top: 10px;">
            <el-tag
              v-for="tag in shareForm.tags"
              :key="tag"
              closable
              @close="removeTag(tag)"
              style="margin-right: 5px;"
            >
              {{ tag }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="是否公开">
          <el-switch v-model="shareForm.is_public" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showShareDialog = false">取消</el-button>
        <el-button type="primary" @click="handleShare" :loading="sharing">
          分享
        </el-button>
      </template>
    </el-dialog>

    <!-- 模板详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      :title="selectedTemplate?.name"
      width="1000px"
      :close-on-click-modal="false"
    >
      <div v-if="selectedTemplate" class="template-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="模板名称">{{ selectedTemplate.name }}</el-descriptions-item>
          <el-descriptions-item label="创建者">{{ selectedTemplate.creator_username }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{ getCategoryName(selectedTemplate.category) }}</el-descriptions-item>
          <el-descriptions-item label="评分">
            <el-rate v-model="selectedTemplate.rating_avg" disabled show-score />
          </el-descriptions-item>
          <el-descriptions-item label="查看次数">{{ selectedTemplate.view_count }}</el-descriptions-item>
          <el-descriptions-item label="使用次数">{{ selectedTemplate.use_count }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ selectedTemplate.description || '无描述' }}
          </el-descriptions-item>
          <el-descriptions-item label="标签" :span="2">
            <el-tag
              v-for="tag in selectedTemplate.tags"
              :key="tag"
              style="margin-right: 5px;"
            >
              {{ tag }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        <div class="template-actions-detail" style="margin-top: 20px;">
          <el-button type="primary" @click="useTemplate(selectedTemplate)">
            使用此模板
          </el-button>
          <el-button
            :type="selectedTemplate.is_favorited ? 'warning' : 'default'"
            @click="toggleFavorite(selectedTemplate)"
          >
            <el-icon><Star /></el-icon>
            {{ selectedTemplate.is_favorited ? '已收藏' : '收藏' }}
          </el-button>
          <el-rate
            v-model="selectedTemplate.user_rating"
            :max="5"
            @change="(value) => rateTemplate(selectedTemplate, value)"
          />
        </div>
      </div>
    </el-dialog>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import MainLayout from '@/components/MainLayout.vue'
import { Search, Share, Star, StarFilled, View, DocumentCopy, Document } from '@element-plus/icons-vue'
import api from '@/api'
import { useWorkflowStore } from '@/stores/workflow'

const router = useRouter()
const workflowStore = useWorkflowStore()

// 数据
const templates = ref<any[]>([])
const myWorkflows = ref<any[]>([])
const loading = ref(false)
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)

// 搜索和筛选
const searchQuery = ref('')
const categoryFilter = ref('')
const sortBy = ref('created_at')
const featuredOnly = ref(false)

// 对话框
const showShareDialog = ref(false)
const showDetailDialog = ref(false)
const selectedTemplate = ref<any>(null)
const sharing = ref(false)

// 分享表单
const shareForm = ref({
  workflow_id: '',
  name: '',
  description: '',
  category: '',
  tags: [] as string[],
  is_public: true
})
const tagsInput = ref('')

// 加载模板列表
const loadTemplates = async () => {
  loading.value = true
  try {
    const params: any = {
      skip: (currentPage.value - 1) * pageSize.value,
      limit: pageSize.value,
      sort_by: sortBy.value,
      sort_order: 'desc'
    }
    
    if (searchQuery.value) {
      params.search = searchQuery.value
    }
    if (categoryFilter.value) {
      params.category = categoryFilter.value
    }
    if (featuredOnly.value) {
      params.featured_only = true
    }
    
    const response = await api.get('/api/v1/template-market', { params })
    templates.value = response.data
    totalCount.value = response.data.length // 实际应该从响应头获取总数
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '加载模板列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadTemplates()
}

// 分页
const handlePageChange = (page: number) => {
  currentPage.value = page
  loadTemplates()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadTemplates()
}

// 查看模板详情
const viewTemplate = async (template: any) => {
  try {
    const response = await api.get(`/api/v1/template-market/${template.id}`)
    selectedTemplate.value = response.data
    showDetailDialog.value = true
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '加载模板详情失败')
  }
}

// 使用模板
const useTemplate = async (template: any) => {
  try {
    await ElMessageBox.prompt('请输入工作流名称', '使用模板', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: `${template.name} (副本)`
    })
    
    const response = await api.post(`/api/v1/template-market/${template.id}/use`, null, {
      params: {
        name: `${template.name} (副本)`
      }
    })
    
    ElMessage.success('工作流已创建')
    router.push(`/workflow/${response.data.workflow_id}`)
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.detail || '使用模板失败')
    }
  }
}

// 收藏/取消收藏
const toggleFavorite = async (template: any) => {
  try {
    if (template.is_favorited) {
      await api.delete(`/api/v1/template-market/${template.id}/favorite`)
      template.is_favorited = false
      ElMessage.success('已取消收藏')
    } else {
      await api.post(`/api/v1/template-market/${template.id}/favorite`)
      template.is_favorited = true
      ElMessage.success('已收藏')
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '操作失败')
  }
}

// 评分
const rateTemplate = async (template: any, rating: number) => {
  try {
    await api.post(`/api/v1/template-market/${template.id}/rate`, {
      rating: rating,
      comment: ''
    })
    template.user_rating = rating
    ElMessage.success('评分成功')
    // 重新加载模板以更新平均评分
    await loadTemplates()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '评分失败')
  }
}

// 加载我的工作流
const loadMyWorkflows = async () => {
  try {
    await workflowStore.fetchWorkflows()
    myWorkflows.value = workflowStore.workflows
  } catch (error) {
    console.error('加载工作流失败', error)
  }
}

// 分享模板
const handleShare = async () => {
  if (!shareForm.value.workflow_id) {
    ElMessage.warning('请选择要分享的工作流')
    return
  }
  if (!shareForm.value.name) {
    ElMessage.warning('请输入模板名称')
    return
  }
  
  sharing.value = true
  try {
    const workflow = myWorkflows.value.find(w => w.id === shareForm.value.workflow_id)
    if (!workflow) {
      ElMessage.error('工作流不存在')
      return
    }
    
    await api.post('/api/v1/template-market', {
      name: shareForm.value.name,
      description: shareForm.value.description,
      category: shareForm.value.category,
      tags: shareForm.value.tags,
      nodes: workflow.nodes,
      edges: workflow.edges,
      is_public: shareForm.value.is_public
    })
    
    ElMessage.success('模板分享成功')
    showShareDialog.value = false
    shareForm.value = {
      workflow_id: '',
      name: '',
      description: '',
      category: '',
      tags: [],
      is_public: true
    }
    tagsInput.value = ''
    loadTemplates()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '分享失败')
  } finally {
    sharing.value = false
  }
}

// 标签处理
const handleTagsInput = () => {
  if (tagsInput.value) {
    const tags = tagsInput.value.split(',').map(t => t.trim()).filter(t => t)
    shareForm.value.tags = [...new Set([...shareForm.value.tags, ...tags])]
    tagsInput.value = ''
  }
}

const removeTag = (tag: string) => {
  shareForm.value.tags = shareForm.value.tags.filter(t => t !== tag)
}

// 加载我的收藏
const loadMyFavorites = async () => {
  try {
    const response = await api.get('/api/v1/template-market/my/favorites')
    templates.value = response.data
    totalCount.value = response.data.length
    ElMessage.success('已加载我的收藏')
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '加载收藏失败')
  }
}

// 加载我分享的
const loadMyShared = async () => {
  try {
    const response = await api.get('/api/v1/template-market/my/shared')
    templates.value = response.data
    totalCount.value = response.data.length
    ElMessage.success('已加载我分享的模板')
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '加载失败')
  }
}

// 获取分类名称
const getCategoryName = (category: string) => {
  const categoryMap: Record<string, string> = {
    'llm': 'LLM',
    'data_processing': '数据处理',
    'automation': '自动化',
    'integration': '集成',
    'other': '其他'
  }
  return categoryMap[category] || category
}

onMounted(() => {
  loadTemplates()
  loadMyWorkflows()
})
</script>

<style scoped>
.template-market {
  width: 100%;
  min-height: 100vh;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.header-content h1 {
  margin: 0;
  font-size: 24px;
}

.search-card {
  margin-bottom: 20px;
}

.templates-card {
  min-height: 500px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-count {
  color: #909399;
  font-size: 14px;
}

.template-card {
  cursor: pointer;
  transition: all 0.3s;
  height: 100%;
}

.template-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.template-thumbnail {
  width: 100%;
  height: 150px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  border-radius: 4px;
  overflow: hidden;
}

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

.template-info {
  padding: 10px;
}

.template-name {
  font-size: 16px;
  font-weight: bold;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.template-description {
  font-size: 12px;
  color: #909399;
  margin: 0 0 10px 0;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.template-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.template-stats {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #909399;
}

.template-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.template-actions-detail {
  display: flex;
  gap: 10px;
  align-items: center;
}

.template-tags {
  margin-top: 8px;
}
</style>
