{% load staticfiles %}
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge，chrome=1">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta http-equiv="Cache-Control" content="max-age=7200" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>{% block title %}{% endblock %} - MrDoc</title>
    <link href="{% static 'layui/css/layui.css' %}?version={{mrdoc_version}}" rel="stylesheet">
    <link rel="stylesheet" href="{% static 'editor.md/css/editormd.css' %}?version={{mrdoc_version}}" />
    <link href="{% static 'mrdoc.css' %}?version={{mrdoc_version}}" rel="stylesheet">
    <link rel="icon" href="{% static 'favicon_16.png' %}"/>
    <style>
        .markdown-body ul li{
            list-style:disc;
        }
        .markdown-body ul > li > ul > li{
            list-style-type: circle;
        }
        .markdown-body ol li{
            list-style-type: decimal;
        }
        .markdown-body ol ol ul,.markdown-body ol ul ul,.markdown-body ul ol ul,.markdown-body ul ul ul li{
            list-style-type: square;
        }
        .select-img-list{
            cursor: pointer;
            position: relative;
            display:flex;
            float: left;
            align-items:center;
            width: 120px;
            height:120px;
            margin: 0 20px 30px 0;
            text-align: center;
            overflow: hidden;
        }

        .select-img-list:hover{
            background-color: #EAFFEA;
        }
        .select-img-list-i{
            display: block;
            width: 100%;
            height: auto;
            -webkit-background-size: contain;
            border: 1px solid transparent;
            border-radius: 3px;
            overflow: hidden;
        }
        /* 编辑器图标样式 */
        .editormd-menu i{
            color: black;
            font-size: 20px;
        }
    </style>
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
    <![endif]-->
    {% block custom_style %}{% endblock %}

</head>
<body class="layui-container">
<!-- 页头 -->
{% include 'app_doc/head_base.html' %}
<!-- 页头结束 -->

<!-- 主体开始 -->
<div class="layui-container">
    {% block content %}
    {% endblock %}
</div>
<!-- 主体结束 -->

<script src="{% static 'jquery/3.1.1/jquery.min.js' %}"></script>
<script src="{% static 'layui/layui.all.js' %}"></script>
<script src="{% static 'editor.md/editormd.min.js' %}"></script>
<script src="{% static 'mrdoc.editor.js' %}"></script>
<script>
    $.ajaxSetup({
            data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
        });
    var layer = layui.layer;
    var form = layui.form;
    var element = layui.element;
    var laypage = layui.laypage;
    var md_changed = false; //初始化一个变量，用于判断编辑器是否修改
    //初始化editormd
    var editor = editormd("editor-md", {
        width       :   "100%",
        height      :   "1000px;",
        placeholder :   "开始使用Markdown书写MrDoc文档，编辑器支持以下功能：\n1.粘贴上传图片\n2.六级标题\n3.代码高亮\n4.本地图片和外链图片\n5.表格\n6.多级列表和任务列表\n7.Katex公式\n8.流程图\n9.时序图\n……",
        toolbarIcons : function() {
            return [
                "undo", "redo", "|",
                "bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase","kaiSpan", "|",
                "h1", "h2", "h3", "h4", "|",
                "list-ul", "list-ol", "hr", "link", "reference-link", "|",
                "imgUpload", "attachment" ,"code", "code-block", "htmltable", "datetime", "emoji", "html-entities", "pagebreak", "|",
                "watch", "preview", "|",
                "help"
            ]
        },
        //自定义工具栏添加楷体按钮
        toolbarIconTexts : {
            kaiSpan : "楷",
        },
        //自定义工具栏添加图片按钮
        toolbarIconsClass : {
            imgUpload:'fa-image',
            attachment:'fa-file-zip-o',
            htmltable:'fa-table',
        },
        //设置自定义工具栏按钮的事件
        toolbarHandlers : {
            /**
             * @param {Object}      cm         CodeMirror对象
             * @param {Object}      icon       图标按钮jQuery元素对象
             * @param {Object}      cursor     CodeMirror的光标对象，可获取光标所在行和位置
             * @param {String}      selection  编辑器选中的文本
             */
             // 点击“楷”字图标的响应函数
            kaiSpan : function(cm, icon, cursor, selection) {
                //var cursor    = cm.getCursor();     //获取当前光标对象，同cursor参数
                //var selection = cm.getSelection();  //获取当前选中的文本，同selection参数
                // 替换选中文本，如果没有选中文本，则直接插入
                cm.replaceSelection('<span style="font-family:楷体">' + selection + "</span>");
                // 如果当前没有选中的文本，将光标移到要输入的位置
                if(selection === "") {
                    cm.setCursor(cursor.line, cursor.ch + 29);
                }
                // this == 当前editormd实例
                //console.log("testIcon =>", this, cm, icon, cursor, selection);
            },
            // 点击工具栏图片图标的响应函数 - 上传图片和选择图片
            imgUpload : function(cm,icon,cursor,selection){
                layer.ready(function(){
                  element.init();
                });
                layer.open({
                    type:'1',
                    title:'添加图片',
                    area:['800px','600px'],
                    id:'uploadImg',//配置ID,
                    content:$('#upload-img'),
                })
            },
            //点击工具栏文件按钮的响应函数 - 上传和选择附件
            attachment : function(cm,icon,cursor,selection){
                layer.ready(function(){
                  element.init();
                });
                layer.open({
                    type:'1',
                    title:'添加附件',
                    area:['800px','600px'],
                    id:'uploadAttach',//配置ID,
                    content:$('#upload-attach'),
                    success: function(layero, index){
                        $.post('{% url "manage_attachment" %}',{types:2},function(r){
                            $("#attach_table tbody").empty()
                            if(r.status){
                                // $.each(r.data,function(k,v){
                                //     console.log(k,v)
                                //     var row = "<tr><td>" + v.filename + "</td><td>"+ v.filesize +"</td><td>"+ v.filetime +"</td><td><button class='layui-btn layui-btn-normal' data-name='"+ v.filename +"'  data-path='"+ v.filepath +"' onclick='insertAttach(this)'>选择</button></td></tr>"
                                //     $("#attach_table tbody").append(row)
                                // })
                                //调用分页显示
                                laypage.render({
                                    elem: 'select-attach-page',//分页的div
                                    count: r.data.length, //数据总数
                                    limit:10, //单页数
                                    jump: function(obj){
                                        //渲染HTML
                                        $("#attach_table tbody").empty();
                                        var thisData = r.data.concat().splice(obj.curr*obj.limit - obj.limit, obj.limit);
                                        layui.each(thisData, function(k, v){
                                            var row = "<tr><td>" + v.filename + "</td><td>"+ v.filesize +"</td><td>"+ v.filetime +"</td><td><button class='layui-btn layui-btn-normal' data-name='"+ v.filename +"'  data-path='"+ v.filepath +"' onclick='insertAttach(this)'>选择</button></td></tr>"
                                            // arr.push(row);
                                            $("#attach_table tbody").append(row)
                                        });
                                    }
                                });
                                //layer.close(loading);//关闭加载提示
                            }else{
                                layer.msg("获取附件失败，请稍后重试！")
                            }
                        })

                    }
                })
            },
            //点击工具栏表格按钮的响应函数 - 添加表格
            htmltable:function(cm,icon,cursor,selection){
                layer.ready(function(){
                  element.init();
                });
                layer.open({
                    type:1,
                    id:'addTable',
                    title:'添加表格',
                    //content:"<div style='margin:10px;'><input type='number' id='row' class='layui-input' placeholder='输入行数'><input type='number' id='col' class='layui-input' placeholder='输入列数'></div>",
                    content:$("#layer-table"),
                    btn:['确定','取消'], //添加按钮
                    yes:function(index,layero){
                        var table_md = convertTable("DataTable1")
                        //console.log(table_md)
                        editor.insertValue("\n" + table_md);
                        $("#TableGroup").empty();//清空表格
                        layer.close(index)
                    },
                    btn2:function(index,layero){
                        $("#TableGroup").empty();//清空表格
                        layer.close(index) // 关闭弹出框
                    }
                });
            }
        },
        //设置语言
        lang : {
            toolbar : {
                kaiSpan : "添加楷体span标签",
                imgUpload:"添加图片到文档",
                attachment:"添加附件",
                htmltable:"添加表格",
            }
        },
        //配置项
        pageBreak : true, //分页符
        path        :   "/static/editor.md/lib/",
        saveHTMLToTextarea : true,
        atLink      :   false,//禁用@链接
        tex         :   true,//开启科学公式
        tocm        :   true,//开启下拉目录
        taskList    :   true,//开启任务列表
        tocTitle    :   '文章导读',//目录标题
        tocContainer:   '',
        tocDropdown :   false,
        emoji       :   true,//开启Emoji
        flowChart   :   true, //开启流程图
        sequenceDiagram : true, //开启序列图
        imageUpload    : true, //开启图片上传
        htmlDecode     : "link,style,script,iframe|on*", //解析部分HTML标签
        imageFormats   : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        imageUploadURL : "{% url 'upload_doc_img' %}",
        onchange:function(){
            md_changed = true
        },
    });
    //粘贴上传图片
    $("#editor-md").on('paste', function (ev) {
        var data = ev.clipboardData;
        var items = (event.clipboardData || event.originalEvent.clipboardData).items;
        for (var index in items) {
            var item = items[index];
            if (item.kind === 'file') {
                var blob = item.getAsFile();
                var reader = new FileReader();
                reader.onload = function (event) {
                    var base64 = event.target.result;
                    //ajax上传图片
                    $.post("{% url 'upload_doc_img' %}",{base:base64}, function (ret) {
                        layer.msg(ret.message);
                        if (ret.success === 1) {
                            //新一行的图片显示
                            editor.insertValue("\n![](" + ret.url + ")");
                        }
                    });
                }; // data url!
                var url = reader.readAsDataURL(blob);
            }
        }
    });
    //未保存离开提示
    window.onbeforeunload =function() {
    　　 if(md_changed){
            //console.log("页面未保存数据")
            return 1;
        }else{
            return null;
        }
    };
    //监听图片Tab选项卡切换
    element.on('tab(img-tab)', function(data){
      //console.log(this); //当前Tab标题所在的原始DOM元素
      //console.log(data.index); //得到当前Tab的所在下标
      //console.log(data.elem); //得到当前的Tab大容器
      if(data.index == 1){
        console.log('选择图片')
        $("#select-img-group").empty(); //删除已有分组按钮
        //请求新的分组数据
        $.post("{% url 'manage_img_group' %}",{'types':3},function(r){
            if(r.status){
                //console.log(r.data)
                group_btn_str = ''
                for(let i in r.data){
                    group_btn_str += '<button class="layui-btn layui-btn-normal layui-btn-sm" onclick="switchImgGroup(' + r.data[i].group_id +')">' + r.data[i].group_name + '(' + r.data[i].group_cnt + ')</button>'
                };
                $("#select-img-group").append(group_btn_str)
            }
        });
        //请求全部图片数据
        var loading = layer.load();
        $.post("{% url 'manage_image' %}",{'types':2,'group_id':0},function(r){
            if(r.status){
                //调用分页显示
                laypage.render({
                    elem: 'select-img-page',//分页的div
                    count: r.data.length, //数据总数
                    limit:15, //单页数
                    jump: function(obj){
                        //渲染HTML
                        document.getElementById('select-img').innerHTML = function(){
                            var arr = []
                            var thisData = r.data.concat().splice(obj.curr*obj.limit - obj.limit, obj.limit);
                            layui.each(thisData, function(index, item){
                                arr.push('<li class="select-img-list"><img class="select-img-list-i" onclick="insertImg(this);" src="' + item.path + '" title="' + item.name + '" /></li>');
                            });
                        return arr.join('');
                        }();
                    }
                });
                layer.close(loading);//关闭加载提示
            }else{
                layer.close(loading);
                layer.msg("获取图片失败")
            }
        })
      }
    });
    //插入选择的图片到编辑器
    insertImg = function(e){
        console.log(e.src);
        editor.insertValue("\n![](" + e.src + ")");
    };
    //切换图片分组
    switchImgGroup = function(e){
        var switch_loading = layer.load();
        $.post("{% url 'manage_image' %}", {
            'types': 2,
            'group_id': e
        },
        function(r) {
            if (r.status) {
                //调用分页显示
                laypage.render({
                    elem: 'select-img-page',//分页的div
                    count: r.data.length,//数据总数
                    limit: 15,//单页数
                    jump: function(obj) {
                        //渲染HTML
                        document.getElementById('select-img').innerHTML = function() {
                            var arr = []
                            var thisData = r.data.concat().splice(obj.curr * obj.limit - obj.limit, obj.limit);
                            layui.each(thisData,
                            function(index, item) {
                                arr.push('<li class="select-img-list"><img class="select-img-list-i" onclick="insertImg(this);" src="' + item.path + '" title="' + item.name + '" /></li>');
                            });
                            return arr.join('');
                        } ();
                    }
                });
                layer.close(switch_loading); //关闭加载提示
            } else {
                layer.close(switch_loading);
                layer.msg("获取分组图片失败")
            }
        })
    };
    //插入选择的附件到编辑器
    insertAttach = function(e){
        editor.insertValue("\n[【附件】"+ $(e).data('name') + "](/media/" + $(e).data('path') + ")");
        layer.closeAll();
    }
</script>
<script src="{% static 'mrdoc.js' %}?version={{mrdoc_version}}"></script>
{% block custom_script %}
{% endblock %}
</body>
{% block custom_div %}
{% endblock %}
<!-- 选择和上传图片div -->
<div id="upload-img" style="display:none;margin:20px;">
    <div class="layui-tab" lay-filter="img-tab">
      <ul class="layui-tab-title">
        <li class="layui-this">上传图片</li>
        <li>选择图片</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
            <button class="layui-btn layui-btn-normal layui-btn-sm" id="upload_img">点击上传图片</button>
        </div>
        <div class="layui-tab-item">
            <div class="layui-row" id="select-img-group">
            </div><hr>
            <div class="layui-row" id="select-img"></div>
            <div id="select-img-page"></div>
        </div>
      </div>
    </div>
</div>
<!-- 选择和上传附件div -->
<div id="upload-attach" style="display:none;margin:20px;">
    <span>* 仅支持.zip格式的压缩文件作为附件，文件大小不超过50Mb</span>
    <div style="margin: 10px 0 0 10px;">
        <button class="layui-btn layui-btn-normal layui-btn-sm" id="upload_attachment">点击上传附件</button>
        <a class="layui-btn layui-btn-normal layui-btn-sm" href="{% url 'manage_attachment' %}" target="_blank">管理附件</a>
    </div>
    <table class="layui-table" id="attach_table" style="margin: 10px;width:90%;">
        <thead>
            <th>附件名称</th>
            <th>附件大小</th>
            <th>上传时间</th>
            <th>操作</th>
        </thead>
        <tbody>

        </tbody>
        
    </table>
    <div id="select-attach-page"></div>
</div>
<!-- 添加表格div -->
<div id="layer-table" style="display: none;margin: 10px;">
    <div class="layui-row" style="margin: 10px;">
        <div class="layui-form-item">
        <div class="layui-inline">
            <div class="layui-input-inline" style="width: 50px;">
            <input type="number"  placeholder="行" id="row" class="layui-input" value="3">
            </div>
            <div class="layui-form-mid">x</div>
            <div class="layui-input-inline" style="width: 50px;">
            <input type="number" placeholder="列" id="col"  class="layui-input" value="3">
            </div>
            <div class="layui-form-mid" style="width: 100px;">
            <button class="layui-btn layui-btn-normal layui-btn-xs" onclick="addtable(1)" >生成表格</button>
            </div>
        </div>
        </div>
    </div>
    <div class="layui-row" style="margin:10px;" id="TableGroup"></div>
</div>
<script>
    //按钮选择上传图片
    var upload = layui.upload;
    upload.render({
        elem: '#upload_img',
        url: '{% url "upload_doc_img" %}',
        done: function(res, index, upload){ //上传后的回调
            //上传成功
            if(res.success == 1){
                editor.insertValue("\n![](" + res.url + ")");
                layer.closeAll();
                layer.msg("上传成功");
            }else{
                layer.msg("上传出错，请重试！")
            }
        },
        accept: 'images', //允许上传的文件类型
        acceptMime:'image/*',
        field:'manage_upload',
        size: 5000, //最大允许上传的文件大小

    });
    // 按钮选择上传附件
    var upload_attach = layui.upload;
    upload_attach.render({
        elem: '#upload_attachment',
        url: '{% url "manage_attachment" %}',
        data:{types:0,csrfmiddlewaretoken: '{{ csrf_token }}'},
        done: function(res, index, upload){ //上传后的回调
            //上传成功，刷新页面
            if(res.status){
                editor.insertValue("\n[【附件】"+ res.data.name + "](/media/" + res.data.url + ")");
                layer.closeAll();
                layer.msg("上传成功");
            }else{
                layer.msg("上传出错，请重试！")
            }
        },
        accept: 'file', //允许上传的文件类型
        exts:'zip', //允许上传zip压缩文件
        field:'attachment_upload',
        size: 50000, //最大允许上传的文件大小
    })
    //修改a标签链接新窗口打开
    $('#content').on('click','a',function(e){
        e.target.target = '_blank';
    });
</script>
</html>