<template>
	<div class="digital-human-audio-container">
		<el-card shadow="hover">
			<div class="search-header mb15">
				<el-form :inline="true" :model="queryParams">
					<el-form-item label="音频名称">
						<el-input v-model="queryParams.name" placeholder="请输入音频名称" clearable style="width: 200px" />
					</el-form-item>
					<el-form-item label="音色类型">
						<el-select v-model="queryParams.voiceType" placeholder="请选择音色类型" clearable style="width: 150px">
							<el-option label="男声" value="male" />
							<el-option label="女声" value="female" />
							<el-option label="童声" value="child" />
						</el-select>
					</el-form-item>
					<el-form-item label="状态">
						<el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px">
							<el-option label="启用" :value="1" />
							<el-option label="禁用" :value="0" />
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="handleSearch">
							<el-icon><ele-Search /></el-icon>
							搜索
						</el-button>
						<el-button @click="handleReset">
							<el-icon><ele-Refresh /></el-icon>
							重置
						</el-button>
						<el-button type="success" @click="handleAdd">
							<el-icon><ele-Plus /></el-icon>
							上传音频
						</el-button>
					</el-form-item>
				</el-form>
			</div>

			<!-- 音频资产表格 -->
			<el-table :data="tableData" v-loading="loading" border stripe>
				<el-table-column type="index" label="序号" width="60" align="center" />
				<el-table-column prop="name" label="音频名称" min-width="150" show-overflow-tooltip />
				<el-table-column prop="voiceType" label="音色类型" width="100" align="center">
					<template #default="{ row }">
						<el-tag :type="getVoiceTypeTag(row.voiceType)">{{ getVoiceTypeLabel(row.voiceType) }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="duration" label="时长" width="100" align="center">
					<template #default="{ row }">
						{{ formatDuration(row.duration) }}
					</template>
				</el-table-column>
				<el-table-column prop="fileSize" label="文件大小" width="100" align="center">
					<template #default="{ row }">
						{{ formatFileSize(row.fileSize) }}
					</template>
				</el-table-column>
				<el-table-column prop="sampleRate" label="采样率" width="100" align="center">
					<template #default="{ row }">
						{{ row.sampleRate }}Hz
					</template>
				</el-table-column>
				<el-table-column label="试听" width="200" align="center">
					<template #default="{ row }">
						<div class="audio-player">
							<el-button
								:type="currentPlayingId === row.id ? 'danger' : 'primary'"
								size="small"
								circle
								@click="togglePlay(row)"
							>
								<el-icon>
									<ele-VideoPlay v-if="currentPlayingId !== row.id" />
									<ele-VideoPause v-else />
								</el-icon>
							</el-button>
							<el-progress
								:percentage="currentPlayingId === row.id ? playProgress : 0"
								:show-text="false"
								style="width: 100px; margin-left: 10px"
							/>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="status" label="状态" width="80" align="center">
					<template #default="{ row }">
						<el-switch
							v-model="row.status"
							:active-value="1"
							:inactive-value="0"
							@change="handleStatusChange(row)"
						/>
					</template>
				</el-table-column>
				<el-table-column prop="createdAt" label="创建时间" width="170" align="center" />
				<el-table-column label="操作" width="150" align="center" fixed="right">
					<template #default="{ row }">
						<el-button type="primary" text size="small" @click="handleEdit(row)">编辑</el-button>
						<el-button type="danger" text size="small" @click="handleDelete(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页 -->
			<div class="pagination-container mt15">
				<el-pagination
					v-model:current-page="queryParams.pageNum"
					v-model:page-size="queryParams.pageSize"
					:page-sizes="[10, 20, 50, 100]"
					:total="total"
					layout="total, sizes, prev, pager, next, jumper"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>
		</el-card>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

interface AudioItem {
	id: number;
	name: string;
	voiceType: string;
	duration: number;
	fileSize: number;
	sampleRate: number;
	audioUrl: string;
	status: number;
	createdAt: string;
}

const queryParams = reactive({
	name: '',
	voiceType: '',
	status: undefined as number | undefined,
	pageNum: 1,
	pageSize: 10,
});

const tableData = ref<AudioItem[]>([]);
const total = ref(0);
const loading = ref(false);
const currentPlayingId = ref<number | null>(null);
const playProgress = ref(0);
let progressTimer: ReturnType<typeof setInterval> | null = null;

// 模拟数据
const mockData: AudioItem[] = [
	{
		id: 1,
		name: '商务男声-标准普通话',
		voiceType: 'male',
		duration: 125,
		fileSize: 2048000,
		sampleRate: 44100,
		audioUrl: '',
		status: 1,
		createdAt: '2024-01-15 10:30:00',
	},
	{
		id: 2,
		name: '甜美女声-温柔风格',
		voiceType: 'female',
		duration: 98,
		fileSize: 1536000,
		sampleRate: 44100,
		audioUrl: '',
		status: 1,
		createdAt: '2024-01-14 14:20:00',
	},
	{
		id: 3,
		name: '活泼童声-儿童教育',
		voiceType: 'child',
		duration: 67,
		fileSize: 1024000,
		sampleRate: 22050,
		audioUrl: '',
		status: 1,
		createdAt: '2024-01-13 09:15:00',
	},
	{
		id: 4,
		name: '知性女声-新闻播报',
		voiceType: 'female',
		duration: 156,
		fileSize: 2560000,
		sampleRate: 48000,
		audioUrl: '',
		status: 0,
		createdAt: '2024-01-12 16:45:00',
	},
	{
		id: 5,
		name: '磁性男声-广告配音',
		voiceType: 'male',
		duration: 89,
		fileSize: 1408000,
		sampleRate: 44100,
		audioUrl: '',
		status: 1,
		createdAt: '2024-01-11 11:00:00',
	},
];

// 获取音色类型标签
const getVoiceTypeTag = (type: string) => {
	const tagMap: Record<string, string> = {
		male: 'primary',
		female: 'danger',
		child: 'warning',
	};
	return tagMap[type] || 'info';
};

// 获取音色类型文本
const getVoiceTypeLabel = (type: string) => {
	const labelMap: Record<string, string> = {
		male: '男声',
		female: '女声',
		child: '童声',
	};
	return labelMap[type] || type;
};

// 格式化时长
const formatDuration = (seconds: number) => {
	const mins = Math.floor(seconds / 60);
	const secs = seconds % 60;
	return `${mins}:${secs.toString().padStart(2, '0')}`;
};

// 格式化文件大小
const formatFileSize = (bytes: number) => {
	if (bytes < 1024) return bytes + 'B';
	if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB';
	return (bytes / 1024 / 1024).toFixed(1) + 'MB';
};

// 获取列表数据
const getList = () => {
	loading.value = true;
	setTimeout(() => {
		let filteredData = [...mockData];
		if (queryParams.name) {
			filteredData = filteredData.filter((item) => item.name.includes(queryParams.name));
		}
		if (queryParams.voiceType) {
			filteredData = filteredData.filter((item) => item.voiceType === queryParams.voiceType);
		}
		if (queryParams.status !== undefined) {
			filteredData = filteredData.filter((item) => item.status === queryParams.status);
		}
		tableData.value = filteredData;
		total.value = filteredData.length;
		loading.value = false;
	}, 300);
};

// 播放/暂停
const togglePlay = (row: AudioItem) => {
	if (currentPlayingId.value === row.id) {
		// 停止播放
		currentPlayingId.value = null;
		playProgress.value = 0;
		if (progressTimer) {
			clearInterval(progressTimer);
			progressTimer = null;
		}
	} else {
		// 开始播放
		currentPlayingId.value = row.id;
		playProgress.value = 0;
		if (progressTimer) {
			clearInterval(progressTimer);
		}
		progressTimer = setInterval(() => {
			playProgress.value += 2;
			if (playProgress.value >= 100) {
				currentPlayingId.value = null;
				playProgress.value = 0;
				if (progressTimer) {
					clearInterval(progressTimer);
					progressTimer = null;
				}
			}
		}, 100);
	}
};

const handleSearch = () => {
	queryParams.pageNum = 1;
	getList();
};

const handleReset = () => {
	queryParams.name = '';
	queryParams.voiceType = '';
	queryParams.status = undefined;
	queryParams.pageNum = 1;
	getList();
};

const handleAdd = () => {
	ElMessage.info('上传音频功能开发中...');
};

const handleEdit = (row: AudioItem) => {
	ElMessage.info(`编辑音频: ${row.name}`);
};

const handleDelete = (row: AudioItem) => {
	ElMessageBox.confirm(`确定要删除音频 "${row.name}" 吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		ElMessage.success('删除成功');
		getList();
	});
};

const handleStatusChange = (row: AudioItem) => {
	ElMessage.success(`状态已${row.status === 1 ? '启用' : '禁用'}`);
};

const handleSizeChange = (size: number) => {
	queryParams.pageSize = size;
	queryParams.pageNum = 1;
	getList();
};

const handleCurrentChange = (page: number) => {
	queryParams.pageNum = page;
	getList();
};

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

onUnmounted(() => {
	if (progressTimer) {
		clearInterval(progressTimer);
	}
});
</script>

<style scoped lang="scss">
.digital-human-audio-container {
	padding: 15px;

	.audio-player {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.pagination-container {
		display: flex;
		justify-content: flex-end;
	}
}
</style>
