/**
 * 文章草稿自动保存功能
 * 定时自动保存编辑中的文章，防止内容丢失
 */

(function() {
    'use strict';

    // 配置
    const CONFIG = {
        AUTO_SAVE_INTERVAL: 30000, // 自动保存间隔（30秒）
        MIN_CONTENT_LENGTH: 10,    // 触发自动保存的最小内容长度
        SESSION_STORAGE_KEY: 'article_draft_session_id',
        LAST_CONTENT_KEY: 'article_draft_last_content'
    };

    // 生成唯一的会话ID
    function generateSessionId() {
        return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }

    // 获取或创建会话ID
    function getSessionId() {
        let sessionId = sessionStorage.getItem(CONFIG.SESSION_STORAGE_KEY);
        if (!sessionId) {
            sessionId = generateSessionId();
            sessionStorage.setItem(CONFIG.SESSION_STORAGE_KEY, sessionId);
        }
        return sessionId;
    }

    // 获取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 ArticleDraftAutoSave {
        constructor(options) {
            this.options = Object.assign({
                titleSelector: '#id_title',
                bodySelector: '#id_body',
                categorySelector: '#id_category',
                tagsSelector: '#id_tags',
                statusSelector: '#id_status',
                commentStatusSelector: '#id_comment_status',
                typeSelector: '#id_type',
                articleIdInput: '#article_id',
                saveApiUrl: '/api/draft/save/',
                getDraftApiUrl: '/api/draft/get/',
                statusElement: '#draft-save-status'
            }, options);

            this.sessionId = getSessionId();
            this.saveTimer = null;
            this.lastContent = '';
            this.isInit = false;

            this.init();
        }

        init() {
            if (this.isInit) return;
            this.isInit = true;

            // 检查是否在文章编辑页面
            const titleElement = document.querySelector(this.options.titleSelector);
            const bodyElement = document.querySelector(this.options.bodySelector);

            if (!titleElement || !bodyElement) {
                console.log('未找到文章编辑器元素，自动保存功能未启动');
                return;
            }

            console.log('文章草稿自动保存功能已启动');

            // 检查是否有未保存的草稿
            this.checkExistingDraft();

            // 启动自动保存
            this.startAutoSave();

            // 监听页面离开事件
            this.setupBeforeUnloadHandler();

            // 创建状态显示元素
            this.createStatusElement();
        }

        // 检查是否有未保存的草稿
        checkExistingDraft() {
            const articleId = this.getArticleId();
            const url = `${this.options.getDraftApiUrl}?${articleId ? 'article_id=' + articleId : 'session_id=' + this.sessionId}`;

            fetch(url, {
                method: 'GET',
                credentials: 'same-origin'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.draft) {
                    this.showDraftRestorePrompt(data.draft);
                }
            })
            .catch(error => {
                console.error('检查草稿失败:', error);
            });
        }

        // 显示草稿恢复提示
        showDraftRestorePrompt(draft) {
            const message = `发现未保存的草稿（最后更新: ${draft.last_update}），是否恢复？`;
            if (confirm(message)) {
                this.restoreDraft(draft);
            }
        }

        // 恢复草稿
        restoreDraft(draft) {
            const titleElement = document.querySelector(this.options.titleSelector);
            const bodyElement = document.querySelector(this.options.bodySelector);
            const categoryElement = document.querySelector(this.options.categorySelector);

            if (titleElement) titleElement.value = draft.title || '';
            if (bodyElement) bodyElement.value = draft.body || '';
            if (categoryElement && draft.category_id) {
                categoryElement.value = draft.category_id;
            }

            this.showStatus('草稿已恢复', 'success');
        }

        // 启动自动保存
        startAutoSave() {
            this.saveTimer = setInterval(() => {
                this.autoSave();
            }, CONFIG.AUTO_SAVE_INTERVAL);

            console.log(`自动保存已启动，间隔: ${CONFIG.AUTO_SAVE_INTERVAL / 1000}秒`);
        }

        // 停止自动保存
        stopAutoSave() {
            if (this.saveTimer) {
                clearInterval(this.saveTimer);
                this.saveTimer = null;
                console.log('自动保存已停止');
            }
        }

        // 执行自动保存
        autoSave() {
            const titleElement = document.querySelector(this.options.titleSelector);
            const bodyElement = document.querySelector(this.options.bodySelector);

            if (!titleElement || !bodyElement) return;

            const title = titleElement.value || '';
            const body = bodyElement.value || '';
            const currentContent = title + body;

            // 检查内容是否有变化且长度足够
            if (currentContent === this.lastContent || currentContent.length < CONFIG.MIN_CONTENT_LENGTH) {
                return;
            }

            this.saveDraft();
        }

        // 保存草稿
        saveDraft() {
            const titleElement = document.querySelector(this.options.titleSelector);
            const bodyElement = document.querySelector(this.options.bodySelector);
            const categoryElement = document.querySelector(this.options.categorySelector);
            const tagsElement = document.querySelector(this.options.tagsSelector);

            if (!titleElement || !bodyElement) return;

            const title = titleElement.value || '';
            const body = bodyElement.value || '';
            const category_id = categoryElement ? categoryElement.value : null;
            const article_id = this.getArticleId();

            // 获取标签
            let tags = [];
            if (tagsElement) {
                const selectedOptions = tagsElement.selectedOptions;
                for (let i = 0; i < selectedOptions.length; i++) {
                    tags.push(parseInt(selectedOptions[i].value));
                }
            }

            const data = {
                title: title,
                body: body,
                category_id: category_id ? parseInt(category_id) : null,
                tags: tags,
                article_id: article_id ? parseInt(article_id) : null,
                session_id: this.sessionId,
                status: 'd',
                comment_status: 'o',
                type: 'a'
            };

            this.showStatus('正在保存...', 'info');

            fetch(this.options.saveApiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                credentials: 'same-origin',
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.lastContent = title + body;
                    this.showStatus(`已自动保存 (${data.last_update})`, 'success');
                    console.log('草稿已保存:', data);
                } else {
                    this.showStatus('保存失败', 'error');
                    console.error('保存草稿失败:', data.message);
                }
            })
            .catch(error => {
                this.showStatus('保存失败', 'error');
                console.error('保存草稿失败:', error);
            });
        }

        // 获取文章ID
        getArticleId() {
            const articleIdInput = document.querySelector(this.options.articleIdInput);
            if (articleIdInput) {
                return articleIdInput.value;
            }

            // 尝试从URL获取
            const match = window.location.pathname.match(/\/article\/\d+\/\d+\/\d+\/(\d+)\.html/);
            if (match) {
                return match[1];
            }

            return null;
        }

        // 创建状态显示元素
        createStatusElement() {
            let statusElement = document.querySelector(this.options.statusElement);
            if (!statusElement) {
                statusElement = document.createElement('div');
                statusElement.id = this.options.statusElement.replace('#', '');
                statusElement.style.cssText = 'position: fixed; bottom: 20px; right: 20px; padding: 10px 20px; ' +
                    'background: #f0f0f0; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.2); ' +
                    'font-size: 14px; z-index: 9999; display: none;';
                document.body.appendChild(statusElement);
            }
        }

        // 显示状态
        showStatus(message, type) {
            const statusElement = document.querySelector(this.options.statusElement);
            if (!statusElement) return;

            const colors = {
                'info': '#2196F3',
                'success': '#4CAF50',
                'error': '#F44336'
            };

            statusElement.textContent = message;
            statusElement.style.background = colors[type] || '#f0f0f0';
            statusElement.style.color = type === 'info' ? '#333' : '#fff';
            statusElement.style.display = 'block';

            setTimeout(() => {
                statusElement.style.display = 'none';
            }, 3000);
        }

        // 设置页面离开前的警告
        setupBeforeUnloadHandler() {
            window.addEventListener('beforeunload', (e) => {
                const titleElement = document.querySelector(this.options.titleSelector);
                const bodyElement = document.querySelector(this.options.bodySelector);

                if (titleElement && bodyElement) {
                    const content = titleElement.value + bodyElement.value;
                    if (content.length > CONFIG.MIN_CONTENT_LENGTH && content !== this.lastContent) {
                        e.preventDefault();
                        e.returnValue = '您有未保存的更改，确定要离开吗？';
                        return e.returnValue;
                    }
                }
            });
        }
    }

    // 自动初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            window.articleDraftAutoSave = new ArticleDraftAutoSave();
        });
    } else {
        window.articleDraftAutoSave = new ArticleDraftAutoSave();
    }

})();
