<script setup>
import { mediaService } from '@/api/mediaService';
import Badge from 'primevue/badge';
import Button from 'primevue/button';
import Card from 'primevue/card';
import { useToast } from 'primevue/usetoast';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const toast = useToast();
const fileInput = ref(null);
const dropZone = ref(null);
const uploadProgress = ref(0);
const isUploading = ref(false);
const currentFile = ref(null);
const ossConfig = ref(null);

const uploadHistory = ref([]);
const STORAGE_KEY = 'media_upload_history';

// Add computed for completed uploads
const completedUploads = computed(() => {
    return uploadHistory.value.filter(item => item.status === 'completed');
});

// Load history from localStorage
const loadUploadHistory = () => {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved) {
        uploadHistory.value = JSON.parse(saved);
    }
};

// Save history to localStorage
const saveUploadHistory = () => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(uploadHistory.value));
};

// Add file to history
const addToHistory = (file, status = 'uploading') => {
    const historyItem = {
        id: Date.now(),
        name: file.name,
        size: file.size,
        type: file.type,
        status,
        uploadTime: new Date().toISOString(),
        progress: 0
    };
    uploadHistory.value.unshift(historyItem);
    saveUploadHistory();
    return historyItem;
};

// Update history item
const updateHistoryItem = (id, updates) => {
    const index = uploadHistory.value.findIndex(item => item.id === id);
    if (index !== -1) {
        uploadHistory.value[index] = { ...uploadHistory.value[index], ...updates };
        saveUploadHistory();
    }
};

// Clear completed uploads
const clearCompleted = () => {
    uploadHistory.value = uploadHistory.value.filter(item => item.status !== 'completed');
    saveUploadHistory();
};

const getOssToken = async () => {
    try {
        const response = await mediaService.getUploadToken();
        ossConfig.value = response;
    } catch (error) {
        toast.add({ severity: 'error', summary: '错误', detail: '获取上传凭证失败', life: 3000 });
    }
};

// Add pending uploads state
const pendingFiles = ref([]);
const uploadQueue = ref([]);
const currentUploadIndex = ref(-1);

// Add sequential upload management
const addToUploadQueue = (files) => {
    const newFiles = Array.from(files).map(file => ({
        id: Date.now() + Math.random(),
        file,
        progress: 0,
        status: 'pending',
        name: file.name,
        size: file.size,
        type: file.type,
        uploadTime: new Date().toISOString()
    }));
    uploadQueue.value.push(...newFiles);
};

const handleFiles = async (files) => {
    addToUploadQueue(files);
    if (!isUploading.value) {
        processNextUpload();
    }
};

const processNextUpload = async () => {
    if (uploadQueue.value.length === 0) {
        currentUploadIndex.value = -1;
        isUploading.value = false;
        return;
    }

    const nextFile = uploadQueue.value[0];
    currentUploadIndex.value = 0;

    try {
        await uploadFile(nextFile.file);
        uploadQueue.value.shift();
        addToHistory(nextFile.file, 'completed');
    } catch (error) {
        console.error('Failed to upload file:', nextFile.file.name, error);
        uploadQueue.value.shift();
        addToHistory(nextFile.file, 'error');
    }

    processNextUpload();
};

const updateQueueItemProgress = (index, progress) => {
    if (uploadQueue.value[index]) {
        uploadQueue.value[index].progress = progress;
    }
};

// Modify uploadFile function
const uploadFile = async (file) => {
    try {
        currentFile.value = file;
        isUploading.value = true;
        uploadProgress.value = 0;

        if (!ossConfig.value) {
            await getOssToken();
        }

        await new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            const formData = new FormData();

            formData.append('success_action_status', '200');
            formData.append('policy', ossConfig.value.policy);
            formData.append('x-oss-signature', ossConfig.value.signature);
            formData.append('x-oss-signature-version', 'OSS4-HMAC-SHA256');
            formData.append('x-oss-credential', ossConfig.value.x_oss_credential);
            formData.append('x-oss-date', ossConfig.value.x_oss_date);
            formData.append('key', ossConfig.value.dir + file.name);
            formData.append('x-oss-security-token', ossConfig.value.security_token);
            formData.append('callback', ossConfig.value.callback);
            formData.append('file', file);

            xhr.upload.onprogress = (e) => {
                if (e.lengthComputable) {
                    const progress = (e.loaded / e.total) * 100;
                    uploadProgress.value = progress;
                    updateQueueItemProgress(currentUploadIndex.value, progress);
                }
            };

            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        resolve(xhr.response);
                    } else {
                        reject(new Error(`Upload failed with status: ${xhr.status}`));
                    }
                }
            };

            xhr.open('POST', ossConfig.value.host, true);
            xhr.send(formData);
        });

        toast.add({ severity: 'success', summary: '成功', detail: '文件上传成功', life: 3000 });
    } catch (error) {
        toast.add({ severity: 'error', summary: '错误', detail: '文件上传失败', life: 3000 });
        throw error;
    }
};

const onDrop = (e) => {
    e.preventDefault();
    dropZone.value?.classList.remove('border-blue-500', 'bg-blue-50');

    const files = [...e.dataTransfer.files];
    if (files.length > 0) {
        handleFiles(files);
    }
};

const onDragOver = (e) => {
    e.preventDefault();
    dropZone.value?.classList.add('border-blue-500', 'bg-blue-50');
};

const onDragLeave = (e) => {
    e.preventDefault();
    dropZone.value?.classList.remove('border-blue-500', 'bg-blue-50');
};

const onClick = () => {
    fileInput.value?.click();
};

const onFileInputChange = (e) => {
    const files = [...e.target.files];
    if (files.length > 0) {
        handleFiles(files);
    }
    // Reset input value to allow uploading same file again
    e.target.value = '';
};

const goBack = () => {
    router.push('/medias');
};

onMounted(() => {
    loadUploadHistory();
});
</script>

<template>
    <Toast />
    <div class="w-full">
        <div class="flex justify-between items-center mb-6">
            <div class="flex items-center gap-4">
                <Button icon="pi pi-arrow-left" text @click="goBack" />
                <h1 class="text-2xl font-semibold text-gray-800">上传媒体</h1>
            </div>
        </div>

        <div class="grid grid-cols-2 gap-6">
            <!-- Upload Area - Left Column -->
            <Card>
                <template #header>
                    <div class="flex justify-between items-center bg-gray-50 p-4 rounded-t-lg">
                        <h3 class="text-lg font-medium">上传</h3>
                    </div>
                </template>
                <template #content>
                    <input ref="fileInput" type="file" multiple accept="image/*,video/*,audio/*,.pdf,.doc,.docx"
                        class="hidden" @change="onFileInputChange">

                    <div ref="dropZone" @drop="onDrop" @dragover="onDragOver" @dragleave="onDragLeave" @click="onClick"
                        class="border-2 border-dashed border-gray-300 rounded-lg transition-all duration-200 hover:border-blue-500 hover:bg-blue-50 cursor-pointer">
                        <div class="flex flex-col items-center justify-center p-8">
                            <i class="pi pi-cloud-upload text-6xl! text-gray-500 mb-4"></i>
                            <p class="text-gray-600 text-center mb-2">拖拽文件到此处或点击上传</p>
                            <p class="text-gray-400 text-sm text-center">支持: MP4, JPG, PNG, GIF, MP4, PDF, DOC</p>
                        </div>
                    </div>

                    <div v-if="isUploading" class="mt-4">
                        <div class="text-sm mb-2">正在上传: {{ currentFile?.name }}</div>
                        <div class="w-full bg-gray-200 rounded-full h-2.5">
                            <div class="bg-blue-600 h-2.5 rounded-full transition-all duration-300"
                                :style="{ width: uploadProgress + '%' }" />
                        </div>
                        <div class="text-sm mt-2">{{ Math.round(uploadProgress) }}%</div>
                    </div>

                    <!-- Upload Queue -->
                    <div v-if="uploadQueue.length > (isUploading.value ? 1 : 0)" class="mt-6">
                        <h3 class="text-lg font-medium mb-4">等待上传 ({{ uploadQueue.length - (isUploading.value ? 1 : 0)
                            }})
                        </h3>
                        <div class="space-y-4">
                            <div v-for="item in uploadQueue.slice(isUploading.value ? 1 : 0)" :key="item.id"
                                class="p-4 bg-gray-50 rounded-lg">
                                <div class="flex justify-between items-center mb-2">
                                    <span class="text-sm font-medium">{{ item.name }}</span>
                                    <Badge value="等待中" severity="warning" />
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
            </Card>

            <!-- Upload History - Right Column -->
            <Card>
                <template #header>
                    <div class="flex justify-between items-center bg-gray-50 p-4 rounded-t-lg">
                        <h3 class="text-lg font-medium">上传历史</h3>
                        <Button v-if="completedUploads.length" icon="pi pi-trash" text @click="clearCompleted"
                            label="清除已完成" />
                    </div>
                </template>
                <template #content>
                    <div class="space-y-4 max-h-[calc(100vh-200px)] overflow-y-auto">
                        <div v-for="item in uploadHistory.filter(i => i.status !== 'uploading')" :key="item.id"
                            class="p-4 bg-gray-50 rounded-lg">
                            <div class="flex justify-between items-center mb-2">
                                <span class="text-sm font-medium">{{ item.name }}</span>
                                <Badge :value="item.status === 'completed' ? '已完成' :
                                    item.status === 'error' ? '失败' : '上传中'" :severity="item.status === 'completed' ? 'success' :
                                        item.status === 'error' ? 'danger' : 'info'" />
                            </div>
                            <div v-if="item.status !== 'completed'" class="w-full bg-gray-200 rounded-full h-2">
                                <div class="bg-blue-600 h-2 rounded-full transition-all duration-300"
                                    :style="{ width: item.progress + '%' }" />
                            </div>
                            <div class="text-xs text-gray-500 mt-2">
                                {{ new Date(item.uploadTime).toLocaleString() }}
                            </div>
                        </div>
                    </div>
                </template>
            </Card>
        </div>
    </div>
</template>

<style scoped>
.custom-upload :deep(.p-fileupload-buttonbar) {
    display: none;
}

.custom-upload :deep(.p-fileupload-content) {
    padding: 0;
    border: none;
}

.custom-upload :deep(.p-fileupload-choose) {
    display: none;
}
</style>
