<!--
 * @Author: ysh
 * @Date: 2025-07-17 18:16:50
 * @LastEditors: wrh
 * @LastEditTime: 2026-01-19 15:24:42
-->
<template>
  <div class="app-container">
    <div class="main-content">
      <!-- 左侧智能体列表 -->
      <div v-if="showLeftPanel" class="left-panel">
        <div class="panel-header">
          <div class="header-left">
  
            <h3>智能体列表</h3>
            <span class="agent-count">{{ agentList.length }} 个智能体</span>
          </div>
          <el-button type="primary" size="small" @click="openAddDialog" icon="el-icon-plus">
            新增智能体
          </el-button>
        </div>

        <!-- 搜索框 -->
        <div class="search-box">
          <el-input v-model="queryParams.agentName" placeholder="请输入智能体名称" clearable @clear="handleQuery"
            @keyup.enter="handleQuery">
            <span slot="append">
              <el-button @click="handleQuery" icon="el-icon-search">
              </el-button>
            </span>
          </el-input>
        </div>

        <!-- 智能体列表 -->
        <div class="agent-cards" v-loading="loading">
          <div v-for="agent in agentList" :key="agent.agentId" class="agent-card"
            :class="{ 'active': selectedAgentId === agent.agentId }" @click="selectAgent(agent)">
            <div class="card-header">
              <div class="card-title">
                <i class="el-icon-folder folder-icon"></i>
                <span class="title-text">{{ agent.agentName }}</span>
              </div>
              <div class="card-actions">
                <el-dropdown @command="handleCommand" trigger="click">
                  <el-button type="text" size="small" icon="el-icon-more">
                  </el-button>
                  <span slot="dropdown">
                    <el-dropdown-menu>
                      <el-dropdown-item :command="{ action: 'edit', agent }">编辑</el-dropdown-item>
                      <el-dropdown-item :command="{ action: 'delete', agent }" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </span>
                </el-dropdown>
              </div>
            </div>
            <div class="card-content">
              <p class="description">{{ agent.description || '暂无描述' }}</p>
              <div class="meta-info">
                <span class="create-time">{{ agent.createTime }}</span>
              </div>
            </div>
          </div>


          <!-- 空状态 -->
          <div v-if="agentList.length === 0 && !loading" class="empty-state">
            <i class="el-icon-folder-opened empty-icon"></i>
            <p>暂无智能体</p>
            <el-button type="primary" @click="openAddDialog">创建第一个智能体</el-button>
          </div>
        </div>
      </div>

      <!-- 右侧详细内容 -->
      <div class="right-panel">
        <div class="agent-detail">
          <AgentDetail :agent-id="selectedAgentId" :show-left-panel="showLeftPanel" @toggle-left-panel="showLeftPanel = !showLeftPanel" />
        </div>
      </div>

      <el-dialog :visible.sync="agentDialogVisible" :title="dialogTitle" width="500px" @close="resetForm">
        <el-form ref="ruleForm" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="智能体名称" prop="agentName">
            <el-input v-model="form.agentName" placeholder="请输入智能体名称" maxlength="20" show-word-limit />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" type="textarea" placeholder="请输入描述" :rows="2" maxlength="200"
              show-word-limit />
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-input v-model="form.role" placeholder="请输入角色" maxlength="50" show-word-limit />
          </el-form-item>
          <el-form-item label="初始提示词" prop="initPrompt">
            <el-input v-model="form.initPrompt" type="textarea" placeholder="请输入初始提示词" :rows="4" maxlength="1000"
              show-word-limit />
          </el-form-item>
          <el-form-item label="模型" prop="modelName">
            <el-select v-model="form.modelName" placeholder="请选择模型" clearable>
              <el-option v-for="model in modelList" :key="model.name" :label="model.name" :value="model.name">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import { listAgent, addAgent, updateAgent, delAgent, opening } from '@/api/llm/agent'
import { answer } from '@/api/llm/mcp'
import AgentDetail from './AgentDetail.vue'

export default {
  name: 'AgentIndex',
  components: {
    AgentDetail
  },
  data() {
    return {
      // 响应式数据
      loading: false,
      agentList: [],
      total: 0,
      selectedAgentId: null,
      showLeftPanel: true,
      dialogVisible: false,
      form: {
        agentName: '',
        description: '',
        avatar: '',
        role: '',
        initPrompt: '',
        modelName: ''
      },
      rules: {
        agentName: [{ required: true, message: '请输入智能体名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入智能体描述', trigger: 'blur' }]
      },
      isEdit: false,
      editAgentId: null,
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        agentName: ''
      },
      // 新增智能体对话框控制变量
      agentDialogVisible: false,
      dialogTitle: '',
      isModifyAgent: false,
      // 模型列表
      modelList: [{name: "Qwen3-VL-8B-Instruct"}]
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    // 获取智能体列表
    getList() {
      this.loading = true
      listAgent(this.queryParams).then(response => {
        this.agentList = response.rows || []
        this.total = response.total || 0
      }).catch(error => {
        console.error('获取智能体列表失败:', error)
        this.$message.error('获取智能体列表失败')
      }).finally(() => {
        this.loading = false
      })
    },

    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 选择智能体
    selectAgent(agent) {
      this.selectedAgentId = agent.agentId
    },

    resetForm() {
      this.isEdit = false
      this.editAgentId = null
      this.form = {
        agentName: '',
        description: '',
        avatar: '',
        role: '',
        initPrompt: '',
        modelName: ''
      }
      // 如果有表单引用，重置验证
      if (this.$refs.ruleForm) {
        this.$refs.ruleForm.resetFields()
      }
    },

    // 打开新增智能体对话框
    openAddDialog() {
      this.agentDialogVisible = true
      this.dialogTitle = "添加智能体"
      this.isModifyAgent = false
      // 重置表单
      this.resetForm()
    },

    // 关闭对话框
    closeDialog() {
      this.agentDialogVisible = false
      this.resetForm()
    },

    // 提交表单
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading = true
          const agentForm = { ...this.form }
          if (this.isModifyAgent) {
            updateAgent(agentForm).then(() => {
              this.$message.success('修改成功')
              this.loading = false
              this.agentDialogVisible = false
              this.getList()
            }).catch(() => {
              this.loading = false
              this.$message.error('修改失败')
            })
          } else {
            addAgent(agentForm).then(() => {
              this.$message.success('新增成功')
              this.loading = false
              this.agentDialogVisible = false
              this.getList()
            }).catch(() => {
              this.loading = false
              this.$message.error('新增失败')
            })
          }
        }
      })
    },

    // 操作菜单处理
    handleCommand(command) {
      const { action, agent } = command

      if (action === 'edit') {
        this.isEdit = true
        this.editAgentId = agent.agentId
        this.form = {
          agentName: agent.agentName,
          description: agent.description,
          avatar: agent.avatar || '',
          role: agent.role || '',
          initPrompt: agent.initPrompt || '',
          modelName: agent.modelName || ''
        }
        this.dialogVisible = true
      } else if (action === 'delete') {
        this.$confirm(
          `确认删除智能体"${agent.agentName}"吗？`,
          '删除确认',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          return delAgent(agent.agentId)
        }).then(() => {
          this.$message.success('删除成功')

          // 如果删除的是当前选中的智能体，清空选中状态
          if (this.selectedAgentId === agent.agentId) {
            this.selectedAgentId = null
          }

          this.getList()
        }).catch(error => {
          if (error !== 'cancel') {
            console.error('删除智能体失败:', error)
            this.$message.error('删除失败')
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.main-content {
  flex: 1;
  display: flex;
  gap: 16px;
  padding: 16px;
  overflow: hidden;
}

.left-panel {
  width: 20%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.right-panel {
  flex: 1;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;

}

.panel-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fafbfc;

  .header-left {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .agent-count {
    font-size: 12px;
    color: #909399;
    background: #f0f2f5;
    padding: 4px 8px;
    border-radius: 4px;
  }

  .search-box {
    padding: 16px;
    border-bottom: 1px solid #e4e4e4;
  }
}

.agent-cards {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.agent-card {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;

  &:hover {
    border-color: #409eff;
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
    transform: translateY(-2px);
  }

  &.active {
    border-color: #409eff;
    background: #f0f9ff;
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
  }

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

    .card-title {
      display: flex;
      align-items: center;
      gap: 8px;
      flex: 1;

      .folder-icon {
        color: #409eff;
        font-size: 18px;
      }

      .title-text {
        font-weight: 600;
        color: #303133;
        font-size: 14px;
        line-height: 1.4;
      }
    }

    .card-actions {
      opacity: 0;
      transition: opacity 0.3s ease;
    }
  }

  &:hover .card-actions {
    opacity: 1;
  }

  .card-content {
    .description {
      color: #606266;
      font-size: 13px;
      line-height: 1.5;
      margin: 0 0 12px 0;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .meta-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;
      color: #909399;

      .create-time {
        background: #f0f2f5;
        padding: 2px 6px;
        border-radius: 3px;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  color: #909399;

  .empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
    opacity: 0.5;
  }

  p {
    margin: 0 0 16px 0;
    font-size: 14px;
  }
}

.agent-detail {
  flex: 1;
  background: white;
}
</style>