<template>
    <div class="video-audio-extract h-full">
        <!-- 头部标题 -->
        <div class="p-6 border-b border-gray-200">
            <div class="flex items-center">
                <i class="iconfont icon-audio text-2xl mr-3 text-blue-600"></i>
                <div>
                    <h2 class="text-xl font-bold text-gray-900">{{ t("视频音频提取") }}</h2>
                    <p class="text-sm text-gray-600">{{ t("从视频文件中提取音频轨道") }}</p>
                </div>
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="p-6">
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <!-- 左侧：输入设置 -->
                <div class="space-y-6">
                    <!-- 视频文件选择 -->
                    <div class="bg-gray-50 rounded-lg p-6">
                        <h3 class="text-lg font-semibold mb-4 flex items-center">
                            <i class="iconfont icon-video mr-2 text-blue-500"></i>
                            {{ t("选择视频文件") }}
                        </h3>

                        <div class="space-y-4">
                            <!-- 文件选择按钮 -->
                            <a-button
                                type="primary"
                                size="large"
                                block
                                @click="selectVideoFile"
                                :loading="false"
                            >
                                <i class="iconfont icon-folder-open mr-2"></i>
                                {{ videoFile ? t("重新选择") : t("选择视频文件") }}
                            </a-button>

                            <!-- 已选择的文件 -->
                            <div v-if="videoFile" class="bg-white p-4 rounded-lg border border-gray-200">
                                <div class="flex items-center justify-between">
                                    <div class="flex items-center flex-1">
                                        <i class="iconfont icon-video text-blue-500 mr-3"></i>
                                        <div class="flex-1">
                                            <p class="font-medium text-gray-900 truncate">{{ videoFileName }}</p>
                                            <p class="text-sm text-gray-500">{{ formatFileSize(fileSize) }}</p>
                                        </div>
                                    </div>
                                    <a-button type="text" @click="removeVideoFile">
                                        <i class="iconfont icon-close text-red-500"></i>
                                    </a-button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 输出设置 -->
                    <div class="bg-gray-50 rounded-lg p-6">
                        <h3 class="text-lg font-semibold mb-4 flex items-center">
                            <i class="iconfont icon-settings mr-2 text-green-500"></i>
                            {{ t("输出设置") }}
                        </h3>

                        <div class="space-y-4">
                            <!-- 音频格式 -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    {{ t("音频格式") }}
                                </label>
                                <a-select
                                    v-model="extractSettings.format"
                                    class="w-full"
                                    size="large"
                                >
                                    <a-option value="mp3">MP3 ({{ t("推荐") }})</a-option>
                                    <a-option value="wav">WAV ({{ t("无损") }})</a-option>
                                    <a-option value="aac">AAC</a-option>
                                    <a-option value="m4a">M4A</a-option>
                                </a-select>
                            </div>

                            <!-- 音频质量 -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    {{ t("音频质量") }}
                                </label>
                                <a-select
                                    v-model="extractSettings.quality"
                                    class="w-full"
                                    size="large"
                                >
                                    <a-option value="320">{{ t("高质量") }} 320kbps</a-option>
                                    <a-option value="256">{{ t("中等质量") }} 256kbps</a-option>
                                    <a-option value="192">{{ t("标准质量") }} 192kbps</a-option>
                                    <a-option value="128">{{ t("压缩质量") }} 128kbps</a-option>
                                </a-select>
                            </div>

                            <!-- 采样率 -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    {{ t("采样率") }}
                                </label>
                                <a-select
                                    v-model="extractSettings.sampleRate"
                                    class="w-full"
                                    size="large"
                                >
                                    <a-option value="44100">44.1 kHz ({{ t("CD质量") }})</a-option>
                                    <a-option value="48000">48 kHz ({{ t("专业质量") }})</a-option>
                                    <a-option value="22050">22.05 kHz ({{ t("节省空间") }})</a-option>
                                </a-select>
                            </div>
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="space-y-3">
                        <a-button
                            type="primary"
                            size="large"
                            block
                            :loading="isExtracting"
                            :disabled="!videoFile"
                            @click="startExtraction"
                        >
                            <i class="iconfont icon-download mr-2"></i>
                            {{ isExtracting ? t("提取中...") : t("开始提取") }}
                        </a-button>

                        <a-button
                            type="outline"
                            size="large"
                            block
                            :disabled="!outputFile || isExtracting"
                            @click="openOutputFolder"
                        >
                            <i class="iconfont icon-folder mr-2"></i>
                            {{ t("打开输出文件夹") }}
                        </a-button>
                    </div>
                </div>

                <!-- 右侧：预览和结果 -->
                <div class="space-y-6">
                    <!-- 进度显示 -->
                    <div v-if="isExtracting" class="bg-blue-50 rounded-lg p-6">
                        <h3 class="text-lg font-semibold mb-4 text-blue-900">
                            {{ t("提取进度") }}
                        </h3>

                        <div class="space-y-4">
                            <a-progress
                                :percent="extractProgress"
                                :status="extractProgress === 100 ? 'success' : 'normal'"
                            />

                            <div class="text-sm text-blue-700">
                                <p v-if="extractProgress === 0">{{ t("准备开始提取...") }}</p>
                                <p v-else-if="extractProgress < 100">
                                    {{ t("正在提取音频") }}... {{ extractProgress }}%
                                </p>
                                <p v-else class="text-green-600 font-medium">
                                    {{ t("提取完成！") }}
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- 结果显示 -->
                    <div v-if="outputFile && !isExtracting" class="bg-green-50 rounded-lg p-6">
                        <h3 class="text-lg font-semibold mb-4 text-green-900">
                            {{ t("提取结果") }}
                        </h3>

                        <div class="space-y-4">
                            <div class="bg-white p-4 rounded-lg border border-green-200">
                                <div class="flex items-center justify-between">
                                    <div class="flex items-center flex-1">
                                        <i class="iconfont icon-audio text-green-500 mr-3"></i>
                                        <div class="flex-1">
                                            <p class="font-medium text-gray-900">{{ outputFileName }}</p>
                                            <p class="text-sm text-gray-500">{{ formatFileSize(outputFileSize) }}</p>
                                        </div>
                                    </div>
                                    <div class="flex space-x-2">
                                        <a-button type="text" @click="previewAudio">
                                            <i class="iconfont icon-play text-blue-500"></i>
                                        </a-button>
                                        <a-button type="text" @click="openOutputFile">
                                            <i class="iconfont icon-folder text-green-500"></i>
                                        </a-button>
                                    </div>
                                </div>
                            </div>

                            <div class="flex space-x-3">
                                <a-button type="primary" block @click="startExtraction">
                                    <i class="iconfont icon-refresh mr-2"></i>
                                    {{ t("重新提取") }}
                                </a-button>
                            </div>
                        </div>
                    </div>

                    <!-- 使用说明 -->
                    <div class="bg-gray-50 rounded-lg p-6">
                        <h3 class="text-lg font-semibold mb-4 text-gray-900">
                            <i class="iconfont icon-info mr-2"></i>
                            {{ t("使用说明") }}
                        </h3>

                        <div class="space-y-3 text-sm text-gray-600">
                            <div class="flex items-start">
                                <span class="text-blue-500 mr-2">1.</span>
                                <span>{{ t("选择要提取音频的视频文件") }}</span>
                            </div>
                            <div class="flex items-start">
                                <span class="text-blue-500 mr-2">2.</span>
                                <span>{{ t("设置输出音频格式和质量参数") }}</span>
                            </div>
                            <div class="flex items-start">
                                <span class="text-blue-500 mr-2">3.</span>
                                <span>{{ t("点击开始提取按钮进行处理") }}</span>
                            </div>
                            <div class="flex items-start">
                                <span class="text-blue-500 mr-2">4.</span>
                                <span>{{ t("提取完成后可在输出文件夹找到音频文件") }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 音频预览对话框 -->
        <a-modal
            v-model:visible="showPreviewDialog"
            :title="t('音频预览')"
            width="600px"
            @cancel="closePreviewDialog"
        >
            <div class="p-4">
                <audio
                    ref="audioPlayer"
                    controls
                    class="w-full"
                    :src="outputFile"
                >
                    {{ t("您的浏览器不支持音频播放") }}
                </audio>
            </div>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import {ref, reactive, computed} from 'vue';
import {t} from '../../lang';
import {Message} from '@arco-design/web-vue';

// 响应式数据
const videoFile = ref('');
const outputFile = ref('');
const fileSize = ref(0);
const outputFileSize = ref(0);
const isExtracting = ref(false);
const extractProgress = ref(0);
const showPreviewDialog = ref(false);
const audioPlayer = ref(null);

// 提取设置
const extractSettings = reactive({
    format: 'mp3',
    quality: '320',
    sampleRate: '44100'
});

// 计算属性
const videoFileName = computed(() => {
    return videoFile.value ? videoFile.value.split(/[/\\]/).pop() || videoFile.value : '';
});

const outputFileName = computed(() => {
    return outputFile.value ? outputFile.value.split(/[/\\]/).pop() || outputFile.value : '';
});

// 选择视频文件
const selectVideoFile = async () => {
    try {
        const result = await window.$mapi.file.openFile({
            title: t('选择视频文件'),
            filters: [
                {
                    name: t('视频文件'),
                    extensions: ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm']
                }
            ]
        });

        if (result) {
            videoFile.value = result;
            // 获取文件大小
            const stats = await window.$mapi.file.stat(result);
            fileSize.value = stats.size;
            Message.success(t('视频文件选择成功'));
        }
    } catch (error: any) {
        Message.error(t('选择文件失败：') + (error.message || error));
    }
};

// 移除视频文件
const removeVideoFile = () => {
    videoFile.value = '';
    fileSize.value = 0;
    outputFile.value = '';
    outputFileSize.value = 0;
};

// 开始提取
const startExtraction = async () => {
    if (!videoFile.value) {
        Message.error(t('请先选择视频文件'));
        return;
    }

    isExtracting.value = true;
    extractProgress.value = 0;

    try {
        const result = await window.$mapi.ipAgent.extractAudioFromVideoEnhanced({
            videoPath: videoFile.value.replace('file://', ''),
            format: extractSettings.format,
            quality: extractSettings.quality,
            sampleRate: extractSettings.sampleRate,
            outputPath: '' // 自动生成输出路径
        });

        if (result.success) {
            outputFile.value = result.audioPath;
            outputFileSize.value = result.fileSize || 0;
            extractProgress.value = 100;
            Message.success(t('音频提取完成'));
        } else {
            Message.error(result.message || t('提取失败'));
        }
    } catch (error: any) {
        Message.error(t('提取失败：') + (error.message || error));
    } finally {
        isExtracting.value = false;
    }
};

// 打开输出文件夹
const openOutputFolder = async () => {
    try {
        if (outputFile.value) {
            await window.$mapi.shell.showItemInFolder(outputFile.value);
        } else {
            Message.warning(t('无法获取输出文件路径'));
        }
    } catch (error: any) {
        Message.error(t('打开文件夹失败：') + (error.message || error));
    }
};

// 打开输出文件
const openOutputFile = async () => {
    try {
        if (outputFile.value) {
            await window.$mapi.shell.showItemInFolder(outputFile.value);
        }
    } catch (error: any) {
        Message.error(t('打开文件失败：') + (error.message || error));
    }
};

// 预览音频
const previewAudio = () => {
    showPreviewDialog.value = true;
};

// 关闭预览对话框
const closePreviewDialog = () => {
    showPreviewDialog.value = false;
    if (audioPlayer.value) {
        audioPlayer.value.pause();
    }
};

// 格式化文件大小
const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
</script>

<style scoped>
.video-audio-extract {
    min-height: calc(100vh - 120px);
}

.iconfont {
    font-size: 18px;
}
</style>