<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <script th:fragment="editJS(postType)">
        var postType = '[[${postType}]]',
        using = ['element', 'layer', 'laydate', 'form', 'upload'];
        if (postType != 'PAGE') using.push('inputTagLay', 'treeTable1');
        
        layui.config({base:'[[@{/admin/layuiadmin/lib/}]]'})
        .use(using, function(){
            var laydate = layui.laydate,
                layer = layui.layer,
                form = layui.form,
                upload = layui.upload,
                postId = [[${post == null?'null':post.postId}]],
                uploadDone = function (res, needEdit) {
                    if (res.ok) {
                        // 上传成功，分析返回
                        var asset = res.data;
                        if (needEdit)
                            packedAsset(asset).edit();
                        else {
                            packedAsset(asset).insert();
                        }
                    }
                    else {
                        layer.msg(res&&res.data||'服务器错误', {
                            offset: '15px',
                            icon: 2,
                            time: 2000
                        });
                    }
                    $('.admin-file-list').removeClass('layui-hide');
                    layui.$('#uploadDemoView').removeClass('layui-hide').find('img').attr('src', res.url);
                    console.log(res)
                },
                packedAsset = function (asset) {
                    var fileList = $('#file-list'),
                    formatBytes = function (a, b) { 
                        if (0 == a) return "0 B"; 
                        var c = 1024, d = b || 2, e = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], f = Math.floor(Math.log(a) / Math.log(c)); 
                        return parseFloat((a / Math.pow(c, f)).toFixed(d)) + " " + e[f];
                    }, updateLi = function (asset) {
                        // Check if file list has it.
                        if (!fileList.find('li.asset').length) {
                            fileList.empty();
                        }
                        var li = fileList.find('li[asset-id="' + asset.assetId + '"]:first');
                        if (!li.length) {
                            li = $('<li class="asset"></li>')
                              .attr('asset-id', asset.assetId)
                              .append($('<a class="insert" title="点击插入文件" href="###"></a>"').text(asset.title).on('click', function(e){
                                  e.preventDefault();li.data('asset').insert();
                              }))
                              .append((function(el) {
                                  $.each([ ['编辑','pencil','dark-blue','edit',0],['解除关联','unlink','cyan','unlink',1],['删除','trash','red','delete',1]],
                                  function (i, v) {
                                      el.append($('<a href="#" title="'+v[0]+'"><i class="fa fa-fw fa-'+v[1]+' op-'+v[2]+'"></i></a>')
                                          .on('click', function (e) {
                                              e.preventDefault();
                                              v[4]?
                                              layui.layer.confirm('您确定要'+v[0]+'吗？',{btn: ['确定', '取消'],title:"提示"}, function (index) {
                                                  layui.layer.close(index);
                                                  li.data('asset')[v[3]]();
                                              }):li.data('asset')[v[3]]();
                                          })      
                                      )
                                  });
                                  return el;
                              })($('<div class="info"></div>').text(asset.byte)));
                            fileList.append(li);
                        } else {
                            li.find('a.insert').text(asset.title)
                        }
                        li.data('asset', asset);
                        resizeEditorMd(),resizeLinkList();
                    }, deleteLi = function (asset) {
                        fileList.find('li[asset-id="' + asset.assetId + '"]:first').remove();
                        if (!fileList.find('li.asset').length) {
                            fileList.empty().append('<li><div class="info" style="text-align:center">暂无关联文件</div></li>');
                        }
                        resizeEditorMd(),resizeLinkList();
                    }, simpleAjax = function (asset, op, opName, complete) {
                        $.ajax({
                            url: '/admin/v2/asset/' + op,
                            method: 'POST',
                            data: {assetId: asset.assetId},
                            success: function (r) {
                                if (!!complete && typeof complete === 'function') {
                                    complete(asset);
                                }
                                layer.msg(r&&r.data||((opName||'操作')+'成功'), {
                                    offset: '15px',
                                    icon: 1,
                                    time: 1000
                                })
                            },
                            error: function (res) {
                                var r = res.responseJSON;
                                layer.msg(r&&r.data||'服务器错误', {
                                    offset: '15px',
                                    icon: 2,
                                    time: 2000
                                });
                            }
                        })
                    };
                    asset = $.extend(asset, {
                        byte: formatBytes(asset.fileSize),
                        insert: function () {
                            var t = '';
                            if (this.fileType == 1 || this.fileType == 'IMAGE') {
                                t += '!';
                                /*t = `<img src="${this.path}" `+
                                    `loading="lazy" ` + 
                                    `width="${this.imageWidth}px" `+
                                    `height="${this.imageHeight}px" `+
                                    `title="${this.title}" `+
                                    `alt="${(this.description||this.title)}"/>`;
                                blogEditor.insertValue(t);
                                return;*/
                            }
                            t += '['+(this.description||this.title)+']('+this.path+' "'+this.title+'")';
                            blogEditor.insertValue(t);
                        },
                        unlink: function () {
                            simpleAjax(this, 'unlink', '解除关联', deleteLi);
                        },
                        delete: function () {
                            simpleAjax(this, 'delete', '删除文件', deleteLi);
                        },
                        edit: function () {
                            var that = this,
                            id = 'editFileForm' + that.assetId,
                            o = $($('#editFile').html()).attr({id: id});
                            o.find('[lay-submit]').attr('lay-filter', 'editFile' + id);
                            
                            layui.layer.open({
                                type: 1,
                                title: '编辑文件信息',
                                btn: ['提交', '关闭'],
                                yes: function(index, layero) {
                                    layero.find('[lay-submit]').click();
                                },
                                area: ['450px', '300px'],
                                content: o[0].outerHTML,
                                success: function (layero, layerIndex) {
                                    layero.find('[name="assetId"]').val(that.assetId);
                                    layero.find('[name="title"]').val(that.title).focus();
                                    layui.form.on('submit(editFile' + id + ')', function (data) {
                                        $.ajax({
                                            url: '/admin/v2/asset/update',
                                            method: 'POST',
                                            data: data.field,
                                            success: function () {
                                                that = $.extend(that, data.field);
                                                layui.layer.close(layerIndex);
                                                updateLi(that);
                                                layer.msg('编辑文件信息成功', {
                                                    offset: '15px',
                                                    icon: 1,
                                                    time: 1000
                                                })
                                            },
                                            error: function (res) {
                                                var r = res.responseJSON;
                                                layer.msg(r&&r.data||'服务器错误', {
                                                    offset: '15px',
                                                    icon: 2,
                                                    time: 2000
                                                });
                                            }
                                        })
                                    });
                                    layui.form.render();
                                }
                            });
                        }    
                    });
                    updateLi(asset);
                    return asset;
                };
            
            
            // 上传插件渲染
            upload.render({
                elem: '#uploadFile',
                accept: 'file',
                url: '/admin/v2/asset/uploadFile',
                data: {
                     [[${post == null?'':'postId:'+post.postId}]]
                },
                done: function(res) {
                    uploadDone(res, true);
                }
            });
            
            if (postType != 'PAGE') {
                var tagsName = "[(${post != null ? post.tagsName : ''})]";
                var tagInput = layui.inputTagLay.render({
                    elem: '#tagsDisplay',
                    data: tagsName == ''?[]:tagsName.split(','),
                    //permanentData: ['hello'],
                    removeKeyNum: 8,
                    createKeyNum: 13,
                    autoComplete: {
                        url: '[[@{/admin/v2/tag/suggest}]]',
                        select: function (data) {
                            tagInput.elem.val(data.value);
                            tagInput.createItem();
                        }
                    },
                    onChange: function (value) {
                        $('[name=tagsName]').val(value.join(','));
                    }
                });
            }
            
            laydate.render({
                elem: '#createTime', type: 'datetime'
            });
            
            $('.file-list-question').on('click', function(e){
                e.preventDefault();
                layer.tips('此处关联的文件关联了本文章。<br/>' + 
                        '点击 <i class="fa fa-fw fa-pencil"></i> 编辑文件基本信息；<br/>' +
                        '点击 <i class="fa fa-fw fa-unlink"></i> 将文件与本文解除关联；<br/>' +
                        '点击 <i class="fa fa-fw fa-trash"></i> 从服务器上删除该文件，文章内的文件引用请手动删除。', 
                    this, {tips: [4, '#3595CC'], time: 5000});
                return false;
            })
            
            $('.link-list-question').on('click', function(e){
                e.preventDefault();
                layer.tips('此处包含的链接可能包括站内链接和站外链接，站内链接包括站内页面或上传的文件、图片。<br/>部分链接可能无法获取和识别，具体以文章发布后渲染结果为准。', 
                    this, {tips: [4, '#3595CC'], time: 5000});
                return false;
            })

            // 文章评论开关
            form.on("switch(enableComment)", function (data) {
                var elem = $(data.elem);
                $('[name=enableComment]').val(elem.prop('checked').toString().toUpperCase());
                //layui.form.render();
            });
            
            form.on("switch(imageCompress)", function (data) {
                var elem = $(data.elem), val = elem.prop('checked');
                
                $.ajax({
                	url: '[[@{/admin/v2/config/site}]]',
                	type: 'post',
                	contentType: "application/json",
                	data: JSON.stringify({
                        imageCompress: val
                    }),
                	complete: (data) => {
                		data = JSON.parse(data.responseText)
                		if (!data.ok) {
                            elem.prop('checked', !val)
                			layer.msg(r&&r.data||'服务器错误', {time: 2000});
                            return
                		}
                	}
                })
                //layui.form.render();
            });
            
            if (postType != 'PAGE') {
            
                $('.refresh-categories').on('click', function (){
                    layui.treeTable1.reload('categories', {});
                    return false;
                });
                
                var categoryTable = layui.treeTable1.render({
                    elem: '#categories',
                    url: '[[@{/admin/v2/category/list}]]',
                    request: {
                        pidName: 'parentId'
                    },
                    page: true, skin:'line',
                    tree: {
                        iconIndex: 1, // 折叠图标显示在第几列
                        isPidData: false, // 是否是id、pid形式数据
                        idName: 'id', // id字段名称
                        pidName: 'parentId', // pid字段名称
                        haveChildName: 'hasChildren',
                        openName: 'spread',
                        checkMode: {
                            indeterminate: true,
                            fullUncheck: {
                                parentToChildren: false,
                                childrenToParent: true
                            },
                            fullCheck: {
                                parentToChildren: false,
                                childrenToParent: true
                            }
                        }
                    },
                    done: function (data) {
                        var selectedIds = $('[name=categoriesId]').val().trim().split(',');
                        if (selectedIds.length == 1 && selectedIds[0] == '') return;
                        categoryTable.removeAllChecked();
                        categoryTable.setChecked(selectedIds);
                    },
                    initPageOption: {
                        layout: ['prev', 'page', 'next', 'limit'],
                        limit: 5,
                        limits: [5, 10]
                    },
                    cols: [ [
                        {type: 'checkbox'},
                        {field: 'name',title: '分类名称',minWidth: 140}]]
                });
                
                layui.treeTable1.on('checkbox(categories)', function (o){
                    //console.log(o);
                    var selectedIds = $('[name=categoriesId]').val().trim().split(',');
                    if (selectedIds.length == 1 && selectedIds[0] == '') selectedIds = [];
                    var pageData = categoryTable.getData(), checkedNode = function (node) {
                        var indexOf = selectedIds.indexOf(node.mid + '');
                        if (node.LAY_CHECKED || (o.type == 'all' && o.checked)) {
                            if (indexOf == -1) {
                                selectedIds.push(node.mid);
                            }
                        }
                        else if (!node.LAY_CHECKED || (o.type == 'all' && !o.checked)) {
                            if (indexOf != -1) {
                                selectedIds.splice(indexOf, 1);
                            }
                        }
                        if (node.children && node.children.length) {
                            $.each(node.children, function (i, v) {
                                checkedNode(v);
                            });
                        }
                    };
                    $.each(pageData, function (i, v) {
                        checkedNode(v);
                    });
                    $('[name=categoriesId]').val(selectedIds.join(','));
                })
                layui.treeTable1.on('fold(categories)', function (rowObj){
                    var el = $('[name=unfolded]'), unfolded = el.val().split(','),
                        id = rowObj.data.mid + '', index = unfolded.indexOf(id);
                    if (el.val().trim() == '') {
                        unfolded = [];
                    }
                    if (rowObj.fold && index > -1) {
                        unfolded.splice(index, 1);
                    }
                    else if (!rowObj.fold && index == -1) {
                        unfolded.push(id);
                        unfolded.sort();
                    }
                    el.val(unfolded.join(','));
                    categoryTable.options.where['unfolded[]'] = el.val();
                });
            }
            window.linkSync = LinkSync();
            var syncFunc = function(blogEditor){
                var refs = linkSync.list(blogEditor.getMarkdown()), linkList = $('#link-list');
                
                if (!!refs && refs.length) {
                    linkList.empty();
                    $.each(refs, function(i, ref){
                        var li = $('<li></li>').append(
                            $('<a title="定位到文章位置" href="#">' + ref.name + '</a>').on('click', function(e){
                                e.preventDefault();
                                blogEditor.setSelection(ref.selector[0], ref.selector[1])
                                return false;
                            }),
                            $('<div>类型：' + (ref.linkType == 'link'?'链接':'图片') + '</div>'),
                            $('<a style="display:inline;padding-right:5px" title="定位到文章位置" href="#"></a>').append('<i class="fa fa-hand-o-right"></i>').on('click', function(e){
                                e.preventDefault();
                                blogEditor.setSelection(ref.selector[0], ref.selector[1])
                                return false;
                            }),
                            $('<a style="display:inline;padding-right:5px" title="定位到链接位置" href="#"></a>').append('<i class="fa fa-link"></i>').on('click', function(e){
                                e.preventDefault();
                                if (ref.scheme == 'direct') {
                                    blogEditor.setSelection(ref.selector[0], ref.selector[1])
                                }
                                else {
                                    blogEditor.setSelection(ref.target.selector[0], ref.target.selector[1])
                                }
                                return false;
                            }),
                        );
                        if (ref.linkType == 'image') {
                            li.prepend($('<img></img>').attr("src", ref.url))
                        }
                        linkList.append(li);
                    })
                }
                else {
                    linkList.empty().append($('<li style="text-align:center">文章中没有找到链接</li>'));
                }
            }, submit = function (data, act) {
                var assetLi = $('li.asset'), postAssets = [];
                $.each(assetLi, function (i, v) {
                    postAssets.push($(v).attr('asset-id'));
                });
                
                if (postType != 'PAGE') {
                    // categoriesId
                    var categoriesId = data.field['categoriesId'].split(',');
                    data.field['_categoriesId[]'] = categoriesId;
                    delete data.field['categoriesId'];
                    
                    // tagsName
                    var tagsName = data.field['tagsName'].split(',');
                    data.field['_tagsName[]'] = tagsName;
                    delete data.field['tagsName'];
                }
                
                $.ajax({
                    url: location.href,
                    data: $.extend(data.field, {assets: postAssets}),
                    method: 'POST',
                    success: function (result) {
                        layer.msg('保存成功', {time:1000}, function(){
                            var x = location.href.split('?')[0], y = result.data;
                            switch(act) {
                                case 'sub':
                                    location.href = `${x}?parentId=${y.postId}`;
                                    break;
                                case 'sib':
                                    location.href = `${x}?parentId=${y.parentId}`;
                                    break;
                                default:
                                    location.href = `${x}?postId=${y.postId}`;
                                    break;
                            }
                        });
                    },
                    error: function (res) {
                        var r = res.responseJSON;
                        layer.msg(r&&r.data||'服务器错误', {time: 2000});
                    }
                });
            };
            
            form.on('submit(submitBtn)', function (data){
                submit(data);
            });
            form.on('submit(submitAndAddSibBtn)', function (data){
                submit(data, 'sib');
            });
            form.on('submit(submitAndAddSubBtn)', function (data){
                submit(data, 'sub');
            });
            
            function renderEditor(id) {
                var elem = $('#' + id);
                elem.siblings().removeClass('layui-show');
                elem.addClass('layui-show');
                if (!window._blogEditors) window._blogEditors = {};
                if (!window._blogEditors[id]) {
                    window._blogEditors[id] = editormd(id, {
                        width: "calc(100% - 2px)",
                        height: '600px',
                        resize: !0,
                        syncScrolling: "single",
                        placeholder: "",
                        path: "/blog/plugins/editormd/lib/",
                        toolbarIcons : function() {
                            // Or return editormd.toolbarModes[name]; // full, simple, mini
                            // Using "||" set icons align right.
                            return ["undo", "redo", "|", "bold", 'italic', 'del', 'quote', 'list-ol', 'list-ul', '|', 'br', "hr", 'more', "|", "watch", "|", "fullscreen"]
                        },
                        toolbarIconsClass : {
                            br : "iconfont icon-huanhang",
                            more : "iconfont icon-editor-paging"
                        },
                        lang : {
                            toolbar : {
                                br : "换行",
                                more: '插入<!--more-->分隔符'
                            }
                        },
                        toolbarHandlers: {
                            br: function(cm, icon, cursor, selection) {
                                blogEditor.insertValue('<br/>\r\n')
                            },
                            more: function(cm, icon, cursor, selection) {
                                blogEditor.insertValue('<!--more-->\r\n')
                            }
                        },
                        emoji: false,
                        watch: false, // 默认关闭预览
                        /**图片上传配置*/
                        imageUpload: false,
                        imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp", "avif"],
                        imageUploadURL: "/admin/v2/post/uploadFile",
                        onload: function (obj) {
                            function setCursor() {
                                if (postId != null) {
                                    localStorage.setItem('prev-cursor-page-' + postId, 
                                    JSON.stringify(blogEditor.getCursor()));
                                }
                            }
                            function getCursor() {
                                if (postId != null) {
                                    var prevCursor = localStorage.getItem('prev-cursor-page-' + postId);
                                    if (prevCursor) {
                                        try {
                                            prevCursor = JSON.parse(prevCursor);
                                            blogEditor.setCursor(prevCursor);
                                        }
                                        catch(_){}
                                    }
                                }
                            }
                            syncFunc(blogEditor);
                            this.cm.on('change', function() {
                                syncFunc(blogEditor);
                                setCursor();
                            });
                            
                            this.cmElement.find('.CodeMirror-sizer').on('click', function() {
                                setCursor();
                            });
                            
                            // 防止滚动条高度错误
                            this.gotoLine(2);
                            this.gotoLine(1);
                            getCursor();
                        },
                        onresize: function(){
                            var e = elem;
                            !e.hasClass('editormd-fullscreen') && e.css({'width': 'calc(100% - 2px)'});
                        }
                    });
                    $('#'+id).on('paste', function (event) {
                        var e = event.originalEvent;
                        var items = (e.clipboardData || window.clipboardData).items;
                        var image = null;
                        if (items && items.length) {
                            // 搜索剪切板items
                            for (var i = 0; i < items.length; i++) {
                                if (items[i].type.indexOf('image') !== -1) {
                                    image = items[i].getAsFile();
                                    break;
                                }
                            }
                        } else {
                            console.debug("当前浏览器不支持");
                            return;
                        }
                        if (!image) {
                            console.debug("粘贴内容非图片");
                            return;
                        }
                        //console.log(image);
                        var formData = new FormData();
                        
                        if (postId != null)
                            formData.append('postId', postId);
                        formData.append('file', image, `image-${image.lastModified}.${image.name.split('.').pop()}`);
                        
                        $.ajax({
                            type: 'POST',
                            url: '/admin/v2/asset/uploadFile',
                            data: formData,
                            mimeType: 'multipart/form-data',
                            contentType: !1,
                            processData: !1,
                            success: (res) => {
                                uploadDone(JSON.parse(res))
                            },
                            error: () => {
                                layer.msg('粘贴文件失败，服务器错误', {
                                    offset: '15px',
                                    icon: 2,
                                    time: 2000
                                });
                            }
                        })
                    });
                }
                window.blogEditor = window._blogEditors[id];
            }
            var resizeEditorMd = function(){
                // 调整 editormd 的高度和宽度
                var e1 = $('.editormd');
                e1.css(e1.hasClass('editormd-fullscreen')?{
                    'width': $(window).width() + 'px', 
                    'height': $(window).height() + 'px'}:
                    {'width': 'calc(100% - 2px)'});
            }
            var resizeLinkList = function () {
                // 调整“文章包含链接”的高度
                var editHeight = $('#editArea').height(),
                tabBriefHeight = $('#docTabBrief>ul.layui-tab-title').outerHeight(),
                tabInsideHeight = $('#fileContext').outerHeight(),
                linkList = $('#link-list'), fileList = $('#file-list'),
                linkListHeight = linkList.outerHeight(), fileListHeight = fileList.outerHeight(),
                totalHeight = editHeight 
                    - (tabBriefHeight +
                        (tabInsideHeight - linkListHeight - fileListHeight) + 19);
                if (totalHeight <= 0) return;
                fileList.css('height', totalHeight / 2);
                linkList.css('height', totalHeight / 2);
            }
            $('#docTabBrief>ul.layui-tab-title>li').on('click', function(){resizeLinkList()});
            $('#editorTab>ul.layui-tab-title>li').on('click', function(){
                if (this.getAttribute('editor'))
                    renderEditor($(this).attr('editor'));
            });
            $(window).resize(function(){
                resizeEditorMd(),resizeLinkList();
            });
            renderEditor('blog-editormd');

            // 获取关联文件
            var assets = [(${assets == null?'null':'"'+assets+'"'})];
            if (assets) {
                assets = JSON.parse(assets);
                $.each(assets, function (i, asset) {
                    packedAsset(asset);
                });
            }
            
            // 密码
            $('[name="password"]').on('click', function (){
                $(this).attr('type', 'password');
            });
        });
    </script>
</html>