<template>
  <span
    class="custom-hover mr-8px cursor-pointer"
    title="AI助手"
    @click="dialogVisible = true"
    style="color: var(--top-header-text-color)"
  >
    <Icon icon="ep:chat-line-round" :size="20" />
  </span>
  <Dialog v-model="dialogVisible" title="AI助手">
    <div class="h-420px flex flex-col">
      <div class="flex-1 overflow-auto p-10px bg-[var(--el-fill-color-light)] rounded">
        <div v-for="(m, idx) in messages" :key="idx" class="mb-10px">
          <div v-if="m.role === 'user'" class="text-right">
            <span
              class="inline-block bg-[var(--el-color-primary-light-9)] text-[var(--el-color-primary)] px-8px py-4px rounded">{{
                m.content }}</span>
          </div>
          <div v-else class="text-left">
            <span
              class="inline-block bg-[var(--el-color-success-light-9)] text-[var(--el-color-success)] px-8px py-4px rounded">{{
                m.content }}</span>
          </div>
        </div>
      </div>
      <div class="pt-10px flex items-center gap-8px">
        <el-input v-model="input" type="textarea" :rows="2" placeholder="问我任何问题..." />
        <el-button type="primary" :loading="loading" @click="handleSend">发送</el-button>
      </div>
    </div>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { Icon } from '@/components/Icon'
import { Dialog } from '@/components/Dialog'
import { ErpAiApi } from '@/api/erp/ai'

const dialogVisible = ref(false)
const input = ref('')
const loading = ref(false)

interface MessageItem { role: 'user' | 'assistant'; content: string }
const messages = ref<MessageItem[]>([])

const handleSend = async () => {
  const content = input.value?.trim()
  if (!content) return
  messages.value.push({ role: 'user', content })
  input.value = ''
  loading.value = true
  try {
    const data = await askAI(content)
    messages.value.push({ role: 'assistant', content: data || '（无回复）' })
  } catch (e: any) {
    const errMsg = e?.message || 'AI服务暂时不可用，请稍后再试。'
    messages.value.push({ role: 'assistant', content: errMsg })
  } finally {
    loading.value = false
  }
}
</script>
