<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<div class="flex h-screen bg-gray-50">
				<!-- Left Panel: Controls -->
				<div class="flex-none w-1/4 min-w-[280px] mr-4 overflow-y-auto">
					<div class="p-5 h-full bg-white rounded-xl shadow-sm">
						<h3 class="mb-6 text-lg font-medium text-gray-800">语音控制</h3>

						<!-- Model Selection -->
						<div class="mb-6">
							<div class="flex justify-between items-center">
								<label class="text-sm font-medium text-gray-700">模型</label>
								<div class="flex-grow ml-4">
									<ModelList ref="modelListComponent" :model-type="['Voice']" />
								</div>
							</div>
						</div>

						<div class="space-y-6">
							<!-- Speech Rate Slider -->
							<div>
								<div class="flex justify-between mb-2">
									<label class="text-sm font-medium text-gray-700">倍速</label>
									<span class="text-sm font-medium text-primary">{{ speechRate }}x</span>
								</div>
								<el-slider v-model="speechRate" :min="0.25" :max="4.0" :step="0.1" class="mx-1"></el-slider>
							</div>

							<!-- Volume Gain Slider -->
							<div>
								<div class="flex justify-between mb-2">
									<label class="text-sm font-medium text-gray-700">音量增益 (dB)</label>
									<span class="text-sm font-medium text-primary">{{ volumeGain }}</span>
								</div>
								<el-slider v-model="volumeGain" :min="-10" :max="10" :step="1" class="mx-1"></el-slider>
							</div>

							<!-- Voice Selection -->
							<div>
								<label class="block mb-2 text-sm font-medium text-gray-700">音色</label>
								<el-select v-model="selectedVoice" placeholder="请选择音色" class="w-full">
									<el-option v-for="voice in voices" :key="voice.value" :label="voice.label" :value="voice.value" />
								</el-select>
							</div>
						</div>
					</div>
				</div>

				<!-- Middle Panel: Audio Player & Prompt Input -->
				<div class="flex-1 mr-4">
					<div class="flex flex-col p-5 h-full bg-white rounded-xl shadow-sm">
						<h3 class="mb-6 text-lg font-medium text-gray-800">音频生成</h3>

						<!-- Audio Player Area -->
						<div class="mb-6 w-full">
							<div v-if="generatedAudioUrl || selectedHistoryAudioUrl" class="flex flex-col">
								<div class="flex items-center mb-4">
									<div class="flex flex-shrink-0 justify-center items-center mr-4 w-12 h-12 rounded-full shadow-sm bg-primary">
										<el-icon :size="24" class="text-white"><Headset /></el-icon>
									</div>
									<div class="overflow-hidden flex-1">
										<h3 class="text-base font-medium text-gray-800 truncate">{{ prompt || 'Untitled Audio' }}</h3>
										<div v-if="selectedHistoryAudioUrl" class="flex items-center mt-1 text-xs text-gray-500">
											<el-icon class="mr-1" :size="12"><Timer /></el-icon>
											<span>历史记录</span>
										</div>
									</div>
									<el-button
										v-if="selectedHistoryAudioUrl"
										class="ml-2"
										size="small"
										type="default"
										@click="
											selectedHistoryAudioUrl = null;
											selectedHistoryPrompt = null;
										"
										icon="Close"
									></el-button>
								</div>

								<div class="p-4 bg-gray-50 rounded-xl border border-gray-100 audio-container">
									<audio controls :src="baseURL + (selectedHistoryAudioUrl || generatedAudioUrl)" class="w-full rounded audio-controls">
										Your browser does not support the audio element.
									</audio>
								</div>
							</div>
							<div v-else-if="isGenerating" class="flex justify-center items-center h-[160px] bg-gray-50 rounded-xl border border-gray-100">
								<div class="flex flex-col items-center text-primary">
									<el-icon class="mb-3 animate-spin" :size="28"><Loading /></el-icon>
									<span class="text-gray-600">正在生成音频...</span>
								</div>
							</div>
							<div v-else class="flex justify-center items-center h-[160px] bg-gray-50 rounded-xl border border-dashed border-gray-200">
								<div class="flex flex-col items-center text-gray-400">
									<el-icon class="mb-3" :size="28"><VideoCameraFilled /></el-icon>
									<span>音频将在这里播放</span>
								</div>
							</div>
						</div>

						<!-- Example Prompts -->
						<div v-if="!selectedHistoryAudioUrl" class="mb-6">
							<div class="flex justify-between items-center mb-3">
								<h3 class="text-sm font-medium text-gray-700">示例描述</h3>
								<el-tooltip content="点击使用示例描述" placement="top">
									<el-icon class="text-gray-400 cursor-help"><InfoFilled /></el-icon>
								</el-tooltip>
							</div>
							<div class="grid overflow-y-auto grid-cols-2 gap-2 pb-1 max-h-36">
								<div
									v-for="example in examplePrompts"
									:key="example.text"
									@click="prompt = example.text"
									class="flex items-center p-3 bg-gray-50 rounded-lg border border-gray-200 transition-all duration-200 cursor-pointer hover:bg-blue-50 hover:border-blue-300"
								>
									<el-icon class="flex-shrink-0 mr-2 text-blue-500"><ChatLineRound /></el-icon>
									<p class="text-sm truncate">{{ truncateText(example.text, 60) }}</p>
								</div>
							</div>
						</div>

						<!-- Prompt Input Area -->
						<div class="mt-auto">
							<div v-if="selectedHistoryAudioUrl" class="mb-3 w-full text-center">
								<div class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-gray-600 bg-gray-100 rounded-full">
									<el-icon class="mr-1.5"><InfoFilled /></el-icon>您正在收听历史音频，可以编辑描述重新生成
								</div>
							</div>
							<div class="flex items-center p-4 w-full bg-gray-50 rounded-xl border border-gray-200">
								<el-input
									v-model="prompt"
									placeholder="请输入你的音频创作指令... "
									class="flex-grow mr-4"
									@keyup.enter.prevent="handlePromptEnter"
									type="textarea"
									autosize
									:maxlength="500"
									:input-style="{
										border: 'none',
										boxShadow: 'none',
										padding: '8px 0',
										lineHeight: '1.5',
										resize: 'none',
										backgroundColor: selectedHistoryAudioUrl ? '#f9f9f9' : 'transparent',
									}"
								/>
								<button
									@click="generateAudio"
									:disabled="!prompt.trim() || isGenerating"
									class="flex flex-shrink-0 justify-center items-center w-14 h-14 text-white rounded-full shadow transition-all duration-200 bg-primary disabled:opacity-50 disabled:cursor-not-allowed hover:shadow-md hover:bg-primary-dark focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"
								>
									<el-icon :size="24" v-if="isGenerating"><Loading /></el-icon>
									<el-icon :size="24" v-else><Promotion /></el-icon>
								</button>
							</div>
						</div>
					</div>
				</div>

				<!-- Right Panel: History -->
				<div class="flex-none w-1/4">
					<div class="h-full bg-white rounded-xl shadow-sm">
						<HistoryPanel
							ref="historyPanelRef"
							title="生成历史"
							material-type="Voice"
							@item-click="handleHistoryItemClick"
							:default-page-size="pageSize"
							:show-time-column="true"
						/>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { Promotion, InfoFilled, ChatLineRound, Headset, VideoCameraFilled, Loading, Timer } from '@element-plus/icons-vue';
import { ElMessage, ElSelect, ElOption, ElSlider } from 'element-plus';
import ModelList from './components/widgets/modelList.vue';
import HistoryPanel, { type HistoryItem } from './components/widgets/historyPanel.vue';
import { genAudio } from '/@/api/knowledge/aiGen'; //需要创建或修改此API
import { Local } from '/@/utils/storage';

// 文本截断的辅助函数
const truncateText = (text: string, maxLength: number) => {
	return text?.length > maxLength ? text.substring(0, maxLength) + '...' : text || '';
};

// 左侧面板: 控制数据
const modelListComponent = ref<any>(null); // 模型选择组件引用

const voices = ref([
	{ label: 'Alex', value: 'alex' },
	{ label: 'Anna', value: 'anna' },
	{ label: 'Bella', value: 'bella' },
	{ label: 'Benjamin', value: 'benjamin' },
	{ label: 'Charles', value: 'charles' },
	{ label: 'Claire', value: 'claire' },
	{ label: 'David', value: 'david' },
	{ label: 'Diana', value: 'diana' },
]);
const selectedVoice = ref('alex'); // 默认音色
const speechRate = ref(1.0); // 默认倍速
const volumeGain = ref(0.0); // 默认音量增益

// 中间面板: 数据
const generatedAudioUrl = ref<string | null>(null); // 当前生成的音频URL
const prompt = ref(''); // 提示词输入
const isGenerating = ref(false); // 是否正在生成音频
const selectedHistoryAudioUrl = ref<string | null>(null); // 选中的历史音频URL
const selectedHistoryPrompt = ref<string | null>(null); // 选中的历史音频的提示

const examplePrompts = ref([
	{ text: '一段平静的钢琴曲，适合冥想。' },
	{ text: '一个男人用深沉的嗓音说出：世界，你好！' },
	{ text: '欢快的背景音乐，带有鸟鸣声。' },
	{ text: '科幻电影中的飞船引擎启动声。' },
	{ text: '暴风雨的声音，包括雷声和雨声。' },
	{ text: '用女声朗读一首关于春天的短诗。' },
]);

// 历史记录和分页相关数据
const pageSize = ref(10);

// 中间面板: 方法
// 处理回车键按下事件
const handlePromptEnter = (event: KeyboardEvent) => {
	if (event.shiftKey) {
		// 允许Shift+Enter换行
		return;
	}
	generateAudio(); // 直接回车则生成音频
};

// 历史面板引用
const historyPanelRef = ref<InstanceType<typeof HistoryPanel> | null>(null);

// 处理历史项目点击
const handleHistoryItemClick = (item: HistoryItem) => {
	if (item.localUrl) {
		// 显示历史音频
		selectedHistoryAudioUrl.value = item.localUrl;
		selectedHistoryPrompt.value = item.prompt || '历史音频';
		// 应用提示词
		prompt.value = item.prompt || '';
		// 如果历史项包含音色等参数，也在此处恢复
		// selectedVoice.value = item.params?.voice || 'alex';
		// speechRate.value = item.params?.rate || 1.0;
	} else {
		ElMessage.info('该记录没有音频文件');
	}
};

// 生成音频的核心方法
const generateAudioCore = async () => {
	if (!prompt.value.trim()) {
		ElMessage.warning('请输入音频描述!');
		return;
	}

	isGenerating.value = true;
	generatedAudioUrl.value = null; // 清除之前的音频
	selectedHistoryAudioUrl.value = null; // 清除选中的历史音频

	try {
		// 获取本地存储的选中模型
		const selectedModel = Local.get(`selectedAiModel:Voice`);
		if (!selectedModel || !selectedModel.name) {
			ElMessage.error('请先选择一个有效的AI模型');
			isGenerating.value = false;
			return;
		}

		// 准备API调用参数
		const params = {
			model: selectedModel.name, // 选中的AI模型名称
			voice: selectedVoice.value, // 选择的音色
			speed: speechRate.value, // 语速
			gain: volumeGain.value, // 音量增益
			input: prompt.value, // 文本提示
		};

		// 调用API生成音频
		const { data: audioUrl } = await genAudio(params); // genAudio是假设的API方法
		if (audioUrl) {
			generatedAudioUrl.value = audioUrl;
			ElMessage.success('音频生成成功!');

			// 生成成功后刷新历史记录
			historyPanelRef.value?.refreshHistory();
		} else {
			ElMessage.error('音频生成失败, 请稍后重试');
		}
	} catch (error) {
		const errorMessage = error instanceof Error ? error.message : 'Unknown error';
		ElMessage.error(`生成音频时发生错误: ${errorMessage}`);
	} finally {
		isGenerating.value = false; // 无论成功或失败，都重置生成状态
	}
};

// 对外暴露的生成音频方法（可能用于快捷键等）
const generateAudio = () => {
	generateAudioCore();
};
</script>
