(function(){
	angular.module("app")
	.controller("indexCtrl",["$rootScope","$scope","HttpService","ToolService","UtilService","$state","$location","DateService","$timeout",indexCtrl]);


	function indexCtrl($rootScope,$scope,HttpService,ToolService,UtilService,$state,$location,DateService,$timeout){

        $rootScope.unfoldFlag = $rootScope.unfoldFlag==undefined?false:$rootScope.unfoldFlag;
        $scope.queryLimit = function(appid){
            if(angular.isDefined(appid)){
                limitPM = HttpService.getInfo("login/limit/"+appid);
            }
            else{
                limitPM = HttpService.getInfo("login/limit");
            }

            limitPM.then(function(data){
                $rootScope.limitInfo = data;
                UtilService.setItem("limitInfo",JSON.stringify($rootScope.limitInfo));
            });
        }

        $rootScope.demoU = ToolService.isDemoUser();
        $scope.goLogin = function(){
            window.location.href = "/login.html";
        }

				//msgflag=1,新建app刷list
        $scope.queryApp = function(msgflag){
					var appPM = HttpService.getInfo("app/findall");
					appPM.then(function(data){
						$scope.appAlllistInfo = data;
						$scope.applistInfo = data.filter(function(item){
								return item.isDebug!=true;
						});

						if(msgflag==1){return false;}

						var lastId = UtilService.getCookie("ryioLastApp");
            var demoapk = UtilService.getCookie("ryioDemoapk");
            UtilService.setCookie("ryioDemoapk","");
						if($scope.applistInfo.length > 0){
							if(UtilService.isNullStr(lastId)){
								lastId = "-1";
							}
							lastId = Number(lastId);
							var apps = $scope.applistInfo.filter(function(item){
                    if(!UtilService.isNullStr(demoapk)){
                        return item.appkey == demoapk;
                    }
                    else{
                        return item.id == lastId;
                    }
									});
									if(apps.length == 0){
										lastId = $scope.applistInfo[0].id;
									}
                else{
                    lastId = apps[0].id;
                }
                if($scope.appidInit == lastId){
                    $scope.appfresh = ++rmd;
                }else{
                    $scope.appidInit = lastId;
                }
                for(i=0; i < $scope.applistInfo.length; i++){
                    if($scope.applistInfo[i].id == $scope.appidInit){
                        $scope.appkey = $scope.applistInfo[i].appkey;
                    }
                }
					}
					else{
						if($rootScope.isSuper || $rootScope.isManage || $rootScope.isAppManage){
							$state.go("collect.app");
						}
	          else{
	              $scope.goLogin();
	          }
					}
			});
		};

		$scope.$on('f5Applist',function(e,msg){
			$scope.queryApp(msg);
		});

    $rootScope.webHideMenus = [];
		$scope.$on("appid",function(e,msg){
        $rootScope.appInstance = msg.info;
        $scope.platform = msg.info.platform;
        $rootScope.isandroid = $scope.platform == 'Android';
        $rootScope.isios = $scope.platform == 'iOS';
        $rootScope.isweb = $scope.platform == 'H5';

				var path = $location.$$path,idx = path.indexOf("Detail");
				if(path.indexOf('appDetail')>-1){return false;}

				if(idx>-1){
					$scope.appid = undefined;
					$location.path(path.substring(0,idx));
				}
        else if($rootScope.isweb && $rootScope.webHideMenus.indexOf($rootScope.pagePath)>-1){
            $scope.appid = undefined;
            $location.path($rootScope.firstMeau);
        }

				if($rootScope.pagePath == '' || $rootScope.pagePath == 'collect'
                    || (!$rootScope.isSuper && $rootScope.curRoleAuth && !$scope.hasTheMenu($rootScope.pagePath)))
				{
					$scope.appid = undefined;
					$location.path($rootScope.firstMeau);
				}

        $rootScope.appid = $scope.appid = msg.info.id;
				UtilService.setCookie("ryioLastApp",$scope.appid,7);
		});

    $scope.goToCustom = function(id,name){
        $location.path("/collect/custommenu/"+id);
        $rootScope.custID = id;
    }
    $scope.gotoCustonMenu = function(menuId){
        var url = $state.href('collect.custommenu');
        window.open(url+'/'+menuId,'_blank');
    }
		var rmd = new Date().getTime();
		$scope.$on("mngappTo",function(e,msg){
			if($scope.appid == msg){return false;}
			if($scope.appidInit == msg){
				$scope.appfresh = ++rmd;
			}else{
				$scope.appidInit = msg;
			}
		});

		var uuser = ToolService.getUser();
    $scope.loginuserName = uuser.email;
		$scope.currentAccountId = uuser.id;
    $scope.userPastDate = uuser.pastDate;

			$scope.errorBack = function(msg){
				ToolService.showTips(msg);
			};

				var rmdId = UtilService.randRangeId(),auid = ToolService.getUser().id;

				$scope.goPage = function(ui){
						$rootScope.channeluniqueName = 'normal';
			      if(ui == 'home'){
							ui = $rootScope.firstMeau;
							ui = ui.substring(1).replace("/",".");
						}

			      if(ui == 'collect.custommenu'){
			          $rootScope.custID = "";
			      }
						var mmenu = ui.substring(ui.indexOf('.')+1);
			      if(mmenu == 'channel'){
			          $rootScope.channeluniqueName = "normal";
			      }
			      if($state.current && $state.current.name == ui){
			          $state.reload(ui,{pageid:null});
			      }else{
			          $state.go(ui,{pageid:null});
			      }
				}

				$rootScope.noLeftMenus = ["userinfo","nopower","auth","app","product"];
        $scope.resizeStyle = function(){
            var mleft = '0px';
            if($rootScope.noLeftMenus.indexOf($rootScope.pagePath) == -1){
			        mleft = $rootScope.unfoldFlag ? '40px' : '186px';
			      }
            $(".conditionAlpha").css('left',mleft);
            $rootScope.panelw = $(window).width()-mleft.slice(0,-2)-84;
            return {'margin-left':mleft};
        }
        $scope.toggleMenu = function(){
            $rootScope.unfoldFlag = !$rootScope.unfoldFlag;
            UtilService.setCookie("unfoldFlag",$rootScope.unfoldFlag);

            $scope.$broadcast("conentresize",true);
        }

        $rootScope.showSubMenus = function(mainMenu){
            if($scope.channelAlert){
                return false;
            }
            if(mainMenu!='management' && $scope.applistInfo && $scope.applistInfo.length == 0){
                if($scope.appAlllistInfo.length > 0){
                    ToolService.showTips("请先完成"+$scope.appAlllistInfo[0].name+"的数据调试");
                }
                else{
                    ToolService.showTips("请先创建应用");
                }
                return false;
            }
            $rootScope.mainMenu = mainMenu;
            var first = "";
            if(mainMenu=='behavior'){
								first = "/collect/"+$rootScope.mainMenus.behavior[0];
						}else if(mainMenu=='export'){
								first = "/collect/"+$rootScope.mainMenus.dataexport[$rootScope.isweb?1:0];
						}else{
								first = "/manage/"+$rootScope.mainMenus.manage[0];
						}
						$location.path(first);
        }
        $rootScope.showMenu = function(name,flag){
            if(name == null){
                name = $scope.pagePath;
            }
            if($scope.isweb && $scope.webHideMenus.indexOf(name)>-1){
                return false;
            }
            if($rootScope.isSuper || $rootScope.isManage || $rootScope.isAppManage){
                return true;
            }
        }
        $rootScope.hasEditPower = function(){
            return $rootScope.showMenu(null,2);
        }

        $scope.formTipMsg = "信息没填全或数据格式有误，请检查";

        $rootScope.$watch("pagePath+isweb",function(n){
          n = $scope.pagePath;
        	if(angular.isDefined(n) && n!='' && n!= "product"){
              var tipPM = HttpService.getInfo("tip/"+n, {});
	        		tipPM.then(function(data){
	        			$rootScope.currentPageTips = data;
	        		},function(data){
	        			$rootScope.currentPageTips = {};
	        		});
        	}
        	else{
        		$rootScope.currentPageTips = {};
        	}
        });

        $scope.userLogout = function(){
        	var lgPM = HttpService.getInfo("login/logout", {});
	    		lgPM.then(function(data){
	    			HttpService.logOutCookie();
	    		});
				}


        $scope.initpage = function(){
            $scope.queryLimit();
            $scope.queryApp();
        }

        var lpath = $location.path();
        if(lpath!='/active/product'){
            $scope.initpage();
        }
        //判断是否需要向后台发送请求检测名称重复
        $scope.judgeNameChange = function(oldname,newname){
            if(!UtilService.isNullStr(newname)  && (oldname !='' && newname !=''  && angular.lowercase(oldname) != angular.lowercase(newname) || (oldname=='' && newname!=''))){
                return true;
            }
            else{
                return false;
            }
        }

				//提示框
        $scope.closeFlow = function(type){
            if($rootScope.pastLong < 0){
                $scope.userLogout();
            }
            else if($scope.behaviorAuth  && $rootScope.ioPercentRel <= -0.05 && !$rootScope.flowRestrict){
                $scope.userLogout();
            }

            $scope.flowKnow = true;
			UtilService.setCookie("ryioRedCircle",true,7);

            var params = {
              accountId: auid
            };
            if(type == 'ioAlert'){
                $scope.ioAlert = false;
                params.ioFlow = true;
            }
            else if(type == 'ioDateAlert'){
                $scope.ioDateAlert = false;
                params.ioPastTime = true;
            }
            var closePM = HttpService.postInfo("mng/accountRestrict/confirm", params);
            closePM.then(function(data) {});
        }

				$rootScope.menuSubmitData = function(submenu){
            ToolService.getMenuSubmitData(submenu);
        }
        $rootScope.operSubmitData = function(opername){
            ToolService.getOperSubmitData(opername);
        }
        $rootScope.$watch("thirdtab",function(n){
            if(angular.isDefined(n)){
                ToolService.getMenuSubmitData(n);
            }
        });

        $scope.pwdPlacehold = "仅支持数字，大小写字母，且至少包含其中2种，长度限制为6-18位";
	}
})();
