(function () {
    'use strict';

    angular.module('app')
    .run(['$rootScope', '$state', '$stateParams','UtilService','$templateCache', '$location','$window','ToolService','HttpService','DateService','$timeout',
	    function($rootScope, $state, $stateParams,UtilService,$templateCache,$location,$window,ToolService,HttpService,DateService,$timeout) {
	        $rootScope.$state = $state;
	        $rootScope.$stateParams = $stateParams;
	        $rootScope.isSuper = UtilService.getCookie("ryioIsSuper")=='true' || UtilService.getCookie("ryioIsSuper")==true;

          var UUUser = ToolService.getUser();
	        var userID = UUUser.id,ryioRole = UUUser.roleCategory;
	        if(ryioRole && ryioRole == 1){ //管理员
	            $rootScope.isManage = true;
	        }
	        else if(ryioRole && ryioRole == 2){//子应用管理员
	            $rootScope.isAppManage = true;
	        }
	        $rootScope.isall = $rootScope.isSuper || $rootScope.isManage || $rootScope.isAppManage;
	        $rootScope.firstMeau = '/collect/custommenu';


	        var flowPM = HttpService.getInfo("mng/accountRestrict/find/"+userID);
        	var queryFlow = function(){
	            flowPM.then(function(data){
                  if(!data){return false;}
	                $rootScope.flowName = data.packageName; //套餐名称
	                $rootScope.flowLevel = data.priceLevel; //套餐级别
	                if(data.flowRestrict == true){  //是否是受限用户  true是
	                    $rootScope.flowRestrict = false;
	                }else{
	                    $rootScope.flowRestrict = true;
	                }
	                if($rootScope.flowLevel <= 4 || $rootScope.flowLevel >= 14){
	                    $rootScope.byflow = true;
	                }else{
	                    $rootScope.byflow = false;
	                }//小于4大于等于14是流量用户，大于是包年

	                $rootScope.ioAll = parseInt(data.iolimit/1000);  //io总量
	                $rootScope.ioPercentRel = data.ioremainPercent;
	                $rootScope.ioPercent = (1 - data.ioremainPercent);  //io使用百分比

	                $rootScope.ioUsed = parseInt(data.thisMonthIOFlow/1000);  //io用量
	                $rootScope.ioRemainDay = parseInt(data.iOremainingDays); //io还能用多少天
	                $rootScope.ioAlert = data.ioflowNotified; //io用量提醒
	                $rootScope.ioDateAlert = data.iopastTimeNotified; //io到期提醒
	                $rootScope.behaviorAuth = true;

	                $rootScope.userPastDate = data.pastDate;  //过期时间
	                var todayDate = DateService.getToday().startDate; //今天日期
	                $rootScope.pastLong = DateService.getDaysNum($rootScope.userPastDate,todayDate);
	                if($rootScope.isSuper && $rootScope.behaviorAuth && $rootScope.ioPercentRel <= -0.05){
	                    $rootScope.ioAlert = false;
	                }
	                if(!$rootScope.isSuper && ($rootScope.pastLong < 0 || ($rootScope.behaviorAuth && $rootScope.ioPercentRel <= -0.05 && !$rootScope.flowRestrict))){
	                    var lgPM = HttpService.getInfo("login/logout", {});
        			    		lgPM.then(function(data){
        			    			HttpService.logOutCookie();
        			    		});
	                }
	            });
	        }
	        queryFlow();

	        var speMenus = ["userinfo","product","nopower","expiration","auth","app"];
	        $rootScope.mainMenus ={
	            behavior:["custommenu","eventstats","retention","funnel","usergroup","profile","event","activityevent","custommenuDetail","intelligentpath"],
	            dataexport:["logtool","report"],
	            manage:["app","auth"]
            };
	        $rootScope.$on('$stateChangeStart', function(event,next,o,current){
	            var name = next.name,nextMenu = name.substring(name.indexOf(".")+1),idd = nextMenu.indexOf("Detail");
	            var curname = current.name,curMenu = curname.substring(curname.indexOf(".")+1);
	            if(curname == '' && nextMenu == 'expiration'){
	            	window.location.href = "index.html";
	            	return false;
	            }

	            var mname = nextMenu?nextMenu:curMenu;
	            if($rootScope.mainMenus.behavior.indexOf(mname) > -1){
	            	$rootScope.mainMenu = 'behavior';
	            }else if($rootScope.mainMenus.dataexport.indexOf(mname) > -1){
	            	$rootScope.mainMenu = 'export';
	            }else if($rootScope.mainMenus.manage.indexOf(mname) > -1){
	            	$rootScope.mainMenu = 'management';
	            }

	            var nextDo = function(){
	            	var isUnfoldFlag = UtilService.getCookie("unfoldFlag");
		            if(isUnfoldFlag){
		                $rootScope.unfoldFlag = isUnfoldFlag=="false"?false:true;
		            }
		            document.getElementById("sysLoad").style.display = "none";
		            document.getElementById("alpLoad").style.display = "none";
		            if(idd > -1){
		            	nextMenu = nextMenu.substring(0,idd);
		            }

                  var submenu = "",submenuDir = {
                      'activityevent':"虚拟事件"
                  };

	                if(nextMenu == 'activityevent'){
                        submenu = nextMenu;
		                    nextMenu = 'event';
	                }

		            var web = $rootScope.isweb && $rootScope.webHideMenus.indexOf(nextMenu)>-1;
		            if(nextMenu=='' || nextMenu == 'collect' || web){
		            	$location.path($rootScope.firstMeau);
		            	return false;
		            }
		            else if(nextMenu == 'systemparam' && $rootScope.demoU){}
		            else if(speMenus.indexOf(nextMenu)>-1){}
		            else if(!$rootScope.isSuper && $rootScope.curRoleAuth && !$rootScope.hasTheMenu(nextMenu)){
		            	var firstMeau = $rootScope.firstMeau,
		            		nowmenu = firstMeau.substring(firstMeau.lastIndexOf("/")+1);

		            	$location.path($rootScope.firstMeau);
		            	if(nowmenu == $rootScope.pagePath){
		            		$window.location.reload();
		            	}
		            	return false;
		            	// console.log(nowmenu,$rootScope.pagePath)
		            }

		            if(speMenus.indexOf(nextMenu)>-1){
		            	$rootScope.backReport = true;
		            }else{
		            	$rootScope.backReport = false;
		            }

		            if(nextMenu == 'product' || (nextMenu=='userinfo' && curMenu=='product')){
		            	$rootScope.preStatus = true;
		            }else{
		            	$rootScope.preStatus = false;
		            }

		            $(".rightWrap").scrollTop(0);

                if($rootScope.byflow && $rootScope.ioPercentRel <= -0.05 && $rootScope.mainMenus.behavior.indexOf(nextMenu)>-1 && !$rootScope.flowRestrict){
		                nextMenu = 'expiration';
		                window.location.href = "index.html#/collect/expiration";
	                	return false;
		            }

		            $rootScope.pagePath = nextMenu;
                //看单的子菜单已经报送
                if(nextMenu == 'custommenu' && next.url.indexOf(":pageid")>-1){}
                else{
                    if( ['nopower','expiration'].indexOf(nextMenu) == -1 ){
                        ToolService.getMenuSubmitData(submenuDir[submenu]);
                    }
                }
	            }
	            if(!$rootScope.limitInfo){
                $timeout(function(){
                  nextDo();
                },100);
              }
              else{
                nextDo();
              }
	        });

	        //清除页面缓存
	        var stateChangeSuccess = $rootScope.$on('$stateChangeSuccess', stateChangeSuccess);
	        function stateChangeSuccess($rootScope) {
	           $templateCache.removeAll();
	        }
	    }
	])
	/*捕获异常*/
	.config(["$provide",function ($provide) {
	    $provide.decorator("$exceptionHandler", ['$delegate', function($delegate) {
	        return function (exception, cause) {
	        	document.getElementById("sysLoad").style.display = "none";
	        	if(String(exception).indexOf("$compile:tpload")==-1){
	        		$delegate(exception, cause);
	        	}
	        }
	    }])
	}])
	.factory('httpInterceptor', [function() {
	    var timestampMarker = {
	        request: function(config) {
	        	var token = $.cookie("io_ryioToken");
	        	  config.headers.Authorization = token;
	            config.requestTimestamp = new Date().getTime();
	            config.timeout = 3000 * 10;
	            return config;
	        },
	        response: function(response) {
	            response.config.responseTimestamp = new Date().getTime();
	            return response;
	        }
	    };
        return timestampMarker;
    }])
	/*设置请求header*/
	 .config(["$httpProvider",function($httpProvider) {
	 		$httpProvider.interceptors.push('httpInterceptor');
	 }]);

})();
