<template>
  <div class="page-content">
    <div class="mb-5">
      <h2 class="text-xl font-semibold">数字员工</h2>
      <p class="text-g-500 mt-1 text-sm">选择已授权数字员工直接对话；未安装的员工可在「资源市场」安装或「我的申请」申请权限</p>
    </div>

    <ElTabs v-model="activeTab" @tab-change="load">
      <ElTabPane label="员工列表" name="list" />
      <ElTabPane label="调用记录" name="runs" />
    </ElTabs>

    <div v-if="activeTab === 'list'" v-loading="loading" class="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
      <ElCard v-for="item in employees" :key="item.code" shadow="hover">
        <div class="flex items-start justify-between">
          <div>
            <b>{{ item.name }}</b>
            <ElTag v-if="item.installed" type="success" size="small" class="ml-2">已安装</ElTag>
          </div>
          <code class="text-xs">{{ item.code }}</code>
        </div>
        <p class="text-g-500 mt-2 min-h-10 text-sm">{{ item.description || '暂无描述' }}</p>
        <div class="mt-3 flex gap-2">
          <ElButton type="primary" size="small" :loading="chatting === item.code" @click="openChat(item)">开始对话</ElButton>
          <ElButton v-if="!item.installed" size="small" @click="$router.push('/portal/marketplace')">去市场安装</ElButton>
        </div>
      </ElCard>
      <ElEmpty v-if="!loading && !employees.length" description="暂无可用的数字员工" class="col-span-full" />
    </div>

    <ElTable v-else v-loading="loading" :data="runs" row-key="created_at">
      <ElTableColumn prop="employee_name" label="数字员工" min-width="160" />
      <ElTableColumn prop="employee_code" label="编码" width="140" />
      <ElTableColumn label="状态" width="100">
        <template #default="{ row }"><ElTag :type="row.status === 'success' ? 'success' : 'danger'">{{ row.status }}</ElTag></template>
      </ElTableColumn>
      <ElTableColumn prop="latency_ms" label="耗时(ms)" width="100" />
      <ElTableColumn prop="retrieval_count" label="检索" width="80" />
      <ElTableColumn prop="tool_count" label="工具" width="80" />
      <ElTableColumn prop="error" label="错误" min-width="160" show-overflow-tooltip />
      <ElTableColumn prop="created_at" label="时间" width="180" />
    </ElTable>

    <ElDialog v-model="chatVisible" :title="`对话 · ${chatTarget?.name || ''}`" width="640px">
      <div class="max-h-80 space-y-3 overflow-auto">
        <ElEmpty v-if="!chatMessages.length" description="发送第一条消息开始对话" :image-size="60" />
        <div v-for="(message, index) in chatMessages" :key="index" class="flex" :class="message.role === 'user' ? 'justify-end' : 'justify-start'">
          <div
            class="max-w-[85%] whitespace-pre-wrap break-words rounded-lg px-3 py-2 text-sm"
            :class="message.role === 'user' ? 'bg-primary-600 text-white' : 'bg-g-100 text-g-800'"
          >{{ message.content }}</div>
        </div>
      </div>
      <div class="mt-3 flex gap-2">
        <ElInput v-model="chatDraft" placeholder="输入消息" @keydown.enter.exact.prevent="sendChat" />
        <ElButton type="primary" :loading="chatting === chatTarget?.code" @click="sendChat">发送</ElButton>
      </div>
    </ElDialog>
  </div>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import {
  DigitalEmployee, EmployeeRun, fetchDigitalEmployees, fetchMyEmployeeRuns, runDigitalEmployee
} from '@/api/portal'

const activeTab = ref('list')
const loading = ref(false)
const employees = ref<DigitalEmployee[]>([])
const runs = ref<EmployeeRun[]>([])
const chatVisible = ref(false)
const chatTarget = ref<DigitalEmployee>()
const chatMessages = ref<Array<{ role: string; content: string }>>([])
const chatDraft = ref('')
const chatting = ref('')

async function load() {
  loading.value = true
  try {
    if (activeTab.value === 'list') employees.value = await fetchDigitalEmployees()
    if (activeTab.value === 'runs') runs.value = await fetchMyEmployeeRuns()
  } finally {
    loading.value = false
  }
}

function openChat(item: DigitalEmployee) {
  chatTarget.value = item
  chatMessages.value = []
  chatDraft.value = ''
  chatVisible.value = true
}

async function sendChat() {
  const text = chatDraft.value.trim()
  if (!text || !chatTarget.value || chatting.value) return
  chatting.value = chatTarget.value.code
  chatMessages.value.push({ role: 'user', content: text })
  chatDraft.value = ''
  try {
    const response = await runDigitalEmployee(chatTarget.value.code, text)
    const choices = (response.choices as Array<{ message?: { content?: string } }>) || []
    const answer = choices[0]?.message?.content || '（无文本回答）'
    chatMessages.value.push({ role: 'assistant', content: answer })
  } catch (error) {
    chatMessages.value.push({ role: 'assistant', content: (error as Error)?.message || '调用失败' })
  } finally {
    chatting.value = ''
  }
}

onMounted(load)
</script>
