(function(){
    angular.module("app.manage")
        .controller("authCtrl",["$rootScope","$scope","HttpService","ToolService","UtilService","$state",authCtrl])
        .controller("authDetailCtrl",["$rootScope","$scope","HttpService","ToolService","UtilService","$q","$state","$stateParams",authDetailCtrl]);

    function authCtrl($rootScope,$scope,HttpService,ToolService,UtilService,$state){

      $scope.demoUSuper = UtilService.getUser().email == 'demoadmin@reyun.com';
    	$scope.deviceList = [
            {id:1,name:"已启用"},
            {id:2,name:"已停用"}
        ];
      $scope.deviceInit = $scope.deviceList[0].id;
      $scope.$on("deviceId",function(e,msg){
          $scope.seeFlag = msg.info.id;
          if( $scope.seeFlag == 1){
              $scope.findName = 'enable';
          }else{
              $scope.findName = 'disable';
          }

          $scope.query();
      });
      if(!$rootScope.accountFlag){
          $rootScope.accountFlag = "account";
      }

    	$scope.query = function(flag){
        if(flag){
            $rootScope.accountFlag = flag;
            $rootScope.thirdtab = '子账号管理';
        }
        if(angular.isUndefined($scope.findName)){return false;}

        $scope.authList = [];
    		var authPM = HttpService.getInfo("mng/auth"+$scope.getSuburl()+"/list/"+$scope.findName);
        ToolService.showLoading();
  	    authPM.then(function(data){
            ToolService.hideLoading();
	    		  $scope.authList = data;
	    	});
    	}
    	$scope.query();

    	$scope.$on('flipinfo',function(e,msg){
            $scope.flipPage = msg;
      });
       $scope.wantOn = false;
       $scope.doOpen = function(info){
         $scope.curOnId = info.id;
         if(info.isSpecialAccount=="1"){
           $scope.wantOn = true;
           ToolService.showAlp();
         }
         else{
           $scope.onUser($scope.curOnId);
         }
       }
       $scope.onUser = function(id){
          if($scope.wantOn){
            $scope.closeOn();
          }
          ToolService.showLoading();
      	  var userPM = HttpService.putInfo("mng/auth"+$scope.getSuburl()+"/"+id+"/enable");
    	    userPM.then(function(data){
            ToolService.hideLoading();
  		      ToolService.showTips("启用成功");
            $rootScope.operSubmitData("启用");
            $scope.query();
    	    });
        }
        $scope.closeOn = function(){
          $scope.wantOn = false;
          ToolService.hideAlp();
        }
        $scope.offUser = function(id){
        	var userPM = HttpService.putInfo("mng/auth"+$scope.getSuburl()+"/"+id+"/disable");
          ToolService.showLoading();
	    	  userPM.then(function(data){
            ToolService.hideLoading();
  		      ToolService.showTips("停用成功");
            $rootScope.operSubmitData("停用");
            $scope.query();
	    	  });
        }
        $scope.deleteAuth = function(d){
            $scope.delInfo = d;
            $scope.wantDelete = true;
            ToolService.showAlp();
        }
        $scope.doDelete = function(){
            $scope.closeWin();
            ToolService.showLoading();
            var deletePM = HttpService.deleteInfo("mng/auth/"+$scope.delInfo.id+"/delete");
            deletePM.then(function(){
                ToolService.hideLoading();
                if(data){
                  ToolService.showTips("删除成功");
                  $scope.query();
                }
                else{
                  ToolService.showTips("该账号已激活，不支持删除，您可以在右侧操作区对账号进行停用。");
                }
            });
        }
        $scope.sendEmailAgain = function(send){
            var sendPM = HttpService.postInfo("mng/auth/mail/"+send.id+"/resend");
            ToolService.showLoading();
            sendPM.then(function(data){
                ToolService.hideLoading();
                send.send = 1;
                ToolService.showTips("发送成功");
            });
        }
        $scope.closeWin = function(flag){
            $scope.wantDelete = false;
            ToolService.hideAlp();
        }
        $scope.gopage = function(info){
            if(angular.isDefined(info)){
                if(!info.valid){return false;}

                $state.go("collect.authDetail",{aid:info.id});
            }else{
                $state.go("collect.authDetail");
            }
        }
        $scope.getSuburl = function(){
            var suburl = "";
            if($rootScope.accountFlag == 'channel'){
                suburl = "/channel";
            }
            return suburl;
        }
        $scope.isdetail = false;
        $scope.showDetails = function(info){
            $scope.detailInfo = info;
            ToolService.showAlp();
            $scope.isdetail = true;
            angular.element(document).on("click",function(){
                $scope.$apply(function(){
                    $scope.hideDetails();
                });
            });
        }
        $scope.hideDetails = function(){
            ToolService.hideAlp();
            $scope.isdetail = false;
        }
    }
    var copyArray = function(arr){
        return $.extend(true, [], arr);
    }
    function authDetailCtrl($rootScope,$scope,HttpService,ToolService,UtilService,$q,$state,$stateParams){

        var infoId = $scope.id = $stateParams.aid;

        $scope.$watch("applistInfo",function(data){
            if(angular.isDefined(data)){
                $scope.authapplist = copyArray(data);
                if($scope.isAppManage && !UtilService.isNullStr(infoId)){
                    var hasAuthAppsPM = HttpService.getInfo("app/find/"+infoId+"/AuthApp");
                    hasAuthAppsPM.then(function(data){
                        $scope.init(data);
                    });
                }
                else{
                    $scope.init();
                }
            }
        });

        $scope.init = function(otherpowers){
            if(!UtilService.isNullStr(infoId)){
                ToolService.showLoading();
                var accountPM = HttpService.getInfo("mng/auth/"+infoId+"/find");
                accountPM.then(function(data){
                    ToolService.hideLoading();

                    $scope.accountInfo = data;
                    $scope.email = $scope.oldEmail = data.email;
                    $scope.name = data.name;
                    $scope.remark = data.remark;
                    $scope.parentRole = data.parentRole;
                    if(UtilService.isNullStr(data.name)){
                        $scope.nameNofix = false;
                    }else{
                        $scope.nameNofix = true;
                    }
                    $scope.roleCategory = data.roleCategory;

                    if($scope.roleCategory == 2){
                        $scope.authapplist = copyArray($scope.appAlllistInfo);
                    }
                    else{
                        $scope.authapplist = copyArray($scope.applistInfo);
                    }

                    if($scope.isAppManage){
                        var appids = [];
                        $scope.authapplist.filter(function(item){
                            appids.push(item.id);
                        });
                        otherpowers.filter(function(item){
                            if(appids.indexOf(item.id)==-1){
                                item.nopower = true;//当前子应用没有该app权限
                                $scope.authapplist.push(item);
                            }
                        });
                    }

                    var authStr = data.authList;
                    authStr.filter(function(power){
                      for(var i=0;i<$scope.authapplist.length;i++){
                          var appinfo = $scope.authapplist[i];
                          if(appinfo.id == power.app){
                              $scope.authapplist[i].ischeck = true;
                              break;
                          }
                      }
                    });

                    $scope.steps = 1;
                    if($scope.roleCategory == 1){
                        $scope.steps = 0;
                        $scope.maxstep = 0;
                    }
                    else if($scope.roleCategory == 2){//子应用管理员
                        $scope.maxstep = 1;
                    }
                });
            }
        }

        $scope.steps = 0;
        $scope.maxstep = 0;
        $scope.changeRole = function(flag){
            switch(flag){
                case 1: //管理员
                    $scope.steps = 0;
                    $scope.maxstep = 0;
                    break;
                case 2: //子应用管理员
                    $scope.steps = 1;
                    $scope.maxstep = 1;
                    break;
                default:
                    break;
            }

            if(flag == 2){ //子应用管理员可以赋予未调式的产品
                $scope.authapplist = copyArray($scope.appAlllistInfo);
            }
            else{
                $scope.authapplist = copyArray($scope.applistInfo);
            }

            $scope.roleCategory = flag;
        }
        $scope.getTips = function(app){
            if(app.nopower){
                return "该应用权限由管理员添加，您无此应用权限";
            }
            else{
                return "";
            }
        }
        //全选操作
        $scope.doCheck = function(k){
            var bol = $scope.isAllCheck = !$scope.isAllCheck;

            if(k == 'app'){ //选择应用时的全选
                $scope.authapplist.filter(function(item){
                    if(!item.nopower){
                        item.ischeck = bol;
                    }
                });
            }
        }

        $scope.isAllCheck = false;
        //第一步选择app
        $scope.selectApp = function(app){
            app.ischeck = true;
            var checkbol = true;
            for(var i=0;i<$scope.authapplist.length;i++){
              var item = $scope.authapplist[i];
              if(!item.nopower && !item.ischeck){
                checkbol = false;
                break;
              }
            }
            $scope.isAllCheck = checkbol;
        }
        $scope.removeApp = function(app){
            if(app.nopower){return false;}

            app.ischeck = false;
            $scope.isAllCheck = false;
        }

        $scope.nameNofix = false;
        $scope.save = function(){
            var par = {
                    "email":$scope.email,
                    "name":$scope.name,
                    "roleCategory":$scope.roleCategory,
                    "remark":$scope.remark
                };
            var verPar = {
                email:{
                    key:"email",
                    val:par.email,
                    nullTxt:"请填写邮箱"
                },
                name:{
                    key:"numLetter",
                    val:par.name,
                    nullTxt:"请填写姓名",
                    max:20,
                    txt:"请输入20位以内的中英文或数字"
                }
            };
            if(!UtilService.isNullStr(par.remark)){
                verPar.remark = {
                    key:'nameLen',
                    val:par.remark,
                    max:200,
                    txt:'最多可输入100字'
                }
            }

            $scope.tip = formJudge(verPar);
            if($scope.tip.succ != true) {
                ToolService.showTips($scope.formTipMsg);
                return false;
            }
            else if(!$scope.roleCategory){
                ToolService.showTips("请选择角色");
                return false;
            }

            if($scope.roleCategory ==2 ){
                var appAuth = [];
                $scope.authapplist.filter(function(item){
                    if(item.ischeck){
                        appAuth.push({app:item.id});
                    }
                });

                if(appAuth.length == 0){
                    ToolService.showTips("请选择应用");
                    return false;
                }
                par.authList = appAuth;
            }

            var savePM = null,txtTips = "已为该账号发送激活邮件，请在72小时内联系相关人员激活并设置密码";
            if(infoId!=null){
                par.id = infoId;
                savePM = HttpService.putInfo("mng/auth"+$scope.getSuburl()+"/"+infoId+"/update",par);
                txtTips = "修改成功";
            }
            else{
                savePM = HttpService.postInfo("mng/auth"+$scope.getSuburl()+"/create",par);
            }
            ToolService.showLoading();
            savePM.then(function(data){
                if(data.code == -6001){
                    ToolService.hideLoading();
                    ToolService.showTips("该邮箱已创建");
                }
                else if(data.code == -300){
                    ToolService.hideLoading();
                    ToolService.showTips("最多可添加3个管理员");
                }
                else{
                    ToolService.hideLoading();
                    ToolService.showTips(txtTips);
                    $scope.cancel();
                    if(!infoId){
                        $rootScope.operSubmitData("新建");
                    }
                }
            },function(data){
                if(data.code == -6001){
                    ToolService.hideLoading();
                    ToolService.showTips("该邮箱已创建");
                }else if(data.code == -300){
                    ToolService.hideLoading();
                    ToolService.showTips("最多可添加3个管理员");
                }
            });
        }
        $scope.getSuburl = function(){
            var suburl = "";
            if($scope.accountFlag == 'channel'){
                suburl = "/channel";
            }
            return suburl;
        }
        $scope.cancel = function(){
            $state.go("collect.auth");
        }
    }
})();
