var uploadPage = {
    uploader: null,

    init: function () {
        var self = this;

        var folderSel = document.getElementById('folder_id');
        if (folderSel) {
            window.currentFolderId = parseInt(folderSel.value || '0') || 0;
            folderSel.addEventListener('change', function () {
                window.currentFolderId = parseInt(this.value || '0') || 0;
            });
        }

        self.initUploader();

        var dropZone = document.getElementById('drop-zone');
        var fileInput = document.getElementById('file-input');

        if (dropZone && fileInput) {
            dropZone.addEventListener('click', function () {
                fileInput.click();
            });

            fileInput.addEventListener('change', function () {
                if (self.uploader && this.files && this.files.length > 0) {
                    self.uploader.addFiles(this.files);
                    this.value = '';
                }
            });

            ['dragenter', 'dragover', 'drop'].forEach(function (evtName) {
                document.addEventListener(evtName, function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                });
            });

            dropZone.addEventListener('dragover', function () {
                this.classList.add('drag-over');
            });

            dropZone.addEventListener('dragleave', function () {
                this.classList.remove('drag-over');
            });

            dropZone.addEventListener('drop', function (e) {
                this.classList.remove('drag-over');
                var files = e.dataTransfer.files;
                if (files && files.length > 0 && self.uploader) {
                    self.uploader.addFiles(files);
                }
            });
        }

        var showHomeChk = document.getElementById('show-home-chk');
        if (showHomeChk && self.uploader) {
            self.uploader.setShowInHome(showHomeChk.checked);
            showHomeChk.addEventListener('change', function () {
                self.uploader.setShowInHome(this.checked);
            });
        }

        var btnStart = document.getElementById('btn-start');
        var btnClear = document.getElementById('btn-clear');
        var btnStartBottom = document.getElementById('btn-start-bottom');
        var btnClearBottom = document.getElementById('btn-clear-bottom');

        if (btnStart) {
            btnStart.addEventListener('click', function () {
                if (self.uploader) self.uploader.start();
            });
        }
        if (btnClear) {
            btnClear.addEventListener('click', function () {
                self.clearCompleted();
            });
        }
        if (btnStartBottom) {
            btnStartBottom.addEventListener('click', function () {
                if (self.uploader) self.uploader.start();
            });
        }
        if (btnClearBottom) {
            btnClearBottom.addEventListener('click', function () {
                self.clearCompleted();
            });
        }

        document.addEventListener('paste', function (e) {
            var items = ((e.clipboardData || window.clipboardData).items) || [];
            var file = null;
            if (items && items.length) {
                for (var i = 0; i < items.length; i++) {
                    if (items[i].type.indexOf('text/') === -1) {
                        file = items[i].getAsFile();
                        break;
                    }
                }
            }
            if (file && self.uploader) {
                self.uploader.addFiles([file]);
            }
        });
    },

    initUploader: function () {
        var self = this;
        if (self.uploader) {
            return;
        }

        self.uploader = new BatchUploader({
            onQueueUpdate: function (queue) {
                self.renderQueue(queue);
            },
            onProgress: function (file, progress, speed) {
                self.renderQueue(self.uploader.queue);
            },
            onSuccess: function (file, res) {
                self.renderQueue(self.uploader.queue);
            },
            onError: function (file, err) {
                self.renderQueue(self.uploader.queue);
            },
            onComplete: function () {
                if (typeof layer !== 'undefined') {
                    layer.msg('所有文件处理完毕');
                }
                setTimeout(function () {
                    window.location.href = './?m=mine';
                }, 800);
            }
        });
    },

    formatSize: function (size) {
        if (size < 1024) return size + ' B';
        if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB';
        if (size < 1024 * 1024 * 1024) return (size / 1024 / 1024).toFixed(2) + ' MB';
        return (size / 1024 / 1024 / 1024).toFixed(2) + ' GB';
    },

    getStatusText: function (status) {
        var map = {
            'pending': '等待中',
            'hashing': '计算哈希',
            'uploading': '上传中',
            'completed': '已完成',
            'error': '失败'
        };
        return map[status] || status;
    },

    getStatusClass: function (status) {
        var map = {
            'pending': 'pending',
            'hashing': 'hashing',
            'uploading': 'uploading',
            'completed': 'completed',
            'error': 'error'
        };
        return map[status] || 'pending';
    },

    renderQueue: function (queue) {
        var tbody = document.getElementById('upload-file-list');
        var queueCount = document.getElementById('queue-count');
        if (!tbody) return;

        if (queueCount) {
            var activeCount = 0;
            for (var i = 0; i < queue.length; i++) {
                if (queue[i].status !== 'completed' && queue[i].status !== 'error') {
                    activeCount++;
                }
            }
            queueCount.textContent = queue.length > 0 ? (activeCount + ' / ' + queue.length) : '0';
        }

        if (queue.length === 0) {
            tbody.innerHTML = '<tr class="empty-queue-row"><td colspan="7"><div class="empty-queue-state"><i class="fa fa-inbox"></i><p>暂无上传任务</p></div></td></tr>';
            return;
        }

        var html = '';
        for (var i = 0; i < queue.length; i++) {
            var f = queue[i];
            var statusText = this.getStatusText(f.status);
            var statusClass = this.getStatusClass(f.status);
            var progressBarClass = f.status === 'completed' ? ' completed' : (f.status === 'error' ? ' error' : '');

            html += '<tr>';
            html += '<td class="file-name-cell" data-label="文件名" title="' + this.escapeHtml(f.file.name) + '">' + this.escapeHtml(f.file.name) + '</td>';
            html += '<td class="file-size-cell" data-label="大小">' + this.formatSize(f.file.size) + '</td>';
            html += '<td data-label="进度"><div class="progress-bar-wrapper"><div class="progress-bar-outer"><div class="progress-bar-inner' + progressBarClass + '" style="width: ' + f.progress + '%">' + f.progress + '%</div></div></div></td>';
            html += '<td class="file-size-cell" data-label="速度">' + (f.speed || '-') + '</td>';
            html += '<td data-label="状态"><span class="status-tag ' + statusClass + '">' + statusText + '</span>';
            if (f.status === 'error' && f.message) {
                html += '<span class="error-msg-text">' + this.escapeHtml(f.message) + '</span>';
            }
            html += '</td>';
            html += '<td data-label="操作"><button class="btn-file-remove" onclick="uploadPage.removeItem(\'' + f.id + '\')" title="移除"><i class="fa fa-times"></i></button></td>';
            html += '</tr>';
        }

        tbody.innerHTML = html;
    },

    escapeHtml: function (str) {
        if (!str) return '';
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(str));
        return div.innerHTML;
    },

    removeItem: function (id) {
        if (this.uploader) {
            this.uploader.removeFile(id);
            this.renderQueue(this.uploader.queue);
        }
    },

    clearCompleted: function () {
        if (!this.uploader) return;
        var queue = this.uploader.queue;
        for (var i = queue.length - 1; i >= 0; i--) {
            if (queue[i].status === 'completed' || queue[i].status === 'error') {
                queue.splice(i, 1);
            }
        }
        this.renderQueue(queue);
    }
};

document.addEventListener('DOMContentLoaded', function () {
    uploadPage.init();
});