<template>
  <div class="flow-market-page">
    <el-card>
      <template #header>
        <span>流模板市场</span>
      </template>

      <el-row :gutter="20">
        <el-col :span="8" v-for="tpl in templates" :key="tpl.id" style="margin-bottom: 20px">
          <el-card shadow="hover" class="flow-card">
            <div class="flow-card-header">
              <h4>{{ tpl.name }}</h4>
              <el-icon :size="20"><component :is="tpl.icon" /></el-icon>
            </div>
            <p class="flow-desc">{{ tpl.description || '暂无描述' }}</p>
            <div class="flow-card-footer">
              <el-tag size="small" type="info">{{ tpl.nodes?.length || 0 }} 节点</el-tag>
              <el-button size="small" type="primary" @click="useTemplate(tpl.id)">使用模板</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-empty v-if="!templates.length" description="暂无流模板" />
    </el-card>

    <el-card style="margin-top: 20px">
      <template #header>
        <span>已上架的工作流</span>
      </template>

      <el-row :gutter="20">
        <el-col :span="8" v-for="flow in flows" :key="flow.id" style="margin-bottom: 20px">
          <el-card shadow="hover" class="flow-card" @click="$router.push(`/admin/flow/market/${flow.id}`)">
            <div class="flow-card-header">
              <h4>{{ flow.name }}</h4>
              <el-tag size="small" type="success">v{{ flow.version }}</el-tag>
            </div>
            <p class="flow-desc">{{ flow.description || '暂无描述' }}</p>
            <div class="flow-card-footer">
              <el-tag size="small" v-if="flow.published_to_wecom" type="warning">企微可用</el-tag>
              <el-button size="small" type="primary" text @click.stop="$router.push(`/admin/flow/market/${flow.id}`)">查看详情</el-button>
              <span style="font-size: 12px; color: #999; margin-left: auto">
                {{ flow.updated_at ? new Date(flow.updated_at).toLocaleDateString() : '' }}
              </span>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-empty v-if="!flows.length" description="暂无已上架的工作流" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { flowApi } from '@/api'
import { Document, Bell, DataAnalysis, Search, Tools } from '@element-plus/icons-vue'

const router = useRouter()
const flows = ref<any[]>([])
const templates = ref<any[]>([])

const iconMap: Record<string, any> = {
  Document, Bell, DataAnalysis, Search, Tools,
}

onMounted(async () => {
  const [marketRes, tplRes]: any = await Promise.all([
    flowApi.getMarket().catch(() => ({ data: [] })),
    flowApi.getTemplates().catch(() => ({ data: [] })),
  ])
  flows.value = Array.isArray(marketRes) ? marketRes : (marketRes?.data || [])
  const rawTemplates = Array.isArray(tplRes) ? tplRes : (tplRes?.data || [])
  templates.value = rawTemplates.map((t: any) => ({
    ...t,
    icon: iconMap[t.icon] || Tools,
  }))
})

async function useTemplate(templateId: string) {
  try {
    const res: any = await flowApi.useTemplate(templateId)
    const data = res?.data || res || {}
    if (data.id) {
      ElMessage.success('模板已创建，请继续编辑')
      router.push(`/admin/flow/editor/${data.id}`)
    }
  } catch (e) {
    ElMessage.error('创建失败')
  }
}
</script>

<style scoped>
.flow-card {
  cursor: pointer;
  transition: all 0.3s;
}
.flow-card:hover {
  transform: translateY(-2px);
}
.flow-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
.flow-card-header h4 {
  margin: 0;
  font-size: 16px;
}
.flow-desc {
  color: #909399;
  font-size: 13px;
  margin-bottom: 12px;
  min-height: 40px;
}
.flow-card-footer {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>