<template>
  <view class="chat-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-left" @tap="goBack" v-if="showBackButton">← 返回</view>
      <view class="navbar-center" :class="{'centered': !showBackButton}">
        <image class="character-avatar" :src="currentCharacter.avatar" mode="aspectFill" />
        <text class="character-name">{{ currentCharacter.name }}</text>
      </view>
      <view class="navbar-right">
        <text class="status-dot" :class="{'online': isOnline}"></text>
      </view>
    </view>

    <!-- 聊天消息区域 -->
    <scroll-view 
      class="chat-messages" 
      scroll-y="true" 
      :scroll-top="scrollTop"
      scroll-with-animation="true"
    >
      <view class="message-list">
        <view 
          v-for="(message, index) in messages" 
          :key="index"
          :class="['message-item', message.type]"
        >
          <!-- AI消息 -->
          <template v-if="message.type === 'ai'">
            <view class="message-avatar">
              <image :src="currentCharacter.avatar" mode="aspectFill" />
            </view>
            <view class="message-content">
              <view class="message-bubble" :class="message.type">
                <text class="message-text">{{ message.content }}</text>
                <view class="message-actions" v-if="isLoggedIn">
                  <view class="play-voice-btn" @click="() => playVoiceResponse(message.content)">
                    <text class="play-icon">🔊</text>
                  </view>
                </view>
                <view class="message-time">{{ message.time }}</view>
              </view>
            </view>
          </template>
          
          <!-- 用户消息 -->
          <template v-else-if="message.type === 'user'">
            <view class="message-content">
              <view class="message-bubble" :class="message.type">
                <text class="message-text">{{ message.content }}</text>
                <view class="message-time">{{ message.time }}</view>
              </view>
            </view>
            <view class="message-avatar">
              <image :src="userAvatar" mode="aspectFill" />
            </view>
          </template>
          
          <!-- 系统消息 -->
          <template v-else-if="message.type === 'system'">
            <view class="system-message">
              <text class="system-text">{{ message.content }}</text>
            </view>
          </template>
        </view>
        
        <!-- 正在输入提示 -->
        <view class="typing-indicator" v-if="isTyping">
          <view class="message-avatar">
            <image :src="currentCharacter.avatar" mode="aspectFill" />
          </view>
          <view class="message-content">
            <view class="message-bubble ai typing">
              <view class="typing-dots">
                <view class="dot"></view>
                <view class="dot"></view>
                <view class="dot"></view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
  
  <!-- 输入区域 - 移出主容器 -->
  <view class="input-area">
    <view class="input-container">
      <!-- AI模板选择按钮 - 放在输入框左边 -->
      <view 
        class="template-btn"
        @click="handleTemplateClick"
        @tap="handleTemplateClick"
      >
        <text class="template-icon">🤖</text>
      </view>
      <!-- 输入框或录音提示 -->
      <view 
        class="input-field"
        :class="{'recording-mode': isRecordingMode}"
      >
        <input 
          v-if="!isRecordingMode"
          class="text-input"
          v-model="inputText"
          placeholder="输入消息..."
          :disabled="isTyping || isLoading"
          @confirm="sendMessage"
          confirm-type="send"
          @input="handleInput"
          @focus="handleInputFocus"
        />
        <view v-else class="recording-input">
          <view 
            class="hold-to-speak-btn"
            :class="{'recording': isActuallyRecording}"
            @touchstart="startActualRecording"
            @touchend="stopActualRecording"
            @touchcancel="cancelActualRecording"
            @touchmove="handleRecordingMove"
          >
            <text class="hold-text">按住说话</text>
          </view>
        </view>
      </view>
      
      <view class="input-actions">
        <!-- 语音按钮 -->
        <view 
          class="voice-btn"
          :class="{'recording': isRecordingMode}"
          @click="toggleRecordingMode"
        >
          <text class="voice-icon">{{ isRecordingMode ? '🎤' : '🎙️' }}</text>
        </view>
        <!-- 发送按钮 -->
        <view 
          class="send-btn"
          :class="{'active': inputText.trim() && !isRecordingMode}"
          @click="sendMessage"
        >
          <text class="send-icon">📤</text>
        </view>
      </view>
    </view>
    
    <!-- 录音状态提示 -->
    <view class="recording-tip" v-if="isActuallyRecording">
      <text class="recording-text">{{ recordingTipText }}</text>
      <view class="recording-wave" v-if="!isRecordingCancelled">
        <view class="wave-bar" v-for="i in 5" :key="i"></view>
      </view>
    </view>
  </view>
  
  <!-- AI模板选择弹窗 -->
  <view class="template-selector" v-if="showTemplateModal" @click="hideTemplateSelector">
    <view class="template-modal" @click.stop>
      <view class="template-header">
        <text class="template-title">智能体选择</text>
        <view class="close-btn" @click="hideTemplateSelector">
          <text class="close-icon">✕</text>
        </view>
      </view>
      <view class="template-list">
        <view 
          class="template-item"
          :class="{'active': currentTemplateId === template.templateId}"
          v-for="template in availableTemplates"
          :key="template.templateId"
          @click="() => selectTemplate(template)"
        >
          <view class="template-info">
            <text class="template-name">{{ template.templateName }}</text>
            <text class="template-desc">{{ template.templateDesc }}</text>
          </view>
          <view class="template-check" v-if="currentTemplateId === template.templateId">
            <text class="check-icon">✓</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue';
import { useUserStore } from '@/stores/user.js';
import { getCharacterById, getSmartResponse } from '@/utils/aiCharacters.js';
import { chatAPI, voiceAPI, cleanText, configAPI } from '@/utils/api.js';
import { debugAPI } from '@/utils/debug.js';

// 状态管理
const userStore = useUserStore();

// 响应式数据
const messages = ref([]);
const inputText = ref('');
const isTyping = ref(false);
const isRecording = ref(false);
const isOnline = ref(true);
const scrollTop = ref(0);
const currentCharacter = ref({});
const userAvatar = ref('/static/default-avatar.png');
const conversationId = ref(null); // 对话ID
const isLoading = ref(false); // API加载状态
const isLoggedIn = ref(false); // 登录状态
const showBackButton = ref(true); // 是否显示返回按钮

// 录音相关状态
const isRecordingCancelled = ref(false); // 录音是否被取消
const recordingTipText = ref('松手发送，上移取消'); // 录音提示文本
const touchStartY = ref(0); // 触摸开始时的Y坐标
const isTouchMoving = ref(false); // 是否正在移动
const isRecordingMode = ref(false); // 是否进入录音模式（第一步）
const isActuallyRecording = ref(false); // 是否真正在录音（第二步）

// AI模型配置
const availableModels = ref([]); // 可用的AI模型列表
const availableTemplates = ref([]); // 可用的模板列表
const currentModelId = ref(null); // 当前选择的模型ID
const currentTemplateId = ref(null); // 当前选择的模板ID

// 模板选择弹窗
const showTemplateModal = ref(false); // 是否显示模板选择弹窗

// 录音相关
const recorderManager = ref(null);
const audioContext = ref(null);

// AI角色配置已移至 utils/aiCharacters.js

// 生命周期
onMounted(() => {
  initPage();
  initRecorder();
});

// 初始化页面
const initPage = async () => {
  // 检查登录状态
  checkLoginStatus();
  
  // 获取传递的参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options || {};

  // 如果没有任何参数，说明是从 tabBar 访问，不显示返回按钮
  if (!options.characterId && !options.roleId) {
    showBackButton.value = false;
  }

  // 检查是否是蔚AI（包括没有参数的情况，默认使用蔚AI）
  if (options.characterId === 'wei-ai' || !options.characterId) {
    // 设置蔚AI角色信息
    currentCharacter.value = {
      id: 'wei-ai',
      name: options.characterName || '蔚AI',
      avatar: options.characterAvatar || '/static/logo.png',
      greeting: decodeURIComponent(options.introMessage || '你好！我是蔚AI，很高兴为您服务！')
    };
    
    // 获取AI模型配置
    await loadAIConfigs();
    
    // 创建新对话
    await createNewConversation('wei-ai');
    
    // 添加蔚AI的欢迎消息
    addMessage('ai', currentCharacter.value.greeting);
    
    // 如果未登录，添加提示消息
    if (!isLoggedIn.value) {
      addMessage('system', '您当前处于未登录状态，将使用本地模拟回复。登录后可享受完整的AI对话功能。');
    }
  } else if (options.roleId) {
    // 处理从首页传递过来的AI角色信息
    currentCharacter.value = {
      id: options.characterId,
      roleId: options.roleId,
      name: decodeURIComponent(options.roleName || 'AI角色'),
      avatar: decodeURIComponent(options.avatar || '/static/logo.png'),
      greeting: decodeURIComponent(options.greeting || '你好！很高兴认识你！'),
      roleDesc: decodeURIComponent(options.roleDesc || ''),
      // 保存角色的模型和模板配置
      modelId: options.modelId || null,
      templateId: options.templateId || null,
      ttsId: options.ttsId || null,
      sttId: options.sttId || null,
      temperature: options.temperature || null,
      topP: options.topP || null
    };
    
    // 获取AI模型配置
    await loadAIConfigs();
    
    // 如果角色有指定的模型和模板ID，使用角色的配置
    if (options.modelId) {
      currentModelId.value = parseInt(options.modelId);
      console.log('使用角色指定的模型ID:', currentModelId.value);
    }
    if (options.templateId) {
      currentTemplateId.value = parseInt(options.templateId);
      console.log('使用角色指定的模板ID:', currentTemplateId.value);
    }
    
    // 创建新对话，使用roleId作为会话标识
    await createNewConversation(options.roleId);
    
    // 添加角色的欢迎消息
    addMessage('ai', currentCharacter.value.greeting);
    
    // 如果未登录，添加提示消息
    if (!isLoggedIn.value) {
      addMessage('system', '您当前处于未登录状态，将使用本地模拟回复。登录后可享受完整的AI对话功能。');
    }
  } else {
    // 原有的角色处理逻辑
    const characterId = options.characterId || 5;
    const character = getCharacterById(characterId);
    if (character) {
      currentCharacter.value = character;
      
      // 获取AI模型配置
      await loadAIConfigs();
      
      // 创建新对话
      await createNewConversation(characterId);
      
      // 添加欢迎消息
      addMessage('ai', character.greeting);
      
      // 如果未登录，添加提示消息
      if (!isLoggedIn.value) {
        addMessage('system', '您当前处于未登录状态，将使用本地模拟回复。登录后可享受完整的AI对话功能。');
      }
    }
  }
  
  // 设置用户头像
  if (userStore.userInfo?.avatar) {
    userAvatar.value = userStore.userInfo.avatar;
  }
};

// 加载AI配置
const loadAIConfigs = async () => {
  try {
    console.log('开始加载AI配置...');
    
    // 获取LLM模型配置
    console.log('正在获取AI模型配置...');
    const modelsResult = await configAPI.getModels();
    console.log('模型配置API响应:', modelsResult);
    
    if (modelsResult.success) {
      availableModels.value = modelsResult.data.data || modelsResult.data;
      console.log('获取到AI模型配置:', availableModels.value);
      
      // 设置默认模型（如果有的话）
      if (availableModels.value.length > 0) {
        currentModelId.value = availableModels.value[0].configId;
        console.log('设置默认模型ID:', currentModelId.value);
      }
    } else {
      console.warn('获取AI模型配置失败:', modelsResult.error);
      // 添加模拟数据用于测试
      availableModels.value = [
        { configId: 7, configName: 'GPT-4', configDesc: 'OpenAI GPT-4模型' },
        { configId: 8, configName: 'GPT-3.5', configDesc: 'OpenAI GPT-3.5模型' }
      ];
      currentModelId.value = 10;
      console.log('使用模拟AI模型配置');
    }

    // 获取模板配置
    console.log('正在获取模板配置...');
    const templatesResult = await configAPI.getTemplates();
    console.log('模板配置API响应:', templatesResult);
    
    if (templatesResult.success) {
      availableTemplates.value = templatesResult.data.data?.list || templatesResult.data.data || templatesResult.data;
      console.log('获取到模板配置:', availableTemplates.value);
      
      // 设置默认模板（如果有的话）
      if (availableTemplates.value.length > 0) {
        currentTemplateId.value = availableTemplates.value[0].templateId;
        console.log('设置默认模板ID:', currentTemplateId.value);
      }
    } else {
      console.warn('获取模板配置失败:', templatesResult.error);
      // 添加模拟数据用于测试
      availableTemplates.value = [
        { templateId: 1, templateName: '默认AI模型', templateDesc: '在用户与AI角色对话时，这个智能体会记住用户的言语习惯，学习用户的表达方式，并逐渐适应个性化的交流风格，让每一次对话都更加自然流畅。' },
        { templateId: 2, templateName: '1号AI模型', templateDesc: '在用户与AI角色对话时，这个智能体会记住用户的言语习惯，学习用户的表达方式，并逐渐适应个性化的交流风格，让每一次对话都更加自然流畅。' },
        { templateId: 3, templateName: '2号AI模型', templateDesc: '在用户与AI角色对话时，这个智能体会记住用户的言语习惯，学习用户的表达方式，并逐渐适应个性化的交流风格，让每一次对话都更加自然流畅。' },
        { templateId: 4, templateName: '3号AI模型', templateDesc: '在用户与AI角色对话时，这个智能体会记住用户的言语习惯，学习用户的表达方式，并逐渐适应个性化的交流风格，让每一次对话都更加自然流畅。' },
        { templateId: 5, templateName: '4号AI模型', templateDesc: '在用户与AI角色对话时，这个智能体会记住用户的言语习惯，学习用户的表达方式，并逐渐适应个性化的交流风格，让每一次对话都更加自然流畅。' }
      ];
      currentTemplateId.value = 6;
      console.log('使用模拟模板配置');
    }
    
    console.log('AI配置加载完成:', {
      models: availableModels.value,
      templates: availableTemplates.value,
      currentModelId: currentModelId.value,
      currentTemplateId: currentTemplateId.value
    });
  } catch (error) {
    console.error('加载AI配置异常:', error);
    // 添加模拟数据作为备用
    availableModels.value = [
      { configId: 7, configName: 'GPT-4', configDesc: 'OpenAI GPT-4模型' }
    ];
    availableTemplates.value = [
      { templateId: 1, templateName: '默认AI模型', templateDesc: '默认AI模型' },
      { templateId: 2, templateName: '1号AI模型', templateDesc: '1号AI模型' }
    ];
    currentModelId.value = 7;
    currentTemplateId.value = 1;
    console.log('使用备用模拟配置');
  }
};

// 检查登录状态
const checkLoginStatus = () => {
  const customToken = uni.getStorageSync('custom_token');
  const userToken = uni.getStorageSync('user_token');
  const userInfo = uni.getStorageSync('userInfo');
  
  isLoggedIn.value = !!(userStore.token || customToken || userToken || userInfo);
  
  console.log('登录状态检查:', {
    isLoggedIn: isLoggedIn.value,
    hasUserStoreToken: !!userStore.token,
    hasCustomToken: !!customToken,
    hasUserToken: !!userToken,
    hasUserInfo: !!userInfo
  });
};

// 初始化录音器
const initRecorder = () => {
  // #ifdef MP-WEIXIN
  recorderManager.value = uni.getRecorderManager();
  
  recorderManager.value.onStart(() => {
    console.log('录音开始');
  });
  
  recorderManager.value.onStop((res) => {
    console.log('录音结束', res);
    // 只有在录音没有被取消的情况下才处理语音消息
    if (!isRecordingCancelled.value) {
      handleVoiceMessage(res.tempFilePath);
    } else {
      console.log('录音被取消，不处理语音消息');
    }
  });
  
  recorderManager.value.onError((err) => {
    console.error('录音错误', err);
    uni.showToast({
      title: '录音失败',
      icon: 'none'
    });
    isRecording.value = false;
  });
  // #endif
};

// 添加消息
const addMessage = (type, content) => {
  const now = new Date();
  const time = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
  
  messages.value.push({
    type,
    content,
    time
  });
  
  // 滚动到底部
  nextTick(() => {
    scrollToBottom();
  });
};

// 滚动到底部
const scrollToBottom = () => {
  const query = uni.createSelectorQuery();
  query.select('.message-list').boundingClientRect();
  query.exec((res) => {
    if (res[0]) {
      scrollTop.value = res[0].height;
    }
  });
};

// 发送文本消息
const sendMessage = async () => {
  const text = inputText.value.trim();
  if (!text || isTyping.value || isLoading.value) return;
  
  // 添加用户消息
  addMessage('user', text);
  inputText.value = '';
  
  // 显示正在输入
  isTyping.value = true;
  
  try {
    // 调用真实的AI API
    await getAIResponse(text);
  } catch (error) {
    console.error('发送消息失败:', error);
    uni.showToast({
      title: '发送失败',
      icon: 'none'
    });
  } finally {
    isTyping.value = false;
  }
};

// 创建新对话
const createNewConversation = async (characterId) => {
  try {
    
    const result = await chatAPI.createConversation(characterId);
    if (result.success) {
      conversationId.value = result.data.conversationId;
      console.log('创建对话成功:', conversationId.value);
    } else {
      console.error('创建对话失败:', result.error);
      // 如果创建失败，使用本地模拟
      conversationId.value = `local_${Date.now()}`;
    }
  } catch (error) {
    console.error('创建对话异常:', error);
    conversationId.value = `local_${Date.now()}`;
  }
};

// 调用AI API获取回复
const getAIResponse = async (userMessage) => {
  try {
    isLoading.value = true;
    
    // 构建请求参数
    const requestParams = {
      message: userMessage,
      characterId: currentCharacter.value.id,
      conversationId: conversationId.value,
      modelId: currentModelId.value, // 传入当前选择的模型ID
      templateId: currentTemplateId.value // 传入当前选择的模板ID
    };
    
    // 如果角色有roleId（从剧情页面传递过来的角色）
    if (currentCharacter.value.roleId) {
      // 优先使用角色指定的模型和模板ID
      if (currentCharacter.value.modelId) {
        requestParams.modelId = currentCharacter.value.modelId;
      }
      if (currentCharacter.value.templateId) {
        requestParams.templateId = currentCharacter.value.templateId;
      } else {
        // 如果没有指定templateId，使用roleId作为templateId
        requestParams.templateId = currentCharacter.value.roleId;
      }
      console.log('使用AI角色配置:', {
        roleId: currentCharacter.value.roleId,
        roleName: currentCharacter.value.name,
        modelId: requestParams.modelId,
        templateId: requestParams.templateId
      });
    }
    
    console.log('发送AI对话请求，参数:', requestParams);
    
    const result = await chatAPI.syncChat(requestParams);
    
    if (result.success) {
      // API调用成功，直接使用处理后的数据
      const aiResponse = result.data;
      console.log('✅ 成功获取AI回复:', aiResponse);
      
      // 添加AI回复到聊天界面
      addMessage('ai', aiResponse);
      
      // 更新对话ID（如果后端返回了新的）
      if (result.originalResponse && result.originalResponse.conversationId) {
        conversationId.value = result.originalResponse.conversationId;
      }
    } else {
      // API调用失败，使用本地模拟回复
      console.warn('AI API调用失败，使用本地模拟回复:', result.error);
      const fallbackResponse = getSmartResponse(currentCharacter.value, userMessage);
      const cleanedResponse = cleanText(fallbackResponse);
      console.log('本地模拟原始回复:', fallbackResponse);
      console.log('本地模拟清理后回复:', cleanedResponse);
      addMessage('ai', cleanedResponse);
      
      // 根据是否匿名模式显示不同的提示
      if (result.isAnonymous) {
        // 未登录状态，不显示错误提示
        console.log('未登录状态，使用本地模拟回复');
      } else {
        // 已登录但API失败
        uni.showToast({
          title: 'AI服务暂时不可用，使用本地回复',
          icon: 'none',
          duration: 2000
        });
      }
    }
  } catch (error) {
    console.error('AI API调用异常:', error);
    
    // 异常情况，使用本地模拟回复
    const fallbackResponse = getSmartResponse(currentCharacter.value, userMessage);
    const cleanedResponse = cleanText(fallbackResponse);
    console.log('异常情况原始回复:', fallbackResponse);
    console.log('异常情况清理后回复:', cleanedResponse);
    addMessage('ai', cleanedResponse);
    
    uni.showToast({
      title: '网络异常，使用本地回复',
      icon: 'none',
      duration: 2000
    });
  } finally {
    isLoading.value = false;
  }
};

// 模拟AI回复（备用方案）
const simulateAIResponse = (userMessage) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 使用智能回复系统
      const response = getSmartResponse(currentCharacter.value, userMessage);
      addMessage('ai', response);
      resolve();
    }, 1000 + Math.random() * 2000); // 1-3秒随机延迟
  });
};

// 切换录音模式（第一步：进入录音模式）
const toggleRecordingMode = () => {
  if (isTyping.value) return;
  
  isRecordingMode.value = !isRecordingMode.value;
  
  if (isRecordingMode.value) {
    console.log('进入录音模式');
    // 清空输入框
    inputText.value = '';
  } else {
    console.log('退出录音模式');
    // 如果正在录音，先停止
    if (isActuallyRecording.value) {
      stopActualRecording();
    }
  }
};

// 开始真正录音（第二步：按住说话）
const startActualRecording = (e) => {
  if (isTyping.value || !isRecordingMode.value) return;
  
  console.log('开始真正录音');
  touchStartY.value = e.touches[0].clientY;
  isTouchMoving.value = false;
  isRecordingCancelled.value = false;
  recordingTipText.value = '松手发送，上移取消';
  
  // #ifdef MP-WEIXIN
  // 先申请录音权限
  uni.authorize({
    scope: 'scope.record',
    success: () => {
      isActuallyRecording.value = true;
      
      recorderManager.value.start({
        duration: 60000, // 最长60秒
        sampleRate: 16000,
        numberOfChannels: 1,
        encodeBitRate: 96000,
        format: 'aac'  // 微信小程序支持aac格式，后端会转换为wav
      });
    },
    fail: () => {
      uni.showModal({
        title: '需要录音权限',
        content: '请在设置中开启录音权限，以便使用语音功能',
        showCancel: false
      });
    }
  });
  // #endif
  
  // #ifndef MP-WEIXIN
  uni.showToast({
    title: '语音功能仅支持微信小程序',
    icon: 'none'
  });
  // #endif
};

// 停止真正录音
const stopActualRecording = () => {
  if (!isActuallyRecording.value) return;
  
  console.log('停止真正录音');
  
  // #ifdef MP-WEIXIN
  isActuallyRecording.value = false;
  isRecordingCancelled.value = false;
  isTouchMoving.value = false;
  recorderManager.value.stop();
  // #endif
};

// 取消真正录音
const cancelActualRecording = () => {
  if (!isActuallyRecording.value) return;
  
  console.log('取消真正录音');
  
  // #ifdef MP-WEIXIN
  isActuallyRecording.value = false;
  isRecordingCancelled.value = true;
  isTouchMoving.value = false;
  recorderManager.value.stop();
  
  // 显示取消提示
  uni.showToast({
    title: '录音已取消',
    icon: 'none',
    duration: 1000
  });
  // #endif
};

// 处理录音移动
const handleRecordingMove = (e) => {
  if (isActuallyRecording.value) {
    const currentY = e.touches[0].clientY;
    const deltaY = touchStartY.value - currentY;
    isTouchMoving.value = true;
    
    // 如果向上移动超过50px，显示取消提示
    if (deltaY > 50) {
      isRecordingCancelled.value = true;
      recordingTipText.value = '松开取消录音';
    } else {
      isRecordingCancelled.value = false;
      recordingTipText.value = '松手发送，上移取消';
    }
    
    console.log('录音中触摸移动，Y坐标:', currentY, '移动距离:', deltaY, '是否取消:', isRecordingCancelled.value);
  }
};

// 处理语音消息
const handleVoiceMessage = async (filePath) => {
  // 如果录音被取消，不处理语音消息
  if (isRecordingCancelled.value) {
    console.log('录音被取消，不处理语音消息');
    return;
  }
  
  // 添加用户语音消息
  addMessage('user', '[语音消息]');
  
  // 显示正在处理
  isTyping.value = true;
  
  try {
    // 确定使用的模型和模板ID（优先使用角色配置）
    let effectiveModelId = currentModelId.value;
    let effectiveTemplateId = currentTemplateId.value;
    
    if (currentCharacter.value.roleId) {
      // 如果是从剧情页面传递的角色，优先使用角色的配置
      if (currentCharacter.value.modelId) {
        effectiveModelId = currentCharacter.value.modelId;
      }
      if (currentCharacter.value.templateId) {
        effectiveTemplateId = currentCharacter.value.templateId;
      } else {
        effectiveTemplateId = currentCharacter.value.roleId;
      }
    }
    
    console.log('语音对话使用的配置:', {
      modelId: effectiveModelId,
      templateId: effectiveTemplateId,
      roleName: currentCharacter.value.name
    });
    
    // 使用新的语音对话API（完整流程：语音识别 -> AI回复 -> 语音合成）
    const voiceChatResult = await voiceAPI.voiceChat(filePath, {
      modelId: effectiveModelId,
      templateId: effectiveTemplateId
    });
    
    if (voiceChatResult.success) {
      const { userText, aiResponse, audioUrl } = voiceChatResult.data;
      console.log('语音对话结果:', voiceChatResult.data);
      
      // 更新用户消息显示
      if (messages.value.length > 0) {
        const lastMessage = messages.value[messages.value.length - 1];
        if (lastMessage.type === 'user' && lastMessage.content === '[语音消息]') {
          lastMessage.content = userText || '[语音消息]';
        }
      }
      
      // 添加AI回复消息
      addMessage('ai', aiResponse);
      
      // 自动播放AI回复的语音
      if (audioUrl) {
        await playVoiceResponse(aiResponse, audioUrl);
      }
    } else {
      console.warn('语音对话失败，尝试使用上传音频文件接口:', voiceChatResult.error);
      
      // 降级处理：使用上传音频文件接口
      const uploadResult = await voiceAPI.uploadVoiceChat(filePath, {
        modelId: effectiveModelId,
        templateId: effectiveTemplateId
      });
      
      if (uploadResult.success) {
        const { userText, aiResponse, audioUrl } = uploadResult.data;
        console.log('上传音频文件语音对话结果:', uploadResult.data);
        
        // 更新用户消息显示
        if (messages.value.length > 0) {
          const lastMessage = messages.value[messages.value.length - 1];
          if (lastMessage.type === 'user' && lastMessage.content === '[语音消息]') {
            lastMessage.content = userText || '[语音消息]';
          }
        }
        
        // 添加AI回复消息
        addMessage('ai', aiResponse);
        
        // 播放AI语音回复
        if (audioUrl) {
          await playVoiceResponse(aiResponse, audioUrl);
        }
      } else {
        console.error('上传音频文件语音对话也失败:', uploadResult.error);
        
        // 检查是否是token错误，如果是则提供更友好的提示
        let errorMessage = '语音处理失败，使用本地回复';
        let shouldShowLoginTip = false;
        
        if (uploadResult.error && uploadResult.error.message) {
          if (uploadResult.error.message.includes('token错误') || uploadResult.error.message.includes('未登录')) {
            errorMessage = '语音功能需要登录，请先登录后使用';
            shouldShowLoginTip = true;
          } else if (uploadResult.error.message.includes('网络')) {
            errorMessage = '网络连接失败，使用本地回复';
          }
        }
        
        // 最终降级：使用本地模拟回复
        const fallbackResponse = getSmartResponse(currentCharacter.value, '[语音消息]');
        const cleanedResponse = cleanText(fallbackResponse);
        console.log('语音降级原始回复:', fallbackResponse);
        console.log('语音降级清理后回复:', cleanedResponse);
        addMessage('ai', cleanedResponse);
        
        // 显示提示
        if (shouldShowLoginTip) {
          uni.showModal({
            title: '语音功能需要登录',
            content: '语音对话功能需要登录后才能使用，是否前往登录？',
            success: (res) => {
              if (res.confirm) {
                // 跳转到登录页面
                uni.navigateTo({
                  url: '/pages/mine/mine'
                });
              }
            }
          });
        } else {
          uni.showToast({
            title: errorMessage,
            icon: 'none',
            duration: 3000
          });
        }
      }
    }
  } catch (error) {
    console.error('处理语音消息失败:', error);
    
    // 异常情况，使用本地模拟回复
    const fallbackResponse = getSmartResponse(currentCharacter.value, '[语音消息]');
    const cleanedResponse = cleanText(fallbackResponse);
    console.log('语音异常原始回复:', fallbackResponse);
    console.log('语音异常清理后回复:', cleanedResponse);
    addMessage('ai', cleanedResponse);
    
    uni.showToast({
      title: '语音处理异常，使用本地回复',
      icon: 'none',
      duration: 2000
    });
  } finally {
    isTyping.value = false;
  }
};

// 播放语音回复
const playVoiceResponse = async (text, audioUrl = null) => {
  // #ifdef MP-WEIXIN
  try {
    let finalAudioUrl = audioUrl;
    
    // 如果没有提供音频URL，则调用TTS API生成
    if (!finalAudioUrl) {
      console.log('没有提供音频URL，调用TTS API生成');
      const ttsResult = await voiceAPI.textToSpeech(text, currentCharacter.value.voiceStyle);
      
      if (ttsResult.success) {
        finalAudioUrl = ttsResult.data.audioUrl;
      } else {
        console.warn('文本转语音失败:', ttsResult.error);
        uni.showToast({
          title: '语音合成失败',
          icon: 'none'
        });
        return;
      }
    } else {
      console.log('使用提供的音频URL:', finalAudioUrl);
    }
    
    // 销毁之前的音频实例
    if (audioContext.value) {
      audioContext.value.destroy();
    }
    
    // 创建音频上下文
    audioContext.value = uni.createInnerAudioContext();
    audioContext.value.src = finalAudioUrl;
    
    // 设置事件监听
    audioContext.value.onPlay(() => {
      console.log('开始播放AI语音回复');
      uni.showToast({
        title: '正在播放语音',
        icon: 'none',
        duration: 1000
      });
    });
    
    audioContext.value.onEnded(() => {
      console.log('AI语音播放结束');
    });
    
    audioContext.value.onError((err) => {
      console.error('语音播放错误:', err);
      uni.showToast({
        title: '语音播放失败',
        icon: 'none'
      });
    });
    
    // 开始播放
    audioContext.value.play();
    
  } catch (error) {
    console.error('语音播放异常:', error);
    uni.showToast({
      title: '语音播放异常',
      icon: 'none'
    });
  }
  // #endif
  
  // #ifndef MP-WEIXIN
  console.log('语音播放功能仅支持微信小程序');
  uni.showToast({
    title: '语音功能仅支持微信小程序',
    icon: 'none'
  });
  // #endif
};

// 显示模板选择器
const showTemplateSelector = () => {
  showTemplateModal.value = true;
};

// 隐藏模板选择器
const hideTemplateSelector = () => {
  showTemplateModal.value = false;
};

// 选择模板
const selectTemplate = (template) => {
  currentTemplateId.value = template.templateId;
  console.log('选择模板:', template.templateName, 'ID:', template.templateId);
  
  // 显示切换提示
  uni.showToast({
    title: `已切换到${template.templateName}`,
    icon: 'none',
    duration: 1500
  });
  
  // 关闭弹窗
  hideTemplateSelector();
};

// 处理输入框输入事件
const handleInput = (e) => {
  // 确保输入框可以正常输入
  console.log('输入框输入:', e.detail.value);
};

// 处理输入框聚焦事件
const handleInputFocus = () => {
  console.log('输入框获得焦点');
};



// 处理模板按钮点击事件
const handleTemplateClick = () => {
  console.log('模板按钮被点击');
  console.log('当前可用模板:', availableTemplates.value);
  console.log('当前模板数量:', availableTemplates.value.length);
  
  if (availableTemplates.value.length === 0) {
    console.log('没有可用模板，尝试重新加载配置...');
    loadAIConfigs().then(() => {
      if (availableTemplates.value.length > 0) {
        showTemplateSelector();
      } else {
        uni.showToast({
          title: '暂无可用模板',
          icon: 'none'
        });
      }
    });
  } else {
    showTemplateSelector();
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>

<style scoped>
/* 页面根元素样式 - 禁用页面滚动 */
page {
  height: 100vh;
  overflow: hidden;
}

/* 聊天页面样式 */
.chat-container {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #1a0b2e 0%, #4a1e6d 25%, #6b2c9c 50%, #8a2be2 75%, #4b0082 100%);
  position: fixed; /* 固定定位，防止页面滚动 */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden; /* 禁用页面滚动 */
  padding-top: calc(100rpx + env(safe-area-inset-top)); /* 为固定导航栏和状态栏留出空间 */
  padding-bottom: 120rpx; /* 为固定输入区域留出空间 */
}

/* 自定义导航栏 */
.custom-navbar {
  height: 100rpx;
  background: linear-gradient(135deg, rgba(26, 11, 46, 0.95) 0%, rgba(74, 30, 109, 0.95) 25%, rgba(107, 44, 156, 0.95) 50%, rgba(138, 43, 226, 0.95) 75%, rgba(75, 0, 130, 0.95) 100%);
  backdrop-filter: blur(10px);
  border-bottom: 1rpx solid rgba(251, 191, 36, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 24rpx;
  padding-top: env(safe-area-inset-top);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  font-weight: bold;
  font-size: 32rpx;
  letter-spacing: 2rpx;
}

.navbar-left {
  position: absolute;
  left: 24rpx;
  color: #f9e076;
  font-size: 28rpx;
  font-weight: 500;
  transition: opacity 0.3s ease;
}

.navbar-left:active {
  opacity: 0.7;
}

.navbar-center {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
}

.navbar-center.centered {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.character-avatar {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  border: 2rpx solid rgba(249, 224, 118, 0.4);
  box-shadow: 0 0 8rpx rgba(249, 224, 118, 0.3);
}

.character-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #ffffff;
  text-shadow: 0 0 10px rgba(249, 224, 118, 0.5);
}

.navbar-right {
  position: absolute;
  right: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.status-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background: #94a3b8;
  box-shadow: 0 0 4rpx rgba(148, 163, 184, 0.5);
}

.status-dot.online {
  background: #10b981;
  box-shadow: 0 0 8rpx rgba(16, 185, 129, 0.8);
  animation: pulse-dot 2s infinite;
}

@keyframes pulse-dot {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

/* 聊天消息区域 */
.chat-messages {
  height: calc(100vh - 100rpx - 120rpx - env(safe-area-inset-top)); /* 减去导航栏和底部输入区域的高度 */
  padding: 16rpx 20rpx;
  overflow-y: auto;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.message-item {
  display: flex;
  align-items: flex-end;
  gap: 16rpx;
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.message-avatar image {
  width: 100%;
  height: 100%;
}

.message-content {
  flex: 1;
  max-width: 70%;
}

.message-bubble {
  padding: 16rpx 20rpx;
  border-radius: 20rpx;
  position: relative;
  word-wrap: break-word;
}

.message-bubble.user {
  background: linear-gradient(135deg, #ff7b7b, #ffb7b7);
  color: #fff;
  border-bottom-right-radius: 8rpx;
}

.message-bubble.ai {
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  border: 2rpx solid rgba(255, 123, 123, 0.2);
  border-bottom-left-radius: 8rpx;
}

.message-text {
  font-size: 28rpx;
  line-height: 1.5;
  display: block;
  margin-bottom: 8rpx;
}

.message-time {
  font-size: 20rpx;
  opacity: 0.7;
  text-align: right;
}

.message-bubble.ai .message-time {
  text-align: left;
}

/* 消息操作按钮 */
.message-actions {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin: 8rpx 0;
}

.play-voice-btn {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background: rgba(255, 123, 123, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.play-voice-btn:hover {
  background: rgba(255, 123, 123, 0.2);
  transform: scale(1.1);
}

.play-icon {
  font-size: 20rpx;
}

/* 正在输入提示 */
.typing-indicator {
  display: flex;
  align-items: flex-end;
  gap: 16rpx;
}

.typing-dots {
  display: flex;
  gap: 8rpx;
  align-items: center;
}

.dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background: #ff7b7b;
  animation: typing 1.4s infinite ease-in-out;
}

.dot:nth-child(1) { animation-delay: -0.32s; }
.dot:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 输入区域 */
.input-area {
  background: linear-gradient(135deg, rgba(26, 11, 46, 0.95) 0%, rgba(74, 30, 109, 0.95) 25%, rgba(107, 44, 156, 0.95) 50%, rgba(138, 43, 226, 0.95) 75%, rgba(75, 0, 130, 0.95) 100%);
  backdrop-filter: blur(10px);
  border-top: 1rpx solid rgba(251, 191, 36, 0.3);
  padding: 16rpx 20rpx;
  padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.input-container {
  display: flex;
  align-items: center;
  gap: 12rpx;
  background: rgba(15, 23, 42, 0.8);
  border-radius: 25rpx;
  padding: 10rpx 16rpx;
  border: 2rpx solid rgba(251, 191, 36, 0.3);
}

/* 输入框容器 */
.input-field {
  flex: 1;
  position: relative;
  transition: all 0.3s ease;
}

.input-field.recording-mode {
  background: rgba(251, 191, 36, 0.1);
  border-radius: 20rpx;
  border: 2rpx solid rgba(251, 191, 36, 0.3);
}

.text-input {
  width: 100%;
  font-size: 28rpx;
  color: #ffffff;
  background: transparent;
  border: none;
  outline: none;
  padding: 12rpx 16rpx;
}

.text-input::placeholder {
  color: #cbd5e1;
}

/* 录音模式输入框 */
.recording-input {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12rpx 16rpx;
  min-height: 60rpx;
}

/* 按住说话按钮 */
.hold-to-speak-btn {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(251, 191, 36, 0.1);
  border: 2rpx solid rgba(251, 191, 36, 0.3);
  border-radius: 20rpx;
  transition: all 0.3s ease;
  cursor: pointer;
  user-select: none;
}

.hold-to-speak-btn.recording {
  background: rgba(251, 191, 36, 0.2);
  border-color: #fbbf24;
  animation: pulse 1s infinite;
}

.hold-to-speak-btn:active {
  background: rgba(251, 191, 36, 0.3);
  transform: scale(0.98);
}

.hold-text {
  font-size: 28rpx;
  color: #fbbf24;
  font-weight: bold;
  text-align: center;
}

.input-actions {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.template-btn {
  width: 55rpx;
  height: 55rpx;
  border-radius: 50%;
  background: rgba(251, 191, 36, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  flex-shrink: 0; /* 防止按钮被压缩 */
  cursor: pointer;
  user-select: none;
}

.template-btn:active {
  background: linear-gradient(135deg, #fbbf24, #f59e0b);
  transform: scale(1.05);
}

.template-icon {
  font-size: 24rpx;
}

.voice-btn {
  width: 55rpx;
  height: 55rpx;
  border-radius: 50%;
  background: rgba(251, 191, 36, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  cursor: pointer;
  user-select: none;
  position: relative;
  z-index: 10;
}

.voice-btn.recording {
  background: linear-gradient(135deg, #fbbf24, #f59e0b);
  animation: pulse 1s infinite;
}

.voice-btn:active {
  background: linear-gradient(135deg, #f59e0b, #d97706);
  transform: scale(0.95);
}

.voice-icon {
  font-size: 28rpx;
}

.send-btn {
  width: 55rpx;
  height: 55rpx;
  border-radius: 50%;
  background: rgba(251, 191, 36, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  cursor: pointer;
  user-select: none;
}

.send-btn.active {
  background: linear-gradient(135deg, #fbbf24, #f59e0b);
  transform: scale(1.1);
}

.send-icon {
  font-size: 24rpx;
}

/* 录音状态提示 */
.recording-tip {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.8);
  color: #ffffff;
  padding: 20rpx 40rpx;
  border-radius: 20rpx;
  text-align: center;
  z-index: 2000;
  backdrop-filter: blur(10px);
  border: 2rpx solid rgba(251, 191, 36, 0.3);
}

.recording-text {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 16rpx;
  display: block;
}

.recording-wave {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
}

.wave-bar {
  width: 8rpx;
  height: 20rpx;
  background: linear-gradient(135deg, #fbbf24, #f59e0b);
  border-radius: 4rpx;
  animation: wave 1.2s infinite ease-in-out;
}

.wave-bar:nth-child(1) { animation-delay: -0.4s; }
.wave-bar:nth-child(2) { animation-delay: -0.3s; }
.wave-bar:nth-child(3) { animation-delay: -0.2s; }
.wave-bar:nth-child(4) { animation-delay: -0.1s; }
.wave-bar:nth-child(5) { animation-delay: 0s; }

@keyframes wave {
  0%, 40%, 100% {
    transform: scaleY(0.4);
  }
  20% {
    transform: scaleY(1);
  }
}

/* 系统消息样式 */
.system-message {
  display: flex;
  justify-content: center;
  margin: 20rpx 0;
}

.system-text {
  background: rgba(0, 0, 0, 0.05);
  color: #666;
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  text-align: center;
  max-width: 80%;
  line-height: 1.4;
}

/* 登录状态提示 */
.login-status {
  font-size: 20rpx;
  color: #fbbf24;
  text-shadow: 0 0 6px rgba(251, 191, 36, 0.8);
}

/* AI模板选择弹窗 */
.template-selector {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.template-modal {
  width: 80%;
  max-width: 600rpx;
  max-height: 80vh;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.3);
}

.template-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
  background: #f8f9fa;
}

.template-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.close-btn:active {
  background: #e0e0e0;
  transform: scale(0.95);
}

.close-icon {
  font-size: 24rpx;
  color: #666;
}

.template-list {
  max-height: 60vh;
  overflow-y: auto;
}

.template-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: all 0.3s ease;
}

.template-item:active {
  background: #f8f9fa;
}

.template-item.active {
  background: rgba(255, 123, 123, 0.1);
}

.template-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.template-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.template-desc {
  font-size: 24rpx;
  color: #666;
  line-height: 1.4;
}

.template-check {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff7b7b, #ffb7b7);
  display: flex;
  align-items: center;
  justify-content: center;
}

.check-icon {
  font-size: 20rpx;
  color: white;
  font-weight: bold;
  margin-left: 8rpx;
}

/* 录音状态提示 */
.recording-tip {
  position: absolute;
  top: -80rpx;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(251, 191, 36, 0.9);
  color: #fff;
  padding: 16rpx 32rpx;
  border-radius: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12rpx;
  backdrop-filter: blur(10px);
}

.recording-text {
  font-size: 24rpx;
  font-weight: 500;
}

.recording-wave {
  display: flex;
  gap: 4rpx;
  align-items: center;
}

.wave-bar {
  width: 4rpx;
  height: 20rpx;
  background: #fff;
  border-radius: 2rpx;
  animation: wave 1s infinite ease-in-out;
}

.wave-bar:nth-child(1) { animation-delay: 0s; }
.wave-bar:nth-child(2) { animation-delay: 0.1s; }
.wave-bar:nth-child(3) { animation-delay: 0.2s; }
.wave-bar:nth-child(4) { animation-delay: 0.3s; }
.wave-bar:nth-child(5) { animation-delay: 0.4s; }

@keyframes wave {
  0%, 100% {
    height: 20rpx;
  }
  50% {
    height: 40rpx;
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

@keyframes star-rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media screen and (max-width: 375px) {
  .custom-navbar {
    padding: 0 16rpx;
  }
  
  .character-name {
    font-size: 28rpx;
  }
  
  .message-bubble {
    padding: 16rpx 20rpx;
  }
  
  .message-text {
    font-size: 26rpx;
  }
  
  .input-area {
    padding: 16rpx 20rpx;
  }
}
</style>
