<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 SparkMD5 from 'spark-md5';
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 uploadHistory = ref([]);
const STORAGE_KEY = 'media_upload_history';

// Add max file size constant (100MB)
const MAX_FILE_SIZE = 300 * 1024 * 1024;
const MAX_FILE_SIZE_DISPLAY = '300MB';

// 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;
};

// Clear completed uploads
const clearCompleted = () => {
    uploadHistory.value = [];
    saveUploadHistory();
};

// Add pending uploads state
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);
};

// Add file size check
const checkFileSize = (file) => {
    if (file.size > MAX_FILE_SIZE) {
        toast.add({
            severity: 'error',
            summary: '错误',
            detail: `文件大小超过限制 (最大 ${MAX_FILE_SIZE_DISPLAY})`,
            life: 3000
        });
        return false;
    }
    return true;
};

const handleFiles = async (files) => {
    // Filter out files that are too large
    const validFiles = Array.from(files).filter(checkFileSize);
    if (validFiles.length > 0) {
        addToUploadQueue(validFiles);
        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 {
        const md5Hash = await calculateMD5(nextFile.file);
        // get file ext
        const fileExt = nextFile.file.name.split('.').pop();

        console.log(nextFile.file)
        // Check if file exists before upload
        const checkResult = await mediaService.preUploadedCheck(md5Hash, fileExt, nextFile.file.type);

        if (checkResult.data.exists) {
            // Skip upload and mark as completed
            uploadQueue.value.shift();
            addToHistory(nextFile.file, 'completed');
            toast.add({
                severity: 'info',
                summary: '提示',
                detail: '文件已存在，已跳过上传',
                life: 3000
            });
        } else {
            // Proceed with upload using pre-signed URL
            await uploadFile(nextFile.file, md5Hash, checkResult.data.pre_sign);
            uploadQueue.value.shift();
            addToHistory(nextFile.file, 'completed');
        }
    } catch (error) {
        console.error('Failed to process 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;
    }
};

// Add MD5 calculation function
const calculateMD5 = (file) => {
    return new Promise((resolve, reject) => {
        const chunkSize = 2097152; // 2MB
        const chunks = Math.ceil(file.size / chunkSize);
        let currentChunk = 0;
        const spark = new SparkMD5.ArrayBuffer();
        const fileReader = new FileReader();

        fileReader.onload = (e) => {
            spark.append(e.target.result);
            currentChunk++;

            if (currentChunk < chunks) {
                loadNext();
            } else {
                resolve(spark.end());
            }
        };

        fileReader.onerror = (e) => {
            reject(e);
        };

        function loadNext() {
            const start = currentChunk * chunkSize;
            const end = start + chunkSize >= file.size ? file.size : start + chunkSize;
            fileReader.readAsArrayBuffer(file.slice(start, end));
        }

        loadNext();
    });
};

// Modify uploadFile function to use pre-signed URL
const uploadFile = async (file, md5Hash, preSign) => {
    try {
        currentFile.value = file;
        isUploading.value = true;
        uploadProgress.value = 0;

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

            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) {
                        // Send additional info to backend after successful upload
                        mediaService.uploadedSuccess({
                            originalName: file.name,
                            md5: md5Hash,
                            mimeType: file.type,
                            size: file.size
                        }).then(() => {
                            resolve(xhr.response);
                        }).catch(reject);
                    } else {
                        reject(new Error(`Upload failed with status: ${xhr.status}`));
                    }
                }
            };

            xhr.open(preSign.Method, preSign.URL, true);

            // Add signed headers if provided
            if (preSign.SignedHeaders) {
                Object.entries(preSign.SignedHeaders).forEach(([key, value]) => {
                    xhr.setRequestHeader(key, value);
                });
            }

            xhr.send(file);
        });

        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 py-36">
                            <i class="pi pi-cloud-upload text-6xl! text-gray-500 mb-4"></i>
                            <p class="text-gray-600 text-2xl! font-bold text-center mb-2">拖拽文件到此处或点击上传</p>
                            <p class="text-gray-400 text-sm text-center">支持: MP4, JPG, PNG, GIF, MP4, PDF, DOC</p>
                            <p class="text-gray-400 text-sm text-center mt-1">单个文件最大 {{ MAX_FILE_SIZE_DISPLAY }}</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 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>
