/*!
 * 应用通用功能
 * 米拓企业建站系统 Copyright (C) 长沙米拓信息技术有限公司 (https://www.metinfo.cn). All rights reserved.
 */
// 系统参数
(function(){
if(typeof MET != 'undefined'){
    for (const key in MET.url) {
        MET.url[key]=MET.url[key].replace('../',M.weburl);
    }
    $.extend(M, MET),MET=M;
}
if(!M.url) M.url=[];
M.url.public=M.weburl+'public/';
M.url.public_admin=M.url.public+'admin/';
M.url.public_images=M.url.public+'images/';
M.url.public_plugins=M.url.public+'plugins/';
M.url.app=M.weburl+'app/app/';
M.url.system=M.weburl+'app/system/';
M.met_ai_open=parseInt(M.met_ai_open||0);
M.met_editor_plugin=(M.met_editor=='ueditor'?[
    M.met_editor,
    M.met_ai_open?`${M.url.app}met_ai/web/templates/js/init.js`:''
]:[
    M.text_markdown?'':'#app/editorswith/editormd/markdown/dist/to-markdown',
    M.met_editor,
    M.synchronous=='cn'?'':'#app/editorswith/editormd/languages/'+M.synchronous
]).filter(value => value);
// 系统功能
$.fn.extend({
    // 编辑器
    metEditor:function(){
        if(!$(this).length) return;
        var $self=$(this);
        if(typeof EDITOR_VAL =='undefined') window.EDITOR_VAL=[];
        M.load(M.met_editor_plugin,function(){
            $self.each(function(index, val) {
                var editor_y=parseInt($(this).data('editor-y'))||400;
                if(M.met_editor=='ueditor'){// 百度编辑器
                    if(!$(this).attr('id')){
                        var id='ueditor-'+new Date().getTime();
                        if($('#'+id).length) id+=index;
                        $(this).attr({id:id});
                    }
                    if(EDITOR_VAL[val.id] && $('#'+val.id+'.edui-default').length) EDITOR_VAL[val.id].destroy();
                    var $scrollbar=$(this).parents('.met-scrollbar').eq(0),
                        wrapper='';
                    if($scrollbar.length){
                        if(!$scrollbar.attr('id')) $scrollbar.attr({id:'scrollbar-'+new Date().getTime()});
                        wrapper='#'+$scrollbar.attr('id');
                    }
                    EDITOR_VAL[val.id]=UE.getEditor(val.id,{
                        lang:M.synchronous=='en'?'en':'zh-cn',
                        wrapper:wrapper,
                        scaleEnabled:true, // 是否可以拉伸长高,默认false(当开启时，自动长高失效)
                        autoFloatEnabled:false, // 是否保持toolbar的位置不动，默认true
                        initialFrameWidth : parseInt($(this).data('editor-x'))||'100%',
                        initialFrameHeight : editor_y,
                        initialContent:$(this).next('script').length?htmlDecode($(this).next('script').prop('innerHTML').slice(1,-2)):$(this).text(),
                    });
                }else if(M.met_editor=='editormd'){// markdown编辑器
                    var id='editormd-'+new Date().getTime(),
                        html=$(this).next('script').length?$(this).next('script').prop('innerHTML').slice(1,-2):$(this).text();
                    if($('#'+id).length) id+=index;
                    if(!M.text_markdown) html=toMarkdown(html, {gfm: true});
                    $(this).wrap(`<div id="${id}" class="mb-0" style="min-height:${editor_y+41}px;"></div>`);
                    var this_editormd=function(id,name,data){
                            EDITOR_VAL[id] = editormd(id, {
                                name:name,
                                width: parseInt($(this).data('editor-x'))||'100%',
                                height: editor_y,
                                htmlDecode: true,
                                markdown:htmlDecode(data)||'',
                                saveHTMLToTextarea: M.text_markdown?false:true,
                                path: M.url.app+'editorswith/editormd/lib/',
                                // emoji:1,
                                imageUpload: true,
                                autoFocus: false,
                                // imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"]
                            });
                            EDITOR_VAL[id].setContent=function(value){
                                EDITOR_VAL[id].setValue(M.text_markdown?htmlDecode(value):toMarkdown(value, {gfm: true}));
                            };
                        };
                    interval({
                        true_val:(time)=>{
                            return $(this).parent().is(':visible');
                        },true_fun:(time)=>{
                            if(M.text_markdown && html.indexOf('text_markdown')>=0){
                                var this_module=$.extend(true,{},admin_module);
                                M.ajax({
                                    url: this_module.own_name+'c='+this_module.data.c+'&a='+this_module.data.a+'&ajax=1&id='+this_module.data.id,
                                    data:{name:$(this).attr('name'),htmlid:id},
                                    success:function(result){
                                        this_editormd(result.id,result.name,result.data);
                                    }
                                });
                            }else{
                                this_editormd(id,$(this).attr('name'),html);
                            }
                        }
                    });
                }
            });
        });
    },
    // 日期时间选择器
    metDatetimepicker:function(){
        if(!$(this).length) return;
        $(this).each(function(index, el) {
            $(this).datetimepicker({
                lang:M.synchronous=='cn'?'ch':'en',
                timepicker:$(this).attr("data-day-type")==2?true:false,
                format:$(this).attr("data-format")||($(this).attr("data-day-type")==2?'Y-m-d H:i:s':'Y-m-d'),
                onSelectDate:(ct,$i)=>{
                    $(this).change();
                },
                onSelectTime:(ct,$i)=>{
                    $(this).change();
                },
                allowBlank:1
            });
        });
    },
    // 联动菜单
    metCitySelect:function(){
        if(!$(this).length) return;
        if(typeof citySelect =='undefined') window.citySelect=[];
        $(this).each(function(index){
            var key=$(this).attr('data-key')&&$(this).attr('data-key')!=''?$(this).attr('data-key'):new Date().getTime()+'-'+index,
                $data=$('.select-linkage-data',this),
                option = {
                    url: $(this).attr('data-select-url')||(M.url.public_plugins+'select-linkage/citydata.min.json'),
                    prov: $(this).find(".prov").attr("data-checked"),
                    city: $(this).find(".city").attr("data-checked"),
                    dist: $(this).find(".dist").attr("data-checked"),
                    nodata: 'none',
                    required:false
                };
            var this_data=$(this).data();
            for (const key in this_data) {
                if(this_data[key]!='') option[key]=this_data[key];
            }
            if(option.url=='json'&&$data.length) option.url=JSON.parse($data.val());
            $(this).attr({'data-key':key});
            if($(this).hasClass('shop-address-select')){
                $.extend(option,{
                    country:$(this).find(".country").attr("data-checked"),
                    country_name_key:'name',
                    p_name_key:'name',
                    n_name_key:'name',
                    s_name_key:'name',
                    p_children_key:'children',
                    n_children_key:'children',
                    getCityjson:function(json,keys){
                        keys=keys||0;
                        return json[keys]['children'];
                    }
                });
            }
            citySelect[key] && citySelect[key].destroy();
            citySelect[key]=$(this).citySelect(option);
        });
    },
    // 拖拽
    metDragsort:function(){
        var $self=$(this);
        if(typeof dragsortFun=='undefined') window.dragsortFun=[];
        $self.each(function(index, el) {
            var scroll_container=window,
                $self=$(this),
                order=$(this).attr('data-dragsort_order')&&$(this).attr('data-dragsort_order')!=''?$(this).attr('data-dragsort_order'):new Date().getTime(),
                $scrollbar=$(this).parents('.met-scrollbar').eq(0);
            if($('[data-plugin="dragsort"][data-listidx][data-dragsort_order="'+order+'"]').length) order+=index;
            $(this).attr({'data-dragsort_order':order});
            $scrollbar.length && (!$scrollbar.attr('data-dragsort_key') && $scrollbar.attr({'data-dragsort_key':order}),(scroll_container='[data-dragsort_key="'+$scrollbar.attr('data-dragsort_key')+'"]'));
            $(this).dragsort('destroy');
            $(this).dragsort({
                dragSelector: $(this).data('drag_selector')||'tr',
                dragBetween: false ,// 设置为“true”，如果你要启用多组列表之间拖动选定的列表。 默认值是false。
                scrollContainer:scroll_container,// CSS选择器的元素，作为滚动容器，例如溢出的div设置为自动。 默认值是“窗口“
                // scrollSpeed:'',// 一个数字，它代表了速度，页面拖动某一项时，将滚动容器外，较高使用价值的是速度和较低的值是较慢的。 如果设置为”0″以禁用滚动。默认值是”5″.
                dragSelectorExclude:typeof $(this).data('drag_selector_exclude')!='undefined'?$(this).data('drag_selector_exclude'):'input,textarea,select,a,i,span,button,.minicolors-panel',
                dragEnd: function() {
                    if(typeof dragsortFun[order]!='undefined') dragsortFun[order]($self,$(this));
                    $self.parents('table').find('.checkall-all:eq(0)').prop({checked:true}).change();
                }
            });
        });
    },
    // 单选、多选默认选中
    metRadioCheckboxChecked:function(){
        if(!$(this).length) return;
        $(this).each(function(index, el) {
            var is_switchery=$(this).attr('data-plugin')=='switchery',
                checked=String(is_switchery?$(this).val():$(this).attr('data-checked')),
                delimiter=$(this).data('delimiter')||'#@met@#';
            if(is_switchery?parseInt(checked):checked !='undefined'){
                checked=checked.indexOf(delimiter)>=0?checked.split(delimiter):[checked];
                var name=$(this).attr('name');
                $(this).parents('form').find('input[name="'+name+'"]').removeAttr('checked');
                for (var i=0; i < checked.length; i++) {
                    $(this).parents('form').find('input[name="'+name+'"][value="'+checked[i]+'"]').attr('checked', true).prop({checked:true}).change();
                }
            }
        });
    },
    // 下拉菜单默认选中
    metSelectChecked:function(){
        if(!$(this).length) return;
        $(this).each(function(index, el) {
            if($(this).attr('multiple')){
                var $self=$(this);
                var value=$(this).attr('data-checked')!=''?$(this).attr('data-checked').split($(this).data('delimiter')||'|'):'';
                $.each(value, function(index1, val1) {
                    $self.find('option[value="'+val1+'"]').attr({selected:true});
                });
            }else $('option[value="'+$(this).attr('data-checked')+'"]',this).attr({selected:true});
        });
    },
    // 图片延迟加载
    metLazyLoad:function(options){
        if(!$(this).length) return;
        var $self=$(this),
            options=options||{};
        if($(this).parents('.met-scrollbar').length){
            var $scrollbar=$(this).parents('.met-scrollbar').eq(0),
                lazyload_container=$scrollbar.attr('data-lazyload_container'),
                container_class=lazyload_container||new Date().getTime();
            if(!lazyload_container){
                if($('.met-scrollbar.'+container_class).length) container_class+=1;
                $scrollbar.attr({'data-lazyload_container':container_class});
            }
            options.container='[data-lazyload_container="'+container_class+'"]';
        }
        M.load('lazyload',function(){
            $self.lazyload(options);
        });
    },
    // 点击ajax请求弹出确认框后以及返回结果通用处理
    metClickConfirmAjax:function(default_options){
        var selector_str=encodeURI(this.selector);
        typeof clickConfirmAjaxStatus=='undefined' && (window.clickConfirmAjaxStatus={});
        if(clickConfirmAjaxStatus[selector_str]){
            return;
        }else{
            clickConfirmAjaxStatus[selector_str]=1;
        }
        var default_options = $.extend({
                ajax_data:'',
                true_text:METLANG.confirm||'确定',
                false_text:METLANG.cancel||'取消',
                confirm_text:METLANG.delete_information||'您确定要删除该信息吗？删除之后无法再恢复。',
                true_fun:function(){
                    var url=typeof this.url=='function'?this.url():this.url,
                        ajax_data=typeof this.ajax_data=='function'?this.ajax_data():this.ajax_data,
                        options_this=this;
                    M.ajax({
                        url: url,
                        data:ajax_data,
                        success:function(result){
                            options_this.ajax_fun(result);
                        }
                    });
                },
                false_fun:'',
                ajax_fun:function(result){
                    metAjaxFun({result:result});
                }
            },default_options);
        $(document).on('click', this.selector, function(event) {
            var options = $.extend({
                    el:$(this),
                    url:$(this).data('url')
                },default_options);
            M.load('alertify',function(){
                var confirm_text=typeof options.confirm_text=='function'?options.confirm_text():options.confirm_text;
                alertify.okBtn(options.true_text).cancelBtn(options.false_text).confirm(confirm_text, function (ev) {
                    options.true_fun();
                },function(){
                    if(typeof options.false_fun=='function') options.false_fun();
                });
            })
        });
    },
    // 表格筛选参数还原默认值
    tabelsearchReset:function(fn){
        M.dataTable_search_stop=1;
        var table_search='[data-table-search]:not([data-table-noreset]):not([type="hidden"]):not([hidden])';
        $(this).find(table_search).val('').change();
        $(this).find(table_search+'select').each(function(index, el) {
            $(this).val($('option:first-child',this).val()).change();
        });
        typeof fn=='function' && fn();
        M.dataTable_search_stop=0;
    },
    clickLoading:function(event){
        if(!$(this).length) return;
        !M.btn_loading_ladda && (M.btn_loading_ladda={});
        var $self=$(this),
            event=event||'start',
            submit_loading_ladda='';
        if(event=='start'){
            $self.attr({disabled:''}).addClass('disabled');
            M.load('ladda',function(){
                var key=new Date().getTime();
                $self.attr({'data-style':'zoom-in','data-key':key});
                submit_loading_ladda = Ladda.create($self[0]);
                submit_loading_ladda.start();
                M.btn_loading_ladda[key]=submit_loading_ladda;
            });
        }else{
            $self.removeAttr('disabled').removeClass('disabled');
            interval({
                true_val:(time)=>{
                    return $self.attr('data-key');
                },true_fun:(time)=>{
                    var key=$self.attr('data-key');
                    M.btn_loading_ladda[key].stop();
                }
            });
        }
    },
    // 通用功能开启
    metCommon:function(){
        var dom=this;
        // 表单验证
        if($('form',dom).length){
            if(typeof validate =='undefined'){
                M.load('form');
            }else{
                $('form',dom).validation();
            }
        }
        // ajax表格
        if($('.dataTable',dom).length){
            if(typeof datatable =='undefined'){
                M.load('table');
            }else{
                $(dom).metDataTable();
            }
        }
        // 弹框自动加载
        $('[data-toggle="modal"],.modal', dom).length && M.load('modal');
        // 编辑器
        $('textarea[data-plugin="editor"]',dom).length && $('textarea[data-plugin="editor"]',dom).metEditor();
        // 颜色选择器
        $('[data-plugin="minicolors"]',dom).length && M.load('minicolors',function(){
            $('[data-plugin="minicolors"]',dom).minicolors().attr({placeholder:METLANG.default_values});
        });
        // 标签
        $('[data-plugin="tokenfield"]',dom).length && M.load('tokenfield',function(){
            $('[data-plugin="tokenfield"]',dom).tokenfield();
        });
        // 滑块
        $('[type="text"][data-plugin="ionRangeSlider"]',dom).length && M.load('ionrangeslider',function(){
            $('[type="text"][data-plugin="ionRangeSlider"]',dom).ionRangeSlider();
        });
        // 日期选择器
        $('[data-plugin="datetimepicker"]',dom).length && M.load('datetimepicker',function(){
            $('[data-plugin="datetimepicker"]',dom).metDatetimepicker();
        });
        // 联动菜单
        $('[data-plugin="select-linkage"]',dom).length && M.load('select-linkage',function(){
            $('[data-plugin="select-linkage"]',dom).metCitySelect();
        });
        // 模态对话框
        $('[data-plugin="alertify"]',dom).length && M.load('alertify');
        // 全选、全不选
        $('[data-plugin="checkAll"]',dom).length && M.load('checkall',function(){
            $('[data-plugin="checkAll"]',dom).checkAll('.checkall-all','.checkall-item:not([disabled])','.checkall-contrary');
        });
        // 上传文件
        $('input[type="file"][data-plugin="fileinput"]',dom).length && M.load('fileinput',function(){
            $('input[type="file"][data-plugin="fileinput"]',dom).metFileInput();
        });
        // 滚动条
        // $('[data-plugin="scrollable"]',dom).length && M.load(M.plugin['asscrollable'],'','siterun');
        $('.met-scrollbar',dom).length && $('.met-scrollbar',dom).addClass('oya').each(function(index, el) {
            $(this).data('height') && $(this).css({'max-height':parseInt($(this).data('height'))});
        });
        // 单选、多选默认选中
        $('input[data-checked],input[data-plugin="switchery"]',dom).length && $('input[data-checked],input[data-plugin="switchery"]',dom).metRadioCheckboxChecked();
        // 下拉菜单默认选中
        $('select[data-checked]',dom).length && $('select[data-checked]',dom).metSelectChecked();
        // 数量改变
        $('[data-plugin="touchSpin"]',dom).length && M.load('touchspin',function(){
            $('[data-plugin="touchSpin"]',dom).TouchSpin();
        });
        // 图片延迟加载
        $('[data-original]',dom).length && !$('.met-web').length && $('[data-original]',dom).metLazyLoad();
        // 多级下拉菜单
        $('[data-submenu]',dom).length && M.load(['popper','submenu'],function(){
            $('[data-submenu]',dom).submenupicker();
        });
        $('[data-toggle="dropdown"]',dom).length && $('[data-toggle="dropdown"]',dom).attr({onClick:'dropdownMenuPosition(this)'});
        // 拖拽
        $('[data-plugin="dragsort"]',dom).length && M.load('dragsort',function(){
            $('[data-plugin="dragsort"]',dom).metDragsort();
        });
        // 图标设置
        $('[data-plugin="iconset"]', dom).length && M.load('iconset', function() {
            $('[data-plugin="iconset"]', dom).metIconSet();
        });
        // 弹出提示框
        $('[data-plugin="webuiPopover"]', dom).length && M.load('webui-popover', function() {
            setTimeout(()=>{
                $('[data-plugin="webuiPopover"]', dom).each(function(index, el) {
                    var option=M.component.webuiPopover($(this),index);
                    $(this).webuiPopover(option);
                });
            },300)
        });
        // 开关
        $('[data-plugin="switchery"]', dom).length && M.load('switchery', function() {
            $('[data-plugin="switchery"]', dom).each(function(index, el) {
                new Switchery(el);
            });
        });
        // 字体大小选择
        $('[data-plugin="select-fontsize"]', dom).length && M.load('fontsize-select', function() {
            $('[data-plugin="select-fontsize"]', dom).fontSizeSelect();
        });
        // 选项卡插入高亮样式
        $('.nav-underline:not([underline])',dom).append('<span class="nav-underline-active"></span>').attr('underline','').find('.nav-link.active').trigger('show.underline');
        // 多行文本输入框样式
        $('textarea.form-control:not(.met-scrollbar)',dom).addClass('met-scrollbar scrollbar-grey oya');
    }
});
// 通用功能开启
$(document).metCommon();
$(function(){
    // 勾选开关
    $(document).on('change', 'input[type="checkbox"][data-plugin="switchery"]', function(event) {
        var val=$(this).is(':checked')?1:0;
        $(this).val(val);
    });
    // tokenfield插件输入框值更新后
    $(document).on('change', '.tokenfield .token-input', function(event) {
        $(this).parents('.tokenfield').find('[name][data-fv-field]').trigger('change');
    });
    // 下拉展开时下拉图标旋转
    $(document).on('click', '[data-toggle="collapse"]', function(event) {
        var $icon=$('i[class*="fa-caret-"],i[class*="fa-angle-"]',this),
            $target=$($(this).data('target'));
        if($icon.length){
            if(!$icon.hasClass('transition500')) $icon.addClass('transition500');
            if($(this).hasClass('collapsed')){
                $icon.removeClass('fa-rotate-90');
            }else{
                $icon.addClass('fa-rotate-90');
            }
        }
        if(!$(this).hasClass('collapsed')){
            var $self=$(this),
                $scrollbar=$(this).parents('.met-scrollbar').eq(0);
            $scrollbar.length && setTimeout(function(){
                if($scrollbar.offset().top+$scrollbar.height()-100<$target.offset().top){
                    var scroll_t=$target.height();
                    if(scroll_t>100) scroll_t=100;
                    scroll_t+=$scrollbar.scrollTop();
                    $scrollbar.stop().animate({scrollTop:scroll_t}, 300);
                }
            },500);
        }
    });
    // 返回顶部
    metGoTop($('.metadmin-rightcontent').length?'.metadmin-rightcontent':'');
    // webuipopover关闭
    $(document).on('click', '.webui-popover [data-webuipopover-hide]', function(event) {
        $('body').click();
    });
    // select组件生成
    var met_select_option_html=function(obj,active,active_value){
            var list='',
                has_checked=obj.find('option[checked]').length;
            obj.find('option').each(function(){
                var val=$(this).attr('value');
                list+='<a href="javascript:;" class="dropdown-item px-2 py-1'+(active&&(has_checked?$(this).attr('checked'):active_value==val)?' active':'')+'" data-value="'+val+'">'+$(this).html()+'</a>';
            });
            return list;
        };
    $(document).on('mouseover','select.form-control:not([multiple]):not([disabled])',function(){
        if(!$(this).parent('.met-select').length){
            var inline_block=$(this).css('display')=='inline-block'?' d-inline-block':' d-block',
                float=$(this).css('float')!='none'?' float-'+$(this).css('float'):'';
            $(this).wrap('<div class="met-select mw-100 navbar p-0 position-relative'+inline_block+float+'" style="margin:'+$(this).css('margin')+' !important;'+($(this).outerWidth()==$(this).parent().width()||float?'':'width:'+$(this).outerWidth()+'px;')+'"></div>');
            var title=$('option:selected',this).length?$('option:selected',this).html():$('option:first-child',this).html(),
                html='<div class="dropdown w-100 position-absolute">'
                +'<button type="button" class="btn btn-default dropdown-toggle w-100 text-left '+($(this).hasClass('form-control-sm')?'sm':'')+'" data-toggle="dropdown" onclick="dropdownMenuPosition(this)">'+title+'</button>'
                +'<div class="dropdown-menu">'+met_select_option_html($(this),1,$(this).val())+'</div>'
            +'</div>';
            $(this).addClass('invisible').after(html);
        }
    });
    // select组件触发
    $(document).on('click clicks','.met-select .dropdown .dropdown-menu .dropdown-item',function(e){
        var $select=$(this).parents('.met-select').find('select');
        if(e.type=='click'){
            $select.val($(this).data('value')).change();
        }else{
            $(this).addClass('active').parents('.dropdown').find('.btn').html($(this).html());
            $(this).siblings().removeClass('active');
        }
    });
    // dropdown、dropup组件在表头表底展开时，表头表底层级兼容
    var table_dropdown_dropup='thead .dropdown,tfoot .dropdown,.dataTables_footer .dropdown,thead .dropup,tfoot .dropup,.dataTables_footer .dropup';
    $(document).on('show.bs.dropdown show.bs.dropup show.bs.dropright show.bs.dropleft',table_dropdown_dropup,function(e){
        $(this).parents('thead,th,.dataTables_footer').css({'z-index':1002});
    });
    $(document).on('hidden.bs.dropdown hidden.bs.dropup hidden.bs.dropleft hidden.bs.dropright',table_dropdown_dropup,function(e){
        setTimeout(()=>{
            !$(this).parents('thead,th,.dataTables_footer').find('.dropdown-menu.show').length && $(this).parents('thead,th,.dataTables_footer').css({'z-index':''});
        },300);
    });
    // select通过js改变后改变下拉菜单
    $(document).on('change changes','.met-select select.form-control',function(){
        var $menu=$(this).next('.dropdown').find('.dropdown-menu'),
            val=$(this).val();
        $menu.html(met_select_option_html($(this))).find('.dropdown-item'+($menu.find('.dropdown-item[data-value="'+val+'"]').length?'[data-value="'+val+'"]':':first-child')).trigger('clicks');
        if($(this).parents('[data-plugin="select-linkage"]').length){
            if(!$(this).html()){
                $(this).parents('.met-select').addClass('hide');
            }else{
                $(this).parents('.met-select').removeClass('hide');
            }
        }
    });
    // 按钮点击效果
    $(document).on('click','.btn:not([disabled]):visible',function(e){
        var $self=$(this),
            diameter = Math.max($(this).outerWidth(),$(this).outerHeight()),
            radius = diameter/2;
        $(this).addClass('btn-ripple').append('<em class="ripple"></em>');
        $('em',this).width(diameter).height(diameter).css({left:e.clientX - $(this).offset().left - radius,top:e.clientY - $(this).offset().top - radius}).addClass('ripple');
        setTimeout(function(){
            $self.removeClass('btn-ripple').find('.ripple').remove();
        },600);
    });
});
})();
// 定时循环
function interval(option){
    var time=0,
        handle=function(clear,callback){
            option.true_val(time)?(option.true_fun&&option.true_fun(time),clear && clearInterval(interval)):(option.false_fun&&option.false_fun(time),!clear&&callback());
        },
        interval;
    handle('',(function(){
        !option.delay && (option.delay=50);
        interval = setInterval(function(){
            time+=option.delay;
            handle(1);
        },option.delay);
    }));
}
// 获取地址栏参数
function getQueryString(name,url) {
    var name=$.isArray(name)?name:[name],
        url=url?(url.split('?')[1]):(window.location.search.substr(1) || window.location.hash.split('?')[1]),
        length=name.length,
        result={};
    url?$.each(name, function(index, val) {
        var r=url.match(new RegExp("(^|&)"+val+"=([^&]*)(&|$)", "i"));
        r=r!=null?r[2]:'';
        if(r==''){
            r=url.match(eval('/'+val+'=(\\w+)/'));
            r=r!=null?r[1]:'';
        }
        var value=r!=''?unescape(decodeURIComponent(r)):'';
        if(length==1){
            result=value;
        }else{
            result[val]=value;
        }
    }):(result='');
    return result;
}
// 修改、添加、删除地址栏参数
function replaceParamVal(param,value) {
    var url=location.href,
        match_url=window.location.search.substr(1) || window.location.hash.split('?')[1]||'',
        param=$.isArray(param)?param:[param],
        value=$.isArray(value)?value:[value];
    $.each(param, function(index, val) {
        var param1='&' + val + '=',
        param2='?' + val + '=',
        re = match_url.match(new RegExp("(^|&)"+val+"=([^&]*)(&|$)", "i"));
        if(!re && (url.indexOf(param1)>0 || url.indexOf(param2)>0)) re=[val + '='];
        re && (re[0]=re[0].replace(/&/g,''));
        value[index]=String(value[index]);
        if(value[index]){
            if(re){
                if(url.indexOf(param1)>0){
                    url = url.replace('&'+re[0], param1 + value[index]);
                }else if(url.indexOf(param2)>0){
                    url = url.replace('?'+re[0], param2 + value[index]);
                }
            }else{
                if(url.indexOf('?')>0){
                    var laststr=url.substr(-1),
                        urls=url.split('?');
                    if(urls[urls.length-1].indexOf('#')>0 && laststr!='/'){
                        url+='/?';
                        laststr=url.substr(-1);
                    }
                    url = url+((laststr=='?'||laststr=='&')?(val + '='):param1) + value[index];
                }else{
                    if((url+'/')==M.weburl) url+='/';
                    var laststr=url.substr(url.lastIndexOf('/')+1);
                    if(laststr.length?laststr.indexOf('.')>0:1){
                        url=url+param2 + value[index];
                    }else{
                        url=url+'/'+param2 + value[index];
                    }
                }
            }
        }else if(re){
            url = url.replace('&'+re[0], '').replace(re[0], '');
        }
    })
    history.pushState('','',url);
}
// 弹出提示信息
function metAlert(text,delay,bg_ok,type){
    delay=typeof delay != 'undefined'?delay:2000;
    bg_ok=bg_ok?'bgshow':'';
    $('.metalert-wrapper,.metalert-text').remove();
    if(text!=' '){
        text=text||METLANG.jsok||'操作成功';
        text='<div>'+text+'</div>';
        if(type) text+='<button type="button" class="close text-white" data-dismiss="alert"><span aria-hidden="true">×</span></button>';
        var html='<div class="metalert-text h6 mb-0 '+(type?'pl-4 pr-5':'px-4')+' py-3 bg-primary text-white">'+text+'</div>';
        if(bg_ok) html='<div class="metalert-wrapper w-100 alert '+bg_ok+'">'+html+'</div>';
        $('body').append(html);
        var $met_alert=$('.metalert-text'),
            $obj=bg_ok?$('.metalert-wrapper'):$met_alert,
            class_name='metalert-'+new Date().getTime();
        if($obj.hasClass(class_name)) class_name+=1;
        $met_alert.html(text);
        $obj.show().addClass(class_name);
        if($met_alert.outerHeight()%2) $met_alert.outerHeight($met_alert.outerHeight()+1);
    }
    if(delay){
        setTimeout(function(){
            var $obj=typeof class_name!='undefined'?$('.'+class_name):$('.metalert-wrapper,.metalert-text');
            $obj.fadeOut();
        },delay);
    }
}
// ajax请求返回后通用处理
function metAjaxFun(options){
    options = $.extend({
        result:'',
        false_fun:'',
        true_fun:'',
        status_key:'status',
        msg_key:'msg',
        true_reload:false
    },options);
    var true_val=parseInt(options.result[options.status_key])==1,
        fun_name=true_val?'true_fun':'false_fun';
    if(typeof options.result[options.msg_key]!='undefined' && options.result[options.msg_key]!='') M.load('alertify', function() {
        true_val?alertify.success(options.result[options.msg_key]):alertify.error(options.result[options.msg_key]);
    });
    if(typeof options[fun_name]=='function') true_val?options.true_fun(options.result):options.false_fun(options.result);
    if($.isArray(options[fun_name])){
        $.each(options[fun_name], function(index, val) {
            if(typeof val=='function') val(options.result);
        });
    }
    true_val && options.true_reload && setTimeout(function(){
        location.reload();
    },1000);
}
// 设置cookie
function setCookie(name,value,path,term){
    var exp = new Date(),
        terms = term==0?0:term||30,
        paths =path||'/';
    exp.setTime(exp.getTime() + terms*24*60*60*1000);
    document.cookie = name + '='+ value + ';path='+paths+';'+(terms?'expires=' + exp.toGMTString():'');
}
// 获取指定名称的cookie的值
function getCookie(name) {
    var cookie_str = document.cookie.split(";");
    for (var i = 0; i < cookie_str.length; i++) {
        cookie_str[i]=$.trim(cookie_str[i]);
        var index = cookie_str[i].indexOf("="),
            cookie_name = cookie_str[i].substring(0, index);
        if (cookie_name == name) {
            var temp = cookie_str[i].substring(index + 1);
            return decodeURIComponent(temp);
        }
    }
}
// 返回顶部
function metGoTop(container){
    if(container){
        $(".met-scroll-top").addClass('mr-2');
        var windows=container;
    }else{
        var container='html,body',
            windows=window;
    }
    $(".met-scroll-top").click(function(){
        $(container).animate({scrollTop:0},300);
    });
    // 返回顶部按钮显示/隐藏
    var wh=$(windows).height();
    $(windows).scroll(function(){
        if($(this).scrollTop()>wh){
            $(".met-scroll-top").removeAttr('hidden');
        }else{
            $(".met-scroll-top").attr({hidden:''});
        }
    });
}
// 下拉菜单高度限制
function dropdownMenuPosition(obj){
    var $self=$(obj),
        $dropdown_menu=$self.next('.dropdown-menu'),
        $parent=$self.parent(),
        parent_top=$parent.offset().top,
        parent_height=$parent.outerHeight(),
        $scrollbar=$self.parents('.met-scrollbar:not(.dropdown-menu):not(html):eq(0)'),
        is_vertical=$parent.hasClass('dropdown-submenu');
    $dropdown_menu.css({'max-height':''});
    if(!$scrollbar.length) $scrollbar=$('html');
    var dropdown_menu_h=$dropdown_menu.outerHeight(),
        delay=dropdown_menu_h>30?0:210,
        scrollbar_top=$scrollbar.hasClass('met-scrollbar')&&$scrollbar.prop('tagName')!='HTML'?$scrollbar.offset().top:$scrollbar.scrollTop(),
        submaxh_top=($scrollbar.hasClass('met-scrollbar')&&$scrollbar.prop('tagName')!='HTML'?$scrollbar.outerHeight():$(window).outerHeight())-(parent_top+(is_vertical?0:parent_height*1.02)-scrollbar_top),
        submaxh_bottom=parent_top-parent_height*(is_vertical?-1:0.02)-scrollbar_top,
        submaxh_array=[submaxh_top,submaxh_bottom],
        default_top=!$self.parents('.dropup').length||$self.parents('.dropright').length||$self.parents('.droleft').length;
    setTimeout(function(){
        if(delay) dropdown_menu_h=$dropdown_menu.outerHeight();
        // 上下位置重置及限高
        $dropdown_menu.css({top:default_top?(is_vertical?'-.625rem':'102%'):'auto',bottom:default_top?'auto':(is_vertical?'-.625rem':'102%')});
        if(default_top){
            if(dropdown_menu_h>submaxh_top){
                if(dropdown_menu_h>submaxh_bottom){
                    if(submaxh_top>submaxh_bottom){
                        $dropdown_menu.addClass('oya met-scrollbar scrollbar-grey').css({'max-height':submaxh_top});
                    }else{
                        $dropdown_menu.addClass('oya met-scrollbar scrollbar-grey').css({'max-height':submaxh_bottom,top:'auto',bottom:is_vertical?'-.625rem':'100%'});
                    }
                }else{
                    $dropdown_menu.css({top:'auto',bottom:is_vertical?'-.625rem':'100%'});
                }
            }
        }else{
            if(dropdown_menu_h>submaxh_bottom){
                if(dropdown_menu_h>submaxh_top){
                    if(submaxh_top>submaxh_bottom){
                        $dropdown_menu.addClass('oya met-scrollbar scrollbar-grey').css({'max-height':submaxh_top,top:is_vertical?'-.625rem':'102%',bottom:'auto'});
                    }else{
                        $dropdown_menu.addClass('oya met-scrollbar scrollbar-grey').css({'max-height':submaxh_bottom});
                    }
                }else{
                    $dropdown_menu.css({top:is_vertical?'-.625rem':'102%',bottom:'auto'});
                }
            }
        }
        // 左右位置重置
        if($parent.outerWidth()>200) $dropdown_menu.width(200).addClass('text-wrap').find('>*').addClass('text-wrap');
        if(Math.abs(parseInt($dropdown_menu.css('left'))-$parent.width())<2){
            if($dropdown_menu.offset().left-$scrollbar.offset().left+$dropdown_menu.outerWidth()>$scrollbar.outerWidth()) $parent.removeClass('dropright').addClass('dropleft'),$dropdown_menu.css({right:'auto',left:'-100%'});
        }
    },delay);
}
// html字符反转义
function htmlDecode (text){
    // var arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
    // return str.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
    var temp = document.createElement("div");
    temp.innerHTML = text;
    var output = temp.innerText || temp.textContent;
    temp = null;
    return output;
}
// 防抖
function debounce(fn, wait=500) {
    var timeout = null;
    return function() {
       if(timeout !== null) clearTimeout(timeout);
       timeout = setTimeout(()=>{fn(...arguments)}, wait);
    }
}
// 启用通用弹框按钮
function showModal(attr={},data={}){
    if(!$('.btn-common-modal').length) $('body').append(`<button type="button" data-toggle="modal" class="btn-common-modal" hidden></button>`);
    $('.btn-common-modal').attr(attr).data(data).click();
    setTimeout(()=>{
        var remove_attr=[],
            remove_data=[];
        $.each(attr,function(index,val){
            remove_attr.push(index);
        });
        $.each(data,function(index,val){
            remove_data.push(index);
        });
        $('.btn-common-modal').removeAttr(remove_attr.join(' ')).removeData(remove_data);
    },200);
}
// 组件
M.component={
    loader:function(options){
        var options=$.extend({
                type:'',
                class_name:'',
                wrapper_class:'',
                height:'',
                colspan:'',
                style:''
            },options);
        var html='<div class="text-center py-5 '+options.class_name+'" style="height:'+options.height+';'+options.style+'"><div class="'+options.wrapper_class+'"><div class="loader loader-round-circle"></div></div></div>';
        switch(options.type){
            case 'table':
                html='<tr><td colspan="'+options.colspan+'">'+html+'</td></tr>';
                break;
            default:
                break;
        }
        return html;
    },
    btn:function(type,options={}){
        var html='';
        options.class=options.class?options.class:('btn btn-sm btn-default '+(options.other_class?options.other_class:''));
        switch(type){
            case 'cancel':
                html= '<button type="button" class="btn btn-sm btn-default ml-1" table-cancel>'+(METLANG.js49||'撤销')+'</button>';
                break;
            case 'del_item':
                html='<button type="button" class="'+options.class+'" data-plugin="webuiPopover" data-webuipopover-component="table-del" data-del_url="'+options.del_url+'">'+(METLANG.delete||'删除')+'</button>';
                break;
            case 'del':
                html='<button type="button" class="'+options.class+'" data-url="'+options.del_url+'" table-delete data-plugin="alertify" data-type="confirm"'+(options.confirm_title?' data-confirm-title="'+options.confirm_title+'"':'')+'>'+(options.title||METLANG.delete||'删除')+'</button>';
                break;
        }
        return html;
    },
    webuiPopoverFun:[],
    webuiPopover:function(obj,key){
        var option={},
            component=obj.data('webuipopoverComponent'),
            class_name='webuipopover-'+new Date().getTime();
        if($('.'+class_name).length) class_name+=key;
        obj.wrap('<div class="position-relative d-inline-block '+class_name+'"></div>');
        if(component && M.component.webuiPopoverFun[component]) option=M.component.webuiPopoverFun[component](class_name);
        return option;
    },
    checkall:function(type,id){
        if(type=='item'){
            return '<div class="custom-control custom-checkbox">'
                    +'<input class="checkall-item custom-control-input" type="checkbox" name="id" value="'+id+'">'
                    +'<label class="custom-control-label"></label>'
                +'</div>';
        }else{
            return '<th data-table-columnclass="text-center" class="text-center" width="30">'
                +'<div class="custom-control custom-checkbox">'
                    +'<input class="checkall-all custom-control-input" type="checkbox">'
                    +'<label class="custom-control-label"></label>'
                +'</div>'
            +'</th>';
        }
    },
    formWidget:function(name,value,type,required,no_formgroup,class_name){
        var html='',
            options=$.extend(true, {
                data_value_key:'value',
                rows:5,
                attr:'',
                class_name:'',
                delimiter:',',
                dt:1,
                inline_block:0,
                other:'',
                other1:'',
            },typeof name=='object'?name:{
                name:name,
                value:value,
                type:type,
                required:required,
                no_formgroup:no_formgroup,
                class_name:class_name||''
            });
        if(options.example_title){
            html='<h3 class="example-title clearfix">'+options.example_title+options.other+'</h3>';
        }else{
            var commonAttr=function(){
                    var attr='',
                        class_name=options.class_name;
                    options.required && (options.required=options.type=='file'?'data-filerequired="1"':'required');
                    $.inArray(options.type,['text','number','checkbox','radio','hidden','file','button'])>=0 && (attr+='type="'+options.type+'"');
                    $.inArray(options.type,['text','number','checkbox','radio','hidden','file'])>=0 && (attr+=' value="'+options.value+'"');
                    !options.key && typeof options.checked!='undefined' && (attr+=' data-checked="'+options.checked+'"');
                    $.inArray(options.type,['checkbox'])>=0 && typeof options.delimiter!='undefined' && (attr+=' data-delimiter="'+options.delimiter+'"');
                    options.placeholder && (attr+=' placeholder="'+options.placeholder+'"');
                    $.inArray(options.type,['checkbox','radio'])>=0 && (attr+=' id="'+options.type+'-'+options.name+'-'+time+'-'+options.key+'"') && (class_name+=' custom-control-input');
                    $.inArray(options.type,['text','number','select','textarea'])>=0 && (class_name+=' form-control');
                    options.type=='textarea' && (class_name+=' met-scrollbar scrollbar-grey');
                    options.name && (attr+=' name="'+options.name+'"');
                    return attr+=' '+options.attr+' '+options.required+' class="'+class_name+'"';
                },
                time=new Date().getTime();
            $.inArray(options.type,['select','checkbox','radio'])>=0 && (options.checked=options.value);
            switch(options.type){
                case 'select':
                    $.each(options.data, function(index, val) {
                        html+='<option value="'+val[options.data_value_key]+'" '+(typeof options.select_option_attr=='function'?options.select_option_attr(index,val):'')+'>'+(typeof options.select_option=='function'?options.select_option(index,val):val.name)+'</option>';
                    });
                    if(!options.wfull) options.class_name+=' w-auto d-inline-block';
                    html='<select '+commonAttr()+'>'+html+'</select>';
                    break;
                case 'textarea':
                    html='<textarea '+commonAttr()+' rows="'+options.rows+'">'+options.value+'</textarea>';
                    break;
                case 'textarea_hidden':
                    html='<textarea '+commonAttr()+' hidden>'+options.value+'</textarea>';
                    break;
                case 'checkbox':
                    $.each(options.data, function(index, val) {
                        options.value=val[options.data_value_key];
                        options.key=index;
                        html+='<div class="custom-control custom-checkbox '+(options.inline_block?'custom-control-inline':'')+'">'
                            +'<input '+commonAttr()+'>'
                            +'<label class="custom-control-label" for="checkbox-'+options.name+'-'+time+'-'+index+'">'+(val.name?val.name:val.value)+'</label>'
                        +'</div>';
                    });
                    break;
                case 'radio':
                    $.each(options.data, function(index, val) {
                        options.value=val[options.data_value_key];
                        options.key=index;
                        html+='<div class="custom-control custom-radio '+(options.inline_block?'custom-control-inline':'')+'">'
                            +'<input '+commonAttr()+'>'
                            +'<label class="custom-control-label" for="radio-'+options.name+'-'+time+'-'+index+'">'+(val.name?val.name:val.value)+'</label>'
                        +'</div>';
                    });
                    break;
                case 'file':
                    var accept=options.accept?(options.accept=='file'?accept='*':options.accept):'image/*';
                    html='<div class="d-inline-block">'
                            +'<input '+commonAttr()+' data-plugin="fileinput" '+(options.multiple?'multiple':'')+' accept="'+accept+'">'
                        +'</div>';
                    break;
                case 'editor':
                    html='<textarea '+commonAttr()+' data-plugin="editor" data-editor-y="200" hidden>'+options.value+'</textarea>';
                    break;
                case 'color':
                    options.type='text';
                    html='<input '+commonAttr()+' data-plugin="minicolors">';
                    break;
                case 'socail_link':
                    var name=options.name,
                        old_value=options.value,
                        value=options.value.split('$M$');
                    options.name=name+'-socail_type';
                    options.type="select";
                    options.checked=value[0];
                    html='<div class="input-group">'
                            +'<select '+commonAttr()+'>'
                                +'<option value="tel">'+METLANG.parameter8+'</option>'
                                +'<option value="sms">'+METLANG.short_message+'</option>'
                                +'<option value="email">'+METLANG.mailbox+'</option>'
                                +'<option value="qq">'+METLANG.common_qq+'</option>'
                                +'<option value="qyqq">'+METLANG.enterprise_qq+'</option>'
                                // +'<option value="wechat">'+METLANG.open_wechat+'</option>'
                            +'</select>';
                    delete options.checked;
                    options.name=name+'-socail_val';
                    options.type="text";
                    options.value=typeof value[1]!='undefined'?value[1]:'';
                    html+='<input '+commonAttr()+'></div>';
                    options.name=name;
                    options.type="hidden";
                    options.value=old_value;
                    html+='<input '+commonAttr()+'>';
                    break;
                case 'icon':
                    options.type='hidden';
                    html='<input '+commonAttr()+' data-plugin="iconset" data-btn_size="'+(options.btn_size||'')+'" data-icon_class="'+(options.icon_class||'')+'">';
                    break;
                case 'collapse':
                    options.type='button';
                    options.class_name+=' btn btn-warning';
                    html='<button '+commonAttr()+' data-toggle="collapse" data-target="'+options.target+'">'+options.title+'<i class="icon fa-caret-right ml-2"></i></button>';
                    break;
                case 'submit':
                    html='<button type="submit" class="btn btn-primary '+options.class_name+'" '+options.attr+'>'+options.title+'</button>';
                default:
                    options.type?'':(options.type='hidden');
                    html='<input '+commonAttr()+'>';
                    break;
            }
            html+=options.other+(options.tips?'<span class="text-help ml-2 '+options.tips_class+'">'+options.tips+'</span>':'')+options.other1;
            (options.required||options.type=='file') && !options.no_formgroup && (html='<div class="form-group">'+html+'</div>');
            options.dl && (html='<dl>'
                    +(options.dt?'<dt><label class="form-control-label">'+options.label+'</label></dt>':'')
                    +'<dd class="clearfix">'
                        +html
                    +'</dd>'
                +'</dl>');
        }
        return html;
    },
    submit_selctor:'.btn[type="submit"]:not([data-submit_type])',
};