<!--
 * @Author: ysh
 * @Date: 2025-07-17 18:16:50
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-07-28 14:46:01
-->
<template>
  <div class="agent-container">
    <!-- 左侧智能体列表 -->
    <div class="agent-list">
      <div class="list-header">
        <h3>智能体列表</h3>
        <el-button type="primary" size="small" @click="openAddDialog">
          <el-icon>
            <Plus />
          </el-icon>
          新增
        </el-button>
      </div>

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

      <!-- 智能体列表 -->
      <div class="list-content" v-loading="loading">
        <div v-for="agent in agentList" :key="agent.agentId" class="agent-item"
          :class="{ 'active': selectedAgentId === agent.agentId }" @click="selectAgent(agent)">
          <div class="agent-info">
            <div class="agent-name">{{ agent.agentName }}</div>
            <div class="agent-desc">{{ agent.description || '暂无描述' }}</div>
            <div class="agent-meta">
              <span class="create-time">{{ agent.createTime }}</span>
            </div>
          </div>
          <div class="agent-actions">
            <el-dropdown @command="handleCommand" trigger="click">
              <el-icon class="action-icon">
                <More />
              </el-icon>
              <template #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>
              </template>
            </el-dropdown>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="agentList.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无智能体数据">
            <el-button type="primary" @click="dialogVisible = true">创建智能体</el-button>
          </el-empty>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :total="total" :page-sizes="[10, 20, 50]" layout="sizes, prev, pager, next" small @size-change="handleQuery"
          @current-change="handleQuery" />
      </div>
    </div>

    <!-- 右侧详细内容 -->
    <div class="agent-detail">
      <AgentDetail :agent-id="selectedAgentId" />
    </div>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑智能体' : '新增智能体'" width="30%" @close="resetForm">
      <el-form :model="form" :rules="rules" label-width="120px">
        <el-form-item label="智能体名称" prop="agentName">
          <el-input v-model="form.agentName" placeholder="请输入智能体名称" />
        </el-form-item>
        <el-form-item label="智能体描述" prop="description">
          <el-input type="textarea" v-model="form.description" placeholder="请输入智能体描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="() => { dialogVisible = false; resetForm(); }">取消</el-button>
        <el-button type="primary" @click="handleSubmit">{{ isEdit ? '保存' : '确定' }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listAgent, addAgent, updateAgent, delAgent, opening } from '@/api/llm/agent'
import { answer } from '@/api/llm/mcp'
import AgentDetail from './AgentDetail.vue'

// 响应式数据
const loading = ref(false)
const agentList = ref([])
const total = ref(0)
const selectedAgentId = ref(null)
const dialogVisible = ref(false)
const form = reactive({
  agentName: '',
  description: ''
})
const rules = reactive({
  agentName: [{ required: true, message: '请输入智能体名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入智能体描述', trigger: 'blur' }]
})
const isEdit = ref(false)
const editAgentId = ref(null)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  agentName: ''
})

// 获取智能体列表
const getList = async () => {
  loading.value = true
  try {
    const response = await listAgent(queryParams)
    agentList.value = response.rows || []
    total.value = response.total || 0
  } catch (error) {
    console.error('获取智能体列表失败:', error)
    ElMessage.error('获取智能体列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 选择智能体
const selectAgent = (agent) => {
  selectedAgentId.value = agent.agentId
}

const resetForm = () => {
  isEdit.value = false
  editAgentId.value = null
  form.agentName = ''
  form.description = ''
}

const openAddDialog = () => {
  resetForm()
  dialogVisible.value = true
}

const handleSubmit = () => {
  if (isEdit.value) {
    updateAgent({ agentId: editAgentId.value, ...form }).then(res => {
      if (res.code === 200) {
        ElMessage.success('编辑成功')
        dialogVisible.value = false
        isEdit.value = false
        editAgentId.value = null
        getList()
      }
    })
  } else {
    addAgent(form).then(res => {
      if (res.code === 200) {
        ElMessage.success('新增成功')
        dialogVisible.value = false
        getList()
      }
    })
  }
}

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

  if (action === 'edit') {
    isEdit.value = true
    editAgentId.value = agent.agentId
    form.agentName = agent.agentName
    form.description = agent.description
    dialogVisible.value = true
  } else if (action === 'delete') {
    try {
      await ElMessageBox.confirm(
        `确认删除智能体"${agent.agentName}"吗？`,
        '删除确认',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      await delAgent(agent.agentId)
      ElMessage.success('删除成功')

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

      getList()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除智能体失败:', error)
        ElMessage.error('删除失败')
      }
    }
  }
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.agent-container {
  display: flex;
  height: calc(100vh - 120px);
  background: #f5f5f5;
}

.agent-list {
  width: 300px;
  background: white;
  border-right: 1px solid #e4e4e4;
  display: flex;
  flex-direction: column;

  .list-header {
    padding: 16px;
    border-bottom: 1px solid #e4e4e4;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
    }
  }

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

  .list-content {
    flex: 1;
    overflow-y: auto;

    .agent-item {
      padding: 12px 16px;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      transition: all 0.2s;
      display: flex;
      justify-content: space-between;
      align-items: center;

      &:hover {
        background: #f8f9fa;
      }

      &.active {
        background: #e6f7ff;
        border-right: 3px solid #1890ff;
      }

      .agent-info {
        flex: 1;

        .agent-name {
          font-size: 14px;
          font-weight: 500;
          color: #333;
          margin-bottom: 4px;
        }

        .agent-desc {
          font-size: 12px;
          color: #666;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .agent-meta {
          font-size: 11px;
          color: #999;

          .create-time {
            margin-right: 8px;
          }
        }
      }

      .agent-actions {
        .action-icon {
          color: #999;
          font-size: 16px;
          padding: 4px;
          border-radius: 4px;

          &:hover {
            background: #f0f0f0;
            color: #666;
          }
        }
      }
    }

    .empty-state {
      padding: 40px 20px;
      text-align: center;
    }
  }

  .pagination-wrapper {
    padding: 16px;
    border-top: 1px solid #e4e4e4;
    background: white;
  }
}

.agent-detail {
  flex: 1;
  background: white;
}

:deep(.el-pagination) {
  justify-content: center;

  .el-pagination__sizes {
    margin-right: 8px;
  }
}
</style>