/**
 * 多媒体管理系统 - 图片选择器
 * 提供图片上传、选择和管理功能
 */

(function() {
    'use strict';

    // 获取CSRF Token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // 图片选择器类
    class MediaPicker {
        constructor(options = {}) {
            this.options = {
                multiple: false,  // 是否允许多选
                fileType: 'image', // 文件类型：image/file/all
                onSelect: null,    // 选择回调
                maxSize: 10,       // 最大文件大小（MB）
                ...options
            };

            this.csrfToken = getCookie('csrftoken');
            this.selectedFiles = [];
            this.currentPage = 1;
            this.totalPages = 1;

            this.init();
        }

        init() {
            this.createModal();
            this.loadFiles();
        }

        createModal() {
            // 创建模态框HTML
            const modalHTML = `
                <div id="media-picker-modal" class="media-picker-modal" style="display: none;">
                    <div class="media-picker-overlay"></div>
                    <div class="media-picker-container">
                        <div class="media-picker-header">
                            <h3>选择${this.options.fileType === 'image' ? '图片' : '文件'}</h3>
                            <button class="media-picker-close">&times;</button>
                        </div>

                        <div class="media-picker-toolbar">
                            <div class="media-picker-search">
                                <input type="text" id="media-search-input" placeholder="搜索文件...">
                            </div>
                            <div class="media-picker-upload">
                                <label for="media-file-input" class="btn-upload">
                                    上传文件
                                </label>
                                <input type="file" id="media-file-input" ${this.options.multiple ? 'multiple' : ''}
                                       accept="${this.getAcceptTypes()}" style="display: none;">
                            </div>
                        </div>

                        <div class="media-picker-content">
                            <div id="media-files-grid" class="media-files-grid">
                                <div class="loading">加载中...</div>
                            </div>
                        </div>

                        <div class="media-picker-footer">
                            <div class="media-picker-pagination">
                                <button id="prev-page" disabled>上一页</button>
                                <span id="page-info">第 1 页</span>
                                <button id="next-page">下一页</button>
                            </div>
                            <div class="media-picker-actions">
                                <button id="btn-cancel" class="btn-cancel">取消</button>
                                <button id="btn-select" class="btn-select" disabled>选择</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            // 添加到body
            document.body.insertAdjacentHTML('beforeend', modalHTML);

            // 绑定事件
            this.bindEvents();
        }

        getAcceptTypes() {
            if (this.options.fileType === 'image') {
                return 'image/*';
            } else if (this.options.fileType === 'file') {
                return '*/*';
            }
            return '*/*';
        }

        bindEvents() {
            const modal = document.getElementById('media-picker-modal');

            // 关闭按钮
            modal.querySelector('.media-picker-close').addEventListener('click', () => {
                this.close();
            });

            // 点击遮罩关闭
            modal.querySelector('.media-picker-overlay').addEventListener('click', () => {
                this.close();
            });

            // 取消按钮
            modal.querySelector('#btn-cancel').addEventListener('click', () => {
                this.close();
            });

            // 选择按钮
            modal.querySelector('#btn-select').addEventListener('click', () => {
                this.selectFiles();
            });

            // 文件上传
            modal.querySelector('#media-file-input').addEventListener('change', (e) => {
                this.uploadFiles(e.target.files);
            });

            // 搜索
            let searchTimeout;
            modal.querySelector('#media-search-input').addEventListener('input', (e) => {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    this.currentPage = 1;
                    this.loadFiles(e.target.value);
                }, 500);
            });

            // 分页
            modal.querySelector('#prev-page').addEventListener('click', () => {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.loadFiles();
                }
            });

            modal.querySelector('#next-page').addEventListener('click', () => {
                if (this.currentPage < this.totalPages) {
                    this.currentPage++;
                    this.loadFiles();
                }
            });
        }

        async loadFiles(search = '') {
            const grid = document.getElementById('media-files-grid');
            grid.innerHTML = '<div class="loading">加载中...</div>';

            try {
                const params = new URLSearchParams({
                    page: this.currentPage,
                    page_size: 20
                });

                if (this.options.fileType !== 'all') {
                    params.append('file_type', this.options.fileType);
                }

                if (search) {
                    params.append('search', search);
                }

                const response = await fetch(`/blog/api/media/list/?${params}`);
                const data = await response.json();

                if (data.success) {
                    this.displayFiles(data.files);
                    this.totalPages = data.total_pages;
                    this.updatePagination();
                } else {
                    grid.innerHTML = '<div class="error">加载失败</div>';
                }
            } catch (error) {
                console.error('加载文件列表失败:', error);
                grid.innerHTML = '<div class="error">加载失败</div>';
            }
        }

        displayFiles(files) {
            const grid = document.getElementById('media-files-grid');

            if (files.length === 0) {
                grid.innerHTML = '<div class="empty">暂无文件</div>';
                return;
            }

            grid.innerHTML = files.map(file => {
                const isSelected = this.selectedFiles.some(f => f.id === file.id);
                return `
                    <div class="media-file-item ${isSelected ? 'selected' : ''}" data-file-id="${file.id}">
                        <div class="media-file-preview">
                            ${file.file_type === 'image'
                                ? `<img src="${file.thumbnail_url}" alt="${file.original_filename}">`
                                : '<div class="file-icon">📄</div>'}
                        </div>
                        <div class="media-file-info">
                            <div class="media-file-name" title="${file.original_filename}">
                                ${file.original_filename}
                            </div>
                            <div class="media-file-meta">
                                ${file.file_size_readable}
                            </div>
                        </div>
                        <div class="media-file-check">
                            <span class="checkmark">✓</span>
                        </div>
                    </div>
                `;
            }).join('');

            // 绑定点击事件
            grid.querySelectorAll('.media-file-item').forEach(item => {
                item.addEventListener('click', () => {
                    const fileId = parseInt(item.dataset.fileId);
                    const file = files.find(f => f.id === fileId);
                    this.toggleFileSelection(file, item);
                });
            });
        }

        toggleFileSelection(file, element) {
            const index = this.selectedFiles.findIndex(f => f.id === file.id);

            if (index > -1) {
                // 取消选择
                this.selectedFiles.splice(index, 1);
                element.classList.remove('selected');
            } else {
                // 选择
                if (!this.options.multiple) {
                    // 单选模式，清除之前的选择
                    this.selectedFiles = [file];
                    document.querySelectorAll('.media-file-item.selected').forEach(el => {
                        el.classList.remove('selected');
                    });
                    element.classList.add('selected');
                } else {
                    // 多选模式
                    this.selectedFiles.push(file);
                    element.classList.add('selected');
                }
            }

            // 更新选择按钮状态
            const btnSelect = document.getElementById('btn-select');
            btnSelect.disabled = this.selectedFiles.length === 0;
        }

        async uploadFiles(files) {
            if (!files || files.length === 0) return;

            const maxSize = this.options.maxSize * 1024 * 1024;

            for (let file of files) {
                if (file.size > maxSize) {
                    alert(`文件 ${file.name} 超过大小限制（${this.options.maxSize}MB）`);
                    continue;
                }

                await this.uploadSingleFile(file);
            }

            // 重新加载文件列表
            this.loadFiles();

            // 清空文件输入
            document.getElementById('media-file-input').value = '';
        }

        async uploadSingleFile(file) {
            const formData = new FormData();
            formData.append('file', file);
            formData.append('is_public', 'true');

            try {
                const response = await fetch('/blog/api/media/upload/', {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': this.csrfToken
                    },
                    credentials: 'same-origin',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    this.showMessage('上传成功', 'success');
                } else {
                    this.showMessage(data.message || '上传失败', 'error');
                }
            } catch (error) {
                console.error('上传失败:', error);
                this.showMessage('上传失败', 'error');
            }
        }

        selectFiles() {
            if (this.options.onSelect && typeof this.options.onSelect === 'function') {
                this.options.onSelect(this.selectedFiles);
            }
            this.close();
        }

        updatePagination() {
            const prevBtn = document.getElementById('prev-page');
            const nextBtn = document.getElementById('next-page');
            const pageInfo = document.getElementById('page-info');

            prevBtn.disabled = this.currentPage === 1;
            nextBtn.disabled = this.currentPage >= this.totalPages;
            pageInfo.textContent = `第 ${this.currentPage} / ${this.totalPages} 页`;
        }

        showMessage(message, type) {
            // 简单的消息提示
            const messageDiv = document.createElement('div');
            messageDiv.className = `media-message media-message-${type}`;
            messageDiv.textContent = message;
            messageDiv.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 15px 20px;
                background: ${type === 'success' ? '#4CAF50' : '#F44336'};
                color: white;
                border-radius: 5px;
                z-index: 10001;
            `;

            document.body.appendChild(messageDiv);

            setTimeout(() => {
                messageDiv.remove();
            }, 3000);
        }

        open() {
            const modal = document.getElementById('media-picker-modal');
            modal.style.display = 'block';
            this.selectedFiles = [];
            this.currentPage = 1;
            this.loadFiles();
        }

        close() {
            const modal = document.getElementById('media-picker-modal');
            modal.style.display = 'none';
            this.selectedFiles = [];
        }
    }

    // 导出到全局
    window.MediaPicker = MediaPicker;

})();
