<template>
    <div class="apps-view">
        <header class="page-header">
            <h1>全部应用</h1>
            <p>选择智能体开始对话，助力您的工作效率提升</p>
        </header>

        <div class="toolbar-section">
            <el-input
                v-model="searchText"
                placeholder="搜索智能体..."
                size="large"
                :prefix-icon="Search"
                clearable
                class="search-input"
            />
            <el-button type="primary" size="large" @click="handleCreateClick">
                <el-icon><Plus /></el-icon>
                新增智能体
            </el-button>
        </div>

        <div class="category-tabs">
            <span
                v-for="cat in categories"
                :key="cat.key"
                class="tab-item"
                :class="{ active: activeCategory === cat.key }"
                @click="activeCategory = cat.key"
            >
                {{ cat.label }}
            </span>
        </div>

        <div class="agents-grid">
            <AgentCard
                v-for="agent in filteredAgents"
                :key="agent.id"
                :agent="agent"
                @click="handleAgentClick(agent)"
            />
        </div>

        <!-- 新增/编辑智能体对话框 -->
        <AgentEdit
            v-model="showEditDialog"
            :agent="editingAgent"
            @save="handleSaveAgent"
        />
    </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Plus } from 'lucide-vue-next'
import { ElMessage } from 'element-plus'
import AgentCard from './components/AgentCard/AgentCard.vue'
import AgentEdit from './components/AgentEdit/AgentEdit.vue'

interface Agent {
    id: string
    name: string
    description: string
    icon?: string
    imageUrl?: string
    color: string
    category: string
    usage: number
    apiUrl?: string
}

const router = useRouter()
const searchText = ref('')
const activeCategory = ref('all')
const showEditDialog = ref(false)
const editingAgent = ref<Agent | null>(null)

const categories = [
    { key: 'all', label: '全部' },
    { key: 'content', label: '内容创作' },
    { key: 'office', label: '办公助手' },
    { key: 'business', label: '业务助手' },
    { key: 'lifeline', label: '城市生命线' }
]

// Mock 数据 - 实际使用时从 API 加载
const agents = ref<Agent[]>([
    {
        id: 'default',
        name: '城市生命线助手',
        description: '智能城市基础设施安全管理，提供隐患排查、应急预案、数据分析等服务',
        icon: '🏙️',
        color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        category: 'lifeline',
        usage: 15680
    },
    {
        id: 'emergency',
        name: '应急处理助手',
        description: '专注于突发事件处理、应急预案制定和响应流程优化',
        icon: '🚨',
        color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
        category: 'lifeline',
        usage: 8320
    },
    {
        id: 'analysis',
        name: '数据分析助手',
        description: '城市设施运行数据分析、故障风险预测、分析报告生成',
        icon: '📊',
        color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
        category: 'lifeline',
        usage: 11200
    },
    {
        id: 'safety',
        name: '安全检查助手',
        description: '协助进行安全隐患排查、标准流程执行、整改计划制定',
        icon: '🔍',
        color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
        category: 'lifeline',
        usage: 9540
    },
    {
        id: 'xiaohongshu',
        name: '小红书文案生成',
        description: '一键生成爆款小红书文案，支持多种风格，自动添加热门话题标签',
        icon: '📕',
        color: '#ff2442',
        category: 'content',
        usage: 12580
    },
    {
        id: 'contract',
        name: '泰豪合同助手',
        description: '智能合同审核、条款分析、风险提示，提高合同处理效率',
        icon: '📄',
        color: '#0055AA',
        category: 'business',
        usage: 8320
    },
    {
        id: 'video',
        name: '泰豪短视频助手',
        description: '短视频脚本创作、文案优化、热门话题推荐',
        icon: '🎬',
        color: '#10b981',
        category: 'content',
        usage: 5640
    },
    {
        id: 'email',
        name: '邮件写作助手',
        description: '商务邮件、会议邀请、工作汇报等各类邮件智能生成',
        icon: '✉️',
        color: '#6366f1',
        category: 'office',
        usage: 7230
    },
    {
        id: 'translate',
        name: '多语言翻译',
        description: '支持中英日韩等多语言互译，专业术语精准翻译',
        icon: '🌐',
        color: '#14b8a6',
        category: 'office',
        usage: 11200
    }
])

// 筛选后的智能体
const filteredAgents = computed(() => {
    let result = agents.value
    
    if (activeCategory.value !== 'all') {
        result = result.filter(a => a.category === activeCategory.value)
    }
    
    if (searchText.value) {
        const keyword = searchText.value.toLowerCase()
        result = result.filter(a => 
            a.name.toLowerCase().includes(keyword) || 
            a.description.toLowerCase().includes(keyword)
        )
    }
    
    return result
})

// 点击智能体卡片
const handleAgentClick = (agent: Agent) => {
    // TODO: 实际使用时路由跳转到聊天页面
    router.push({
        path: '/aichat',
        query: { agentId: agent.id }
    })
}

// 点击新增按钮
const handleCreateClick = () => {
    editingAgent.value = null
    showEditDialog.value = true
}

// 保存智能体
const handleSaveAgent = async (agentData: Partial<Agent>) => {
    try {
        if (editingAgent.value) {
            // TODO: 调用更新 API
            // await agentAPI.update(editingAgent.value.id, agentData)
            
            const index = agents.value.findIndex(a => a.id === editingAgent.value!.id)
            if (index > -1) {
                agents.value[index] = { ...agents.value[index], ...agentData }
            }
            ElMessage.success('智能体更新成功')
        } else {
            // TODO: 调用创建 API
            // const newAgent = await agentAPI.create(agentData)
            
            const newAgent: Agent = {
                id: 'custom_' + Date.now(),
                name: agentData.name || '',
                description: agentData.description || '',
                icon: agentData.imageUrl ? '' : '🤖',
                imageUrl: agentData.imageUrl,
                color: agentData.color || '#0055AA',
                category: agentData.category || 'office',
                apiUrl: agentData.apiUrl,
                usage: 0
            }
            agents.value.unshift(newAgent)
            ElMessage.success('智能体创建成功')
        }
        showEditDialog.value = false
    } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请稍后重试')
    }
}

// TODO: 组件挂载时加载数据
// onMounted(async () => {
//     try {
//         const data = await agentAPI.getList()
//         agents.value = data
//     } catch (error) {
//         console.error('加载失败:', error)
//     }
// })
</script>

<style lang="scss" scoped>
@import url('./AgentPlatformView.scss');
</style>
