/*!
 * 后台功能
 * 米拓企业建站系统 Copyright (C) 长沙米拓信息技术有限公司 (https://www.metinfo.cn). All rights reserved.
 */
(function(){
M.is_admin=$('html').hasClass('met-admin');
M.noside=getQueryString('noside');
(M.is_admin || $('.met-pageset').length) && setCookie('met_auths',1,'',0);
// 加载模板
$.metLoadTemp=function(path,data,fn){
    if(!path) return false;
    var prefix=file_path='',
        is_app=0,
        data=data||{},
        data_url='';
    if(path.substr(0,1)=='#'){
        prefix=path.substr(1,path.indexOf('/'));
        path=path.substr(path.indexOf('/')+1);
    }
    if(path.indexOf('?')>0){
        data_url=path.substr(path.indexOf('?')+1);
        path=path.split('?')[0];
        if(path.substr(-1,1)=='/') path=path.substr(0,path.length-1);
    }
    if(data_url!=''){
        $.each(data_url.split('&'), function(index, val) {
            if(val){
                var value=val.split('=');
                if(value[1]&&value[1]!='') data[value[0]]=value[1];
            }
        });
    }
    var paths=path.indexOf('/')?path.split('/'):[path];
    if(paths[0]=='app'){
        paths.splice(0,1);
        is_app=1;
    }
    // M.load('routers',function(){
        if(!ROUTERS[paths[0]]) ROUTERS[paths[0]]={};
        if(!ROUTERS[paths[0]].module) ROUTERS[paths[0]].module=paths[0];
        if(!ROUTERS[paths[0]].path) ROUTERS[paths[0]].path='index';
        if(paths[1]=='index') paths.splice(1);
        if(paths[1]){
            paths[1]=paths.slice(1).join('/');
            paths=paths.slice(0,2);
            if(!ROUTERS[paths[0]].sub) ROUTERS[paths[0]].sub={};
            if(!ROUTERS[paths[0]].sub[paths[1]]) ROUTERS[paths[0]].sub[paths[1]]={};
            if(!ROUTERS[paths[0]].sub[paths[1]].path) ROUTERS[paths[0]].sub[paths[1]].path=paths.slice(1).join('/');
        }
        var routers_data=paths[1]?ROUTERS[paths[0]].sub[paths[1]].data:ROUTERS[paths[0]].data;
        routers_data && $.extend(data, routers_data);
        if(prefix){
            file_path=prefix+path;
        }else{
            prefix=(is_app?'apps':'sys')+'/';
            file_path=prefix+ROUTERS[paths[0]].module+'/admin/templates/'+(paths[1]?ROUTERS[paths[0]].sub[paths[1]].path:ROUTERS[paths[0]].path);
            if(prefix=='apps/') prefix='app/';
        }
        $.ajax({
            url: M.url.admin+'?m=include&c=loadtemp&a=doviewhtml',
            type: 'POST',
            dataType: 'json',
            data: {path:file_path,data:data},
            success:function(result){
                metAjaxFun({
                    result:result,
                    true_fun:function(){
                        typeof fn==='function'?fn(result,prefix,paths,file_path,data):''
                    }
                });
            }
        });
    // });
};
// 通过锚点加载模板
function metLoadModule(){
    if(!checkLogin()) return;
    var hash_start=location.hash;
    hash_start=hash_start.length>2&&hash_start.substr(0,2)=='#/'?hash_start.substr(2):'';
    if(hash_start==''){
        return false;
    }else{
        var path=hash_start;
        if(hash_start.indexOf('?')>0){
            hash_start=hash_start.substr(0,hash_start.indexOf('?'));
            if(hash_start.substr(-1,1)=='/') hash_start=hash_start.substr(0,hash_start.length-1);
        }
    }
    var hash=hashHandle(hash_start);
    hash_start=hash_start.substr(0,4)=='app/'?'app/'+hash:hash;
    var $this_content=$('.metadmin-content[data-page="'+hash_start+'"]'),
        $loader=$('.metadmin-loader'),
        loadFun=function(this_content){// 切换页面后回调
            var $content=this_content||$this_content;
            $loader.stop().fadeOut(100,function(){
                $content.fadeIn(100);
            });
            if(hash_start!='manage'){
                setTimeout(function(){
                    $content.find('.met-headtab[data-ajaxchange]:eq(0) a:eq('+(getQueryString('head_tab_active')||0)+')').click();
                },0);
            }
        };
    interval({
        true_val:function(){
            return $('.metadmin-sidebar-nav>li').length>2;
        },
        true_fun:function(){
            $navtabs_active=$('.metadmin-sidebar-nav a[href="#/'+hash_start+'"]'),
            $('.metadmin-sidebar-nav li').removeClass('active');
            var $only_active=$navtabs_active.eq(0);
            $only_active.parents('.metadmin-sidebar-nav>li').is(':visible') && ($only_active.parents('li').index()>1 || $only_active.parents('.sub').length) && $only_active.parents('li').addClass('active');
            hash_start.indexOf('app/')==0 && hash_start.indexOf('app/met_template')<0 && $('.metadmin-sidebar-nav a[href="#/myapp"]').parents('li').addClass('active');
        }
    });
    // 获取页面加载参数
    $('.metadmin-content').hide();
    $loader.stop().fadeIn(100);
    M.list=[];
    if($this_content.length && $this_content.attr('data-loaded')){// 老页面切换
        setTimeout(function(){
            loadFun();
            loadedTempReload(hash_start);
        },200);
    }else{// 新页面加载
        // 获取页面模板数据
        $.metLoadTemp(path,'',function(result,prefix,paths,file_path,data){
            // 新页面加载完后回调
            $('.metadmin-main').append('<div class="metadmin-content card p-4 border-none position-static" data-page="'+hash_start+'" data-loaded="1" style="display: none;"></div>');
            var $this_content=$('.metadmin-content[data-page="'+hash_start+'"]');
            $this_content[0].innerHTML=result.html;
            if($this_content.find('.metadmin-content-min').length) $this_content.removeClass('card p-4 border-none');
            loadFun($this_content);
            adminModuleInfo($this_content,prefix,hash_start,paths,file_path,data);
            _TEMPLOADFUN(hash_start);
        });
    }
}
window.TEMPLOADFUN={};
window.TEMPLOADFUNS={};
checkLogin();
// 渲染后台菜单
if((M.is_admin || $('.met-pageset').length)){
    window.getAdminMenus=(
        reload={
            left_nav:1,
            top_nav:1,
        },
        callback
    )=>{
        M.ajax({
            url:M.url.adminurl+'c=index&a=doGetMenus',
            success:res=>{
                if(res.data){
                    if(M.is_admin){
                        if($('.metadmin-sidebar-nav').length && reload.left_nav){
                            var left_nav_sub={},
                                left_icon=(icon)=>{
                                    return icon.indexOf('fa-')==0?icon:`metinfo-admin-icon metinfo-admin-icon-${icon}`;
                                },
                                left_nav_html=res.data.left_nav.filter(value => {
                                    var is_sub=parseInt(value.pid);
                                    if(is_sub) {
                                        if(!left_nav_sub[is_sub]) left_nav_sub[is_sub]=[];
                                        left_nav_sub[is_sub].push(value);
                                    }
                                    return !is_sub;
                                }).map(value => {
                                    var nav_sub=left_nav_sub[parseInt(value.id)];
                                    return `<li class="transition500 position-relative">
                                        <a href="${value.url?`#/${value.url}`:'javascript:;'}" title="${value.menu_lang}" class="d-flex justify-content-between align-items-center px-4">
                                            <div>
                                                <i class="${left_icon(value.icon)} mr-3"></i>
                                                <span>${value.menu_lang}</span>
                                            </div>
                                            ${nav_sub?`<span class="fa fa-caret-right h6 mb-0 position-relative"></span>`:''}
                                        </a>
                                        ${nav_sub?`<ul class="sub list-unstyled text-nowrap py-2">
                                            ${nav_sub.filter(value1 => {
                                                return value1.url||left_nav_sub[parseInt(value1.id)];
                                            }).map(value1 => {
                                                var nav_sub1=left_nav_sub[parseInt(value1.id)];
                                                if(nav_sub1 && nav_sub1.length==1){
                                                    value1.url=nav_sub1[0].url;
                                                    nav_sub1='';
                                                }
                                                return `<li class="transition500 position-relative">
                                                    <a href="${value1.url?`#/${value1.url}`:'javascript:;'}" title="${value1.menu_lang}" class="d-block px-4">
                                                        <i class="${left_icon(value1.icon)} mr-3"></i>
                                                        <span>${value1.menu_lang}</span>
                                                    </a>
                                                    ${nav_sub1?`<ul class="sub list-unstyled text-nowrap py-2">
                                                        ${nav_sub1.map(value2 => {
                                                            return `<li class="transition500 position-relative">
                                                                <a href="${value2.url?`#/${value2.url}`:'javascript:;'}" title="${value2.menu_lang}" class="d-block px-4">
                                                                    ${value2.icon?`<i class="${left_icon(value2.icon)} mr-3"></i>`:''}
                                                                    <span>${value2.menu_lang}</span>
                                                                </a>
                                                            </li>`;
                                                        }).join('')}
                                                    </ul>`:''}
                                                </li>`;
                                            }).join('')}
                                        </ul>`
                                        :`<ul class="sub nosub hide list-unstyled text-nowrap py-2">
                                            <li class="transition500 position-relative">
                                                <a href="#/${value.url}" title="${value.menu_lang}" class="d-block px-4"><span>${value.menu_lang}</span></a>
                                            </li>
                                        </ul>`}
                                    </li>`
                                }).join('');
                            $('.metadmin-sidebar-nav li:gt(1)').remove();
                            $('.metadmin-sidebar-nav').append(left_nav_html);
                        }
                        if($('.metadmin-head-right').length && reload.top_nav){
                            var env_detection=res.data.top_nav.find((value, index, array) => value.name=='env_detection'),
                                top_nav_html=res.data.top_nav.map((value, index, array) => {
                                    switch(value.name){
                                        case 'cache_clear':
                                            return `<div class="btn-group mr-4">
                                                <button class="btn btn-light dropdown-toggle" type="button" data-toggle="dropdown">
                                                    <i class="metinfo-admin-icon metinfo-admin-icon-clear-chache"></i>
                                                    <span class="d-none d-md-inline-block">${value.menu_lang}</span>
                                                </button>
                                                <ul class="dropdown-menu dropdown-menu-right">
                                                    <a href="${M.url.adminurl}n=system&c=sysfunc&a=doclearCache" title="${METLANG.clearCache}" class='dropdown-item px-3 clear-cache'>${METLANG.system_cache}</a>
                                                    <a href="${M.url.adminurl}n=system&c=sysfunc&a=doClearThumb" title="${METLANG.clearThumb}" class='dropdown-item px-3 clear-cache'>${METLANG.modimgurls}</a>
                                                </ul>
                                            </div>`;
                                        case `updates`:
                                                return `<a href="javascript:;" class="text-content mr-4" data-toggle="modal" data-target=".update-modal" data-modal-size="lg" data-modal-url="update" data-modal-fullheight="1" data-modal-title="${value.menu_lang}" data-modal-oktext="" data-modal-notext="${METLANG.close}">
                                                <i class="metinfo-admin-icon metinfo-admin-icon-update"></i>
                                                <span class="d-none d-md-inline-block">${value.menu_lang}</span>
                                            </a>`
                                        case 'func_collection':
                                            return `<a href="javascript:;" class="text-content mr-4" data-toggle="modal" data-target=".function-ency-modal" data-modal-size="lg" data-modal-url="#pub/function_ency/?n=system&c=sysfunc&a=doFuncList" data-modal-refresh="one" data-modal-fullheight="1" data-modal-title="${value.menu_lang}" data-modal-oktext="" data-modal-notext="${METLANG.close}">
                                                <i class="metinfo-admin-icon metinfo-admin-icon-function"></i>
                                                <span class="d-none d-md-inline-block">${value.menu_lang}</span>
                                            </a>`;
                                    }
                                }).join('');
                            $('.metadmin-head-right>.btn-group:nth-last-child(3)').before(top_nav_html);
                            if(env_detection){
                                $('.metadmin-head-right>.btn-group:nth-last-child(3) .dropdown-menu').append(`<a href="javascript:;" class='dropdown-item px-3' data-toggle="modal" data-target=".system-check-env-modal" data-modal-size="lg" data-modal-url="system/envmt_check/?c=patch&a=docheckEnv" data-modal-fullheight="1" data-modal-title="${env_detection.menu_lang}" data-modal-oktext="" data-modal-notext="${METLANG.close}">${env_detection.menu_lang}</a>`);
                            }
                        }
                    }else{
                        // <if value="$c['met_agents_app'] && $data['auth']['myapp'] eq 1">
	                    // 	<list data="$data['applist']" name="$v">
						// 	<a <if value="$v['newapp']">href="javascript:;" data-toggle="modal" data-target=".pageset-nav-modal" data-url='{$v.url}'<else/>href="{$v.url}" target="_blank"</if> class='dropdown-item px-3 py-2'>{$v.appname}</a>
						// 	</list>
						// 	</if>
                        var uiset_nav_sub={},
                            headnav_ml=M.synchronous=='cn'?'':'en-headnav-padiing',
                            uiset_nav_switch=(value)=>{
                                var nav_sub=uiset_nav_sub[parseInt(value.id)];
                                switch(value.name){
                                    case 'style':
                                        return `<div class="btn-group ${headnav_ml}">
                                            <button class="btn btn-outline-light border-none dropdown-toggle" type="button" data-toggle="dropdown">${value.menu_lang}</button>
                                            ${nav_sub?`<ul class="dropdown-menu mt-2">
                                                ${nav_sub.map(uiset_nav_switch).join('')}
                                            </ul>`:''}
                                        </div>`;
                                    case 'style_settings':
                                        return `<a href="javascript:;" class='dropdown-item px-3 pageset-other-config' data-config-url='${M.url.own_form}a=doget_public_config' data-form_action="doset_public_config">${value.menu_lang}</a>`;
                                    case 'banner_manage':
                                        return `<a href="javascript:;" class='dropdown-item px-3' data-toggle="modal" data-target=".pageset-nav-modal" data-url='banner'>${value.menu_lang}</a>`;
                                    case 'watermark':
                                        return `<a href="javascript:;" class='dropdown-item px-3' data-toggle="modal" data-target=".pageset-nav-modal" data-url='imgmanage'>${value.menu_lang}</a>`;
                                    case 'mobile_menus':
                                        return `<a href="javascript:;" class='dropdown-item px-3' data-toggle="modal" data-target=".pageset-nav-modal" data-url='menu'>${value.menu_lang}</a>`;
                                    case 'site_template':
                                        return `<a href="javascript:;" class='dropdown-item px-3 nav-tem-choose' data-toggle="modal" data-target=".pageset-nav-modal" data-url='app/met_template'>${value.menu_lang}</a>`;
                                    case 'content_manage':
                                        return `<a href='javascript:;' class="btn btn-outline-light border-none ${headnav_ml}" data-toggle="modal" data-target=".pageset-nav-modal" data-url='manage' title='${METLANG.indexcontent}'>${value.menu_lang}</a>`;
                                    case 'column_manage':
                                        return `<a href='javascript:;' class="btn btn-outline-light border-none ${headnav_ml}" data-toggle="modal" data-target=".pageset-nav-modal" data-url='column' title='${METLANG.columumanage}'>${value.menu_lang}</a>`;
                                    case 'seo_settings':
                                        return `<a href='javascript:;' class="btn btn-outline-light border-none ${headnav_ml}" data-toggle="modal" data-target=".pageset-nav-modal" data-url='seo'>SEO</a>`;
                                    case 'multilingual':
                                        return `<a href='javascript:;' class="btn btn-outline-light border-none ${headnav_ml}" data-toggle="modal" data-target=".pageset-nav-modal" data-url='language'>${value.menu_lang}</a>`;
                                    case 'application':
                                        return `<a href="javascript:;" class='btn btn-outline-light border-none ${headnav_ml}' data-toggle="modal" data-target=".pageset-nav-modal" data-url='myapp'>${value.menu_lang}</a>`;
                                    case 'cache_clear':
                                        return `<div class="btn-group ${headnav_ml}">
                                            <button class="btn btn-outline-light border-none dropdown-toggle" type="button" data-toggle="dropdown">${value.menu_lang}</button>
                                            <ul class="dropdown-menu mt-2">
                                                <a href="${M.url.adminurl}n=system&c=sysfunc&a=doclearCache" title="${METLANG.clearCache}" class='dropdown-item px-3 clear-cache'>${METLANG.system_cache}</a>
                                                <a href="${M.url.adminurl}n=system&c=sysfunc&a=doClearThumb" title="${METLANG.clearThumb}" class='dropdown-item px-3 clear-cache'>${METLANG.modimgurls}</a>
                                            </ul>
                                        </div>`;
                                    case 'updates':
                                        return `<a href="javascript:;" class='dropdown-item px-3' data-toggle="modal" data-target=".pageset-nav-modal" data-url='update'>${value.menu_lang}</a>`;
                                    case 'more_func':
                                        return `<div class="btn-group ${headnav_ml}">
                                            <button class="btn btn-outline-light border-none dropdown-toggle" type="button" data-toggle="dropdown">${value.menu_lang}</button>
                                            ${nav_sub?`<ul class="dropdown-menu dropdown-menu-right mt-2">
                                                ${nav_sub.map(uiset_nav_switch).join('')}
                                            </ul>`:''}
                                        </div>`;
                                    case 'basic_info':
                                        return `<a href="javascript:;" class='dropdown-item px-3' data-toggle="modal" data-target=".pageset-nav-modal" data-url='webset'>${value.menu_lang}</a>`;
                                    case 'online_settings':
                                        return `<a href="javascript:;" class='dropdown-item px-3' data-toggle="modal" data-target=".pageset-nav-modal" data-url='online'>${value.menu_lang}</a>`;
                                    case 'safety_efficiency':
                                        return `<a href="javascript:;" class='dropdown-item px-3' data-toggle="modal" data-target=".pageset-nav-modal" data-url='safe'>${value.menu_lang}</a>`;
                                    case 'backup_Recovery':
                                        return `<a href="javascript:;" class='dropdown-item px-3' data-toggle="modal" data-target=".pageset-nav-modal" data-url='databack/?head_tab_active=0'>${value.menu_lang}</a>`;
                                    case 'members':
                                        return `<a href="javascript:;" class='dropdown-item px-3' data-toggle="modal" data-target=".pageset-nav-modal" data-url='user'>${value.menu_lang}</a>`;
                                    case 'admins':
                                        return `<a href="javascript:;" class='dropdown-item px-3' data-toggle="modal" data-target=".pageset-nav-modal" data-url="permission">${value.menu_lang}</a>`;
                                    case 'func_collection':
                                        return `<a href="javascript:;" class='dropdown-item px-3' data-toggle="modal" data-target="#functionEncy" data-modal-size="lg" data-modal-url="#pub/function_ency/?n=system&c=sysfunc&a=doFuncList" data-modal-refresh="one" data-modal-fullheight="1" data-modal-title="${value.menu_lang}" data-modal-oktext="" data-modal-notext="${METLANG.close}">${value.menu_lang}</a>`;
                                    case 'enterprise_market':
                                        return `<a href="javascript:;" class='dropdown-item px-3' data-toggle="modal" data-target=".pageset-nav-modal" data-url="partner">${value.menu_lang}</a>`;
                                    case 'env_detection':
                                        return `<a href="javascript:;" class='dropdown-item px-3' data-toggle="modal" data-target=".pageset-nav-modal" data-url="system/envmt_check/?c=patch&a=docheckEnv">${value.menu_lang}</a>`;
                                }
                            },
                            uiset_nav=res.data.uiset_nav.filter(value => {
                                var is_sub=parseInt(value.pid);
                                if(is_sub) {
                                    if(!uiset_nav_sub[is_sub]) uiset_nav_sub[is_sub]=[];
                                    uiset_nav_sub[is_sub].push(value);
                                }
                                return !is_sub;
                            }),
                            uiset_nav_right=uiset_nav.pop(),
                            uiset_nav_html=uiset_nav.map(uiset_nav_switch).join("\n"),
                            right_uiset_nav_html=[uiset_nav_right].map(uiset_nav_switch).join("\n");
                            $('.pageset-head-nav .navbar>div:eq(0)').append(uiset_nav_html);
                            $('.pageset-head-nav .navbar>div:eq(1)').prepend(right_uiset_nav_html);
                    }
                    callback && callback();
                }
            }
        });
    };
    getAdminMenus();
}
// 后台锚点加载初始化
if(M.is_admin){
    // 历史记录切换
    M.useragent_tlc.indexOf('rv:11.0')>0?window.onhashchange=function(){
        metLoadModule();
    }:window.addEventListener("popstate", function() {
        metLoadModule();
    });
    if(location.hash.length<2){
        location.hash='/home';
    }else{
        metLoadModule();
    }
}
$(function(){
    // 页面元素点击登录状态判断
    $(document).on('click', 'a,button,input', function(event) {
        $('html.met-admin,html.met-pageset').length && !$(this).parents('.alertify').length && !$(this).hasClass('dropdown-toggle') && (checkLogin()||event.preventDefault());
    });
    // 登录页面
    if($('.met-login-form').length){
        M.load('form',function(){
            setTimeout(function(){
                formSaveCallback($('.met-login-form').attr('data-validate_order'),{
                    true_fun:function(result){
                        setTimeout(function(){
                            var referrer=$('.met-login-form [name="referrer"]').val();
                            if(referrer.indexOf(M.url.admin)>=0){
                                var referrer_n=referrer.match(/\?n=(\w+)/)||referrer.match(/&n=(\w+)/);
                                if(referrer_n && referrer_n[1]!='ui_set'){
                                    setCookie('met_auths',1,'',0);
                                    location.href=referrer;
                                    return;
                                }
                                if(top!=self){
                                    top.window.location.reload();
                                    return;
                                }
                            }
                            location.href=M.url.admin+'?lang='+result.data.admin_lang+'&n=ui_set';
                        },1000);
                    },
                    false_fun:(result)=>{
                        if(result.data && result.data.captcha){
                            var $captcha=$('.met-login-form .captcha');
                            if(!$captcha.find('img').attr('src')){
                                $captcha.removeClass('hide');
                                $captcha.find('img').attr('src',$captcha.find('img').data('src')).addClass('met-getcode');
                            }
                        }
                    }
                })
            },0);
        });
    }
    // 找回密码页面
    if($('.met-getpassword-form[data-submit-ajax]').length){
        M.load('form',function(){
            setTimeout(function(){
                formSaveCallback($('.met-getpassword-form').attr('data-validate_order'),{
                    true_fun:function(result){
                        result.url && setTimeout(function(){
                            location.href=result.url;
                        },1500);
                    }
                })
            },0);
        });
    }
    // 传统后台侧边栏子菜单
    $(document).on('mouseover','.metadmin-sidebar-nav li',function(){
        $('>.sub',this).stop().fadeIn(300);
    }).on('mouseout','.metadmin-sidebar-nav li',function(){
        $('>.sub',this).stop().fadeOut(300);
    })
    // 切换语言站点
    $('.metadmin-head-langlist a[data-val]').click(function(event) {
        var val=$(this).data('val');
        setCookie('admin_lang',val);
        location.href=M.url.admin+(location.href.indexOf('&n=ui_set')>=0?`?lang=${val}&n=ui_set`:'');
        setCookie('page_iframe_url','');
    });
    // 功能大全跳转
    $(document).on('click', '.function-ency-list .list-group-item a[href*="/#/"]', function(event) {
        if(M.is_admin){
            event.preventDefault();
            $('.function-ency-modal').modal('hide');
            var module=$(this).attr('href').split('/')[1];
            if(module!='manage' && $('.metadmin-content[data-page="'+module+'"] .met-headtab[data-ajaxchange]').length){
                var head_tab_active=getQueryString('head_tab_active',$(this).attr('href'))||0;
                $('.metadmin-content[data-page="'+module+'"] .met-headtab a:eq('+head_tab_active+')').click();
            }else{
                location.href=$(this).attr('href');
            }
        }
    });
    // tab页面ajax切换
    $(document).on('click', '.met-headtab[data-ajaxchange] .nav-link[href^="#"]', function(event) {
        if(M.is_admin) replaceParamVal('head_tab_active',$(this).index());
        var $headtab_content=$($(this).attr('href')),
            url=$(this).data('url'),
            hash=url.indexOf('?')>0?url.split('?')[0]:url;
        if(hash.substr(-1,1)=='/') hash=hash.substr(0,hash.length-1);
        hash=hashHandle(hash);
        if($(this).attr('data-reload')||$(this).parent().attr('data-reload')) $headtab_content.removeAttr('data-loaded');
        if($headtab_content.attr('data-loaded')){
            loadedTempReload(hash,$headtab_content);
        }else{
            metLoadTemp(url,'',$headtab_content,function(html){
                $headtab_content[0].innerHTML=html;
                if($headtab_content.find('.metadmin-content-min').length) $headtab_content.removeClass('bg-white p-4');
            },function(obj,data){
                _TEMPLOADFUN(hash);
                $headtab_content.attr({'data-loaded':1});
            });
        }
        // 动画切换
        var $tab_content=$headtab_content.parents('.tab-content:eq(0)');
        $tab_content.css({'min-height':Math.max.call(null,300,$tab_content.height())});
        $tab_content.find('.tab-pane').addClass('hide');
        if(!$tab_content.find('>.headtab-content-loader').length) $tab_content.append(M.component.loader({
            class_name: 'w-100 bg-white position-absolute headtab-content-loader',
            wrapper_class:'d-flex align-items-center justify-content-center h-100',
            style:'left:0;top:0;z-index:100;',
            height:'300px'
        }));
        $tab_content.addClass('position-relative').find('>.headtab-content-loader').removeClass('hide');
        $tab_content.parents('.oya').scrollTop(0);
        var tab_show=()=>{
                $tab_content.removeClass('position-relative').find('>.headtab-content-loader').addClass('hide');
                $headtab_content.removeClass('hide');
                $tab_content.css({'min-height':''});
            };
        if($headtab_content.attr('data-loaded')){
            setTimeout(function(){
                tab_show();
            },300);
        }else{
            interval({
                true_val:function(){
                    return $headtab_content.attr('data-loaded');
                },
                true_fun:function(){
                    tab_show();
                }
            });
        }
    });
    // 列表加载
    M.component.datatablePlay=function(info,table_order,option){
        M.load(['table','datatables'],function(){
            var $table=info.obj.find('.dataTable'),
                table_order=table_order||$table.data('datatable_order')||('#'+$table.attr('id'));
            if(table_order=='#') table_order='met-datatable-'+new Date().getTime()+$table.index('.dataTable');
            $table.attr({'data-datatable_order':table_order,'data-table-ajaxurl':$table.data('ajaxurl')});
            // datatable表格返回数据的处理
            datatable_option[table_order]=$.extend(true,{
                ajax:{
                    dataFilter:(json,a,b)=>{
                        json = JSON.parse(json);
                        if(!json.data){
                            json.data=[];
                            json.recordsTotal=0;
                            json.recordsFiltered=0;
                            json.draw=json.draw||0;
                        }
                        if(json.msg){
                            metAjaxFun({
                                result:{
                                    status:typeof json.status!='undefined'?json.status:0,
                                    msg:json.msg
                                }
                            });
                        }
                        return JSON.stringify(json);
                    }
                }
            },typeof option=='function'?option(info,table_order):{});
            setTimeout(function(){
                info.obj.metDataTable();
            },50);
        });
    };
    // 通用ajax列表
    M.component.commonList=function(option){
        var thats=$.extend(true,{}, admin_module),
            table_order=thats.obj.find('[data-datatable_order]').data('datatable_order');
        M.component.datatablePlay(thats,table_order,option);
        TEMPLOADFUNS[thats.hash]=function(){
            var thats_new=$.extend(true,{}, admin_module),
                table_order_new=thats_new.obj.find('[data-datatable_order]').data('datatable_order'),
                datatableReload=function(){
                    if(thats_new.obj.attr('data-loaded')||''){
                        thats_new.obj.tabelsearchReset();
                        setTimeout(function(){typeof datatable[table_order_new]!='undefined' && datatable[table_order_new].ajax.reload()},0);
                    }else{
                        M.component.datatablePlay(thats_new,table_order_new,option);
                    }
                };
            if(thats_new.obj.selector==thats.obj.selector){
                // console.log(1);
                datatableReload();
            }else{
                if(typeof datatable[table_order_new]!='undefined'){
                    // console.log(3);
                    datatableReload();
                }else{
                    // console.log(2);
                    M.component.datatablePlay(thats_new,table_order_new,option);
                }
            }
        };
    };
    // 头部导航栏清空缓存、清除缩略图
    $(document).on('click','.clear-cache',function(event) {
        event.preventDefault();
        metAlert(($(this).attr('title')||$(this).text())+'...',0,1);
        M.ajax({
            url: $(this).attr('href')
        },function(result){
            metAjaxFun({result:result,true_fun:function(){
                metAlert(' ',0);
                setTimeout(function(){
                    window.location.reload();
                },500);
            }});
        });
    });
    // 传统后台侧栏列表展开/收起
    $('.btn-adminsidebar-control').click(function(event) {
        var is_retract=$('i',this).hasClass('fa-angle-left'),
            delay=is_retract?0:300;
        $('i',this).removeClass(is_retract?'fa-angle-left':'fa-angle-right').addClass(is_retract?'fa-angle-right':'fa-angle-left');
        $('.metadmin-sidebar').toggleClass('min').find('.nosub').toggleClass('hide');
        setTimeout(function(){
            $('.metadmin-sidebar').toggleClass('retract');
        },delay);
    });
    if(M.is_admin || $('.met-pageset').length){
        M.load('modal',function(){
            // 许可协议
            M.component.modal_options['.syslicense-modal']={
                modalSize:'lg',
                modalOktext:'',
                modalNotext:METLANG.close,
                modalFullheight:1,
                modalHeight100:1,
            };
            M.component.modal_options['.syslicense-content-modal']=$.extend(true,{},M.component.modal_options['.syslicense-modal']);
            M.component.modal_options['.syslicense-modal'].modalRefresh='one';
            M.component.modal_options['.syslicense-modal'].callback=function(){
                $('.syslicense-modal tbody tr:gt(0) td a').each(function(){
                    var url=M.weburl+($(this).attr('data-modal-title')||$(this).text()+'LICENSE');
                    $(this).attr({
                        'data-toggle':"modal",
                        'data-target':".syslicense-content-modal",
                        'data-modal-title':url
                    });
                })
            };
            $(document).on('click','.syslicense-modal tbody tr:gt(0) td a',function(){
                M.ajax({
                    url:M.url.adminurl+'n=system&c=license&a=doGetLicense&id='+($(this).parents('tr').index()-2),
                    success:function(result){
                        $('.syslicense-content-modal .modal-body').html(`<pre class="mb-0 font-size-14">${result.data}</pre>`);
                    }
                });
            });
        });
        // 版本信息
        M.syspackage='';
        var $btn_syspackage=M.is_admin?$('.metadmin-head-right a[data-target=".syspackage-modal"]'):$('.pageset-head-nav a[data-url*="ui_set/package"]');
        M.ajax({
            url:'n=index&c=index&a=doGetPackageInfo',
            success:function(result){
                if($btn_syspackage.length){
                    M.syspackage=result.data;
                    if(!parseInt(result.status)||result.data.exit||result.data.show){
                        $btn_syspackage.click();
                        if(result.data && result.data.exit){
                            $(document).on('hide.bs.modal', '.pageset-nav-modal,.syspackage-modal', function(event) {
                                if(result.data.exit) location.href=M.url.adminurl+'n=login&c=login&a=dologinout';
                            });
                        }
                    }
                    result.data && result.data.package && $btn_syspackage.find('span').html(result.data.package);
                }
            }
        });
        if($btn_syspackage.length){
            TEMPLOADFUNS['ui_set/package']=function(){
                var that = $.extend(true, {}, admin_module);
                interval({
                    true_val:(time)=>{
                        return M.syspackage||time>60000;
                    },true_fun:(time)=>{
                        if(time>60000){
                            M.load('alertify',function(){
                                alertify.error('版本信息获取失败');
                            });
                        }else{
                            if(M.syspackage){
                                var html='<tr>'
                                        +'<td class="text-center bg-grey" colspan="2"><h5 class="mb-0">'+M.syspackage.title+'</h1></td>'
                                    +'</tr>',
                                    messageHtml=M.syspackage.messageHtml?'<div class="text-center mt-3">'+M.syspackage.messageHtml+'</div>':'';
                                if(M.syspackage.productList){
                                    $.each(M.syspackage.productList,function(index,val){
                                        html+='<tr>'
                                            +'<td class="text-right bg-grey" width="100">'+val.name+'</td>'
                                            +'<td width="100">'
                                            +'<span class="text-help text-dark">'+val.time+'</span>'
                                            +'</td>'
                                        +'</tr>';
                                    });
                                }else if(!M.syspackage.messageHtml){
                                    html='<tr>'
                                        +'<td class="text-center" colspan="2">未获得当前域名的授权信息，免费使用时请务必遵守<br><a href="https://www.metinfo.cn/metinfo/license.html" title="米拓企业建站系统最终用户授权许可协议" target="_blank">《最终用户授权许可协议》</a></td>'
                                    '</tr>';
                                }else{
                                    html='';
                                }
                                that.obj.find('table').html(html).after(messageHtml);
                            }
                        }
                    }
                });
            };
        }
    }
});
})();
// 判断后台登录状态
function checkLogin(){
    var status=true;
    if($('.met-check-login').length){
        status=false;
    }else{
        if(!getCookie('met_auths')){
            if($('html.met-admin,html.met-pageset').length){
                M.load('alertify', function() {
                    alertify.confirm('<span class="text-danger met-check-login">'+(METLANG.jsx32||'登录超时，请重新登录！')+'</span>', function (ev) {
                        location.href=M.url.admin;
                    });
                });
            }else{
                var hash=location.hash.substr(2);
                hash=hash.indexOf('/')>0?hash.split('/'):[hash];
                if(hash[0] && hash[0]!='login') location.href=M.url.admin;
            }
            status=false;
        }
    }
    !status && setCookie('met_auths','','',-1);
    return status;
}
// hash处理
function hashHandle(hash){
    if(hash.indexOf('/')>0){
        var hashs=hash.split('/');
        if(hashs[0]=='app'){
            delete hashs[0];
            hashs=$.grep(hashs, function(n) {return $.trim(n).length > 0;});
            hash=hashs.join('/');
        }
        if(hashs[1]=='index'||hashs[1]=='') hash=hashs[0];
    }
    return hash;
}
// 模板加载回调-模块信息定义、回调函数、加载模块css/js
function adminModuleInfo(obj,prefix,hash,paths,file_path,data,fn){
    var own_tem='#'+prefix+ROUTERS[paths[0]].module+'/admin/templates/',
        path_info=paths[1]?ROUTERS[paths[0]].sub[paths[1]]:ROUTERS[paths[0]],
        css_path=path_info.css,
        js_path=path_info.js;
    if(prefix=='app/' && !ROUTERS[paths[0]].custom){
        var app_file_status=obj.find('>input[name="app_file_status"]').val().split('|');
        css_path=parseInt(app_file_status[0])?paths[0]:'';
        js_path=parseInt(app_file_status[1])?paths[0]:'';
    }
    js_path&&(js_path=js_path.substr(0,1)=='#'?js_path:own_tem+'js/'+js_path);
    css_path&&(css_path=css_path.substr(0,1)=='#'?css_path:own_tem+'css/'+css_path);
    window.admin_module={};
    admin_module.obj=obj;
    admin_module.hash=hash;
    admin_module.own=M.url.system+ROUTERS[paths[0]].module+'/admin/';
    admin_module.own_tem=admin_module.own+'templates/';
    admin_module.own_name=M.url.admin+'index.php?n='+ROUTERS[paths[0]].module+'&';
    admin_module.file_path=file_path;
    admin_module.data=data;
    admin_module.module=ROUTERS[paths[0]].module;
    admin_module.reload=function(){
        if(this.obj.hasClass('tab-pane')){
            this.obj.parents('.tab-content').eq(0).parent().find('.met-headtab[data-ajaxchange]:eq(0) a.active').click();
        }else if(this.obj.find('.met-headtab:not([data-ajaxchange])').length && this.hash!='manage'){
            var $headtab_a=this.obj.find('.met-headtab:not([data-ajaxchange]):eq(0) a.active');
            M.is_admin?(location.href=location.href):$headtab_a.click();
        }else{
            if(M.is_admin){
                !this.obj.parents('.modal').length && (location.href=location.href);
            }else{
                if(this.obj.parents('.pageset-nav-modal').length){
                    if(this.obj.hasClass('content-show-item')){
                        $('.pageset-head-nav [data-url="manage"]').attr({
                            'data-module':this.data.module,
                            'data-class1':this.data.class1,
                            'data-class2':this.data.class2,
                            'data-class3':this.data.class3
                        }).trigger('clicks');
                    }else{
                        $('.btn-pageset-common-page').attr({'data-url':this.hash,title:this.obj.parents('.pageset-nav-modal').find('.modal-title').text()}).trigger('clicks');
                        setTimeout(function(){
                            $('.btn-pageset-common-page').attr({title:''});
                        },500);
                    }
                }
            }
        }
        this.obj.parents('.met-scrollbar').eq(0).scrollTop(0);
    };
    typeof admin_module_arr =='undefined'&&(window.admin_module_arr={});
    admin_module_arr[hash]=$.extend(true,{},admin_module);
    typeof fn==='function'&&fn();
    typeof data.nocommon=='undefined'&&obj.metCommon();
    js_path&&M.load(js_path);
    css_path&&M.link(css_path);
    // 表单内提交按钮位置
    var $btn_submit=obj.find('form .metadmin-fmbx dl .btn[type="submit"]');
    if($btn_submit.length){
        var $dl=$btn_submit.parents('dl');
        if($dl.find('dt').html()=='') $dl.find('dt').remove();
        $dl.addClass('form-submit-position position-sticky bg-white border-top');
    }
}
// 加载任意模板回调
function metLoadTemp(path,data,obj,fn1,fn2){
    if(!checkLogin()) return;
    // 加载模板
    $.metLoadTemp(path,data,function(result,prefix,paths,file_path,datas){
        typeof fn1==='function'&&fn1(result.html);
        obj=$(obj.selector);
        adminModuleInfo(obj,prefix,obj.attr('data-path')||paths.join('/'),paths,file_path,datas,function(){
            typeof fn2==='function'&&fn2(obj,datas);
        });
    });
}
// 已加载页面重新切换后处理
function loadedTempReload(hash,obj,fn){
    admin_module=admin_module_arr[hash];
    if(obj) admin_module.obj=obj;
    typeof fn=='function'&&fn();
    _TEMPLOADFUN(hash,1);
}
/**
 * 加载模板函数
 * TEMPLOADFUNS：加载模板函数，可能该函数所在模板js还未加载完，所以需要延时循环加载新的模板函数TEMPLOADFUN
 * TEMPLOADFUN：模板js加载后加载对应模板函数
 */
function _TEMPLOADFUN(hash,only_s=0){
    typeof TEMPLOADFUNS[hash]=='function' && TEMPLOADFUNS[hash]();
    !only_s && interval({
        true_val:(time)=>{
            return typeof TEMPLOADFUN[hash]=='function'||time>10000;
        },true_fun:(time)=>{
            (time>10000?0:1)&&(TEMPLOADFUN[hash](),TEMPLOADFUNS[hash]=TEMPLOADFUN[hash]);
        }
    });
}