{% extends base.html %} 

{% block head %}
    {% init codemirror_show_hint = False %}
    {% include common/script/load_codemirror.html %}
    <script type="text/javascript" src="{{_server_home}}/_static/lib/csv.js/csv.js"></script>
    <script type="text/javascript" src="{{_server_home}}/_static/lib/marked/marked.js"></script>
    <script type="text/javascript" src="{{_server_home}}/_static/js/marked-ext.js?ts={{_ts}}"></script>

    <script type="text/javascript" src="{{_server_home}}/_static/lib/webuploader/webuploader.nolog.min.js"></script>
    {% include note/component/css/edit_css.html %}
{% end %} 

{% block body_left %} 

{% init error = "" %} 
{% init download_csv = False %}
{% init edit_token = "" %}

<div class="alert">
    {{error}}
</div>

<form id="mainFrame" action="{{_server_home}}/note/update" enctype="multipart/form-data" method="POST" class="col-md-12">
    <div class="card">
        <!-- note-edit-header -->
        <div class="col-md-12" id="submit-div">
            <div>
                <span id="fileId" class="hide">{{file.id}}</span>
            </div>
            <div class="grid-title btn-line-height">
                <span>文档编辑器 - {{file.name}}</span>
                <div class="float-right">
                    <button class="inline-btn save-note-btn">保存</button>
                    {% include common/button/back_button.html %}
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <!-- note-edit-body -->
        <div class="col-md-12 note-edit-body">
            <span id="result" style="color:green"></span>
            <div class="col-md-12 toolbox">
                <input type="button" id="insertCode" class="toolbox-btn" value="代码" />
                <input type="button" id="insertStrong" class="toolbox-btn" value="加粗" />
                <input type="button" id="insertDel" class="toolbox-btn" value="删除线" />
                <input type="file" id="file" name="file" class="hidden-file" />
                <input type="button" id="uploadBtn" class="toolbox-btn" value="文件" onclick="xnote.editor.uploadFile()"/>
                <input type="button" class="toolbox-btn" value="笔记链接" onclick="xnote.note.openDialogToAddLink()"/>
                <input type="button" class="toolbox-btn" value="格式化" onclick="xnote.editor.formatMarkdownTable()" />
                <div class="float-right">
                    <div class="float-left">
                        <span id="uploadProgress" class="upload-progress"></span>
                        <span id="autosaveResult" class="hide float-left">自动保存草稿成功</span>
                        <input type="button" class="toolbox-btn right btn-primary" 
                            onclick="togglePreview(this)" value="预览" />
                    </div>
                </div>
            </div>

            <div class="col-md-12" id="editor-area">
                <div id="edit-div">
                    <input class="hide" name="id" value="{{file.id}}" />
                    <input type="text" name="version" value="{{file.version}}" class="hide" />
                    <input type="text" name="type" value="md" class="hide" />
                    <input type="hidden" name="edit_token", value="{{edit_token}}">
                </div>

                <div class="col-md-12">
                    <div id="editor" class="col-md-12" style="height: auto; ">
                        <div id="markdown-input-div" class="col-md-12">
                            <textarea id="markdown-input" class="form-control" name="content" rows=50>{{file.content}}</textarea>
                        </div>

                        <div id="markdown-output-div" class="col-md-6 hide"></div>
                    </div>
                </div>
            </div>
            
        </div>
    </div>
</form>

<script type="text/javascript">
    function codeInsert(code) {
        codeMirror.replaceSelection(code, 'around');
    }

    // 注册到xnote的接口中
    xnote.editor.codeInsert = codeInsert;
    xnote.editor.lastKeyUpTime = 0;
    xnote.state.reloadDraft = false;

    function initMdCodeMirror() {
        if (window.codeMirror) {
            return;
        }
        var height = Math.max(500, $("#markdown-output-div").height());
        var editor = $("#markdown-input")[0];

        if ($("#markdown-input").text() == "") {
            $("#markdown-input").text("\n\n\n\n\n");
        }

        window.codeMirror = initCodeMirror("#markdown-input", {
            mode: "text/x-markdown",
            height: "auto"
        });

        xnote.codeMirror = window.codeMirror;
    }

    function initEditor() {
        var clientWidth = document.body.clientWidth;
        if (clientWidth < 1000) {
            // 至少需要500px方便编写
            mobileEdit();
            return;
        }
        initMdCodeMirror();
    }

    function mobileEdit() {
        window.location.href = "/note/edit?id={{file.id}}&device=mobile";
    }

    function togglePreview(target) {
        if ($("#markdown-input-div").hasClass("col-md-12")) {
            // 开启预览
            // 全屏模式
            $("#markdown-input-div").addClass("col-md-6").removeClass("col-md-12");
            $("#markdown-output-div").removeClass("hide");
            $(target).val("关闭预览");

            // 强制刷新页面
            updatePreview(true);
        } else {
            // 半屏模式
            $("#markdown-input-div").removeClass("col-md-6").addClass("col-md-12");
            $("#markdown-output-div").addClass("hide");
            $(target).val("预览");
        }
        // 重新初始化codeMirror
        codeMirror.setSize("auto", "auto");
    }

    $(document).ready(function () {
        var oldContent = $("#markdown-input").val();
        var lastSaved = $("#markdown-input").val();
        var fileId = $("#fileId").text();
        var updatePreviewIntervalId = null;

        function contentUnchanged() {
            var input = $("#markdown-input").val();
            return input == oldContent;
        }

        window.updatePreview = function(force) {
            var input = $("#markdown-input").val();

            if (force === undefined) {
                force = false;
            }
            
            if (!force && contentUnchanged()) {
                return;
            }

            if ($("#markdown-output-div").hasClass("hide")) {
                return;
            }
            oldContent = input;
            var options = { hideMenu: true };
            marked.parseAndRender(input, "#markdown-output-div", options);
            $("#markdown-output-div").height($("#editor").height());

            xnote.fire("editor.change", {});
        }

        function autoSave(force) {
            var input = $("#markdown-input").val();
            // not modified
            if (force != true && input == lastSaved) {
                return;
            }

            lastSaved = input;
            var params = {
                action: "lock_and_save",
                id: fileId,
                content: input,
                token: "{{edit_token}}",
                version: "{{file.version}}"
            };

            xnote.http.post("/note/draft", params, function (resp) {
                console.log(resp);
                if (resp.code == "success") {
                    $("#autosaveResult").show().fadeOut(1000);
                } else if (resp.code == "conflict") {
                    xnote.codeMirror.options.readOnly = "nocursor"; // 不允许编辑了
                    xnote.confirm(resp.message, function () {
                        // 偷锁编辑
                        stealLockAndEdit();
                    });
                } else if (resp.code == "version_too_low") {
                    xnote.codeMirror.options.readOnly = "nocursor"; // 不允许编辑了
                    xnote.confirm(resp.message, function() {
                        // 重新加载草稿
                        reloadDraft();
                    })
                } else {
                    xnote.toast(resp.message)
                };
            });

            xnote.fire("editor.change", {});
        };

        function stealLockAndEdit() {
            var params = {
                action: "steal_lock",
                id: fileId,
                token: "{{edit_token}}"
            }
            xnote.http.post("/note/draft", params, function (resp) {
                if (resp.code == "success") {
                    if (resp.data != null) {
                        xnote.codeMirror.setValue(resp.data);
                    }
                    xnote.codeMirror.options.readOnly = false; // 开启编辑
                } else {
                    xnote.alert(resp.message);
                }
            });
        }

        function reloadDraft() {
            xnote.state.reloadDraft = true;
            window.location.reload();
        }

        $("#insertCode").on("click", function () {
            var selection = codeMirror.getSelection();
            if (selection != "" && selection != null) {
                if (selection.indexOf('\n') >= 0) {
                    codeMirror.replaceSelection("```" + selection + "```", "around");
                } else {
                    codeMirror.replaceSelection("`" + selection + "`", "around");
                }
            } else {
                codeInsert("```\n[代码]\n```");
            }
        });

        function toggleSurround(chars) {
            var selection = codeMirror.getSelection();
            if (selection.startsWith(chars) && selection.endsWith(chars)) {
                codeMirror.replaceSelection(selection.substring(chars.length, selection.length - chars.length), "around");
            } else {
                codeMirror.replaceSelection(chars + selection + chars, "around");
            }
        }

        $("#insertStrong").on("click", function () {
            toggleSurround("**");
        });

        $("#insertDel").click(function () {
            toggleSurround("~~");
        });

        xnote.note.openDialogToAddLink = function() {
            var result = {};
            result.close = true;
            var options = {};
            options.callback = function (noteList) {
                if (noteList.length > 1) {
                    xnote.toast("只能选择一个笔记");
                    result.close = false;
                    return result;
                }
                for (var i = 0; i < noteList.length; i++) {
                    var noteInfo = noteList[i];
                    var link = "[" + noteInfo.name + "](" + noteInfo.url + ")";
                    codeInsert(link);
                }
                return result;
            }

            xnote.note.openSearchNoteDialog(options);
        };

        // 格式化表格
        xnote.editor.formatMarkdownTable = function () {
            var cursor = codeMirror.getCursor();
            var oldValue = codeMirror.doc.getValue();
            var formatedText = formatMarkdownTable(oldValue);
            // codeMirror.replaceSelection(formatedText, "around");
            if (oldValue != formatedText) {
                // console.log(formatedText);
                codeMirror.doc.setValue(formatedText);
                codeMirror.setCursor(cursor);
            }
        };

        // 文件上传        
        xnote.editor.uploadFile = function () {
            console.log("准备上传文件...");
            xnote.requestUploadAuto("#file", false, function (resp) {
                console.log("上传文件:", resp);
                var fileLink = resp.link;
                codeInsert(fileLink);
            });
        };

        // 通过剪切板上传
        $(document).on("paste", function (e) {
            e.preventDefault();
            xnote.requestUploadByClip(e, '', function (respJson) {
                console.log(respJson);
                var link = respJson.link;
                codeInsert(link);
            });
        });

        function serverSaveNote() {
            var input = $("#markdown-input").val();
            var params = {
                id: fileId,
                content: input,
                type: "md",
                edit_token: "{{edit_token}}",
                version: "{{file.version}}"
            };


            xnote.http.post("/note/save", params, function (resp) {
                console.log("save result:", resp);
                if (resp.success) {
                    if (resp.message) {
                        xnote.toast(resp.message);
                    } else {
                        xnote.toast("保存成功");
                    }
                    window.SUBMIT_FORM = true;
                    window.location.href = resp.data;
                } else {
                    xnote.alert("保存失败:" + resp.message);
                }
            }).fail(function (err) {
                xnote.alert("保存失败:" + err);
            });
        }

        // 保存笔记操作
        $(".save-note-btn").click(function (e) {
            e.preventDefault();
            if (!xnote.config.isMaster) {
                xnote.confirm("当前是从节点运行, 保存后可能被覆盖, 确认保存?", function (resp) {
                    serverSaveNote();
                })
            } else {
                serverSaveNote();
            }
        });

        // 退出确认的询问
        window.onbeforeunload=function(e){
            if (contentUnchanged()) {
                return;
            }
            
            if (xnote.state.reloadDraft) {
                console.log("reload draft");
                return;
            }

            if (window.SUBMIT_FORM) {
                console.log("form is submit");
                return;
            }
            
            var e = window.event||e;  
            e.returnValue = "确定离开当前页面吗？";
        };

        function onPageLoad() {
            initEditor();

            if ("{{_user_config.show_md_preview}}" == "true") {
                togglePreview();
                updatePreview(true);
            } else {
                // do nothing
            }

            updatePreviewIntervalId = setInterval(updatePreview, 200);
            // 调整高度
            adjustHeight("#editor-area", 30);
            window.SUBMIT_FORM = false;

            setInterval(autoSave, 500);

            // 强制执行一次
            autoSave(true);
        };

        function autoFormat() {
            // 体验不行, 先关闭
            // if (!xnote.isTyping()) {
            //     xnote.editor.formatMarkdownTable();
            // }
            // setTimeout(autoFormat, 1000);
        }

        onPageLoad();

        // 自动格式化
        autoFormat();
    });

</script>

<!-- GROUPS: {{file.groups}} -->
{% end %}


{% block body_right %}
    {% include note/component/sidebar/markdown_edit_sidebar.html %}
{% end %}
