{% init can_edit = False %}
{% init edit_token = "" %}
{% init show_draft_edit = False %}
{% init show_content = True %}

<style>
/* 预览浮窗样式 */
.preview-popup {
    position: absolute;
    display: none;
    background-color: #fff;
    border: 1px solid #ccc;
    padding: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    max-width: 300px;
    z-index: 100;
}

.preview-popup img {
    max-width: 100%;
}
</style>

{% set-global markdown_content = file.content %}
{% include common/script/load_markdown.html %}

<div class="card">
    {% include "note/component/view_header.html" %}
</div>

<div class="card">
    {% include note/component/note_path.html %}
</div>

<div class="card">
    {% raw note_detail_tab.render() %}
</div>

{% if len(note_alias_list) > 0 %}
<div class="card">
    {% include note/component/view_header_alias.html %}
</div>
{% end %}

{% if show_tag %}
<div class="card btn-line-height">
    {% include note/component/view_header_tag.html %}
</div>
{% end %}

{% if show_relation_row %}
    {% include note/page/note_relation_row.html %}
{% end %}

{% if show_relation %}
    {% include note/page/note_relation.html %}
{% end %}

{% if show_draft_edit %}
<div class="card btn-line-height">
    <span>发现未提交的草稿</span>
    <a href="{{_server_home}}/note/edit?id={{file.id}}&is_iframe={{is_iframe}}&load_draft=true">前往编辑</a>
</div>
{% end %}

{% if show_content %}
<div class="card col-md-12">
    {% if file.content == "" %}
        {% include common/text/empty_text.html %}
    {% end %}
    
    <div class="row">
        <div id="markdown-input-div" class="col-md-6 hide">
            <textarea id="markdown-input" class="form-control" name="content" rows=50>{{file.content}}</textarea>
        </div>

        <div id="markdown-output-div" class="col-md-12 markdown-output-div">

        </div>
    </div>
</div>

<div id="preview_popup_window" class="preview-popup"></div>

<script type="text/javascript">
    $(function () {

        function trimText(text) {
            text = text.trimLeft();
            if (text.indexOf("<ul>") >= 0) {
                return text.split("<ul>")[0];
            }
            if (text.indexOf("<ol>") >= 0) {
                return text.split("<ol>")[0];
            }
            return text;
        }

        function convertTextToNew(text) {
            var newText = text;
            if (newText.startsWith("[]")) {
                return "[x]" + newText.substring(2);
            }
            if (newText.startsWith("[x]") || newText.startsWith("[X]")) {
                return "[]" + newText.substring(3);
            }
            return newText;
        }

        // 编辑csv事件
        xnote.note.openEditCsvDialog = function(target) {
            var oldCode = $(target).attr("data-code");
            var codeIndex = parseInt($(target).attr("data-index"));
            var lang = $(target).attr("data-lang");
            var formattedCode = xnote.csv.formatCode(oldCode);

            xnote.showTextDialog("编辑csv", formattedCode, ["更新", "取消"], function (index, layero, dialogInfo) {
                var newCode = $(layero).find("textarea").val().trim();
                // xnote.alert("newCode:" + newCode);

                if (newCode === oldCode) {
                    return;
                }

                var fenceLeft = "```" + lang + "\n";
                var fenceRight = "\n```";

                oldCode = fenceLeft + oldCode + fenceRight;
                newCode = fenceLeft + newCode + fenceRight;

                var oldContent = $("#markdown-input").val();
                if (oldContent.indexOf(oldCode) < 0) {
                    console.log("text not match:", oldCode);
                    xnote.alert("笔记内容有变化，请刷新页面");
                    return false;
                }

                var newContent = xnote.string.replaceByIndex(oldContent, oldCode, newCode, codeIndex);
                console.log("newContent", newContent);

                var params = {};
                params.id = "{{file.id}}";
                params.content = newContent;
                params.resp_type = "json";
                params.edit_token = "{{edit_token}}";
                params.version = "{{file.version}}";

                xnote.http.post("/note/update", params, function (resp) {
                    if (resp.code == "success") {                    
                        xnote.toast("更新成功，正在刷新页面");
                        window.location.reload();
                    } else {
                        xnote.toast("更新失败:" + resp.message);
                    }
                });

                return false;
            }, ["large"]);
        }
        
        function onCheckboxClicked(e) {
            // 按下单选项的行为
            var text = $(e.target).attr("data-text");
            var index = parseInt($(e.target).attr("data-index"));
            console.log("onCheckboxClicked", text);
            text = trimText(text);
            
            var newText = convertTextToNew(text);

            var oldContent = $("#markdown-input").val();
            if (oldContent.indexOf(text) < 0) {
                console.log("text not match:", text);
                xnote.alert("标记任务失败，请刷新后重试");
                return;
            }

            // console.log("text:", text, "newText:", newText);

            // TODO: 先简单用replace处理一下
            var newContent = xnote.string.replaceByIndex(oldContent, text, newText, index);
            var params = {};
            params.id = "{{file.id}}";
            params.content = newContent;
            params.resp_type = "json";
            params.edit_token = "{{edit_token}}";
            params.version = "{{file.version}}";

            console.log("newContent:", newContent);

            xnote.http.post("/note/update", params, function (resp) {
                if (resp.code == "success") {                    
                    xnote.toast("更新成功，正在刷新页面");
                    window.location.reload();
                } else {
                    xnote.toast("更新失败:" + resp.message);
                }
            });
        }

        var input = $("#markdown-input").val();

        // 扩展选项
        var options = {};
        options.onCheckboxClicked = onCheckboxClicked;
        options.csvEditFunc = "xnote.note.openEditCsvDialog";
        marked.parseAndRender(input, "#markdown-output-div", options);

        $("body").on("mouseover", ".marked-strong", function (e) {
            xnote.note.openPreviewPopup(e, "#preview_popup_window");
        });

        $("body").on("click", ".marked-strong", function (e) {
            // 移动端点击触发
            xnote.note.openPreviewPopup(e, "#preview_popup_window");
        })

        $("body").click(function(event) {
            $("#preview_popup_window").html("").hide();
        })
    });
</script>

{% end %}