<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>

    <ElTable v-loading="loading" :data="items" row-key="id">
      <ElTableColumn prop="name" label="名称" min-width="140" />
      <ElTableColumn prop="code" label="代码" width="150" />
      <ElTableColumn prop="model" label="绑定模型" min-width="160" />
      <ElTableColumn prop="provider_code" label="供应商" width="120" />
      <ElTableColumn prop="last_used_at" label="最近调用" width="180">
        <template #default="{ row }">{{ row.last_used_at || '—' }}</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="primary" @click="showInbound(row)">调用地址</ElButton>
          <ElButton link type="warning" @click="regenerate(row)">重置令牌</ElButton>
          <ElButton link type="danger" @click="remove(row)">删除</ElButton>
        </template>
      </ElTableColumn>
    </ElTable>

    <ElCard shadow="never" class="mb-5">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="font-medium">可使用渠道</div>
          <span class="text-g-400 text-xs">部门可见或已获授权；需要更多渠道请到「我的申请」发起申请</span>
        </div>
      </template>
      <ElTable v-loading="loading" :data="visibleChannels" row-key="code">
        <ElTableColumn prop="name" label="名称" min-width="150" />
        <ElTableColumn prop="code" label="代码" width="150" />
        <ElTableColumn label="类型" width="110">
          <template #default="{ row }">{{ kindLabel(row.kind) }}</template>
        </ElTableColumn>
        <ElTableColumn label="绑定模型" min-width="170">
          <template #default="{ row }">{{ row.model_binding?.model || '—' }}</template>
        </ElTableColumn>
        <ElTableColumn label="授权方式" width="110">
          <template #default="{ row }">
            <ElTag :type="grantedCodes.includes(row.code) ? 'success' : 'info'">{{ grantedCodes.includes(row.code) ? '已授权' : '部门可见' }}</ElTag>
          </template>
        </ElTableColumn>
      </ElTable>
      <ElEmpty v-if="!visibleChannels.length && !loading" description="暂无可用渠道" :image-size="60" />
    </ElCard>

    <ElDialog v-model="visible" title="新建 Webhook 渠道" width="560px">
      <ElForm label-width="100px">
        <ElFormItem label="名称" required><ElInput v-model="form.name" maxlength="128" placeholder="例如 报表机器人" /></ElFormItem>
        <ElFormItem label="代码" required><ElInput v-model="form.code" placeholder="例如 my_bot（小写字母开头）" /></ElFormItem>
        <ElFormItem label="绑定模型" required>
          <ElSelect v-model="selectedModel" filterable class="w-full" placeholder="选择已批准的模型">
            <ElOptionGroup v-for="group in modelGroups" :key="group.provider" :label="group.provider">
              <ElOption v-for="m in group.models" :key="m.model" :label="m.model" :value="`${m.provider_code}\n${m.model}`" />
            </ElOptionGroup>
          </ElSelect>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="visible = false">取消</ElButton>
        <ElButton type="primary" :loading="saving" @click="submit">创建</ElButton>
      </template>
    </ElDialog>

    <ElDialog v-model="inboundVisible" :title="`调用地址 · ${current?.name || ''}`" width="620px">
      <div class="space-y-3 text-sm">
        <div>
          <div class="text-g-500 mb-1">入站 URL（POST JSON：{"message":"你好"}）</div>
          <ElInput :model-value="inboundURL" readonly>
            <template #append><ElButton @click="copy(inboundURL)">复制</ElButton></template>
          </ElInput>
        </div>
        <div>
          <div class="text-g-500 mb-1">入站令牌（请求头 X-Inbound-Token 或 ?token=，只显示一次）</div>
          <ElInput :model-value="inboundToken" readonly>
            <template #append><ElButton @click="copy(inboundToken)">复制</ElButton></template>
          </ElInput>
          <p class="text-g-400 mt-1 text-xs">令牌仅创建/重置时显示；丢失请在列表中重置</p>
        </div>
        <ElAlert type="info" :closable="false" title="示例：curl -X POST https://你的域名/v1/personal-channels/CODE/inbound -H 'Content-Type: application/json' -H 'X-Inbound-Token: TOKEN' -d 「{&quot;message&quot;:&quot;你好&quot;}」" />
      </div>
    </ElDialog>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ChatModel, PersonalChannel, VisibleChannel,
  createPersonalChannel, deletePersonalChannel, fetchChatModels,
  fetchMyChannels, fetchPersonalChannels, regeneratePersonalToken
} from '@/api/portal'

const loading = ref(false)
const saving = ref(false)
const visible = ref(false)
const inboundVisible = ref(false)
const items = ref<PersonalChannel[]>([])
const visibleChannels = ref<VisibleChannel[]>([])
const grantedCodes = ref<string[]>([])
const models = ref<ChatModel[]>([])
const selectedModel = ref('')
const current = ref<PersonalChannel>()
const inboundURL = ref('')
const inboundToken = ref('')
const form = reactive({ name: '', code: '' })

const modelGroups = computed(() => {
  const groups: { provider: string; models: ChatModel[] }[] = []
  const index = new Map<string, ChatModel[]>()
  for (const m of models.value) {
    if (!index.has(m.provider_code)) index.set(m.provider_code, [])
    index.get(m.provider_code)!.push(m)
  }
  for (const [provider, list] of index) groups.push({ provider, models: list })
  return groups
})

const kindMap: Record<string, string> = { webhook: 'Webhook', wecom: '企业微信', dingtalk: '钉钉', feishu: '飞书' }
const kindLabel = (kind: string) => kindMap[kind] || kind

async function load() {
  loading.value = true
  try {
    const [personal, visible] = await Promise.all([fetchPersonalChannels(), fetchMyChannels()])
    items.value = personal
    visibleChannels.value = visible.channels || []
    grantedCodes.value = visible.granted_codes || []
  } finally {
    loading.value = false
  }
}

async function openCreate() {
  models.value = await fetchChatModels()
  if (!models.value.length) {
    ElMessage.warning('暂无已批准的模型，请先在「模型权限」申请')
    return
  }
  form.name = ''
  form.code = ''
  selectedModel.value = ''
  visible.value = true
}

async function submit() {
  if (!form.name.trim() || !form.code.trim() || !selectedModel.value) {
    ElMessage.warning('请填写名称、代码并选择模型')
    return
  }
  const [provider_code, model] = selectedModel.value.split('\n')
  saving.value = true
  try {
    const result = await createPersonalChannel({ name: form.name.trim(), code: form.code.trim(), provider_code, model })
    visible.value = false
    await load()
    current.value = result.channel
    inboundURL.value = window.location.origin + result.inbound_url
    inboundToken.value = result.inbound_token
    inboundVisible.value = true
  } catch (error) {
    ElMessage.error((error as Error)?.message || '创建失败')
  } finally {
    saving.value = false
  }
}

function showInbound(row: PersonalChannel) {
  current.value = row
  inboundURL.value = `${window.location.origin}/v1/personal-channels/${row.code}/inbound`
  inboundToken.value = ''
  inboundVisible.value = true
}

async function regenerate(row: PersonalChannel) {
  await ElMessageBox.confirm('重置后旧令牌立即失效，确定重置？', '重置入站令牌', { type: 'warning' })
  const result = await regeneratePersonalToken(row.id)
  current.value = row
  inboundURL.value = `${window.location.origin}/v1/personal-channels/${row.code}/inbound`
  inboundToken.value = result.inbound_token
  inboundVisible.value = true
  ElMessage.success('令牌已重置')
}

async function remove(row: PersonalChannel) {
  await ElMessageBox.confirm('删除后该渠道立即停止响应，确定删除？', '删除渠道', { type: 'warning' })
  await deletePersonalChannel(row.id)
  items.value = items.value.filter((item) => item.id !== row.id)
  ElMessage.success('已删除')
}

async function copy(value: string) {
  await navigator.clipboard.writeText(value)
  ElMessage.success('已复制')
}

onMounted(load)
</script>
