<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>

      <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 }"
                  @click="selectedAgent = agent.id"
                >
                  <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 class="pagination-dots" v-if="totalPages > 1">
                <span
                  v-for="page in totalPages"
                  :key="page"
                  class="dot"
                  :class="{ active: currentPage === page - 1 }"
                  @click="currentPage = page - 1"
                ></span>
              </div>
            </div>
            <div class="agents-footer">
              <el-button type="primary" round size="large" class="start-btn" @click="startChat">
                开始对话
              </el-button>
            </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 } from 'vue'
import { ArrowUp, ArrowDown, Microphone, PhoneFilled, ChatDotRound, Mute } from '@element-plus/icons-vue'
import { useVoiceRecognition } from './composables/useVoiceRecognition.js'
import { ElMessage } from 'element-plus'

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 { isRecording, currentTranscription, tempTranscription, startRecording, stopRecording } = useVoiceRecognition()

// 音频播放
const playAudio = (base64Audio) => {
  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)

    audio.onended = () => {
      URL.revokeObjectURL(audioUrl)
    }

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

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

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

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

// 波形数据
const waveformData = ref(Array(60).fill(20))
let waveformInterval = 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 {
        const selectedAgentData = agents.value.find(a => a.id === selectedAgent.value)
        const response = await fetch('http://localhost:8080/talk/message', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            message: newContent,
            agentId: selectedAgent.value,
            agentGender: selectedAgentData?.gender === 'male' ? '0' : '1',
            ttsVcnList: ttsVcnList.value
          })
        })

        const data = await response.json()

        // 添加客服回复
        chatHistory.value.push({
          type: 'agent',
          content: data.reply
        })
        scrollToBottom()

        // 播放语音
        if (data.audio) {
          playAudio(data.audio)
        }
      } catch (error) {
        console.error('发送消息失败:', error)
        ElMessage.error('发送消息失败')
      }
    }
  }
})

// 监听 showChat 变化,开始对话时自动启动语音识别
watch(showChat, async (newVal) => {
  if (newVal && !isRecording.value) {
    try {
      await startRecording()
      ElMessage.success('语音识别已启动')

      // 启动波形动画
      waveformInterval = setInterval(updateWaveform, 100)
    } catch (error) {
      ElMessage.error('启动语音识别失败: ' + error.message)
    }
  } else if (!newVal && isRecording.value) {
    stopRecording()
    if (waveformInterval) {
      clearInterval(waveformInterval)
      waveformInterval = null
    }

    // 对话结束，将客服状态改回正常
    if (selectedAgent.value) {
      try {
        await fetch('http://localhost:8080/talk/agent/' + selectedAgent.value, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            id: selectedAgent.value,
            status: '0'
          })
        })
        console.log('客服状态已恢复为正常')
      } catch (error) {
        console.error('更新客服状态失败:', error)
      }
    }
  }
})

// 监听输入方式切换
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 {
    const selectedAgentData = agents.value.find(a => a.id === selectedAgent.value)
    const response = await fetch('http://localhost:8080/talk/message', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message: content,
        agentId: selectedAgent.value,
        agentGender: selectedAgentData?.gender === 'male' ? '0' : '1',
        ttsVcnList: ttsVcnList.value
      })
    })

    const data = await response.json()
    console.log('解析后的audio字段长度:', data.audio ? data.audio.length : 0)

    // 添加客服回复
    chatHistory.value.push({
      type: 'agent',
      content: data.reply
    })
    scrollToBottom()

    // 播放语音
    if (data.audio) {
      playAudio(data.audio)
    }
  } 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('http://localhost:8080/talk/dict/ttsVcn')
    const data = await response.json()
    ttsVcnList.value = data || []
  } catch (error) {
    console.error('获取发言人字典失败:', error)
  }
}

// 获取客服列表
const fetchAgents = async () => {
  try {
    const response = await fetch('http://localhost:8080/talk/agent/list?status=0')
    const result = await response.json()
    if (result.code === 200 && result.rows) {
      agents.value = result.rows.map(agent => ({
        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
      }))
      if (agents.value.length > 0) {
        selectedAgent.value = agents.value[0].id
      }
    }
  } catch (error) {
    console.error('获取客服列表失败:', error)
    ElMessage.error('获取客服列表失败')
  }
}

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

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

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

  try {
    // 更新客服配置
    const selectedAgentData = agents.value.find(a => a.id === selectedAgent.value)
    if (selectedAgentData) {
      const response = await fetch('http://localhost:8080/talk/agent/' + selectedAgent.value, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          id: selectedAgent.value,
          ttsSpeed: config.value.speed,
          ttsPitch: config.value.pitch,
          ttsVolume: config.value.volume,
          ttsBgs: config.value.bgSoundEnabled ? 1 : 0,
          status: '2'  // 设置状态为对话中
        })
      })

      if (response.ok) {
        console.log('客服配置已更新')
      }

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

        // 调用后端生成欢迎语语音
        try {
          const ttsResponse = await fetch('http://localhost:8080/talk/message', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              message: selectedAgentData.greetingMessage,
              agentId: selectedAgent.value,
              isGreeting: true
            })
          })

          const ttsData = await ttsResponse.json()
          if (ttsData.audio) {
            playAudio(ttsData.audio)
          }
        } catch (error) {
          console.error('生成欢迎语语音失败:', error)
        }
      } else {
        chatHistory.value = []
      }
    }
  } catch (error) {
    console.error('更新客服配置失败:', error)
  }

  showChat.value = true
}

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;
}

.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: 0;
  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;
  padding-top: 36px;
  padding-bottom: 0;
  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;
  padding: 0;
  flex-shrink: 0;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: calc(36px + 220px + 16px + 220px + 24px + 40px);
}

.agents-list {
  display: grid;
  grid-template-columns: repeat(3, 220px);
  gap: 16px;
  width: 100%;
  max-width: 100%;
  padding: 0 12px;
  margin-top: 0;
  margin-bottom: 0;
  justify-content: center;
}

.agent-card {
  width: 220px;
  height: 220px;
  padding: 10px;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  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);
}

.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: 120px;
  height: 120px;
  border-radius: 50%;
  margin: 20px auto 12px;
  border: 3px solid #e5e7eb;
}

.avatar-img {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  margin: 20px auto 12px;
  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: 14px;
  color: #1f2937;
  font-weight: 600;
  margin-top: 8px;
}

.start-btn {
  font-size: 16px;
  padding: 12px 48px;
  align-self: center;
  margin: 0;
}

.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>
