<template>
  <div class="playground-page">
    <el-card shadow="never" class="control-card">
      <template #header>
        <div class="header-row">
          <span>中台联调工作台</span>
          <el-tag type="info">真人模拟 + 中台真实接口</el-tag>
        </div>
      </template>

      <el-form inline>
        <el-form-item label="Session ID">
          <el-input v-model="sessionId" style="width: 220px" />
        </el-form-item>
        <el-form-item label="User ID">
          <el-input v-model="userId" style="width: 180px" />
        </el-form-item>
        <el-form-item label="Agent 灰度">
          <el-switch v-model="agentEnabled" />
        </el-form-item>
        <el-form-item label="回滚传统链路">
          <el-switch v-model="rollbackToLegacy" />
        </el-form-item>
        <el-form-item label="会话模式">
          <el-select v-model="sessionMode" style="width: 150px">
            <el-option label="BOT_ACTIVE" value="BOT_ACTIVE" />
            <el-option label="HUMAN_ACTIVE" value="HUMAN_ACTIVE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :loading="switchingMode" @click="handleSwitchMode">应用模式</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" :loading="cancellingFlow" @click="handleCancelFlow">取消流程</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleNewSession">新建会话</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-row :gutter="16">
      <el-col :span="16">
        <el-card shadow="never" class="chat-card">
          <template #header>
            <div class="header-row">
              <span>实时对话</span>
              <el-space>
                <el-button size="small" @click="clearConversation">清空</el-button>
                <el-button size="small" type="warning" :loading="reporting" @click="handleReportMessages">上报消息</el-button>
                <el-button size="small" type="primary" @click="showShareDialog">分享对话</el-button>
              </el-space>
            </div>
          </template>

          <div class="chat-list">
            <div
              v-for="(msg, idx) in conversation"
              :key="idx"
              class="chat-item"
              :class="`role-${msg.role}`"
            >
              <div class="meta">
                <el-tag size="small" :type="tagType(msg.role)">{{ msg.role }}</el-tag>
                <span class="time">{{ msg.timestamp }}</span>
                <span v-if="msg.segment_id" class="segment">{{ msg.segment_id }}</span>
              </div>
              <div class="content">{{ msg.content }}</div>
            </div>
          </div>

          <div class="composer">
            <el-input
              v-model="userInput"
              type="textarea"
              :rows="3"
              placeholder="输入用户消息后发送，触发 /mid/dialogue/respond"
            />
            <div class="composer-actions">
              <el-button type="primary" :loading="sending" @click="handleSend">发送</el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card shadow="never" class="trace-card">
          <template #header>
            <div class="header-row">
              <span>Trace 观测</span>
            </div>
          </template>

          <div v-if="lastTrace">
            <el-descriptions :column="1" border size="small">
              <el-descriptions-item label="mode">{{ lastTrace.mode }}</el-descriptions-item>
              <el-descriptions-item label="intent">{{ lastTrace.intent || '-' }}</el-descriptions-item>
              <el-descriptions-item label="request_id">{{ lastTrace.request_id || '-' }}</el-descriptions-item>
              <el-descriptions-item label="generation_id">{{ lastTrace.generation_id || '-' }}</el-descriptions-item>
              <el-descriptions-item label="fallback_reason_code">{{ lastTrace.fallback_reason_code || '-' }}</el-descriptions-item>
              <el-descriptions-item label="react_iterations">{{ lastTrace.react_iterations ?? '-' }}</el-descriptions-item>
              <el-descriptions-item label="guardrail_triggered">{{ lastTrace.guardrail_triggered ?? '-' }}</el-descriptions-item>
            </el-descriptions>

            <div class="json-panel">
              <div class="json-title">tool_calls</div>
              <div class="json-content">
                <el-button
                  class="copy-btn"
                  size="small"
                  text
                  type="primary"
                  @click="copyJson(lastTrace.tool_calls || [], 'tool_calls')"
                >
                  复制
                </el-button>
                <pre>{{ JSON.stringify(lastTrace.tool_calls || [], null, 2) }}</pre>
              </div>
            </div>

            <div class="json-panel">
              <div class="json-title">metrics_snapshot</div>
              <div class="json-content">
                <el-button
                  class="copy-btn"
                  size="small"
                  text
                  type="primary"
                  @click="copyJson(lastTrace.metrics_snapshot || {}, 'metrics_snapshot')"
                >
                  复制
                </el-button>
                <pre>{{ JSON.stringify(lastTrace.metrics_snapshot || {}, null, 2) }}</pre>
              </div>
            </div>
          </div>
          <el-empty v-else description="暂无 Trace" :image-size="90" />
        </el-card>

        <el-card shadow="never" class="shares-card" style="margin-top: 16px">
          <template #header>
            <div class="header-row">
              <span>历史分享（旧）</span>
              <el-button size="small" text @click="loadShares">刷新</el-button>
            </div>
          </template>
          <div v-if="shares.length" class="shares-list">
            <div v-for="share in shares" :key="share.share_token" class="share-item">
              <div class="share-info">
                <span class="share-title">{{ share.title || '无标题' }}</span>
                <el-tag size="small" :type="share.is_active ? 'success' : 'info'">
                  {{ share.is_active ? '有效' : '已失效' }}
                </el-tag>
              </div>
              <div class="share-meta">
                <span>在线: {{ share.current_users }}/{{ share.max_concurrent_users }}</span>
                <span>过期: {{ formatShareExpires(share.expires_at) }}</span>
              </div>
              <div class="share-actions">
                <el-button size="small" text type="primary" @click="copyShareUrl(share.share_url)">复制链接</el-button>
                <el-button size="small" text type="danger" @click="handleDeleteShare(share.share_token)">删除</el-button>
              </div>
            </div>
          </div>
          <el-empty v-else description="暂无分享链接" :image-size="60" />
        </el-card>
      </el-col>
    </el-row>

    <el-dialog v-model="shareDialogVisible" title="分享对话（安全链接）" width="500px">
      <el-form :model="shareForm" label-width="120px">
        <el-form-item label="有效期">
          <el-select v-model="shareForm.expires_in_minutes" style="width: 100%">
            <el-option label="15 分钟" :value="15" />
            <el-option label="1 小时" :value="60" />
            <el-option label="6 小时" :value="360" />
            <el-option label="24 小时" :value="1440" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="shareDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="creatingShare" @click="handleCreateShare">创建安全分享</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="shareResultVisible" title="分享成功" width="500px">
      <el-result icon="success" title="安全分享链接已创建" :sub-title="shareResult?.share_url">
        <template #extra>
          <el-input :model-value="shareResult?.share_url" readonly>
            <template #append>
              <el-button @click="copyShareUrl(shareResult?.share_url || '')">复制</el-button>
            </template>
          </el-input>
        </template>
      </el-result>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  respondDialogue,
  switchSessionMode,
  reportMessages,
  createPublicShareToken,
  listShares,
  deleteShare,
  cancelActiveFlow,
  type DialogueMessage,
  type DialogueResponse,
  type SessionMode,
  type CreatePublicShareTokenResponse,
  type ShareListItem
} from '@/api/mid-platform'

type ChatRole = 'user' | 'assistant' | 'human' | 'system'

interface ChatItem {
  role: ChatRole
  content: string
  timestamp: string
  segment_id?: string
}

const sessionId = ref(`sess_${Date.now()}`)
const userId = ref(`user_${Date.now()}`)
const sessionMode = ref<SessionMode>('BOT_ACTIVE')
const agentEnabled = ref(true)
const rollbackToLegacy = ref(false)

const sending = ref(false)
const switchingMode = ref(false)
const reporting = ref(false)
const cancellingFlow = ref(false)

const userInput = ref('')
const conversation = ref<ChatItem[]>([])
const lastTrace = ref<DialogueResponse['trace'] | null>(null)

const shares = ref<ShareListItem[]>([])
const shareDialogVisible = ref(false)
const shareResultVisible = ref(false)
const creatingShare = ref(false)
const shareResult = ref<CreatePublicShareTokenResponse | null>(null)
const shareForm = ref({
  expires_in_minutes: 60
})

const now = () => new Date().toLocaleTimeString()

const tagType = (role: ChatRole): 'primary' | 'success' | 'info' | 'warning' | 'danger' => {
  if (role === 'user') return 'info'
  if (role === 'assistant') return 'success'
  if (role === 'human') return 'warning'
  return 'primary'
}

const toHistory = (): DialogueMessage[] => {
  return conversation.value
    .filter((m) => m.role === 'user' || m.role === 'assistant' || m.role === 'human')
    .map((m) => ({ role: m.role as 'user' | 'assistant' | 'human', content: m.content }))
}

const handleSend = async () => {
  const content = userInput.value.trim()
  if (!content) {
    ElMessage.warning('请输入用户消息')
    return
  }

  conversation.value.push({ role: 'user', content, timestamp: now() })
  userInput.value = ''

  sending.value = true
  try {
    const res = await respondDialogue({
      session_id: sessionId.value,
      user_id: userId.value,
      user_message: content,
      history: toHistory(),
      feature_flags: {
        agent_enabled: agentEnabled.value,
        rollback_to_legacy: rollbackToLegacy.value
      }
    })

    lastTrace.value = res.trace
    for (const seg of res.segments || []) {
      conversation.value.push({
        role: 'assistant',
        content: seg.text,
        segment_id: seg.segment_id,
        timestamp: now()
      })
    }

    if (!res.segments?.length) {
      ElMessage.warning('接口返回了空 segments')
    }
  } catch {
    ElMessage.error('调用中台 respond 接口失败')
  } finally {
    sending.value = false
  }
}

const handleSwitchMode = async () => {
  switchingMode.value = true
  try {
    await switchSessionMode(sessionId.value, sessionMode.value, 'playground manual switch')
    ElMessage.success(`会话模式已切换为 ${sessionMode.value}`)
  } catch {
    ElMessage.error('切换会话模式失败')
  } finally {
    switchingMode.value = false
  }
}

const handleCancelFlow = async () => {
  cancellingFlow.value = true
  try {
    const result = await cancelActiveFlow(sessionId.value)
    if (result.success) {
      ElMessage.success(result.message)
    } else {
      ElMessage.warning(result.message)
    }
  } catch {
    ElMessage.error('取消流程失败')
  } finally {
    cancellingFlow.value = false
  }
}

const handleNewSession = () => {
  const newSessionId = `sess_${Date.now()}`
  const newUserId = `user_${Date.now()}`
  sessionId.value = newSessionId
  userId.value = newUserId
  conversation.value = []
  lastTrace.value = null
  ElMessage.success(`新会话已创建: ${newSessionId}`)
}

const handleReportMessages = async () => {
  if (!conversation.value.length) {
    ElMessage.warning('暂无可上报消息')
    return
  }

  reporting.value = true
  try {
    await reportMessages({
      session_id: sessionId.value,
      messages: conversation.value.map((m) => ({
        role: m.role,
        content: m.content,
        source: m.role === 'human' ? 'human' : m.role === 'assistant' ? 'bot' : 'channel',
        timestamp: new Date().toISOString(),
        segment_id: m.segment_id
      }))
    })
    ElMessage.success('消息上报成功')
  } catch {
    ElMessage.error('消息上报失败')
  } finally {
    reporting.value = false
  }
}

const clearConversation = () => {
  conversation.value = []
  lastTrace.value = null
}

const showShareDialog = () => {
  shareForm.value = {
    expires_in_minutes: 60
  }
  shareDialogVisible.value = true
}

const handleCreateShare = async () => {
  creatingShare.value = true
  try {
    const result = await createPublicShareToken({
      session_id: sessionId.value,
      user_id: userId.value,
      expires_in_minutes: shareForm.value.expires_in_minutes
    })
    shareResult.value = result
    shareDialogVisible.value = false
    shareResultVisible.value = true
    ElMessage.success('安全分享链接创建成功')
  } catch {
    ElMessage.error('创建安全分享链接失败')
  } finally {
    creatingShare.value = false
  }
}

const loadShares = async () => {
  try {
    const result = await listShares(sessionId.value, true)
    shares.value = result.shares
  } catch {
    // ignore
  }
}

const handleDeleteShare = async (shareToken: string) => {
  try {
    await deleteShare(shareToken)
    ElMessage.success('分享链接已删除')
    await loadShares()
  } catch {
    ElMessage.error('删除分享链接失败')
  }
}

const copyShareUrl = (url: string) => {
  navigator.clipboard.writeText(url)
  ElMessage.success('链接已复制到剪贴板')
}

const copyJson = (data: unknown, name: string) => {
  const jsonStr = JSON.stringify(data, null, 2)
  navigator.clipboard.writeText(jsonStr)
  ElMessage.success(`${name} 已复制到剪贴板`)
}

const formatShareExpires = (expiresAt: string) => {
  const expires = new Date(expiresAt)
  return expires.toLocaleDateString()
}

onMounted(() => {
  loadShares()
})
</script>

<style scoped>
.playground-page {
  padding: 20px;
}

.control-card,
.chat-card,
.trace-card {
  margin-bottom: 16px;
}

.header-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chat-list {
  max-height: 520px;
  overflow: auto;
  padding: 8px;
  background: var(--el-fill-color-lighter);
  border-radius: 8px;
}

.chat-item {
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 8px;
  background: #fff;
}

.chat-item.role-user {
  border-left: 4px solid var(--el-color-info);
}

.chat-item.role-assistant {
  border-left: 4px solid var(--el-color-success);
}

.chat-item.role-human {
  border-left: 4px solid var(--el-color-warning);
}

.meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}

.time,
.segment {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.content {
  white-space: pre-wrap;
  line-height: 1.5;
}

.composer {
  margin-top: 12px;
}

.composer-actions {
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;
}

.json-panel {
  margin-top: 12px;
}

.json-title {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 4px;
}

.json-content {
  position: relative;
}

.json-content .copy-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  z-index: 10;
  background: var(--el-bg-color);
  opacity: 0.8;
}

.json-content .copy-btn:hover {
  opacity: 1;
}

pre {
  background: var(--el-fill-color-lighter);
  padding: 8px;
  border-radius: 6px;
  max-height: 220px;
  overflow: auto;
  font-size: 12px;
}

.shares-card {
  margin-bottom: 16px;
}

.shares-list {
  max-height: 200px;
  overflow-y: auto;
}

.share-item {
  padding: 8px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.share-item:last-child {
  border-bottom: none;
}

.share-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.share-title {
  font-weight: 500;
  font-size: 13px;
}

.share-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 4px;
}

.share-actions {
  display: flex;
  gap: 8px;
}
</style>
