<template>
  <div class="page-content">
    <div class="mb-5">
      <h2 class="text-xl font-semibold">AI 助手</h2>
      <p class="text-g-500 mt-1 text-sm">基于平台实时状态(供应商/模型/账号/用量/事件投递)回答管理问题</p>
    </div>
    <ElCard shadow="never" class="mb-4">
      <div class="max-h-96 space-y-3 overflow-y-auto">
        <div v-for="(item, index) in messages" :key="index" class="flex" :class="item.role === 'user' ? 'justify-end' : 'justify-start'">
          <div
            class="max-w-[80%] whitespace-pre-wrap rounded-lg px-4 py-2 text-sm"
            :class="item.role === 'user' ? 'bg-primary text-white' : 'bg-g-100 text-g-800'"
          >{{ item.content }}</div>
        </div>
        <div v-if="thinking" class="text-g-400 text-sm">助手思考中…</div>
      </div>
    </ElCard>
    <div class="flex gap-2">
      <ElInput v-model="input" placeholder="例如:平台目前有多少个供应商和 API Key?今日 Token 消耗多少?" @keyup.enter="send" />
      <ElButton type="primary" :loading="thinking" @click="send">发送</ElButton>
    </div>
    <div class="mt-3 flex flex-wrap gap-2">
      <ElTag v-for="suggestion in suggestions" :key="suggestion" class="cursor-pointer" @click="ask(suggestion)">
        {{ suggestion }}
      </ElTag>
    </div>
  </div>
</template>

<script setup lang="ts">
  import request from '@/utils/http'

  interface ChatItem {
    role: 'user' | 'assistant'
    content: string
  }

  const messages = ref<ChatItem[]>([])
  const input = ref('')
  const thinking = ref(false)
  const suggestions = ['平台概览', '今日用量与 Token 消耗', '有哪些待处理事件?', '如何新增模型供应商?']

  function ask(text: string) {
    input.value = text
    send()
  }

  async function send() {
    const message = input.value.trim()
    if (!message || thinking.value) return
    input.value = ''
    messages.value.push({ role: 'user', content: message })
    thinking.value = true
    try {
      const result = await request.post<{ answer: string }>({ url: '/api/v1/admin/assistant/chat', params: { message } })
      messages.value.push({ role: 'assistant', content: result.answer })
    } finally {
      thinking.value = false
    }
  }
</script>
