require.config({
    baseUrl: Config.cdn+'/static/',
    urlArgs: "v="+(Config.app_debug==1?new Date().getTime():Config.version),
    map: {
        '*': {
            'css': 'libs/require/css.min'
        }
    },
    paths: {
        "jquery": "libs/jquery/jquery.min",
        "bootstrap": "libs/bootstrap/js/bootstrap.bundle.min",
        "adminlte": Config.static_path+'/js/adminlte.min',
        "bootstrap-table": 'libs/bootstrap-table-master/bootstrap-table.min',
        "bootstrap-table-lang": 'libs/bootstrap-table-master/locale/bootstrap-table-'+Config.admin_lang+'.min',
        "validator": 'libs/nice-validator/jquery.validator.min',
        "validatorLang": 'libs/nice-validator/local/'+Config.admin_lang, // 语言包
        "jquery-ui-widget": 'libs/jquery-fileupload/jquery.ui.widget',
        "jquery-fileupload": 'libs/jquery-fileupload/jquery.fileupload',
        "jquery-ui": 'libs/jquery-ui/jquery-ui.min',
        "layerJs": 'libs/layer/layer',
        "laydate": 'libs/laydate/laydate',
        "selectpage": 'libs/selectpage/selectpage.min',
        "jstree": 'libs/jstree/jstree.min',
        "selectpicker": 'libs/bootstrap-select/js/bootstrap-select.min',
    },
    shim: {
        'bootstrap': ['jquery'],
        'adminlte': ['jquery','bootstrap'],
        'bootstrap-table': ['bootstrap'],
        'bootstrap-table-lang': ['bootstrap-table'],
        'validator': ['css!libs/nice-validator/jquery.validator.css'],
        'validatorLang': ['validator'],
        'jquery-fileupload': ['jquery-ui-widget'],
        'jquery-ui': ['css!libs/jquery-ui/jquery-ui.min.css'],
        'selectpage': ['css!libs/selectpage/selectpage.css'],
        'jstree': ['jquery','css!libs/jstree/themes/default/style.min.css'],
        'selectpicker': ['jquery','css!libs/bootstrap-select/css/bootstrap-select.min.css'],
    },
    waitSeconds: 30
});

/**
 * 语言包
 * @param name
 * @param arr
 * @returns {*}
 */
function lang(name, arr) {
    name = name.toLowerCase();
    name = Lang[name] ? Lang[name] : name;
    if (arr) {
        for(var key in arr) {
            name = name.replace('%s', arr[key]);
        }
    }
    return name;
}

/**
 * layer初始化
 */
define('layer', ['jquery', 'layerJs'], function ($, layer) {
    layer.config({
        // path: Config.cdn+'/static/libs/layer/',
        extend: 'admin/layer.css', //加载新皮肤
    });

    // 全局
    window.Layer = layer;
    return layer;
})

/**
 * Util常用函数库
 * @returns {UtilHelpApp20190708}
 * @constructor
 */
function UtilHelpApp20190708() {
    if (this.constructor != UtilHelpApp20190708) {
        return new UtilHelpApp20190708();
    }

    /**
     * 设置URL常用参数
     * @param options object {url:'', query:[]}
     * @returns {string|*}
     */
    this.setUrlParams = function (options) {
        let {url,query} = options;
        if(query) {
            let queryArr = [];
            for (const key in query) {
                if (query.hasOwnProperty(key)) {
                    queryArr.push(`${key}=${query[key]}`)
                }
            }
            if(url.indexOf('?') !== -1) {
                url =`${url}&${queryArr.join('&')}`
            } else {
                url = url ? `${url}?${queryArr.join('&')}` : queryArr.join('&');
            }
        }
        return url;
    };

    /**
     * 获取URL地址参数
     * @param url
     * @returns {{}}
     */
    this.getUrlParams = function getRequest(url) {
        url = url || window.location.search; //获取url中"?"符后的字串
        var params = {};
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            str = str.split("&");
            for(var i = 0; i < str.length; i ++) {
                params[str[i].split("=")[0]]=decodeURI(str[i].split("=")[1]);
            }
        }
        return params;
    }

    /**
     * ajax请求
     * @param options ajax选项，覆盖ajax
     * @param before    请求前的回调
     * @param success   请求后的回调
     * @param error 响应成功，但状态码错误的回调
     * @param btnSumit 提交按钮对象
     * @returns {*}
     */
    this.ajax = function (options, before, success, error, btnSumit) {
        options = typeof options === 'string' ? {url: options} : options;

        if (options.type==='post') {
            var token = $('meta[name="csrf-token"]').attr('content');
            if (token) {
                if (Object.prototype.toString.call(options.data) === '[object Array]') {
                    options.data.push({name:'__token__',value:token});
                } else if(typeof options.data == "object") {
                    options.data['__token__'] = token;
                }
            }
        }

        var index = 0;
        var defaultConfig = {
            type: 'get',
            dataType:'json',
            beforeSend:function(XMLHttpRequest,self) {
                if (typeof before === "function") {
                    var data = before(options.data);
                    if (false===data) {
                        if (btnSumit){btnSumit.removeClass('disabled')}
                        return false;
                    }
                    self.data = $.param(data);
                }
                index = layer.load(1);
            },
            cache: false,
            complete: function (xhr) {
                var token = xhr.getResponseHeader('__token__');
                if (token) {
                    $('meta[name="csrf-token"]').attr('content',token);
                }
            },
            success: function(response) {
                layer.close(index);

                if (response.code === 200) {
                    if (typeof success === "function") {
                        if (false===success(response.data,response)) {
                            return false;
                        }
                    }
                } else {
                    if (typeof error === "function") {
                        if (false===error(response)) {
                            return false;
                        }
                    }
                    layer.msg(response.msg, {time:4000,icon:2});
                }
            },
            error: function(e) {
                layer.close(index);

                if (btnSumit){
                    btnSumit.removeClass('disabled')
                }

                if (e.status>0) {
                    let txt = e.statusText;
                    if (e.responseJSON && e.responseJSON.message) {
                        txt = e.responseJSON.message;
                    } else if (e.responseJSON && e.responseJSON.msg) {
                        txt = e.responseJSON.msg;
                    }
                    layer.alert('['+e.status+'] '+txt);
                } else {
                    layer.alert(lang('Request exception'));
                }
            }
        };
        return $.ajax($.extend(defaultConfig,options));
    }

    /**
     * 获取唯一值
     * @returns {string}
     */
    this.guid = function () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        });
    }
}

var UtilHelpApp = UtilHelpApp20190708;
window.Util = new UtilHelpApp();

/**
 * 自定义layer.open弹出层
 */
window.cmsOpen = function (url, title, options) {
    options = options ? options : {};

    if (typeof offset_val === 'undefined') {
        offset_val = [100, 100];
    }

    // 是否默认全屏,2=全屏
    var area = Tpl.popup==1 ? [$(window).width() > 800 ? '800px' : '90%', $(window).height() > 600 ? '600px' : '90%'] : ['100%', '100%'];

    var defaultOptions = {
        type: 2,
        title: title,
        shadeClose: false,
        shade: false,
        area: area,
        maxmin: true,
        resize: true,
        moveOut: true,
        content: url,
        success: (layero) => {
            offset_val[0] = offset_val[0] + 20;
            offset_val[1] = offset_val[1] + 20;
            if (typeof open_z_index === 'undefined') {
                open_z_index = layero.css("z-index");
            } else {
                layero.css("z-index", open_z_index++);
            }

            // 解决全屏下无法正常缩小问题
            if (typeof options.area =="object" && options.area[0]=='100%' && options.area[1]=='100%') {
                var width = $(window).width();
                var height = $(window).height();
                var area = [
                    width > 800 ? 800 : width*0.9,
                    height > 600 ? 600 : height*0.9,
                    (height - (height > 600 ? 600 : height*0.9))/2,
                    (width - (width > 800 ? 800 : width*0.9))/2
                ];
                layero.find('.layui-layer-max').addClass('layui-layer-maxmin');
                layero.attr({area: area});
            }
        },
        moveEnd: (layero) => {
            layero.css("z-index", open_z_index++);
        },
    };

    options = $.extend(defaultOptions, options);
    return layer.open(options);
};

/**
 * 页面表单的处理
 */
define('Form', ['jquery','layer','validator','validatorLang'], function ($, undefined) {
    var Form = {
        config: {
            frmOperate: '.frm-operate', // 表单标签class
            btnSubmit: '.btn-submit', // 表单提交按钮class
            isValidate: true, // 是否开启验证
        },
        api: {
            init: function (config) {
                config = config ? config : {};
                config = $.extend(Form.config, config);
                let form = typeof config.frmOperate == 'object' ? config.frmOperate : $(config.frmOperate);

                if (config.isValidate) {
                    Form.event.validator(form, config.validator, config.before, config.success, config.error);
                } else {
                    form.submit(function (e) {
                        e.preventDefault();
                        Form.api.submit(form, config.before, config.success, config.error);
                    });
                }
                Form.event.selectpage(form);
                Form.event.laydate(form);
                Form.event.fileSelect(form);
                Form.event.fileUpload(form);
                Form.event.filePreview(form);
                Form.event.tips(form);
                Form.event.keyvalue(form);
                Form.event.selectpicker(form);
                Form.event.more(form);
            },
            submit: function(form, before, success, error) {
                let btnSumit = $('[type=submit]', form);
                if (btnSumit.hasClass('disabled')) {
                    return false;
                }
                btnSumit.addClass('disabled');

                // 数据提交
                let url = form.attr('action');
                url = url ? url : location.href;
                let method = form.attr('method');
                method = method ? method : 'post';

                let obj = Util.ajax({
                    url: url,
                    type: method,
                    data: form.serializeArray(),
                    enableToken: true
                }, before,function (data,response) {
                    btnSumit.removeClass('disabled');

                    // 是否有设置响应成功后的回调
                    if (typeof success === "function") {
                        if (false===success(data,response)) {
                            return false;
                        }
                    }

                    if ($('.operatePage').length) {
                        layer.msg(response.msg, {time:2000, icon:1}, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                            if (parent.$('button[name="refresh"]').length>0) {
                                parent.$('button[name="refresh"]').trigger('click');
                            } else if (parent.$('.btn-refresh').length>0) {
                                parent.$('.btn-refresh').trigger('click');
                            }
                        });
                    } else {
                        layer.msg(response.msg, {time:2000, icon:1}, function () {
                            self.location=document.referrer;
                        });
                    }
                }, function (data) {
                    // 错误回调
                    btnSumit.removeClass('disabled');

                    // 是否有设置回调
                    if (typeof error === "function") {
                        if (false===error(data)) {
                            return false;
                        }
                    }
                    layer.msg(data.msg,{time:4000, icon:2});
                }, btnSumit);
            },
        },
        event: {
            validator: function (form, option, before, success, error) {
                option = option || {};
                let options = {
                    formClass: "n-default n-bootstrap",
                    msgClass: "n-bottom",
                    theme: 'bootstrap',
                    invalidClass: 'is-invalid',
                    target: function(elem){ // 自定义消息位置
                        let formitem = $(elem).closest('.form-group>div'),
                            msgbox = formitem.find('span.msg-box');
                        if (!msgbox.length) {
                            msgbox = $('<span class="msg-box"></span>').appendTo(formitem);
                        }
                        return msgbox;
                    },
                    valid: function(result) {
                        Form.api.submit(form, before, success, error);
                    },
                    invalid: function (result) {
                        if ($(result).find('.card.card-tabs').length==1) {
                            // is-invalid
                            var href = $('.nav-tabs').find('.nav-link.active').attr('href');
                            if ($(href).find('.is-invalid').length<=0) {
                                $('.nav-tabs').find('.nav-link:not(.active)').each(function (e) {
                                    href = $(this).attr('href');
                                    if ($(href).find('.is-invalid').length) {
                                        $(this).trigger('click');
                                        return false;
                                    }
                                });
                            }
                        }
                    }
                };
                form.validator($.extend(options, option));
            },
            selectpage: function (form) {
                if (form.find('.selectpage').length>0) {
                    // 加载selectpage插件
                    require(['selectpage'], function (undefined) {
                        let option = {
                            showField: 'name',
                            keyField: 'id',
                            // searchField: 'name',    // ajax查询时，需要提交的查询字段，多个英文逗号分隔(废弃默认，默认与showField一致，可外面指定)
                            data: [], // 格式：[{id:1,name:'张三',sex:'男'},{id:2,name:'李四',sex:'男'}]
                            selectOnly: false,
                            pagination: true,
                            listSize: 10,   // 列表显示的项目个数，其它的项目以滚动条滚动方式展现
                            multiple: false,
                            lang: 'cn',
                            maxSelectLimit: 10,
                            eAjaxSuccess: function (data) {
                                if (data.code && data.code!=200) {
                                    layer.alert(data.msg);
                                    return {list:[],totalRow:[]};
                                }
                                // 动态下拉返回值的格式化
                                data.list = typeof data.rows !== 'undefined' ? data.rows : [];
                                data.totalRow = typeof data.total !== 'undefined' ? data.total : data.list.length;
                                return data;
                            }
                        };
                        form.find('.selectpage').each(function (key,item) {
                            let id = $(this).attr('id'),data = $(this).data();
                            data = $.extend(false, option, data); // 通过input data属性覆盖默认属性，更多属性查看文档

                            // 自动加上域名
                            if (data.data.indexOf(Config.root_file)<0) {
                                data.data = Config.root_domain+(data.data.substr(0,1)=='/'?data.data:'/'+data.data);
                            }

                            // 判断是否自定义条件json类型
                            let jsonStr = data.params;
                            if (typeof jsonStr!=='function' && typeof jsonStr!=='undefined') {
                                data.params = function(){return jsonStr;}
                            }
                            $('#'+id).selectPage(data);
                        })
                    })
                }
            },
            selectpicker: function (form) {
                if (form.find('.selectpicker').length>0) {
                    // 加载selectpicker下拉插件
                    require(['selectpicker'], function (undefined) {
                        let option = {
                            style: "btn-white",
                            noneSelectedText: lang('Please choose'), // 多重选择没有选定选项时显示的文本。
                        }

                        $.fn.selectpicker.defaults = {
                            noneSelectedText: '没有选中任何项',
                            noneResultsText: '没有找到匹配项',
                            countSelectedText: '选中{1}中的{0}项',
                            maxOptionsText: ['超出限制 (最多选择{n}项)', '组选择超出限制(最多选择{n}组)'],
                            multipleSeparator: ', ',
                            selectAllText: '全选',
                            deselectAllText: '取消全选'
                        };

                        form.find('.selectpicker').each(function (key,item) {
                            let id = $(this).attr('id'),data = $(this).data();
                            data = $.extend(false, option, data);

                            $('#'+id).selectpicker(data);
                        })
                    });
                }
            },
            laydate: function (form) {
                if (form.find('.laydate').length>0) {
                    // 加载laydate插件
                    require(['laydate'], function (Laydate) {
                        form.find('.laydate').each(function (idx,vo) {
                            let obj = {
                                elem: vo,
                                type: 'datetime',
                                trigger: 'click',
                                value: $(this).val()
                            };
                            obj = $.extend(obj, $(this).data());
                            Laydate.render(obj);
                        });
                    })
                }
            },
            fileSelect: function (form) { // 文件选择
                form.on('click', '.btn-imgSelect', function (e) {
                    let option = {
                        field: 'image',
                        mimetype: '*',
                        multiple: false,
                        fileNum: 10
                    };
                    option = $.extend(option, $(this).data());
                    let url = Util.setUrlParams({url:Config.root_domain+'/routine.attachment/select', query:option});
                    cmsOpen(url,lang('Select image'));
                })
            },
            fileUpload: function (form) { // 文件上传插件
                if (form.find('.btn-imgUpload').length>0) {
                    require(['jquery-fileupload'], function (undefined) { // 加载文件上传插件
                        form.find('.btn-imgUpload').each(function (index) {
                            if ($(this).parent().find('input[type=file]').length!=0) {
                                return true;
                            }
                            let option = {
                                url: Config.upload_url,
                                field: 'image',
                                mimetype: '*',
                                multiple: false
                            };
                            option = $.extend(option, $(this).data());
                            $(this).after('<input type="file" class="input-file'+index+'" style="display: none" name="files[]" '+(option.multiple==true?'multiple':'')+' accept="'+option.mimetype+'">');
                            $(this).bind('click', {}, function (e) {
                                if (!$(this).is('.disabled')) {
                                    $(this).next().click();
                                }
                            });

                            var chunkSize = 0; // 每次上次的分块字节
                            var error = 0; // 1-错误，0-继续上传分块
                            var count = 1;
                            option = {
                                url: Config.upload_url,
                                type: 'POST',
                                dataType: 'json', // 服务器返回的数据类型
                                autoUpload: true, // 选择文件后自动上传
                                mimetype: '*',  // 文件类型
                                size: Config.file_size || (2*1024*1024),
                                singleFileUploads: false,
                                fileNum: 10,
                                filesguid: Util.guid(),
                                maxChunkSize: Config && Config.chunk && Config.chunk==1 ? Config.chunk_size:0,  // 2MB
                                formData: function (form) { // 额外表单
                                    var allow = [];
                                    if (option && option.fields) {
                                        var arr = option.fields.split(',');
                                        if (arr.length>0) {
                                            $.each(form.serializeArray(), function (idx, item) {
                                                if ($.inArray(item.name,arr)!=-1) {
                                                    allow.push(item);
                                                }
                                            })
                                        }
                                    }
                                    return allow;
                                },
                                add: function (e, data) { // 文件添加验证
                                    let arr = option.mimetype.split(',');
                                    if (data.originalFiles.length > option.fileNum) {
                                        layer.msg(lang('Only %s file can be uploaded at a time!',[option.fileNum]),{time: 4000,icon:2});
                                        return false;
                                    }
                                    for (let idx in data.originalFiles) {
                                        // 文件格式限制
                                        if (option.mimetype.indexOf("/")===-1) { // .jpg,.png格式
                                            var index1 = data.originalFiles[idx]['name'].lastIndexOf(".");
                                            var index2 = data.originalFiles[idx]['name'].length;
                                            var ext = data.originalFiles[idx]['name'].substring(index1,index2);
                                            if (option.mimetype!='*' && 0>$.inArray(ext, arr)) {
                                                layer.msg(lang('Unsupported file suffix'), {time: 4000,icon:2});
                                                return false;
                                            }
                                        } else {
                                            // image/png 格式判断
                                            var type = data.originalFiles[idx]['type'];
                                            if (option.mimetype.indexOf("/*") !== -1) {
                                                type = type.split('/');
                                                type[1] = '*';
                                                type = type.join('/');
                                            }

                                            if (option.mimetype!='*' && 0>$.inArray(type, arr)) {
                                                layer.msg(lang('Unsupported file suffix'), {time: 4000,icon:2});
                                                return false;
                                            }
                                        }

                                        //文件大小判断
                                        if(data.originalFiles[idx].size > option.size) {
                                            layer.msg(lang('Please upload a leaflet that does not exceed %s',[(option.size/1024).toFixed(2)+'KB']),{time: 4000,icon:2});
                                            return false;
                                        }
                                    }
                                    count = 1;
                                    chunkSize = 0;
                                    data.submit();
                                },
                                progressall: function (e, data) { // 进度
                                    var progress = parseInt(data.loaded / data.total * 100, 10);
                                    var obj = $(e.target).parent().find('.btn-imgUpload');

                                    obj.addClass('disabled');

                                    var value = '';
                                    if (obj.is('input')) {
                                        value = obj.val();
                                        obj.val(progress+'%');
                                    } else {
                                        value = obj.html();
                                        obj.html(progress+'%');
                                    }
                                    if (!obj.data('value')) {
                                        obj.attr('data-value', value);
                                    }
                                },
                                done: function (e, data) { // 成功回调
                                    count = 1;
                                    var obj = $(e.target).parent().find('.btn-imgUpload');

                                    if (obj.is('input')) {
                                        obj.val(obj.data('value'));
                                    } else {
                                        obj.html(obj.data('value'));
                                    }

                                    obj.removeClass('disabled');
                                    if (data.result.code==200) {
                                        if (!data.result.data || data.result.data.length==0) {
                                            layer.msg(lang('Not uploaded successfully'),{time: 4000,icon:2});
                                            return false;
                                        }
                                        var paths = [];
                                        $.each(data.result.data, function (idx, item) {
                                            paths.push(item.path);
                                        })
                                        var newfilesnum = paths.length;
                                        paths = paths.join(',');
                                        var multiple = $(e.target).attr('multiple');
                                        if (multiple=='multiple' || multiple==1) {
                                            var oldfiles = $('#'+option.field).val();
                                            if (oldfiles.length==0) {
                                                $('#'+option.field).val(paths);
                                            } else {
                                                oldfiles = oldfiles.split(',');
                                                if (oldfiles.length+newfilesnum>option.fileNum) {
                                                    layer.msg(lang('Only %s file can be uploaded at a time!',[option.fileNum]),{time: 4000,icon:2})
                                                    return false;
                                                }
                                                $('#'+option.field).val($('#'+option.field).val()+','+paths);
                                            }
                                        } else {
                                            $('#'+option.field).val(paths);
                                        }
                                        $('#'+option.field).trigger('change');
                                    } else {
                                        layer.alert(data.result.msg);
                                    }
                                },
                                chunksend: function (e, data) { // 分块上传前的回调，返回false，结束上传
                                    if (error) {
                                        return false;
                                    }
                                    data.data.append('chunksize', chunkSize += data.chunkSize);
                                    data.data.append('filesize', data.files[0].size);
                                    data.data.append('fileid', data.filesguid);
                                    data.data.append('fileindex', count);

                                    count++;
                                },
                                chunkdone: function (e, data) { // 每个分块上传完成的回调
                                    if (data.result.code!=200) {
                                        layer.alert(data.result.msg);
                                        error = 1;
                                        return false;
                                    }
                                },
                                fail: function (e, data) {
                                    if (data.maxChunkSize>0) {
                                        // 切片上传处理
                                        var url = Util.setUrlParams({url:data.url, query:{action:'clear',fileid:data.filesguid}})
                                        $.get({url: url});
                                    }
                                    count = 1;

                                    layer.alert(data._response.jqXHR.responseJSON.message);
                                }
                            };

                            option = $.extend(option, $(this).data());
                            $('.input-file'+index).fileupload(option);
                        })
                    })
                }
            },
            filePreview: function (form) { // 文件input框更改事件,预览
                form.on('change','.txt-files', function (e) {
                    if (!$(this).parent().parent().find('.file-preview')) {
                        return false;
                    }
                    let imgStr = $(this).val();
                    if (imgStr.length==0) {
                        return false;
                    }

                    // 判断是否是：base图片
                    let html = '';
                    if (/^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s]*?)\s*$/i.test(imgStr)) {
                        html += '<div class="col-md-3">\n' +
                            '<a href="'+imgStr+'" target="_blank"><img src="'+imgStr+'" class="img-thumbnail"></a>\n' +
                            '<a href="#" class="btn btn-danger btn-xs preview-del mt-2" data-index="0"><i class="fas fa-trash-alt"></i></a>\n' +
                            '</div>';
                        $(this).parent().parent().find('.file-preview').html(html);
                        return true;
                    }

                    let arr = imgStr.split(',');
                    var reg = /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i
                    var file = '';
                    var ext = '';
                    
                    for (var idx in arr) {
                        file = reg.test(arr[idx]) ? arr[idx] : Config.cdn_url+arr[idx];
                        if (file.length==0) {
                            continue;
                        }
                        ext = file.split('.').pop().toLowerCase();
                        if (ext=='mp4') {
                            html += '<div class="col-md-3">\n' +
                                '<a href="'+arr[idx]+'" target="_blank"><img src="'+Config.static_path+'/img/video.png" class="img-thumbnail"></a>\n' +
                                '<a href="#" class="btn btn-danger btn-xs preview-del mt-2" data-index="'+idx+'"><i class="fas fa-trash-alt"></i></a>\n' +
                                '</div>';
                        } else if ($.inArray(ext, ['png','jpg','jpeg','gif','bmp','ico'])!=-1) {
                            html += '<div class="col-md-3">\n' +
                                '<a href="'+arr[idx]+'" target="_blank"><img src="'+(file)+'" class="img-thumbnail"></a>\n' +
                                '<a href="#" class="btn btn-danger btn-xs preview-del mt-2" data-index="'+idx+'"><i class="fas fa-trash-alt"></i></a>\n' +
                                '</div>';
                        } else {
                            html += '<div class="col-md-3">\n' +
                                '<a href="'+arr[idx]+'" target="_blank"><img src="'+Config.static_path+'/img/zip.png" class="img-thumbnail"></a>\n' +
                                '<a href="#" class="btn btn-danger btn-xs preview-del mt-2" data-index="'+idx+'"><i class="fas fa-trash-alt"></i></a>\n' +
                                '</div>';
                        }
                    }
                    $(this).parent().parent().find('.file-preview').html(html);
                });
                form.find('.txt-files').trigger('change');
                form.on('click', '.preview-del', function (e) {
                    let obj = $(this).parents('.fileGroup').find('.txt-files');
                    let arr = obj.val().split(',');
                    let index = $(this).parents('.fileGroup').find('.preview-del').index(this)
                    arr.splice(index,1);
                    obj.val(arr.join(','));
                    $(this).parent().remove();
                });
            },
            tips: function (form) {
                var tips_index = 0;
                form.on('mouseover', '.form-tips span', function (e) {
                    if ($(this).data('tips')) {
                        tips_index = layer.tips($(this).data('tips'), this, {
                            tips: 2,
                            time: 0
                        });
                    } else if (typeof($(this).attr('title111'))!= "undefined") {
                        tips_index = layer.tips($(this).attr('title'), this, {
                            tips: 2,
                            time: 0
                        });
                    }
                }).on('mouseleave', '.form-tips span', function(){
                    layer.close(tips_index);
                });
            },
            keyvalue: function (form) {
                if (form.find('.keyvalue').length>0) {
                    require(['jquery-ui'], function (undefined) {
                        // 更新
                        var updateJson = function (e) {
                            var arr = {};
                            e.children('.row').each(function (idx, item) {
                                var tmp = $(this).find('[data-name="keyvalue-key"]').val();
                                if (tmp) {
                                    arr[tmp] = $(this).find('[data-name="keyvalue-value"]').val();
                                }
                            })
                            e.parent().find('.key-value-textarea').val($.isEmptyObject(arr)?'':JSON.stringify(arr));
                        };

                        form.find('.keyvalue').each(function (idx, item) {
                            updateJson($(this).find('.keyvalue-item'));
                            $(this).find('.keyvalue-item').sortable({update: function (e) {
                                    updateJson($(this));
                                }});
                        });

                        // 删除行
                        $(document).on('click', '.btn-keyvalue-row-del', function (e) {
                            var obj = $(this).closest('.keyvalue-item');
                            $(this).parent().parent().remove();
                            updateJson(obj);
                            e.preventDefault();
                        })
                        // 添加行
                        $(document).on('click', '.btn-keyvalue-row-add', function (e) {
                            var obj = $(this).closest('.keyvalue');
                            var html = obj.find('.keyvalue-template').html();
                            obj.find('.keyvalue-item').append(html);
                            e.preventDefault();
                        })

                        // 值更改
                        $(document).on('change keyup', ".keyvalue .keyvalue-item input", function () {
                            updateJson($(this).closest('.keyvalue-item'))
                        });
                    });
                }
            },
            more: function (form) {
            }
        }
    }
    return Form;
});

define('cmsTable', ['jquery','bootstrap-table','bootstrap-table-lang'], function ($, undefined) {

    var cmsTable = {
        defaults: { // 对应bootstraptable属性，表格选项,(doc: https://www.bootstrap-table.com.cn/doc/api/table-options/)
            classes: 'table table-bordered table-hover table-striped',
            theadClasses: '',
            sortName: 'id', // 排序字段
            sortOrder: 'desc',
            url:'',
            method: 'get',
            pagination: true, //为在表格底部显示分页工具栏
            sidePagination: 'server', // 服务端分页
            pageSize: Tpl && Tpl.page && Tpl.page>10 ? parseInt(Tpl.page) : 10, // 初始分页大小
            pageList: [10, 15, 25, 50, 100, 'all'], // all 显示所有
            paginationLoop: true, // 分页连续循环模式。
            search: false, // 快速搜索，formatSearch:function(){return"Search"},更改提示
            toolbar:'#toolbar', //工具栏
            showColumns: true, // 显示行下拉选项
            showRefresh: false, // 显示表格刷新
            showToggle: true,   // 卡片/表格切换
            showFullscreen: false, // 全屏按钮
            escape: true, // 转义用于插入HTML的字符串，并替换 &, <, >, “, `, and ‘ 字符
            clickToSelect: true, // 行点击选中
            singleSelect: false, // 是否开启单选
            multipleSelectRow: false, // 设置true以启用多选行。可以使用ctrl键单击以选择一行，或使用shift键单击以选择一系列行
            pk: 'id',
            responseHandler: function(res) {
                if (res && res.code && res.code===-1000) {
                    layer.msg(res.msg, {time: 4000,icon:2});
                    return [];
                }
                return res;
            },
            queryParams: function(params) {
                let exp = {};
                $('.filter-panel').find('[data-op]').each(function (id, vo) {
                    var name = $(this).attr('name');
                    if (typeof name == 'undefined'){
                        return true;
                    }
                    if ($.inArray($(this).data('op').toUpperCase(), ['BETWEEN','NOT BETWEEN','BETWEEN TIME','NOT BETWEEN TIME'])>=0 && !$(this).hasClass('laydate')) {
                        var start = $('#'+$(this).attr('name')+'_start').val() ? $('#'+$(this).attr('name')+'_start').val() : '';
                        var end = $('#'+$(this).attr('name')+'_end').val() ? $('#'+$(this).attr('name')+'_end').val() : '';
                        if (!start && !end) {
                            $(this).val('');
                        } else {
                            $(this).val(start+' - '+end);
                        }
                    }
                    if (($(this).data('op').toUpperCase()=='IN' || $(this).data('op').toUpperCase()=='NOT IN') && $(this).hasClass('selectpage')) {
                        var str = $(this).attr('id');
                        if (str.indexOf('_text')>=0) {
                            str = str.substr(0, str.length-5);
                        }
                        name = $('#'+str).attr('name');
                    }
                    exp[name] = $(this).data('op');
                });

                params.filter = $('.frm-filter').serialize();
                params.op = JSON.stringify(exp);

                var lan = $('.J-hk-contentLang').val();
                if (!lan) {
                    lan = Config.content_lang_mode
                }
                params.clang = lan;
                return params;
            }
        },
        columnDefaults: {   // 列表选项
            align: 'center',
            valign: 'middle'
        },
        config: {
            table: '#table',
            disabledbtn: '.btn-disabled', // 禁用按钮
            btnAdd: '.btn-add',  // 添加按钮标识
            btnEdit: '.btn-edit',  // 添加按钮标识
            btnDel: '.btn-del',  // 删除按钮
            btnRecycle: '.btn-recycle',  // 回收站按钮
            btnRestoreAll: '.btn-restoreAll',  // 还原全部
            btnRestore: '.btn-restore',  // 还原
            btnDestroyAll: '.btn-destroyAll',  // 销毁全部
            btnDestroy: '.btn-destroy',  // 销毁全部
        },
        init: function(customDefault,customColumnDefaults,config){

            customDefault = customDefault ? customDefault : {};
            customColumnDefaults = customColumnDefaults ? customColumnDefaults : {};
            config = config ? config : {};

            // 合并覆盖
            $.extend($.fn.bootstrapTable.defaults, this.defaults, customDefault);
            $.extend(true, $.fn.bootstrapTable.columnDefaults, this.columnDefaults, customColumnDefaults);
            $.extend(this.config, config);
            var table = $(this.config.table);
            $.extend(true,$.fn.bootstrapTable.columnDefaults, {table:table});
            table.bootstrapTable();
            return this.run(table);
        },
        api: {
            getSelectionsId: function(table, isStr) {
                var ids = table.bootstrapTable('getSelections');
                if (ids.length===0) {
                    layer.msg(lang('Please select a record line'),{time: 4000,icon:2});
                    return false;
                }
                var idsArr = [];
                $.each(ids, function (key, value) {
                    idsArr.push(value.id);
                });
                if (isStr) {
                    ids = idsArr.join(',');
                } else {
                    ids = idsArr;
                }
                return ids;
            }
        },
        run: function (table) {
            var that = this;

            // 获取选项
            var options = table.bootstrapTable('getOptions');
            // 内容多语言切换.
            if (Config.content_lang_on==1 && options.contentLangSw) {
                var html = '';
                $.each(Config.content_lang_list, function (idx, vo) {
                    html += '<option value="'+idx+'" '+(Config.content_lang_mode==idx?'selected':'')+'>'+(Config.content_lang_mode==idx?"("+lang('Current')+")"+vo:vo)+'</option>';
                })
                $('.J-hk-contentLang').html(html);
                $('.J-hk-contentLang').attr('data-toggle','tooltip');
                $('.J-hk-contentLang').attr('data-original-title',lang('Only for query, will not affect edit mode'));
                $('.J-hk-contentLang').removeClass('d-none');
                $(document).on('change', '.J-hk-contentLang', function (e) {
                    table.bootstrapTable('refresh');
                });
            }

            // checkbox 选中事件、取消、全选事件
            table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function (e) {
                var ids = table.bootstrapTable('getSelections');
                $(that.config.disabledbtn, options.toolbar).toggleClass('disabled', !ids.length);
            });
            //当刷新表格时
            table.on('refresh.bs.table', function (e, settings, data) {
                $(that.config.disabledbtn, options.toolbar).addClass("disabled");
            });
            // 重载页面
            $(options.toolbar).on('click','.btn-refresh',function (e) {
                //window.location.reload();
                table.bootstrapTable('refresh');
            });

            // 渲染完成后
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $('[data-toggle="tooltip"]').tooltip();
                $(that.config.disabledbtn, options.toolbar).addClass("disabled");
            });

            // 工具栏【增、改、删、导入、导出、状态更改、回收站】
            $(options.toolbar).on('click',this.config.btnAdd,function (e) {
                var data = $(this).data();

                if (options && options.addCallback && typeof options.addCallback === "function") { // 回调
                    var res = options.addCallback.call(e, data);
                    if (res===false) {
                        return false;
                    }
                }
                if (data.popup===false) {
                    // 新页面
                    window.location.href = Util.setUrlParams({url:data.url, query:{popup:0}});
                } else {
                    cmsOpen(Util.setUrlParams({url:data.url, query:{popup:1}}),lang('Add'))
                }
            });

            // 修改
            $(options.toolbar).on('click',this.config.btnEdit,function (e) {
                if ($(this).hasClass('disabled')) {
                    return false;
                }

                var ids = cmsTable.api.getSelectionsId(table);
                var data = $(this).data();

                if (options && options.editCallback && typeof options.editCallback === "function") { // 回调
                    var res = options.editCallback.call(e, data, ids);
                    if (res===false) {
                        return false;
                    }
                }

                if (data.popup===false) {
                    // 新页面
                    if (ids.length>1) {
                        layer.msg(lang('Only one line of record can be operated~'),{time: 4000,icon:2});
                        return false;
                    }
                    window.location.href = Util.setUrlParams({url:data.url, query:{popup:0,id:ids[0]}});
                } else {
                    $.each(ids, function (key, value) {
                        cmsOpen(Util.setUrlParams({url:data.url, query:{popup:1,id:value}}), lang('Edit'));
                    });
                }
            });

            // 删除
            $(options.toolbar).on('click',this.config.btnDel,function (e) {
                if ($(this).hasClass('disabled')) {
                    return false;
                }

                var ids = cmsTable.api.getSelectionsId(table,true);
                var url = Util.setUrlParams({url:$(this).data('url'), query:{ids:ids}});

                //询问框
                layer.confirm(lang('Confirm operation?'), {
                    btn: [lang('Confirm'),lang('Cancel')] //按钮
                }, function(){
                    Util.ajax({url:url},'',function (data,res) {
                        layer.msg(res.msg,{time:1000, icon:1},function (e) {
                            table.bootstrapTable('refresh');
                        });
                    });
                });
            });

            // 回收站
            $(options.toolbar).on('click', this.config.btnRecycle, function (e) {
                var data = $(this).data();

                if (options && options.recycleCallback && typeof options.recycleCallback === "function") { // 回调
                    var res = options.recycleCallback.call(e, data);
                    if (res===false) {
                        return false;
                    }
                }
                if (data.popup===false) {
                    // 新页面
                    window.location.href = Util.setUrlParams({url:data.url, query:{popup:0}});
                } else {
                    cmsOpen(Util.setUrlParams({url:data.url, query:{popup:1}}),lang('Recycle'))
                }
            });

            // 还原全部
            $(options.toolbar).on('click', this.config.btnRestoreAll, function (e) {
                let that = this;
                //询问框
                layer.confirm(lang('Are you sure to restore everything?'), {
                    btn: [lang('Confirm'),lang('Cancel')] //按钮
                }, function(){
                    Util.ajax({url:$(that).data('url')},'',function (data,res) {
                        layer.msg(res.msg,{time:1000,icon:1},function (e) {
                            table.bootstrapTable('refresh');
                        });
                    });
                });
            });
            // 还原选中项
            $(options.toolbar).on('click', this.config.btnRestore, function (e) {
                if ($(this).hasClass('disabled')) {
                    return false;
                }
                var ids = cmsTable.api.getSelectionsId(table,true);
                var url = Util.setUrlParams({url:$(this).data('url'), query:{ids:ids}});
                layer.confirm(lang('Are you sure to restore the selected items?'), {
                    btn: [lang('Confirm'),lang('Cancel')] //按钮
                }, function(){
                    Util.ajax({url:url},'',function (data,res) {
                        layer.msg(res.msg,{time:1000,icon:1},function (e) {
                            table.bootstrapTable('refresh');
                        });
                    });
                });
            });

            // 销毁全部
            $(options.toolbar).on('click', this.config.btnDestroyAll, function (e) {
                let that = this;
                layer.confirm(lang('Are you sure to destroy the selected item? Document data will be included'), {
                    btn: [lang('Confirm'),lang('Cancel')] //按钮
                }, function(){
                    Util.ajax({url:$(that).data('url')},'',function (data,res) {
                        layer.msg(res.msg,{time:1000,icon:1},function (e) {
                            table.bootstrapTable('refresh');
                        });
                    });
                });
            });
            // 销毁选中项
            $(options.toolbar).on('click', this.config.btnDestroy, function (e) {
                if ($(this).hasClass('disabled')) {
                    return false;
                }
                var ids = cmsTable.api.getSelectionsId(table,true);
                var url = Util.setUrlParams({url:$(this).data('url'), query:{ids:ids}});
                layer.confirm(lang('Are you sure to destroy the selected item? Document data will be included'), {
                    btn: [lang('Confirm'),lang('Cancel')] //按钮
                }, function(){
                    Util.ajax({url:url},'',function (data,res) {
                        layer.msg(res.msg,{time:1000,icon:1},function (e) {
                            table.bootstrapTable('refresh');
                        });
                    });
                });
            });

            // 状态更改
            $(options.toolbar).find('.btn-toggle').on('click','.dropdown-item.status',function (e) {
                var ids = cmsTable.api.getSelectionsId(table,true);
                if (table.data('batches')) {
                    Util.ajax({url: table.data('batches'),data:{ids: ids,params:$(this).data('params')}},'',function (data,res) {
                        layer.msg(res.msg,{time:1000,icon:1},function (e) {
                            table.bootstrapTable('refresh');
                        });
                    })
                } else {
                    layer.msg(lang('Request address is empty'),{time:4000,icon:2});
                }
            })

            // 数据筛选
            if (options.customFilter) {
                $('.filter-panel .frm-filter').submit(function (e) {
                    table.bootstrapTable('refresh', {pageNumber: 1});
                    return false;
                });
                $(document).on('click','.btn-filter',function (e) {
                    $('.filter-panel').toggleClass('d-none');
                });
                if ($('.frm-filter .selectpage').length>0) {
                    require(['Form'], function (Form) {
                        Form.event.selectpage($('.frm-filter'));
                    })
                }
                if ($('.frm-filter .laydate').length>0) {
                    require(['Form'], function (Form) {
                        Form.event.laydate($('.frm-filter'));
                    })
                }
                // 重置表单
                $('.frm-filter').find("input[type=reset]").click(function (e) {
                    setTimeout(function () {
                        table.bootstrapTable('refresh');
                    }, 600);
                })
            }

            // 修改单个字段
            $(document).on('click','.btn-txtSubmit',function (e) {
                var obj = $(this).parent().find('input[type=text]');
                var that = this;
                var data = obj.data();
                Util.ajax({url: table.data('batches'),data:{ids:data.id,params:data.field+'='+obj.val()},type: 'post'},'',function (data, res) {
                    $(that).parents('.frm-tooltip').tooltip('hide');
                    layer.msg(res.msg,{time:1000, icon:1},function (e) {
                        table.bootstrapTable('refresh');
                    });
                })
            });

            // 绑定文件上传事件
            if ($(options.toolbar).find('.btn-uploads').length>0) {
                require(['jquery-fileupload'], function (undefined) {
                    $(options.toolbar).on('click', '.btn-uploads', function (e) {
                        if ($(this).is('.disabled')) {
                            return false;
                        }

                        var chunkSize = 0; // 每次上次的分块字节
                        var error = 0; // 1-错误，0-继续上传分块
                        var count = 1;
                        let op = {
                            url: Config.upload_url,
                            type: 'POST',
                            dataType: 'json', // 服务器返回的数据类型
                            autoUpload: true, // 选择文件后自动上传
                            mimetype: '*',  // 文件类型
                            size: Config.file_size || (2*1024*1024),
                            singleFileUploads: false,
                            multiple: false,
                            fileNum: 10,
                            filesguid: Util.guid(),
                            maxChunkSize: Config && Config.chunk && Config.chunk==1 ? Config.chunk_size:0,  // 2MB
                            add: function (e, data) {
                                count = 1;
                                let arr = op.mimetype.split(',');
                                if (data.originalFiles.length > op.fileNum) {
                                    layer.msg(lang('Only %s file can be uploaded at a time!',[op.fileNum]),{time:4000,icon:2});
                                    return false;
                                }
                                for (let idx in data.originalFiles) {
                                    // 文件格式限制
                                    if (op.mimetype.indexOf("/")===-1) { // .jpg,.png格式
                                        var index1 = data.originalFiles[idx]['name'].lastIndexOf(".");
                                        var index2 = data.originalFiles[idx]['name'].length;
                                        var ext = data.originalFiles[idx]['name'].substring(index1,index2);
                                        if (op.mimetype!='*' && 0>$.inArray(ext, arr)) {
                                            layer.msg(lang('Unsupported file suffix'), {time: 4000,icon:2});
                                            return false;
                                        }
                                    } else {
                                        // image/png 格式判断
                                        var type = data.originalFiles[idx]['type'];
                                        if (op.mimetype.indexOf("/*") !== -1) {
                                            type = type.split('/');
                                            type[1] = '*';
                                            type = type.join('/');
                                        }

                                        if (op.mimetype!='*' && 0>$.inArray(type, arr)) {
                                            layer.msg(lang('Unsupported file suffix'), {time: 4000,icon:2});
                                            return false;
                                        }
                                    }

                                    //文件大小判断
                                    if(data.originalFiles[idx].size > op.size) {
                                        layer.msg(lang('Please upload a leaflet that does not exceed %s',[(op.size/1024).toFixed(2)+'kb']),{time:4000,icon:2});
                                        return false;
                                    }
                                }
                                data.submit();
                            },
                            progressall: function (e, data) {
                                var progress = parseInt(data.loaded / data.total * 100, 10);
                                var obj = $(e.target).parent().find('.btn-uploads');

                                obj.addClass('disabled');

                                var value = '';
                                if (obj.is('input')) {
                                    value = obj.val();
                                    obj.val(progress+'%');
                                } else {
                                    value = obj.html();
                                    obj.html(progress+'%');
                                }
                                if (!obj.data('value')) {
                                    obj.attr('data-value', value);
                                }
                            },
                            done: function (e, data) {
                                count = 1;
                                var obj = $(e.target).parent().find('.btn-uploads');
                                if (obj.is('input')) {
                                    obj.val(obj.data('value'));
                                } else {
                                    obj.html(obj.data('value'));
                                }
                                obj.removeClass('disabled');
                                if (data.result.code==200) {
                                    if (!data.result.data || data.result.data.length==0) {
                                        layer.msg(lang('Not uploaded successfully'),{time:4000,icon:2});
                                        return false;
                                    }
                                    layer.msg(data.result.msg,{time:1000,icon:1},function (e) {
                                        table.bootstrapTable('refresh');
                                    });
                                } else {
                                    layer.alert(data.result.msg);
                                }
                            },
                            chunksend: function (e, data) { // 分块上传前的回调，返回false，结束上传
                                if (error) {
                                    return false;
                                }
                                data.data.append('chunksize', chunkSize += data.chunkSize);
                                data.data.append('filesize', data.files[0].size);
                                data.data.append('fileid', data.filesguid);
                                data.data.append('fileindex', count);

                                count++;
                            },
                            chunkdone: function (e, data) { // 每个分块上传完成的回调
                                if (data.result.code!=200) {
                                    layer.alert(data.result.msg);
                                    error = 1;
                                    return false;
                                }
                            },
                            fail: function (e, data) {
                                if (data.maxChunkSize>0) {
                                    // 切片上传处理
                                    var url = Util.setUrlParams({url:data.url, query:{action:'clear',fileid:data.filesguid}})
                                    $.get({url: url});
                                }
                                count = 1;
                            }
                        };
                        op = $.extend(op, $(this).data());
                        $(this).after('<input type="file" class="toolbar-input-file" style="display: none" name="files[]" '+(op.multiple==true?'multiple':'')+' accept="'+op.mimetype+'">');
                        $(this).next().click();

                        $('.toolbar-input-file').fileupload(op);
                    });
                });
            }

            // 文件选择事件
            $(document).on('click', '.btn-img-select', function (e) {
                let data = table.bootstrapTable('getSelections');
                if (data.length===0) {
                    layer.msg(lang('Please select a record line'),{time:4000,icon:2});
                    return false;
                }
                let arr = [];
                $.each(data, function(key, value) {
                    arr.push(value.path);
                });

                // 判断文件最大选择数
                let fileNum = $(this).data('file-num') || 10;
                if (arr.length>fileNum) {
                    layer.msg(lang('Only %s file can be uploaded at a time!',[fileNum]),{time:4000,icon:2});
                    return false;
                }

                let index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引

                // 判断是否有回调
                var toCallback = parent.$("#layui-layer" + index).data("callback");
                if (toCallback && typeof toCallback === "function") {
                    if (false===toCallback(arr)) {
                        return false;
                    }
                } else {
                    let field = $(this).data('field');
                    if (field) {
                        var multiple = $(this).data('multiple');
                        if (multiple=='multiple' || multiple==1) {
                            var oldfiles = $(parent.document).find('#'+field).val();
                            if (oldfiles.length==0) {
                                $(parent.document).find('#'+field).val(arr.join(','))
                            } else {
                                oldfiles = oldfiles.split(',');
                                if (oldfiles.length+arr.length>fileNum) {
                                    layer.msg(lang('Only %s file can be uploaded at a time!',[fileNum]),{time: 4000,icon:2})
                                    return false;
                                }
                                $(parent.document).find('#'+field).val($(parent.document).find('#'+field).val()+','+(arr.join(',')));
                            }
                        } else {
                            $(parent.document).find('#'+field).val(arr.join(','))
                        }


                        // 触发change事件
                        let $obj = parent.$;
                        $obj('#'+field).trigger('change');
                    }
                }
                parent.layer.close(index);
            });

            return table;
        },

        // 通用格式 输出
        formatter: {
            SN: function(value, row, index) {
                return index+1;
            },
            operate: function (value,row,index) {
                var table = this.table;
                var html = '';
                if (table.data('edit')) {
                    html += '<button type="button" class="btn btn-primary btn-xs btn-row-edit" data-toggle="tooltip" data-placement="top" title="'+lang('Edit')+'" data-popup="'+(typeof(this.popup) !== "undefined"?this.popup:'true')+'"><i class="fas fa-pen"></i></button>&nbsp;';
                }
                if (table.data('del')) {
                    html += '<button type="button" class="btn btn-danger btn-xs btn-row-del" data-toggle="tooltip" data-placement="top" title="'+lang('Delete')+'" data-tips="'+(this.delTips || '')+'"><i class="fas fa-trash-alt"></i></button>&nbsp;';
                }
                return html;
            },
            switchBtn: function (value, row, index, field) { // 切换按钮。1-打开 0-关闭
                var table = this.table;
                var checked = 1;
                if (!value || value===0 || value === '0' || value=='hidden') {
                    checked = 0;
                }
                if (table.data('batches')) {
                    return '<div class="custom-control custom-switch custom-switch-on-teal " data-toggle="tooltip" data-trigger="hover" data-placement="top" title="'+lang('Click to switch')+'">\n' +
                        '<input type="checkbox" class="custom-control-input" id="switch'+field+'_'+index+'" data-field="'+field+'" '+(checked===1?'checked':'')+' >\n' +
                        '<label class="custom-control-label" for="switch'+field+'_'+index+'"></label>\n' +
                        '</div>'
                } else {
                    return '<div class="custom-control custom-switch" data-toggle="tooltip" data-trigger="hover" data-placement="top" title="'+lang('Permission denied')+'">\n' +
                        '<input type="checkbox" class="custom-control-input" disabled id="switch'+field+'_'+index+'" data-field="'+field+'" '+(checked===1?'checked':'')+' >\n' +
                        '<label class="custom-control-label" for="switch'+field+'_'+index+'"></label>\n' +
                        '</div>'
                }
            },
            txtEditBtn: function (value, row, index, field) {
                var table = this.table;
                if (table.data('batches')) {
                    value = value+'&nbsp;<a class="btn-txtEditBtn" data-html="true" data-trigger="click" href="#" data-field="'+field+'"><i class="fa fa-pencil-alt"></i></a>';
                    return value;
                } else {
                    return value;
                }
            },
            textBox: function (value, row, index, field) { // 设置超过多少隐藏文本
                let textLength = typeof this.textLength === 'undefined' || this.textLength=='' ? 0 : this.textLength;
                let html = '';
                if (value.length>textLength) {
                    html += '<a class="btn btn-sm btn-default text-box-btn" data-field="'+this.field+'"><i class="fas fa-eye"></i></a>';
                } else {
                    html += value;
                }
                return html;
            },
            image: function (value, row, index, field) {
                if (!value) {
                    return '';
                }
                let html = '';
                if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG|ICO)$/.test(value)) {
                    if (/\.mp4$/.test(value)) {
                        html += '<a href="'+Config.static_path+'/img/video.png" target="_blank"><img src="'+Config.static_path+'/img/video.png" data-toggle="tooltip" title="'+lang('Click to open')+'" data-url="'+value+'" style="width: auto;height:60px;object-fit: cover;cursor: pointer" class="img-thumbnail"></a>';
                    } else if (/^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s]*?)\s*$/i.test(value)) {
                        html += '<img src="'+value+'" style="width: 100px;height:60px;object-fit: cover;cursor: pointer" data-toggle="tooltip" title="'+lang('Click to open')+'" class="img-thumbnail">';
                    } else {
                        html += '<a href="'+Config.static_path+'/img/zip.png" target="_blank"><img src="'+Config.static_path+'/img/zip.png" data-toggle="tooltip" title="'+lang('Click to open')+'" data-url="'+value+'" style="width: auto;height:60px;object-fit: cover;cursor: pointer" class="img-thumbnail"></a>';
                    }
                } else {
                    html += '<a href="'+value+'" target="_blank"><img src="'+value+'" style="width: 100px;height:60px;object-fit: cover;cursor: pointer" data-toggle="tooltip" title="'+lang('Click to open')+'" data-url="'+value+'" class="img-thumbnail" style=""></a>';
                }
                return html;
            }
        },
        //单元格元素事件
        events: {
            operate: {
                'click .btn-row-edit': function (e, value, row, index) {
                    e.stopPropagation();
                    var table = $(e.currentTarget).closest('table');
                    var options = table.bootstrapTable('getOptions');
                    var id = row[options.pk];
                    var data = $(e.currentTarget).data();
                    var url = table.data('edit');
                    if (!url) {
                        layer.msg(lang('Request address is empty'),{time:4000,icon:2});
                        return false;
                    }

                    if (options && options.editCallback && typeof options.editCallback === "function") { // 回调
                        var res = options.editCallback.call(e, {url:url}, id, row);
                        if (res===false) {
                            return false;
                        }
                    }

                    if (data.popup===false) {
                        // 新页面
                        window.location.href = Util.setUrlParams({url:url, query:{popup:0,id:id}});
                    } else {
                        cmsOpen(Util.setUrlParams({url:url,query:{popup:1,id:id}}), lang('Edit'));
                    }
                },
                'click .btn-row-del': function (e, value, row, index) {
                    e.stopPropagation();

                    var table = $(e.currentTarget).closest('table');
                    var options = table.bootstrapTable('getOptions');
                    var id = row[options.pk];
                    var url = table.data('del');
                    if (!url) {
                        layer.msg(lang('Request address is empty'),{time:4000,icon:2});
                        return false;
                    }

                    var data = $(e.currentTarget).data();
                    layer.confirm(data && data.tips || lang('Confirm operation?'), {
                        btn: [lang('Confirm'),lang('Cancel')] //按钮
                    }, function(){
                        Util.ajax({url:Util.setUrlParams({url:url, query:{ids:id}})},'',function (data,res) {
                            layer.msg(res.msg,{time:1000,icon:1},function (e) {
                                table.bootstrapTable('refresh');
                            });
                        });
                    });
                }
            },
            switchBtn: {
                'change .custom-control-input': function (e, value, row, index) {
                    var table = $(e.currentTarget).closest('table');
                    var options = table.bootstrapTable('getOptions');
                    var r=/^\d+$/;
                    var val;
                    if (r.test(value)) {
                        val = value===1?0:1;
                    } else {
                        val = value==='normal'?'hidden':'normal';
                    }
                    if (table.data('batches')) {
                        Util.ajax({url: table.data('batches'),data:{ids: row[options.pk],params:$(e.currentTarget).data('field')+'='+val}},'',function (data,res) {
                            layer.msg(res.msg,{time:1000,icon:1},function (e) {
                                table.bootstrapTable('refresh');
                            });
                        })
                    } else {
                        layer.msg(lang('Permission denied'),{time:4000,icon:2});
                    }
                }
            },
            txtEditBtn: {   // 快速修改字段值
                'click .btn-txtEditBtn': function (e, value, row, index) {
                    e.stopPropagation();
                    e.preventDefault();
                    var table = $(e.currentTarget).closest('table');
                    var options = table.bootstrapTable('getOptions');
                    $(e.currentTarget).tooltip({
                        title:'<div class="txtEditBtn-content"><input class="form-control" type="text" data-field="'+$(e.currentTarget).data('field')+'" data-id="'+row[options.pk]+'" value="'+value+'">&nbsp;<button class="btn btn-primary btn-xs btn-txtSubmit" title="'+lang('Confirm')+'"><i class="fa fa-check"></i></button>&nbsp;<button class="btn btn-danger btn-xs" title="'+lang('取消')+'" onclick="$(this).parents(\'.frm-tooltip\').tooltip(\'hide\')"><i class="fa fa-times"></i></button></div>',
                        template: '<div class="tooltip frm-tooltip" role="tooltip">' + '<div class="arrow"></div>' + '<div class="tooltip-inner"></div></div>',
                        sanitizeFn: function (content) {
                            return content;
                        }
                    });
                    $(e.currentTarget).tooltip('show');
                }
            },
            textBoxBtn: { // 弹出式显示文本内容
                'click .text-box-btn': function (e, value, row, index) {
                    e.stopPropagation();
                    if (typeof offset_val === 'undefined') {
                        offset_val = [100,100];
                    }
                    window.cmsOpen(`<div style="word-wrap:break-word;padding: 10px;">`+value+'</div>',lang('Details'),{
                        type: 1,
                        offset:[offset_val[0]+'px',offset_val[1]+'px'],
                        area: ['30%', '40%'],
                        id:'frm-'+$(e.currentTarget).data('field')+index
                    })
                }
            },
            image: {
                'click .img-thumbnail': function (e, value, row, index) {
                    e.stopPropagation();
                    e.preventDefault();
                    let img = $(e.currentTarget).data('url');
                    window.open(img)
                }
            }
        }
    };
    return cmsTable;
});

require(['jquery','bootstrap','adminlte'], function ($) {
    if ($('.operatePage').find('.card-body').length==1) {
        function resizeFrom() {
            var heights = {
                body: $('body').outerHeight(),
                header: $('.frm-operate').find('.card-header').outerHeight() || 0,
                footer: $('.frm-operate').find('.card-footer').outerHeight() || 0
            };
            $('.frm-operate').find('.card-body').css('overflow-y','auto');
            $('.frm-operate').find('.card-body').css('height', heights.body - heights.header - heights.footer);
        }

        $(window).resize(function() {
            resizeFrom();
        });
        resizeFrom();
    }
    $(document).on('click','.btn-newMenu', function (e) {
        e.preventDefault();

        var obj;
        if(top.location!=self.location){
            obj = window.top.$;
        } else {
            obj = $;
        }

        if ($(this).data('id')) {
            var link = $(this).data('id').toString();
        } else {
            var link = $(this).attr('href');
        }

        link = link.replace('./', '').replace(/["&'./:=?[\]]/gi, '-').replace(/(--)/gi, '');

        var len = obj('.iframe-mode .navbar-nav').find('#tab-'+link).length;
        if (len>0) {
            obj('.content-wrapper').IFrame('switchTab', '#tab-'+link)
        } else {
            obj('.content-wrapper').IFrame('createTab', $(this).data('title'), $(this).attr('href'), link, true)
        }
    })
})