<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="showCreateDialog = true">
        <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">
      <div
        v-for="agent in filteredAgents"
        :key="agent.id"
        class="agent-card"
        @click="handleAgentClick(agent)"
      >
        <div class="card-header">
          <div class="agent-icon" :style="{ background: agent.imageUrl ? 'transparent' : agent.color }">
            <img v-if="agent.imageUrl" :src="agent.imageUrl" :alt="agent.name" />
            <span v-else>{{ agent.icon }}</span>
          </div>
        </div>
        <h3 class="agent-name">{{ agent.name }}</h3>
        <p class="agent-desc">{{ agent.description }}</p>
        <div class="card-footer">
          <span class="usage-count">{{ agent.usage }} 次使用</span>
          <el-button type="primary" size="small" round>开始对话</el-button>
        </div>
      </div>
    </div>

    <!-- 新增智能体对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="新增智能体"
      width="520px"
      :close-on-click-modal="false"
    >
      <el-form :model="newAgent" label-width="80px" label-position="top">
        <el-form-item label="智能体图片">
          <div class="upload-area" @click="triggerUpload">
            <input
              type="file"
              ref="fileInput"
              accept="image/*"
              @change="handleFileChange"
              style="display: none"
            />
            <div v-if="newAgent.imageUrl" class="preview-image">
              <img :src="newAgent.imageUrl" alt="preview" />
              <div class="change-tip">点击更换</div>
            </div>
            <div v-else class="upload-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <span>上传图片</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="智能体名称">
          <el-input v-model="newAgent.name" placeholder="请输入智能体名称" />
        </el-form-item>
        <el-form-item label="智能体介绍">
          <el-input
            v-model="newAgent.description"
            type="textarea"
            :rows="3"
            placeholder="请输入智能体功能介绍"
          />
        </el-form-item>
        <el-form-item label="API链接">
          <el-input v-model="newAgent.apiUrl" placeholder="请输入API接口地址" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="newAgent.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="内容创作" value="content" />
            <el-option label="办公助手" value="office" />
            <el-option label="业务助手" value="business" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCreateAgent">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useAgentStore } from '@/stores/agent'

const router = useRouter()
const agentStore = useAgentStore()
const searchText = ref('')
const activeCategory = ref('all')

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

const agents = ref([
  {
    id: 'xiaohongshu',
    name: '小红书文案生成',
    description: '一键生成爆款小红书文案，支持多种风格，自动添加热门话题标签',
    icon: '📕',
    color: '#ff2442',
    category: 'content',
    usage: 12580
  },
  {
    id: 'contract',
    name: '泰豪合同助手',
    description: '智能合同审核、条款分析、风险提示，提高合同处理效率',
    icon: '📄',
    color: '#7c3aed',
    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) => {
  // 先设置当前智能体
  agentStore.setCurrentAgent(agent.id)
  router.push({
    path: '/',
    query: { agentId: agent.id }
  })
}

// 新增智能体相关
const showCreateDialog = ref(false)
const fileInput = ref(null)
const newAgent = ref({
  name: '',
  description: '',
  apiUrl: '',
  category: '',
  imageUrl: ''
})

const triggerUpload = () => {
  fileInput.value?.click()
}

const handleFileChange = (e) => {
  const file = e.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (event) => {
      newAgent.value.imageUrl = event.target.result
    }
    reader.readAsDataURL(file)
  }
}

const handleCreateAgent = () => {
  if (!newAgent.value.name) {
    ElMessage.warning('请输入智能体名称')
    return
  }
  if (!newAgent.value.description) {
    ElMessage.warning('请输入智能体介绍')
    return
  }
  
  // 生成随机颜色
  const colors = ['#7c3aed', '#10b981', '#f59e0b', '#3b82f6', '#ef4444', '#6366f1', '#14b8a6']
  const randomColor = colors[Math.floor(Math.random() * colors.length)]
  
  // 添加新智能体
  agents.value.unshift({
    id: 'custom_' + Date.now(),
    name: newAgent.value.name,
    description: newAgent.value.description,
    icon: newAgent.value.imageUrl ? '' : '🤖',
    imageUrl: newAgent.value.imageUrl,
    color: randomColor,
    category: newAgent.value.category || 'office',
    apiUrl: newAgent.value.apiUrl,
    usage: 0
  })
  
  // 重置表单
  newAgent.value = {
    name: '',
    description: '',
    apiUrl: '',
    category: '',
    imageUrl: ''
  }
  showCreateDialog.value = false
  ElMessage.success('智能体创建成功')
}
</script>

<style lang="scss" scoped>
.apps-view {
  padding: 32px 48px;
  height: 100%;
  overflow-y: auto;
  background: #f9fafb;
}

.page-header {
  margin-bottom: 24px;
  
  h1 {
    font-size: 24px;
    color: #1f2937;
    margin-bottom: 8px;
  }
  
  p {
    color: #6b7280;
    font-size: 14px;
  }
}

.toolbar-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  
  .search-input {
    max-width: 400px;
  }
}

.category-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 24px;
  
  .tab-item {
    padding: 8px 20px;
    border-radius: 20px;
    font-size: 14px;
    color: #6b7280;
    background: #fff;
    border: 1px solid #e5e7eb;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover {
      color: #7c3aed;
      border-color: #7c3aed;
    }
    
    &.active {
      color: #fff;
      background: #7c3aed;
      border-color: #7c3aed;
    }
  }
}

.agents-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.agent-card {
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 16px;
  padding: 24px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: #7c3aed;
    box-shadow: 0 8px 24px rgba(124, 58, 237, 0.12);
    transform: translateY(-4px);
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16px;
    
    .agent-icon {
      width: 52px;
      height: 52px;
      border-radius: 14px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 26px;
      overflow: hidden;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
  
  .agent-name {
    font-size: 17px;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 8px;
  }
  
  .agent-desc {
    font-size: 13px;
    color: #6b7280;
    line-height: 1.6;
    margin-bottom: 16px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  
  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .usage-count {
      font-size: 12px;
      color: #9ca3af;
    }
  }
}

.upload-area {
  width: 120px;
  height: 120px;
  border: 2px dashed #d1d5db;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  overflow: hidden;
  
  &:hover {
    border-color: #7c3aed;
  }
  
  .upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    color: #9ca3af;
    
    .upload-icon {
      font-size: 28px;
    }
    
    span {
      font-size: 13px;
    }
  }
  
  .preview-image {
    width: 100%;
    height: 100%;
    position: relative;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .change-tip {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.6);
      color: #fff;
      text-align: center;
      font-size: 12px;
      padding: 4px 0;
      opacity: 0;
      transition: opacity 0.2s;
    }
    
    &:hover .change-tip {
      opacity: 1;
    }
  }
}
</style>
