<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">企业微信/钉钉/飞书/通用 Webhook 渠道:入站消息经绑定模型应答后按平台协议回复</p>
      </div>
      <ElButton type="primary" @click="openCreate">新增渠道</ElButton>
    </div>

    <ElAlert class="mb-4" type="info" :closable="false" title="接入方式:平台回调/机器人 Webhook 指向 POST /v1/channels/{code}/inbound;企微需在管理端配置回调 URL 并启用签名校验。" />

    <ElTable v-loading="loading" :data="channels" row-key="id">
      <ElTableColumn prop="code" label="代码" width="140" />
      <ElTableColumn prop="name" label="名称" min-width="140" />
      <ElTableColumn label="类型" width="110">
        <template #default="{ row }">{{ kindLabel(row.kind) }}</template>
      </ElTableColumn>
      <ElTableColumn label="绑定模型" min-width="180">
        <template #default="{ row }">{{ modelLabel(row.model_binding) }}</template>
      </ElTableColumn>
      <ElTableColumn label="API Key" width="90">
        <template #default="{ row }">
          <ElTag :type="row.has_api_key ? 'success' : 'info'">{{ row.has_api_key ? '已配置' : '未配置' }}</ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn label="状态" width="90">
        <template #default="{ row }">
          <ElTag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '启用' : '停用' }}</ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <ElButton link type="success" :loading="testingId === row.id" @click="test(row)">测试</ElButton>
          <ElButton link type="primary" @click="openEdit(row)">编辑</ElButton>
          <ElButton link type="danger" @click="remove(row)">删除</ElButton>
        </template>
      </ElTableColumn>
    </ElTable>

    <ElDialog v-model="dialogVisible" :title="editingId ? '编辑渠道' : '新增渠道'" width="640px">
      <ElForm :model="form" label-width="110px">
        <ElFormItem label="代码" required>
          <ElInput v-model="form.code" :disabled="!!editingId" placeholder="小写字母开头,如 wecom-main" />
        </ElFormItem>
        <ElFormItem label="名称" required><ElInput v-model="form.name" /></ElFormItem>
        <ElFormItem label="类型" required>
          <ElSelect v-model="form.kind" class="w-full">
            <ElOption label="通用 Webhook" value="webhook" />
            <ElOption label="企业微信" value="wecom" />
            <ElOption label="钉钉" value="dingtalk" />
            <ElOption label="飞书" value="feishu" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="绑定模型">
          <div class="flex w-full gap-2">
            <ElInput v-model="form.binding_provider" placeholder="供应商代码(留空用默认)" />
            <ElInput v-model="form.binding_model" placeholder="模型名,如 gpt-4o-mini" />
          </div>
        </ElFormItem>
        <ElFormItem label="网关 API Key">
          <ElInput v-model="form.api_key" type="password" show-password :placeholder="editingId ? '留空不更换' : '必填'" />
        </ElFormItem>
        <ElFormItem label="入站令牌">
          <ElInput v-model="form.inbound_token" placeholder="webhook/企微回调鉴权令牌" />
        </ElFormItem>
        <template v-if="form.kind === 'wecom'">
          <ElFormItem label="CorpID"><ElInput v-model="form.corp_id" /></ElFormItem>
          <ElFormItem label="Secret"><ElInput v-model="form.secret" type="password" show-password /></ElFormItem>
          <ElFormItem label="AgentID"><ElInput v-model="form.agent_id" /></ElFormItem>
        </template>
        <template v-else-if="form.kind === 'dingtalk'">
          <ElFormItem label="机器人 Token"><ElInput v-model="form.ding_robot_token" /></ElFormItem>
        </template>
        <template v-else-if="form.kind === 'feishu'">
          <ElFormItem label="App ID"><ElInput v-model="form.feishu_app_id" /></ElFormItem>
          <ElFormItem label="App Secret"><ElInput v-model="form.feishu_app_secret" type="password" show-password /></ElFormItem>
        </template>
      </ElForm>
      <template #footer>
        <ElButton @click="dialogVisible = 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 request from '@/utils/http'

  interface Channel {
    id: string
    code: string
    name: string
    kind: string
    model_binding: Record<string, any>
    has_api_key: boolean
    enabled: boolean
  }

  const kindMap: Record<string, string> = { webhook: 'Webhook', wecom: '企业微信', dingtalk: '钉钉', feishu: '飞书' }
  const kindLabel = (kind: string) => kindMap[kind] || kind
  const modelLabel = (binding: Record<string, any>) => (binding?.model ? `${binding.provider ? binding.provider + ' / ' : ''}${binding.model}` : '未绑定')

  const channels = ref<Channel[]>([])
  const loading = ref(false)
  const saving = ref(false)
  const testingId = ref('')
  const dialogVisible = ref(false)
  const editingId = ref('')
  const form = reactive({
    code: '', name: '', kind: 'webhook', binding_provider: '', binding_model: '', api_key: '',
    inbound_token: '', corp_id: '', secret: '', agent_id: '', ding_robot_token: '', feishu_app_id: '', feishu_app_secret: ''
  })

  async function load() {
    loading.value = true
    try {
      channels.value = await request.get<Channel[]>({ url: '/api/v1/admin/channels' })
    } finally {
      loading.value = false
    }
  }

  function openCreate() {
    editingId.value = ''
    Object.assign(form, { code: '', name: '', kind: 'webhook', binding_provider: '', binding_model: '', api_key: '', inbound_token: '', corp_id: '', secret: '', agent_id: '', ding_robot_token: '', feishu_app_id: '', feishu_app_secret: '' })
    dialogVisible.value = true
  }

  function openEdit(row: Channel) {
    editingId.value = row.id
    Object.assign(form, {
      code: row.code, name: row.name, kind: row.kind, api_key: '',
      binding_provider: row.model_binding?.provider || '', binding_model: row.model_binding?.model || ''
    })
    dialogVisible.value = true
  }

  async function submit() {
    if (!form.code || !form.name) {
      ElMessage.warning('请填写代码和名称')
      return
    }
    saving.value = true
    try {
      const config: Record<string, string> = {}
      if (form.inbound_token) config.inbound_token = form.inbound_token
      if (form.kind === 'wecom') {
        if (form.corp_id) config.corp_id = form.corp_id
        if (form.secret) config.secret = form.secret
        if (form.agent_id) config.agent_id = form.agent_id
      }
      if (form.kind === 'dingtalk' && form.ding_robot_token) config.ding_robot_token = form.ding_robot_token
      if (form.kind === 'feishu') {
        if (form.feishu_app_id) config.feishu_app_id = form.feishu_app_id
        if (form.feishu_app_secret) config.feishu_app_secret = form.feishu_app_secret
      }
      const payload = {
        code: form.code, name: form.name, kind: form.kind, config,
        model_binding: { provider: form.binding_provider || undefined, model: form.binding_model || undefined },
        api_key: form.api_key
      }
      if (editingId.value) {
        await request.put({ url: `/api/v1/admin/channels/${editingId.value}`, params: payload })
        ElMessage.success('渠道已更新')
      } else {
        await request.post({ url: '/api/v1/admin/channels', params: payload })
        ElMessage.success('渠道已创建')
      }
      dialogVisible.value = false
      await load()
    } finally {
      saving.value = false
    }
  }

  async function test(row: Channel) {
    testingId.value = row.id
    try {
      const result = await request.post<{ answer: string }>({ url: `/api/v1/admin/channels/${row.id}/test` })
      ElMessage.success(`模型应答: ${result.answer.slice(0, 60)}`)
    } catch { /* 全局错误提示 */ } finally {
      testingId.value = ''
    }
  }

  async function remove(row: Channel) {
    try {
      await ElMessageBox.confirm(`确认删除渠道「${row.name}」？`, '删除渠道', { type: 'warning' })
    } catch {
      return
    }
    try {
      await request.del({ url: `/api/v1/admin/channels/${row.id}` })
      ElMessage.success('已删除')
      await load()
    } catch { /* 全局错误提示 */ }
  }

  onMounted(load)
</script>
