<template>
  <div class="container">
    <el-card class="main-card" :body-style="{ padding: 0 }">
      <div class="header">
        <div class="toggle-link" @click="sidebarVisible = !sidebarVisible">
          ≡ {{ sidebarVisible ? '收起配置' : '展开配置' }}
        </div>
        <h1 class="title">智能客服</h1>
        <div class="logout-btn" @click="handleLogout">退出登录</div>
      </div>

      <div class="content-wrapper">
        <div class="main-content">
          <aside v-if="sidebarVisible" class="sidebar" :class="{ disabled: showChat }">
            <div class="collapse-section">
              <div class="collapse-header" @click="basicExpanded = !basicExpanded">
                <span>基础设置</span>
                <el-icon class="arrow">
                  <ArrowUp v-if="basicExpanded" />
                  <ArrowDown v-else />
                </el-icon>
              </div>
              <div v-if="basicExpanded" class="collapse-content">
                <el-form label-position="top" size="default">
                  <el-form-item label="背景音">
                    <el-radio-group v-model="config.bgSoundEnabled">
                      <el-radio-button :value="true">开启</el-radio-button>
                      <el-radio-button :value="false">关闭</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
              </div>
            </div>

            <div class="collapse-section">
              <div class="collapse-header" @click="otherExpanded = !otherExpanded">
                <span>其他设置</span>
                <el-icon class="arrow">
                  <ArrowUp v-if="otherExpanded" />
                  <ArrowDown v-else />
                </el-icon>
              </div>
              <div v-if="otherExpanded" class="collapse-content">
                <el-form label-position="top" size="default">
                  <el-form-item label="语速" class="compact-slider">
                    <div class="slider-value">{{ config.speed }}</div>
                    <el-slider
                      v-model="config.speed"
                      :min="0"
                      :max="100"
                      :step="1"
                    />
                    <div class="slider-labels">
                      <span>慢</span>
                      <span>快</span>
                    </div>
                  </el-form-item>

                  <el-form-item label="音调" class="compact-slider">
                    <div class="slider-value">{{ config.pitch }}</div>
                    <el-slider
                      v-model="config.pitch"
                      :min="0"
                      :max="100"
                      :step="1"
                    />
                    <div class="slider-labels">
                      <span>低</span>
                      <span>高</span>
                    </div>
                  </el-form-item>

                  <el-form-item label="音量" class="compact-slider">
                    <div class="slider-value">{{ config.volume }}</div>
                    <el-slider
                      v-model="config.volume"
                      :min="0"
                      :max="100"
                      :step="1"
                    />
                    <div class="slider-labels">
                      <span>小</span>
                      <span>大</span>
                    </div>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </aside>

          <main class="right-panel" v-if="!showChat" @wheel="handleWheel">
            <div class="agents-container">
              <div class="agents-list">
                <div
                  v-for="agent in paginatedAgents"
                  :key="agent.id"
                  class="agent-card"
                  :class="{
                    selected: selectedAgent === agent.id,
                    disabled: agent.status === '2'
                  }"
                  @click="agent.status === '0' ? selectedAgent = agent.id : null"
                >
                  <img v-if="agent.avatarUrl" :src="getAvatarUrl(agent.avatarUrl)" class="avatar-img" />
                  <div v-else class="avatar" :class="agent.gender"></div>
                  <div class="gender-icon" :class="agent.gender">{{ agent.gender === 'female' ? '♀' : '♂' }}</div>
                  <div class="status-badge" :class="'status-' + agent.status">
                    {{ agent.status === '0' ? '空闲中' : agent.status === '1' ? '停用' : '工作中' }}
                  </div>
                  <div class="agent-name">{{ agent.name }}</div>
                </div>
              </div>
            </div>
            <div class="agents-footer">
              <div class="footer-input">
                <el-input
                  v-model="customerPhone"
                  placeholder="请输入客户电话号码(可选)"
                  class="customer-phone-input"
                  clearable
                />
              </div>
              <div class="footer-actions">
                <el-button type="primary" round size="large" class="start-btn" @click="startChat">
                  开始对话
                </el-button>
              </div>
            </div>
          </main>

          <main class="right-panel chat-panel" v-else>
            <!-- 对话历史 -->
            <div class="chat-content" ref="chatContent">
              <div
                v-for="(msg, index) in chatHistory"
                :key="index"
                class="message"
                :class="msg.type === 'user' ? 'user-message' : 'ai-message'"
              >
                <div class="message-text">
                  {{ msg.content }}
                </div>
              </div>
            </div>

            <div class="chat-footer">
              <el-button class="keyboard-btn" @click="isTextInput = !isTextInput">
                <el-icon><ChatDotRound v-if="!isTextInput" /><Microphone v-else /></el-icon>
              </el-button>

              <el-input
                v-if="isTextInput"
                v-model="textMessage"
                placeholder="输入消息..."
                class="text-input"
                @keyup.enter="sendTextMessage"
              >
                <template #append>
                  <el-button @click="sendTextMessage" :disabled="!textMessage.trim()">
                    发送
                  </el-button>
                </template>
              </el-input>
              <div v-else class="voice-input-btn" @click="toggleMic">
                <el-icon class="mic-icon" :class="{ muted: isMicMuted, recording: isRecording }">
                  <Microphone v-if="!isMicMuted" />
                  <Mute v-else />
                </el-icon>
                <!-- 波形显示 -->
                <div v-if="isRecording" class="waveform">
                  <div
                    class="wave-bar"
                    v-for="(height, index) in waveformData"
                    :key="index"
                    :style="{ height: height + 'px' }"
                  ></div>
                </div>
                <div v-else class="input-placeholder"></div>
              </div>

              <el-button class="hangup-btn" @click="showChat = false">
                <el-icon><PhoneFilled /></el-icon>
              </el-button>
            </div>
          </main>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { ArrowUp, ArrowDown, Microphone, PhoneFilled, ChatDotRound, Mute } from '@element-plus/icons-vue'
import { useVoiceRecognition } from './composables/useVoiceRecognition.js'
import { useStreamChat } from './composables/useStreamChat.js'
import { ElMessage } from 'element-plus'
import { API_ENDPOINTS } from './config/api.js'

// 获取请求头（包含token）
const getHeaders = () => {
  const token = localStorage.getItem('talk_token')
  return {
    'Content-Type': 'application/json',
    'Authorization': token ? `Bearer ${token}` : '',
    'clientid': '812b745b34558590c92e6f13fe8b716b'
  }
}

const showChat = ref(false)
const isTextInput = ref(false)
const isMicMuted = ref(false)
const sidebarVisible = ref(true)
const basicExpanded = ref(true)
const otherExpanded = ref(false)
const currentPage = ref(0)
const chatContent = ref(null)
const customerPhone = ref('')

// 语音识别
const { isRecording, currentTranscription, tempTranscription, startRecording, stopRecording } = useVoiceRecognition()

// 流式聊天
const { displayText, conversationId: streamConversationId, sendMessage: sendStreamMessage, stopAudio: stopStreamAudio, resetConversation } = useStreamChat()

// 当前播放的音频对象
const currentAudio = ref(null)

// 当前请求的序列号，用于标识最新的请求
const currentRequestId = ref(0)

// 停止当前的音频播放和输出
const stopCurrentOutput = () => {
  // 停止流式音频播放
  stopStreamAudio()
  // 停止本地音频播放
  if (currentAudio.value) {
    currentAudio.value.pause()
    currentAudio.value.currentTime = 0
    currentAudio.value = null
  }
}

// 停止音频播放
const stopAudio = () => {
  if (currentAudio.value) {
    currentAudio.value.pause()
    currentAudio.value.currentTime = 0
    currentAudio.value = null
  }
}

// 音频播放
const playAudio = (base64Audio) => {
  // 如果不在对话状态，不播放音频
  if (!showChat.value) {
    return
  }

  try {
    if (!base64Audio) {
      ElMessage.error('音频数据为空')
      return
    }

    const audioData = atob(base64Audio)
    const arrayBuffer = new ArrayBuffer(audioData.length)
    const view = new Uint8Array(arrayBuffer)
    for (let i = 0; i < audioData.length; i++) {
      view[i] = audioData.charCodeAt(i)
    }
    const blob = new Blob([arrayBuffer], { type: 'audio/mpeg' })
    const audioUrl = URL.createObjectURL(blob)
    const audio = new Audio(audioUrl)

    // 停止之前的音频
    stopAudio()

    // 保存当前音频引用
    currentAudio.value = audio

    audio.onended = () => {
      URL.revokeObjectURL(audioUrl)
      if (currentAudio.value === audio) {
        currentAudio.value = null
      }
    }

    audio.onerror = (e) => {
      console.error('音频播放错误:', e)
      ElMessage.error('音频播放失败')
      URL.revokeObjectURL(audioUrl)
      if (currentAudio.value === audio) {
        currentAudio.value = null
      }
    }

    audio.play().catch(err => {
      console.error('播放失败:', err)
      ElMessage.error('音频播放失败: ' + err.message)
    })
  } catch (error) {
    console.error('播放音频失败:', error)
    ElMessage.error('音频处理失败: ' + error.message)
  }
}

// 对话历史
const chatHistory = ref([])

// 保存当前对话的 conversationId
const currentConversationId = ref(null)

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContent.value) {
      chatContent.value.scrollTop = chatContent.value.scrollHeight
    }
  })
}

// 波形数据
const waveformData = ref(Array(60).fill(20))
let waveformInterval = null

// 客服列表刷新定时器
let agentRefreshInterval = null

// 更新波形
const updateWaveform = () => {
  waveformData.value = waveformData.value.map(() => {
    return Math.random() * 24 + 8
  })
}

// 监听转写结果变化，当有确定性结果时添加到对话历史
watch(currentTranscription, async (newVal, oldVal) => {
  // 只有在录音状态下才处理语音识别结果
  if (!isRecording.value || isMicMuted.value) {
    return
  }

  if (newVal && newVal !== oldVal && newVal.length > oldVal.length) {
    const newContent = newVal.slice(oldVal.length).trim()
    if (newContent) {
      // 添加用户消息
      chatHistory.value.push({
        type: 'user',
        content: newContent
      })
      scrollToBottom()

      // 发送到后端处理（使用流式接口）
      try {
        // 停止当前的音频播放
        stopCurrentOutput()

        const selectedAgentData = agents.value.find(a => a.id === selectedAgent.value)

        // 使用流式接口发送消息
        await sendStreamMessage(
          newContent,
          selectedAgent.value,
          selectedAgentData?.gender === 'male' ? '0' : '1',
          ttsVcnList.value,
          false
        )
      } catch (error) {
        console.error('发送消息失败:', error)
        ElMessage.error('发送消息失败')
      }
    }
  }
})

// 监听流式文本变化，实时更新聊天历史
watch(displayText, (newText) => {
  if (newText && showChat.value) {
    const lastMessage = chatHistory.value[chatHistory.value.length - 1]
    if (lastMessage && lastMessage.type === 'agent' && !lastMessage.isGreeting) {
      lastMessage.content = newText
    } else {
      chatHistory.value.push({
        type: 'agent',
        content: newText,
        isGreeting: false
      })
    }
    scrollToBottom()
  }
})

// 同步conversationId
watch(streamConversationId, (newId) => {
  if (newId) {
    currentConversationId.value = newId
  }
})

// 监听 showChat 变化,开始对话时自动启动语音识别
watch(showChat, async (newVal) => {
  if (newVal && !isRecording.value) {
    // 尝试启动语音识别，最多重试 3 次
    let retryCount = 0
    const maxRetries = 3

    const tryStartRecording = async () => {
      try {
        await startRecording()
        ElMessage.success('语音识别已启动')

        // 启动波形动画
        waveformInterval = setInterval(updateWaveform, 100)
        return true
      } catch (error) {
        retryCount++
        console.error(`语音识别启动失败 (尝试 ${retryCount}/${maxRetries}):`, error)

        if (retryCount < maxRetries) {
          ElMessage.warning(`语音识别启动失败，正在重试 (${retryCount}/${maxRetries})...`)
          // 等待 1 秒后重试
          await new Promise(resolve => setTimeout(resolve, 1000))
          return tryStartRecording()
        } else {
          ElMessage.error('语音识别启动失败，已切换到文字输入模式')
          // 多次重试都失败，切换到文字输入模式
          isTextInput.value = true
          return false
        }
      }
    }

    await tryStartRecording()
  } else if (!newVal) {
    // 对话结束时，无论什么状态都执行清理操作
    if (isRecording.value) {
      stopRecording()
    }

    // 停止音频播放
    stopStreamAudio()
    if (currentAudio.value) {
      currentAudio.value.pause()
      currentAudio.value.currentTime = 0
      currentAudio.value = null
    }

    // 清理波形动画
    if (waveformInterval) {
      clearInterval(waveformInterval)
      waveformInterval = null
    }

    // 对话结束，将客服状态改回空闲中
    if (selectedAgent.value && currentConversationId.value) {
      try {
        const sessionId = currentConversationId.value
        await fetch(API_ENDPOINTS.agentHangup(selectedAgent.value), {
          method: 'POST',
          headers: getHeaders(),
          body: JSON.stringify({
            sessionId: sessionId,
            chatHistory: chatHistory.value
          })
        })
        console.log('客服状态已恢复为空闲中，会话ID:', sessionId)

        // 立即刷新客服列表，让用户看到状态变化
        await fetchAgents(true)
      } catch (error) {
        console.error('更新客服状态失败:', error)
      }
    }

    // 清空 conversationId，确保下次开始对话时是新的会话
    currentConversationId.value = null
    resetConversation()

    // 重置输入模式为语音输入
    isTextInput.value = false
    // 重置麦克风静音状态
    isMicMuted.value = false
  }
})

// 监听输入方式切换
watch(isTextInput, async (newVal) => {
  if (newVal && isRecording.value) {
    // 切换到文本输入时停止语音识别
    stopRecording()
    isMicMuted.value = true
    if (waveformInterval) {
      clearInterval(waveformInterval)
      waveformInterval = null
    }
  } else if (!newVal && !isRecording.value && showChat.value) {
    // 切换回语音模式时重新启动语音识别
    try {
      await startRecording()
      isMicMuted.value = false
      waveformInterval = setInterval(updateWaveform, 100)
    } catch (error) {
      ElMessage.error('启动语音识别失败: ' + error.message)
    }
  }
})

// 切换麦克风静音状态
const toggleMic = () => {
  if (isRecording.value) {
    // 当前正在录音，点击后停止并静音
    isMicMuted.value = true
    stopRecording()
    if (waveformInterval) {
      clearInterval(waveformInterval)
      waveformInterval = null
    }
    // 清空未完成的转写内容
    currentTranscription.value = ''
    tempTranscription.value = ''
  } else {
    // 当前未录音，点击后开始录音
    startRecording().then(() => {
      isMicMuted.value = false
      waveformInterval = setInterval(updateWaveform, 100)
    }).catch(err => {
      ElMessage.error('启动录音失败: ' + err.message)
    })
  }
}

// 文本输入
const textMessage = ref('')

// 发送文本消息
const sendTextMessage = async () => {
  const content = textMessage.value.trim()
  if (!content) return

  // 添加用户消息
  chatHistory.value.push({
    type: 'user',
    content: content
  })
  scrollToBottom()

  // 清空输入框
  textMessage.value = ''

  // 发送到后端处理（使用流式接口）
  try {
    // 停止当前的音频播放
    stopCurrentOutput()

    const selectedAgentData = agents.value.find(a => a.id === selectedAgent.value)

    // 使用流式接口发送消息
    await sendStreamMessage(
      content,
      selectedAgent.value,
      selectedAgentData?.gender === 'male' ? '0' : '1',
      ttsVcnList.value,
      false,
      customerPhone.value,
      'zoomphone'  // source 固定为 zoomphone
    )
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  }
}

const agents = ref([])
const ttsVcnList = ref([])

const config = ref({
  bgSoundEnabled: false,
  speed: 50,
  pitch: 50,
  volume: 50
})

const selectedAgent = ref(null)

// 获取发言人字典列表
const fetchTtsVcnList = async () => {
  try {
    const response = await fetch(API_ENDPOINTS.ttsVcn, {
      headers: getHeaders()
    })
    const data = await response.json()

    // 检查响应是否成功
    if (response.ok && Array.isArray(data)) {
      ttsVcnList.value = data
    } else if (data && data.code === 200 && Array.isArray(data.data)) {
      ttsVcnList.value = data.data
    } else {
      console.error('获取发言人字典失败:', data)
      ttsVcnList.value = []
    }
  } catch (error) {
    console.error('获取发言人字典失败:', error)
    ttsVcnList.value = []
  }
}

// 获取客服列表
const fetchAgents = async (silent = false) => {
  try {
    const response = await fetch(API_ENDPOINTS.agentMy, {
      headers: getHeaders()
    })
    const result = await response.json()

    // 检查token是否过期
    if (result.code === 401) {
      console.error('Token已过期,请重新登录')
      localStorage.removeItem('talk_token')
      localStorage.removeItem('talk_user')
      window.location.reload()
      return
    }

    if (result.code === 200 && result.data) {
      const agent = result.data
      // 只显示状态为0（空闲中）或2（工作中）的客服
      if (agent.status === '0' || agent.status === '2') {
        agents.value = [{
          id: agent.id,
          name: agent.name,
          gender: agent.gender === '0' ? 'male' : 'female',
          avatarUrl: agent.avatarUrl,
          greetingMessage: agent.greetingMessage,
          ttsVcn: agent.ttsVcn,
          ttsSpeed: agent.ttsSpeed,
          ttsPitch: agent.ttsPitch,
          ttsVolume: agent.ttsVolume,
          ttsBgs: agent.ttsBgs,
          status: agent.status
        }]
        selectedAgent.value = agent.id
        console.log('自动匹配到当前用户的客服:', agent.name)
      } else {
        agents.value = []
        selectedAgent.value = null
        if (!silent) {
          ElMessage.warning('您的客服当前不可用')
        }
      }
    } else {
      agents.value = []
      selectedAgent.value = null
      if (!silent) {
        ElMessage.warning('未找到对应的客服')
      }
    }
  } catch (error) {
    console.error('获取客服失败:', error)
    if (!silent) {
      ElMessage.error('获取客服失败')
    }
  }
}

// 启动客服列表定期刷新
const startAgentRefresh = () => {
  if (!agentRefreshInterval) {
    agentRefreshInterval = setInterval(() => {
      fetchAgents(true)
    }, 5000)
  }
}

// 停止客服列表定期刷新
const stopAgentRefresh = () => {
  if (agentRefreshInterval) {
    clearInterval(agentRefreshInterval)
    agentRefreshInterval = null
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    // 调用后端退出登录接口
    await fetch(API_ENDPOINTS.logout, {
      method: 'POST',
      headers: getHeaders()
    })
  } catch (error) {
    console.error('退出登录失败:', error)
  } finally {
    // 清除本地存储
    localStorage.removeItem('talk_token')
    localStorage.removeItem('talk_user')
    // 刷新页面返回登录页
    window.location.reload()
  }
}

// 组件挂载时获取客服列表和发言人字典
onMounted(async () => {
  await fetchAgents()
  await fetchTtsVcnList()

  // 启动客服列表定期刷新
  startAgentRefresh()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopAgentRefresh()
  if (waveformInterval) {
    clearInterval(waveformInterval)
  }
})

// 获取头像完整URL
const getAvatarUrl = (avatarUrl) => {
  if (!avatarUrl) return ''
  if (avatarUrl.startsWith('http://') || avatarUrl.startsWith('https://')) {
    return avatarUrl
  }
  return API_ENDPOINTS.avatar(avatarUrl)
}

// 开始对话
const startChat = async () => {
  if (!selectedAgent.value) {
    ElMessage.warning('请先选择一个客服')
    return
  }

  // 检查选中的客服是否可用
  const selectedAgentData = agents.value.find(a => a.id === selectedAgent.value)
  if (!selectedAgentData) {
    ElMessage.error('所选客服不存在')
    return
  }

  if (selectedAgentData.status === '2') {
    ElMessage.warning('该客服正在工作中，请选择其他客服')
    return
  }

  // 清空 conversationId，确保每次开始对话时都是新的会话
  currentConversationId.value = null
  resetConversation()

  try {
    // 调用对话前端的开始对话接口（带并发控制）
    const response = await fetch(API_ENDPOINTS.agentStart(selectedAgent.value), {
      method: 'POST',
      headers: getHeaders(),
      body: JSON.stringify({
        customerPhone: customerPhone.value
      })
    })

    const result = await response.json()

    // 检查token是否过期
    if (result.code === 401) {
      console.error('Token已过期,请重新登录')
      localStorage.removeItem('talk_token')
      localStorage.removeItem('talk_user')
      window.location.reload()
      return
    }

    // 检查后端返回结果，判断是否成功占用客服
    if (!result.success || result.code !== 200) {
      ElMessage.error(result.msg || '该客服已被其他用户占用，请选择其他客服')
      // 刷新客服列表
      await fetchAgents(true)
      return
    }

    // 保存后端返回的 sessionId
    if (result.sessionId) {
      currentConversationId.value = result.sessionId
      // 同步到 useStreamChat 中的 conversationId
      streamConversationId.value = result.sessionId
      console.log('保存临时 sessionId:', result.sessionId)
    }

    // 更新客服的TTS配置
    await fetch(API_ENDPOINTS.agentUpdate(selectedAgent.value), {
      method: 'PUT',
      headers: getHeaders(),
      body: JSON.stringify({
        ttsSpeed: config.value.speed,
        ttsPitch: config.value.pitch,
        ttsVolume: config.value.volume,
        ttsBgs: config.value.bgSoundEnabled ? 1 : 0
      })
    })

    console.log('客服状态已更新为工作中')

    // 先切换到对话界面，确保音频可以播放
    showChat.value = true

    // 显示欢迎语并转语音
    if (selectedAgentData.greetingMessage) {
      chatHistory.value = [{
        type: 'agent',
        content: selectedAgentData.greetingMessage,
        isGreeting: true
      }]

      // 使用流式接口生成欢迎语语音
      try {
        await sendStreamMessage(
          selectedAgentData.greetingMessage,
          selectedAgent.value,
          null,
          [],
          true
        )
      } catch (error) {
        console.error('生成欢迎语语音失败:', error)
      }
    } else {
      chatHistory.value = []
    }
  } catch (error) {
    console.error('更新客服配置失败:', error)
    ElMessage.error('开始对话失败，请重试')
    return
  }
}

const pageSize = 6
const totalPages = computed(() => Math.ceil(agents.value.length / pageSize))
const paginatedAgents = computed(() => {
  const start = currentPage.value * pageSize
  return agents.value.slice(start, start + pageSize)
})

const handleWheel = (e) => {
  e.preventDefault()
  // 支持垂直滚动（上下）和水平滚动（左右）
  const delta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY

  if (delta > 0 && currentPage.value < totalPages.value - 1) {
    currentPage.value++
  } else if (delta < 0 && currentPage.value > 0) {
    currentPage.value--
  }
}
</script>

<style scoped>
:global(html),
:global(body) {
  height: 100%;
  overflow: hidden;
  margin: 0;
}

:global(#app) {
  height: 100%;
  overflow: hidden;
}

.container {
  min-height: 100vh;
  height: 100vh;
  background: linear-gradient(to bottom, #bfdbfe, #dbeafe, #e0f2fe);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 16px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', sans-serif;
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
}

.container::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -20%;
  width: 80%;
  height: 100%;
  background: linear-gradient(135deg, rgba(147, 197, 253, 0.3) 0%, rgba(191, 219, 254, 0.2) 100%);
  transform: rotate(-15deg);
  border-radius: 30% 70% 70% 30% / 30% 30% 70% 70%;
  box-shadow: 0 8px 32px rgba(59, 130, 246, 0.15);
  z-index: -1;
}

.container::after {
  content: '';
  position: absolute;
  bottom: -30%;
  left: -10%;
  width: 60%;
  height: 80%;
  background: linear-gradient(225deg, rgba(191, 219, 254, 0.25) 0%, rgba(224, 242, 254, 0.15) 100%);
  transform: rotate(25deg);
  border-radius: 70% 30% 30% 70% / 70% 70% 30% 30%;
  box-shadow: 0 8px 32px rgba(96, 165, 250, 0.12);
  z-index: -1;
}

.main-card {
  width: 100%;
  max-width: 1200px;
  border-radius: 24px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1) !important;
  height: calc(100vh - 117px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
}

:deep(.main-card .el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.header {
  padding: 16px 20px;
  text-align: center;
  border-bottom: 1px solid #e5e7eb;
  background: white;
  border-radius: 24px 24px 0 0;
  position: relative;
}

.toggle-link {
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
  color: #9ca3af;
  font-size: 14px;
  cursor: pointer;
  user-select: none;
  transition: color 0.2s;
}

.toggle-link:hover {
  color: #6b7280;
}

.title {
  font-size: 20px;
  font-weight: 500;
  color: #1f2937;
  margin: 0;
}

.logout-btn {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  padding: 6px 16px;
  background: white;
  color: #ef4444;
  border: 1px solid #ef4444;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  user-select: none;
  transition: all 0.2s;
}

.logout-btn:hover {
  background: #ef4444;
  color: white;
}

.content-wrapper {
  position: relative;
  background: white;
  border-radius: 0 0 24px 24px;
  flex: 1;
  display: flex;
  min-height: 0;
  overflow: hidden;
}

.toggle-btn {
  position: absolute;
  top: 16px;
  left: 16px;
  z-index: 10;
}

.main-content {
  display: flex;
  gap: 8px;
  padding: 0 12px 0 12px;
  flex: 1;
  height: auto;
  min-height: 0;
  max-height: none;
  align-items: stretch;
  overflow: hidden;
}

.sidebar {
  width: 320px;
  flex-shrink: 0;
  padding: 20px;
  background: #ffffff;
  border-radius: 8px;
  height: 100%;
  overflow-y: auto;
  min-height: 0;
  max-height: 100%;
  box-sizing: border-box;
}

.sidebar.disabled :deep(.el-form) {
  opacity: 0.5;
  pointer-events: none;
}

.right-panel {
  flex: 1 1 0;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  justify-content: flex-start;
  padding: 20px;
  background: #f9fafb;
  border-radius: 8px;
  height: 100%;
  overflow: hidden;
  min-width: 0;
  position: relative;
}

.time-info {
  align-self: flex-end;
  color: #9ca3af;
  margin-bottom: 40px;
  font-size: 13px;
}

.agents-container {
  flex: 0 0 auto;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 72px 40px 28px;
  overflow: visible;
  min-height: 0;
  position: relative;
}

.agents-container .pagination-dots {
  position: absolute;
  top: calc(36px + 220px + 16px + 220px + 24px);
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
}

.agents-footer {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 520px;
  margin-left: auto;
  margin-right: auto;
  gap: 14px;
  flex-shrink: 0;
  margin-top: 0;
}

.footer-input {
  width: 100%;
  padding: 0;
  background: transparent;
  border: none;
  border-radius: 0;
  box-shadow: none;
}

.footer-actions {
  width: 100%;
  display: flex;
  justify-content: center;
}

.agents-list {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  max-width: 100%;
  padding: 0 20px;
  margin-bottom: 28px;
}

.agent-card {
  width: 280px;
  height: 280px;
  padding: 20px;
  border: 2px solid #e5e7eb;
  border-radius: 16px;
  text-align: center;
  cursor: pointer;
  position: relative;
  transition: all 0.3s ease;
  background: white;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.agent-card:hover {
  border-color: #3b82f6;
  transform: translateY(-4px);
  box-shadow: 0 8px 20px rgba(59, 130, 246, 0.15);
}

.agent-card.selected {
  border-color: #3b82f6;
  background: #eff6ff;
  box-shadow: 0 0 0 1px #3b82f6, 0 8px 20px rgba(59, 130, 246, 0.2);
}

.agent-card.disabled {
  opacity: 0.5;
  cursor: not-allowed;
  pointer-events: none;
}

.agent-card.disabled:hover {
  transform: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.delete-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: rgba(239, 68, 68, 0.9);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
  z-index: 10;
}

.agent-card:hover .delete-btn {
  opacity: 1;
}

.delete-btn:hover {
  background: rgba(220, 38, 38, 1);
}

.agent-card:hover {
  border-color: #3b82f6;
  transform: translateY(-4px);
  box-shadow: 0 12px 32px rgba(59, 130, 246, 0.25);
}

.agent-card.selected {
  border-color: #3b82f6;
  background: #eff6ff;
  box-shadow: 0 0 0 1px #3b82f6, 0 8px 24px rgba(59, 130, 246, 0.2);
}

.add-card {
  border: 2px dashed #d1d5db;
  background: transparent;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 120px;
}

.add-card:hover {
  border-color: #3b82f6;
  background: #f9fafb;
  transform: translateY(-4px);
}

.add-icon {
  font-size: 36px;
  color: #9ca3af;
  margin-bottom: 8px;
}

.add-card:hover .add-icon {
  color: #3b82f6;
}

.add-text {
  font-size: 14px;
  color: #6b7280;
  font-weight: 500;
}

.add-card:hover .add-text {
  color: #3b82f6;
}

.avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  margin: 20px auto 16px;
  border: 3px solid #e5e7eb;
}

.avatar-img {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  margin: 20px auto 16px;
  object-fit: cover;
  border: 3px solid #e5e7eb;
  background: #f9fafb;
}

.avatar.female {
  background: linear-gradient(135deg, #fce7f3, #fbcfe8);
}

.avatar.male {
  background: linear-gradient(135deg, #dbeafe, #bfdbfe);
}

.gender-icon {
  position: absolute;
  top: 110px;
  right: calc(50% - 70px);
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 700;
  font-size: 14px;
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.gender-icon.female {
  background: #ec4899;
}

.gender-icon.male {
  background: #3b82f6;
}

.status-badge {
  position: absolute;
  top: 8px;
  left: 8px;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 11px;
  font-weight: 600;
  z-index: 1;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.status-badge.status-0 {
  background: #10b981;
  color: white;
}

.status-badge.status-1 {
  background: #9ca3af;
  color: white;
}

.status-badge.status-2 {
  background: #ef4444;
  color: white;
}

.agent-name {
  font-size: 18px;
  color: #1f2937;
  font-weight: 600;
  margin-top: 8px;
}

.start-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 600;
  padding: 0 18px;
  align-self: center;
  border: none;
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  box-shadow: 0 10px 18px rgba(37, 99, 235, 0.25);
  transition: transform 0.15s ease, box-shadow 0.15s ease, filter 0.15s ease;
}

.start-btn:hover {
  filter: brightness(1.02);
  transform: translateY(-1px);
  box-shadow: 0 14px 24px rgba(37, 99, 235, 0.32);
}

.start-btn:active {
  transform: translateY(0);
  box-shadow: 0 10px 18px rgba(37, 99, 235, 0.25);
}

.customer-phone-input {
  width: 100%;
  max-width: 100%;
}

.customer-phone-input :deep(.el-input__wrapper) {
  height: 44px;
  border-radius: 9999px;
  padding: 0 16px;
  border: 1px solid rgba(229, 231, 235, 1);
  background: rgba(255, 255, 255, 0.98);
  box-shadow: 0 6px 16px rgba(15, 23, 42, 0.06);
  transition: box-shadow 0.15s ease, border-color 0.15s ease;
}

.customer-phone-input :deep(.el-input__inner) {
  font-size: 14px;
}

.customer-phone-input :deep(.el-input__wrapper.is-focus) {
  border-color: rgba(59, 130, 246, 0.9);
  box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.16), 0 10px 20px rgba(37, 99, 235, 0.10);
}

.pagination-dots {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
  padding: 0;
  flex-shrink: 0;
}

.pagination-dots .dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #d1d5db;
  cursor: pointer;
  transition: all 0.3s;
}

.pagination-dots .dot:hover {
  background: #9ca3af;
}

.pagination-dots .dot.active {
  width: 24px;
  border-radius: 4px;
  background: #3b82f6;
}

.slider-value {
  font-size: 14px;
  color: #1f2937;
  margin-bottom: 8px;
  font-weight: 500;
}

.slider-labels {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #9ca3af;
  margin-top: 2px;
  width: 100%;
}

/* 紧凑型滑块样式 */
.compact-slider {
  margin-bottom: 12px;
}

.compact-slider :deep(.el-form-item__label) {
  margin-bottom: 0px;
  padding-bottom: 0;
}

.compact-slider .slider-value {
  margin-bottom: 0px;
}

.compact-slider :deep(.el-form-item__content) {
  width: 100%;
}

/* 自定义折叠组件样式 */
.collapse-section {
  margin-bottom: 0;
}

.collapse-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 16px 0;
  cursor: pointer;
  user-select: none;
  font-weight: 600;
  font-size: 15px;
  color: #1f2937;
}

.collapse-header:hover {
  color: #3b82f6;
}

.collapse-header .arrow {
  font-size: 14px;
  color: #6b7280;
  margin-left: 8px;
}

.collapse-content {
  padding-bottom: 16px;
}

/* Element Plus 样式覆盖 */
:deep(.el-collapse) {
  border: none;
}

:deep(.el-collapse-item) {
  margin-bottom: 0;
}

:deep(.el-collapse-item__header) {
  font-weight: 600;
  font-size: 15px;
  color: #1f2937;
  border: none;
  padding: 16px 0;
  height: auto;
  line-height: 1.5;
  background: transparent;
  justify-content: flex-start;
}

:deep(.el-collapse-item__arrow) {
  font-size: 14px;
  color: #6b7280;
  margin-left: 8px;
  margin-right: 0;
}

:deep(.el-collapse-item__arrow.is-active) {
  transform: rotate(180deg);
}

:deep(.el-collapse-item__wrap) {
  border: none;
  background: transparent;
}

:deep(.el-collapse-item__content) {
  padding: 0 0 16px 0;
  color: inherit;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  color: #9ca3af;
  font-size: 13px;
  margin-bottom: 8px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-radio-group) {
  width: 100%;
  display: flex;
}

:deep(.el-radio-button) {
  flex: 1;
}

:deep(.el-radio-button__inner) {
  width: 100%;
  border-radius: 6px;
}

:deep(.el-slider__runway) {
  height: 4px;
  background-color: #e5e7eb;
}

:deep(.el-slider__bar) {
  background-color: #3b82f6;
}

:deep(.el-slider__button) {
  width: 16px;
  height: 16px;
  border: 2px solid #3b82f6;
}

:deep(.el-button--primary) {
  background-color: #3b82f6;
  border-color: #3b82f6;
}

:deep(.el-button--primary:hover) {
  background-color: #2563eb;
  border-color: #2563eb;
}

/* 对话界面样式 */
.chat-panel {
  display: flex;
  flex-direction: column;
  padding: 0;
  height: 100%;
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message {
  display: flex;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.ai-message {
  justify-content: flex-start;
}

.ai-message .message-text {
  background: white;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  max-width: 70%;
}

.user-message {
  justify-content: flex-end;
}

.user-message .message-text {
  background: #3b82f6;
  color: white;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
  max-width: 70%;
}

.quick-questions {
  margin-top: 12px;
}

.question-item {
  padding: 8px 0;
  font-size: 14px;
  color: #333;
}

.pause-icon {
  position: absolute;
  right: 12px;
  bottom: 12px;
  color: #3b82f6;
}

.chat-footer {
  padding: 20px 16px;
  background: white;
  border-top: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  gap: 16px;
  flex-shrink: 0;
}

.keyboard-btn {
  width: 48px;
  height: 48px;
  border: 1px solid #e5e7eb;
  background: white;
  flex-shrink: 0;
  border-radius: 50%;
  padding: 0;
  min-width: 48px;
}

.voice-input-btn {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 16px;
  height: 48px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 24px;
  padding: 0 20px;
  overflow: hidden;
}

.mic-icon {
  font-size: 24px;
  color: #6b7280;
  flex-shrink: 0;
}

.text-input {
  flex: 1;
}

.input-placeholder {
  flex: 1;
  height: 2px;
  border-bottom: 2px dotted #d1d5db;
  align-self: center;
}

.hangup-btn {
  width: 56px;
  height: 56px;
  background: #ef4444;
  border: none;
  color: white;
  flex-shrink: 0;
  border-radius: 50%;
  padding: 0;
  min-width: 56px;
}

.hangup-btn:hover {
  background: #dc2626;
}

/* 波形显示 */
.waveform {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 2px;
  height: 32px;
}

.wave-bar {
  width: 3px;
  background: #3b82f6;
  border-radius: 2px;
  transition: height 0.1s ease;
  max-height: 32px;
}

.mic-icon.recording {
  color: #ef4444;
  animation: pulse 1.5s ease-in-out infinite;
}

.input-placeholder.recording {
  border-bottom-color: #ef4444;
  animation: pulse-border 1.5s ease-in-out infinite;
}

@keyframes pulse-border {
  0%, 100% {
    border-bottom-color: #ef4444;
  }
  50% {
    border-bottom-color: #fca5a5;
  }
}

</style>
