<template>
  <div class="voice-config">
    <div class="config-header" @click="togglePanel">
      <img src="../../assets/svg/voice.png" alt="voice" class="config-icon" />
      <span>语音配置</span>
      <img
        :src="isPanelOpen ? upIcon : downIcon"
        alt="toggle"
        class="toggle-icon"
      />
    </div>
    
    <div v-show="isPanelOpen" class="config-panel">
      <!-- 语音角色选择 -->
      <div class="config-item">
        <label>语音角色</label>
        <div class="voice-select-container">
          <select v-model="voiceConfig.role" @change="handleConfigChange">
            <option v-for="voice in voiceList" 
                    :key="voice.id" 
                    :value="voice.id">
              {{ voice.name+'_'+voice.gender }} ({{ getLanguageName(voice.language) }})
            </option>
          </select>
        </div>
      </div>
      
      <!-- 语速调节 -->
      <div class="config-item">
        <label>语速</label>
        <div class="slider-container">
          <input
            type="range"
            v-model="voiceConfig.speed"
            min="0.5"
            max="2"
            step="0.1"
            @change="handleConfigChange"
          />
          <span class="slider-value">{{ voiceConfig.speed }}x</span>
        </div>
      </div>
      
      <!-- 语言选择 -->
      <div class="config-item" style="display: flex;justify-content: space-around;">
        <button 
            class="preview-button" 
            @click="handlePreviewVoice"
            :disabled="isPreviewPlaying">
            {{ isPreviewPlaying ? '播放中...' : '试听' }}
          </button>
        <button 
            class="switch-button" 
            @click="handleSwitchVoice"
            :disabled="switchingVoice">
            {{ switchingVoice ? '切换中...' : '切换语音' }}
          </button>
       <!--  <label>语言</label>
        <select v-model="voiceConfig.language" @change="handleConfigChange">
          <option value="zh">中文</option>
          <option value="en">英文</option>
          <option value="ja">日语</option>
        </select> -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { useStore } from 'vuex';
import axios from 'axios';

import upIcon from '@/assets/svg/ups.svg';
import downIcon from '@/assets/svg/down.svg';
import voiceIcon from '@/assets/svg/voice.svg'

const store = useStore();
const isPanelOpen = ref(false);
const voiceList = ref([]);

const voiceConfig = reactive({
  role: '',
  speed: 1,
  language: 'zh'
});

const switchingVoice = ref(false);
const isPreviewPlaying = ref(false);
const audioElement = ref(null);

// 获取当前语音配置
const fetchCurrentVoiceConfig = async () => {
  try {
    const response = await axios.get(`${import.meta.env.VITE_BASE_AI_API}/chatbot/current_voice_config`);
    const currentConfig = response.data.data;
    console.log('Current config:', currentConfig); // 添加日志
    if (currentConfig && currentConfig.voice_name && voiceList.value.length > 0) {
      // 在 voiceList 中查找匹配的语音
      const matchedVoice = voiceList.value.find(voice => voice.name === currentConfig.voice_name);
      console.log('Matched voice:', matchedVoice); // 添加日志
      if (matchedVoice) {
        voiceConfig.role = matchedVoice.id;
        voiceConfig.speed = currentConfig.speed || 1;
        voiceConfig.language = matchedVoice.language;
        // 触发配置更新
        handleConfigChange();
      }
    }
  } catch (error) {
    console.error('获取当前语音配置失败:', error);
  }
};

// 获取语音列表
const fetchVoiceList = async () => {
  try {
    const response = await axios.get(`${import.meta.env.VITE_BASE_AI_API}/chatbot/list_voices`);
    const voices = response.data.data.voices;
    voiceList.value = Object.values(voices).flat();
    console.log('Voice list:', voiceList.value); // 添加日志
    // 获取语音列表后再获取当前配置
    await fetchCurrentVoiceConfig();
  } catch (error) {
    console.error('获取语音列表失败:', error);
  }
};

// 获取语言名称
const getLanguageName = (language) => {
  const languageMap = {
    'zh-cn': '中文',
    'en-us': '英文',
    'ja-jp': '日语',
    'ko-kr': '韩语'
  };
  return languageMap[language] || language;
};

onMounted(() => {
  fetchVoiceList();
});

const togglePanel = () => {
  isPanelOpen.value = !isPanelOpen.value;
};

const handleConfigChange = () => {
  store.commit('updateVoiceConfig', { ...voiceConfig });
};

// 添加切换语音的方法
const handleSwitchVoice = async () => {
  if (!voiceConfig.role) return;
  
  switchingVoice.value = true;
  try {
    const formData = new FormData();
    formData.append('voice_id', voiceConfig.role);
    
    await axios.post(
      `${import.meta.env.VITE_BASE_AI_API}/switch_voice_config`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    );
    
    // 切换成功后可以添加提示
    /* alert('语音切换成功'); */
  } catch (error) {
    console.error('切换语音失败:', error);
    alert('语音切换失败');
  } finally {
    switchingVoice.value = false;
  }
};

// 添加试听功能
const handlePreviewVoice = async () => {
  if (!voiceConfig.role || isPreviewPlaying.value) return;
  
  try {
    isPreviewPlaying.value = true;
    
    // 获取预览音频数据
    const response = await axios.get(`${import.meta.env.VITE_BASE_AI_API}/get_voice_preview?voice_id=${voiceConfig.role}`);
    const audioData = response.data;

    // 检查响应状态
    if (audioData.code !== 200) {
      throw new Error(audioData.msg || '获取音频失败');
    }

    // 如果已存在音频元素，先停止并移除
    if (audioElement.value) {
      audioElement.value.pause();
      audioElement.value = null;
    }
    
    // 创建新的音频元素
    let audio;
    
    // 优先使用 base64 音频数据
    if (audioData.audio && audioData.audio.startsWith('data:audio')) {
      audio = new Audio(audioData.audio);
    } 
    // 如果没有 base64 数据，尝试使用音频 URL
    else if (audioData.audio_url) {
      const baseUrl = import.meta.env.VITE_BASE_AI_API;
      const fullUrl = audioData.audio_url.startsWith('http') 
        ? audioData.audio_url 
        : `${baseUrl}${audioData.audio_url}`;
      audio = new Audio(fullUrl);
    } else {
      throw new Error('无效的音频数据');
    }

    audioElement.value = audio;
    
    // 监听播放结束事件
    audio.onended = () => {
      isPreviewPlaying.value = false;
      audioElement.value = null;
    };
    
    // 监听错误事件
    audio.onerror = (e) => {
      console.error('音频播放失败:', e);
      isPreviewPlaying.value = false;
      audioElement.value = null;
      alert('试听失败');
    };

    // 确保音频已加载
    audio.oncanplaythrough = async () => {
      try {
        await audio.play();
      } catch (error) {
        console.error('播放音频失败:', error);
        isPreviewPlaying.value = false;
        audioElement.value = null;
        alert('播放失败');
      }
    };
    
  } catch (error) {
    console.error('试听失败:', error);
    isPreviewPlaying.value = false;
    alert(error.message || '试听失败');
  }
};

// 组件卸载时清理音频
onUnmounted(() => {
  if (audioElement.value) {
    audioElement.value.pause();
    audioElement.value = null;
  }
});
</script>

<style scoped>
.voice-config {
  border-top: 1px solid rgba(0, 0, 0, 0.06);
  background: var(--secondary-bg);
  color: var(--primary-text);
}

.config-header {
  padding: 12px 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.config-header:hover {
  background: rgba(0, 0, 0, 0.02);
}

.config-icon {
  width: 16px;
  height: 16px;
}

.toggle-icon {
  width: 12px;
  height: 12px;
  margin-left: auto;
}

.config-panel {
  padding: 12px 20px;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
}

.config-item {
  margin-bottom: 16px;
}

.config-item:last-child {
  margin-bottom: 0;
}

.config-item label {
  display: block;
  font-size: 12px;
  color: var(--primary-text);
  margin-bottom: 8px;
}

select {
  width: 100%;
  padding: 6px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  color: var(--primary-text);
  background: var(--secondary-bg);
}

.slider-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

input[type="range"] {
  flex: 1;
  height: 4px;
  -webkit-appearance: none;
  background: #e5e6eb;
  border-radius: 2px;
  outline: none;
}

input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: #1677ff;
  cursor: pointer;
  border: none;
}

.slider-value {
  font-size: 12px;
  color: var(--primary-text);
  min-width: 36px;
}

.voice-select-container {
  display: flex;
  gap: 8px;
  align-items: center;
}

.switch-button {
  padding: 4px 15px;
  height: 32px;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  background: var(--secondary-bg);
  color: var(--primary-text);
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.switch-button:hover {
  color: #1677ff;
  border-color: #1677ff;
}

.switch-button:disabled {
  color: var(--primary-text);
  border-color: #d9d9d9;
  background: var(--secondary-bg);
  cursor: not-allowed;
}

select {
  flex: 1;
  min-width: 0; /* 防止select溢出 */
}

.preview-button {
  padding: 4px 15px;
  height: 32px;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  background: var(--secondary-bg);
  color: var(--primary-text);
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.preview-button:hover {
  color: #1677ff;
  border-color: #1677ff;
}

.preview-button:disabled {
  color: var(--primary-text);
  border-color: #d9d9d9;
  background: var(--secondary-bg);
  cursor: not-allowed;
}

.voice-select-container {
  display: flex;
  gap: 8px;
  align-items: center;
}

select {
  flex: 1;
  min-width: 0;
}
</style> 