/**
 * 富文本编辑器 - UEditor风格
 */
var RichEditor = {
    currentId: null,
    
    init: function(id, textareaId) {
        this.currentId = id;
        var container = document.getElementById(id);
        var toolbar = document.createElement('div');
        toolbar.className = 'rich-editor-toolbar';
        toolbar.innerHTML = '<button type="button" onclick="RichEditor.execCmd(\'bold\')" title="加粗"><b>B</b></button>' +
            '<button type="button" onclick="RichEditor.execCmd(\'italic\')" title="斜体"><i>I</i></button>' +
            '<button type="button" onclick="RichEditor.execCmd(\'underline\')" title="下划线"><u>U</u></button>' +
            '<div class="toolbar-divider"></div>' +
            '<button type="button" onclick="RichEditor.execCmd(\'justifyLeft\')" title="左对齐">⬅</button>' +
            '<button type="button" onclick="RichEditor.execCmd(\'justifyCenter\')" title="居中">⬆</button>' +
            '<button type="button" onclick="RichEditor.execCmd(\'justifyRight\')" title="右对齐">➡</button>' +
            '<div class="toolbar-divider"></div>' +
            '<button type="button" onclick="RichEditor.execCmd(\'insertUnorderedList\')" title="无序列表">•</button>' +
            '<button type="button" onclick="RichEditor.execCmd(\'insertOrderedList\')" title="有序列表">1.</button>' +
            '<div class="toolbar-divider"></div>' +
            '<input type="color" id="foreColorPicker" onchange="RichEditor.setColor(this.value)" title="文字颜色" style="width:26px;height:26px;padding:2px;border:1px solid #e2e8f0;cursor:pointer;">' +
            '<div class="toolbar-divider"></div>' +
            '<button type="button" onclick="RichEditor.insertLink()" title="插入链接">🔗</button>' +
            '<button type="button" onclick="RichEditor.insertImage()" title="插入图片">🖼️</button>' +
            '<div class="toolbar-divider"></div>' +
            '<button type="button" onclick="RichEditor.execCmd(\'formatBlock\',\'h2\')" title="大标题">H2</button>' +
            '<button type="button" onclick="RichEditor.execCmd(\'formatBlock\',\'h3\')" title="小标题">H3</button>' +
            '<button type="button" onclick="RichEditor.execCmd(\'formatBlock\',\'p\')" title="段落">P</button>' +
            '<div class="toolbar-divider"></div>' +
            '<button type="button" onclick="RichEditor.execCmd(\'removeFormat\')" title="清除格式" style="color:#ef4444;">X</button>' +
            '<button type="button" onclick="RichEditor.execCmd(\'undo\')" title="撤销">↩</button>' +
            '<button type="button" onclick="RichEditor.execCmd(\'redo\')" title="重做">↪</button>';
        
        var editor = document.createElement('div');
        editor.id = 'editor-' + id;
        editor.className = 'rich-editor-content';
        editor.contentEditable = true;
        editor.innerHTML = document.getElementById(textareaId).value;
        
        var textarea = document.getElementById(textareaId);
        textarea.style.display = 'none';
        
        container.innerHTML = '';
        container.appendChild(toolbar);
        container.appendChild(editor);
        
        var self = this;
        editor.addEventListener('input', function() {
            document.getElementById(textareaId).value = editor.innerHTML;
        });
        
        // 粘贴图片处理
        editor.addEventListener('paste', function(e) {
            var items = e.clipboardData && e.clipboardData.items;
            if (items) {
                for (var i = 0; i < items.length; i++) {
                    if (items[i].type.indexOf('image') !== -1) {
                        e.preventDefault();
                        var file = items[i].getAsFile();
                        RichEditor.uploadImage(file, function(url) {
                            RichEditor.insertImageUrl(url);
                        });
                        break;
                    }
                }
            }
        });
    },
    
    execCmd: function(cmd, value) {
        document.execCommand(cmd, false, value || null);
        var editor = document.querySelector('[id^=editor-]');
        if (editor) {
            var textareaId = editor.parentElement.querySelector('textarea').id;
            document.getElementById(textareaId).value = editor.innerHTML;
        }
    },
    
    setColor: function(color) {
        this.execCmd('foreColor', color);
    },
    
    insertLink: function() {
        var url = prompt('输入链接地址:');
        if (url) this.execCmd('createLink', url);
    },
    
    insertImageUrl: function(url) {
        this.execCmd('insertImage', url);
        this.execCmd('formatBlock', 'p');
    },
    
    insertImage: function() {
        var url = prompt('输入图片地址:');
        if (url) this.insertImageUrl(url);
    },
    
    uploadImage: function(file, callback) {
        if (file.size > 5 * 1024 * 1024) {
            alert('图片大小不能超过5MB');
            return;
        }
        var formData = new FormData();
        formData.append('file', file);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=upload', true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                var d = JSON.parse(xhr.responseText);
                if (d.code === 200) {
                    callback(d.data.url);
                } else {
                    alert(d.msg);
                }
            }
        };
        xhr.send(formData);
    }
};