<template>
  <div class="page-content">
    <div class="mb-5 flex items-center justify-between gap-4">
      <div>
        <h2 class="text-xl font-semibold">平台环境变量</h2>
        <p class="text-g-500 mt-1 text-sm">平台级配置注入到 skill / MCP 运行时；个人环境变量可覆盖同名平台变量</p>
      </div>
      <ElButton type="primary" @click="openCreate">新增变量</ElButton>
    </div>

    <ElTable v-loading="loading" :data="items" row-key="key">
      <ElTableColumn prop="key" label="变量名" min-width="200">
        <template #default="{ row }"><code class="text-xs">{{ row.key }}</code></template>
      </ElTableColumn>
      <ElTableColumn prop="description" label="说明" min-width="260" show-overflow-tooltip />
      <ElTableColumn label="状态" width="100">
        <template #default="{ row }"><ElTag :type="row.configured ? 'success' : 'info'">{{ row.configured ? '已配置' : '无值' }}</ElTag></template>
      </ElTableColumn>
      <ElTableColumn prop="updated_at" label="更新时间" width="180" />
      <ElTableColumn label="操作" width="140" fixed="right">
        <template #default="{ row }">
          <ElButton link type="primary" @click="openEdit(row)">编辑</ElButton>
          <ElButton link type="danger" @click="remove(row)">删除</ElButton>
        </template>
      </ElTableColumn>
    </ElTable>

    <ElDialog v-model="visible" :title="editingKey ? `编辑 ${editingKey}` : '新增环境变量'" width="520px">
      <ElForm label-width="90px">
        <ElFormItem label="变量名" required>
          <ElInput v-model="form.key" :disabled="!!editingKey" placeholder="例如 LLM_API_BASE" />
        </ElFormItem>
        <ElFormItem label="值" required>
          <ElInput v-model="form.value" type="textarea" :rows="3" placeholder="变量值（加密存储）" />
        </ElFormItem>
        <ElFormItem label="说明">
          <ElInput v-model="form.description" maxlength="512" placeholder="用途说明" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="visible = false">取消</ElButton>
        <ElButton type="primary" :loading="saving" @click="submit">保存</ElButton>
      </template>
    </ElDialog>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { PlatformEnvVar, deletePlatformEnvVar, fetchPlatformEnvVars, upsertPlatformEnvVar } from '@/api/governance'

const loading = ref(false)
const saving = ref(false)
const visible = ref(false)
const editingKey = ref('')
const items = ref<PlatformEnvVar[]>([])
const form = reactive({ key: '', value: '', description: '' })

async function load() {
  loading.value = true
  try {
    items.value = await fetchPlatformEnvVars()
  } finally {
    loading.value = false
  }
}

function openCreate() {
  editingKey.value = ''
  Object.assign(form, { key: '', value: '', description: '' })
  visible.value = true
}

function openEdit(row: PlatformEnvVar) {
  editingKey.value = row.key
  Object.assign(form, { key: row.key, value: '', description: row.description || '' })
  visible.value = true
}

async function submit() {
  if (!form.key.trim() || !form.value.trim()) {
    ElMessage.warning('变量名与值不能为空')
    return
  }
  saving.value = true
  try {
    await upsertPlatformEnvVar(form.key.trim(), form.value, form.description)
    ElMessage.success('已保存')
    visible.value = false
    await load()
  } catch (error) {
    ElMessage.error((error as Error)?.message || '保存失败')
  } finally {
    saving.value = false
  }
}

async function remove(row: PlatformEnvVar) {
  await ElMessageBox.confirm(`删除后运行时将不再注入 ${row.key}，确定删除？`, '删除变量', { type: 'warning' })
  await deletePlatformEnvVar(row.key)
  items.value = items.value.filter((item) => item.key !== row.key)
  ElMessage.success('已删除')
}

onMounted(load)
</script>
