<script setup lang="ts">
import { Delete, Edit, Plus, RefreshRight } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, reactive, ref } from 'vue';

import { deleteAgent, queryAgents, saveAgent, type AgentDefinition } from '@/api/agent';
import { listRagStores, type RagStore } from '@/api/ragStores';

const loading = ref(false);
const saving = ref(false);
const dialogVisible = ref(false);
const agents = ref<AgentDefinition[]>([]);
const stores = ref<RagStore[]>([]);

const statusOptions = [
  { label: '启用', value: 'ENABLED' },
  { label: '禁用', value: 'DISABLED' },
];

const editForm = reactive<AgentDefinition>({
  agentCode: '',
  agentName: '',
  systemPrompt: '',
  storeId: '',
  status: 'ENABLED',
  remark: '',
});

const dialogTitle = computed(() => (editForm.id ? '编辑Agent' : '新增Agent'));

function resetForm(row?: AgentDefinition) {
  editForm.id = row?.id;
  editForm.agentCode = row?.agentCode ?? '';
  editForm.agentName = row?.agentName ?? '';
  editForm.systemPrompt = row?.systemPrompt ?? '';
  editForm.storeId = row?.storeId ?? stores.value[0]?.id ?? '';
  editForm.status = row?.status ?? 'ENABLED';
  editForm.remark = row?.remark ?? '';
}

async function loadStores() {
  const response = await listRagStores();
  stores.value = response.data ?? [];
}

async function loadAgents() {
  loading.value = true;
  try {
    const response = await queryAgents();
    agents.value = response.data ?? [];
  } finally {
    loading.value = false;
  }
}

function openCreateDialog() {
  resetForm();
  dialogVisible.value = true;
}

function openEditDialog(row: AgentDefinition) {
  resetForm(row);
  dialogVisible.value = true;
}

async function submitAgent() {
  if (!editForm.agentCode || !editForm.agentName || !editForm.storeId) {
    ElMessage.warning('请填写Agent编码、名称和绑定知识库');
    return;
  }
  saving.value = true;
  try {
    await saveAgent({ ...editForm });
    ElMessage.success('保存成功');
    dialogVisible.value = false;
    await loadAgents();
  } finally {
    saving.value = false;
  }
}

async function removeAgent(row: AgentDefinition) {
  if (!row.id) {
    return;
  }
  await ElMessageBox.confirm(`确认删除Agent「${row.agentName || row.agentCode}」？`, '删除确认', {
    type: 'warning',
    confirmButtonText: '删除',
    cancelButtonText: '取消',
  });
  await deleteAgent(row.id);
  ElMessage.success('已删除');
  await loadAgents();
}

function storeLabel(storeId?: string) {
  const store = stores.value.find((item) => item.id === storeId);
  return store?.storeName ?? store?.storeCode ?? storeId ?? '-';
}

onMounted(async () => {
  await loadStores();
  resetForm();
  await loadAgents();
});
</script>

<template>
  <section class="page-panel">
    <div class="page-panel__header">
      <h2>Agent 管理</h2>
      <span>Agent Config</span>
    </div>

    <div class="toolbar">
      <div class="toolbar__actions">
        <el-button :icon="RefreshRight" @click="loadAgents">刷新</el-button>
        <el-button type="primary" :icon="Plus" @click="openCreateDialog">新增Agent</el-button>
      </div>
    </div>

    <el-table v-loading="loading" :data="agents" row-key="id">
      <el-table-column prop="agentCode" label="Agent编码" min-width="140" />
      <el-table-column prop="agentName" label="Agent名称" min-width="140" />
      <el-table-column label="知识库" min-width="140">
        <template #default="{ row }">{{ storeLabel(row.storeId) }}</template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'ENABLED' ? 'success' : 'info'">
            {{ row.status === 'ENABLED' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="systemPrompt" label="系统提示词" min-width="220" show-overflow-tooltip />
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" :icon="Edit" @click="openEditDialog(row)">编辑</el-button>
          <el-button link type="danger" :icon="Delete" @click="removeAgent(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="720px">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="Agent编码" required>
          <el-input v-model="editForm.agentCode" placeholder="如 AGENT_RAG_HELPER" />
        </el-form-item>
        <el-form-item label="Agent名称" required>
          <el-input v-model="editForm.agentName" placeholder="如 知识问答助手" />
        </el-form-item>
        <el-form-item label="绑定知识库" required>
          <el-select v-model="editForm.storeId">
            <el-option
              v-for="store in stores"
              :key="store.id"
              :label="`${store.storeName}(${store.storeCode})`"
              :value="store.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="系统提示词">
          <el-input v-model="editForm.systemPrompt" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.status">
            <el-radio-button v-for="item in statusOptions" :key="item.value" :value="item.value">
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submitAgent">保存</el-button>
      </template>
    </el-dialog>
  </section>
</template>

<style scoped>
.toolbar {
  display: flex;
  justify-content: flex-end;
  padding: 16px 22px;
}

.toolbar__actions {
  display: flex;
  gap: 8px;
}
</style>
