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

    var isLog = false; //标识是不是从列表直接进入到调试界面
    function appCtrl($rootScope,$scope,HttpService,ToolService,UtilService,$state,$timeout){
        $scope.isDemo = ToolService.isDemoUser();

    	$scope.$on('flipinfo',function(e,msg){
            $scope.flipPage = msg;
        });
        $scope.specialsAppkey = [
            "e31caee07ebedf8c172267e73204802f",
            "f4c6764d10bec9a3c4bd4f79a442a947",
            "022da4f8bd53ac212141bd7fdfa9532d",
            "5eb29a7e239537f4bedef93f8289d1c6",
            "e0b3000ebd3f54b791a405f68d3e520c"];
        $scope.doRemove = function(id){
            $scope.delstatus = true;
            $scope.delId = id;
        }
        $scope.removeInfo = function(){
            var removePM = HttpService.deleteInfo("mng/app/delete/"+$scope.delId);
            ToolService.showLoading();
            removePM.then(function(data){
                ToolService.hideLoading();
                $scope.delstatus = false;
                ToolService.showTips("删除成功")
                $scope.$emit("f5Applist",true);
                $rootScope.operSubmitData("删除");
            });
        }
        $timeout(function(){
            var clipboard = new Clipboard('.copyBtn');
            clipboard.on('success', function(e) {
                $scope.$apply(function(){
                    ToolService.showTips("复制成功");
                });
            });
            clipboard.on('error', function(e) {
                $scope.$apply(function(){
                    ToolService.showTips("复制失败");
                });
            });
        },200);
        //启用停用
        $scope.onOff = function(info){
            var url = "mng/app/enable/"+info.id,tipmsg = "启用成功";
            if(info.regedbutton){
                url = "mng/app/forbidden/"+info.id;
                tipmsg = "停用成功";
            }
            var userPM = HttpService.putInfo(url,{});
            ToolService.showLoading();
            userPM.then(function(data){
                ToolService.hideLoading();
                ToolService.showTips(tipmsg)
                $scope.$emit("f5Applist",true);
                $rootScope.operSubmitData(tipmsg.slice(0,2));
            });
        }

        $scope.limitCount = 9;
        $scope.isShow = function() {
          if(!$scope.appAlllistInfo){
             return false;
          }
          $scope.resultList = $scope.appAlllistInfo;
          if($scope.resultList && $scope.resultList.length > $scope.limitCount){
             return true;
          }else{
             return false;
          }
        }
        var panelH = $(".rightWrap");
        $(".rightWrap").scroll(function(event){  
            if(panelH.get(0).scrollHeight<=panelH.height())return;
            var _this = this;
            $timeout(function() {
                if($scope.isShow() && $scope.filterResult.length>0){
                    var viewH =$(_this).height(),//可见高度  
                    contentH =$(_this).get(0).scrollHeight,//内容高度  
                    scrollTop =$(_this).scrollTop();//滚动高度  
                    if(scrollTop>=contentH -viewH){ //到达底部100px时,加载新内容  
                        $scope.getMore();
                    }  
                }
            }, 10);
        }); 
        $(".rightWrap").on('mousewheel', function(event){ 
            if(panelH.get(0).scrollHeight>panelH.height() || event.originalEvent.deltaY<=0)return;
            if($scope.isShow() && $scope.filterResult.length>0){
                $timeout(function() { 
                    $scope.getMore();
                }, 10);
            }
        });  
        $scope.getMore = function(){
            $scope.limitCount += 9;
        }
        $scope.gopage = function(id,flag){
            if(flag){
                isLog = true;
            }
            else{
                isLog = false;
            }
            if(angular.isDefined(id)){
                $state.go("collect.appDetail",{aid:id});
            }else{
                $state.go("collect.appDetail");
            }
        }

        $scope.goReport = function(info,e){
            if($(e.target).hasClass('copyBtn')) return;
            $rootScope.isweb = info.platform == 'H5';
            $('.rightWrap').unbind("scroll");
            $('.rightWrap').unbind("mousewheel");
            $scope.$emit("mngappTo",info.id);

            var url = $rootScope.firstMeau.substring(1).replace('/','.');
            $state.go(url);
        }
    }

    function appDetailCtrl($scope,$rootScope,HttpService,ToolService,UtilService,$q,$state,$stateParams,$filter,$timeout){
        var infoId = $scope.infoId = $scope.id = $stateParams.aid;
        $scope.isLog = isLog;
        if(!infoId){
          $scope.tagType = 'game';
        }
        $scope.typeinit = '请选择游戏类型';
        $scope.themeinit = '请选择游戏题材';
        $scope.styleinit = '请选择美术风格';
        $scope.firstinit = '请选择应用分类';
        $scope.secondinit = '应用分类-细分分类';
        var boundOldID = "",oldName = "";

        var gameTypeId = 38;
        var tagPM = HttpService.getInfo("/dic/findbycampaign");
        tagPM.then(function(data){
            $scope.tagList = data;
            init();
        });
        if(!$scope.isLog){
            var typePM = HttpService.getInfo("mng/app/find/getcategorys");
            typePM.then(function(data){
                var typeArr = [],gameArr = [];
                data.filter(function(item){
                    item.name = item.categoryname;
                    if(item.isgame == 1){
                        gameArr.push(item);
                    }else{
                        typeArr.push(item);
                    }
                });
                $scope.typeList = typeArr;
                $scope.gameList = gameArr;

                $scope.appGenreInit = $scope.typeList[0].categoryid;
                $scope.gameGenreInit = $scope.gameList[0].categoryid;
            });
        }
        $scope.downloadsdk = function(){
          $rootScope.operSubmitData("查看并下载SDK");
        }
        $scope.$on("appGenre",function(e,msg){
            $scope.showGame = msg.info.categoryid == gameTypeId;
            $scope.appGenre = msg.info.categoryid;

            $scope.appGenreName = msg.info.categoryname;
        });
        $scope.$on("gameGenre",function(e,msg){
            $scope.gameGenre = msg.info.categoryid;
            $scope.gameGenreName = msg.info.categoryname;
        });
        $scope.$on("typeIds",function(e,msg){
            $scope.typeIds = msg.info;
        });
        $scope.$on("themeIds",function(e,msg){
            $scope.themeIds = msg.info;
        });
        $scope.$on("styleIds",function(e,msg){
            $scope.styleIds = msg.info;
        });
        $scope.$on("firstId",function(e,msg){
            $scope.firstId = msg.info.itemCode;
            $scope.tagList.app.filter(function(item){
                if($scope.firstId == item.itemCode){
                   $scope.secondList = item.child;
                }
            });
        });
        $scope.$on("secondId",function(e,msg){
            $scope.secondId = msg.info.itemCode;
        });
        $scope.ckSync = function(){
            $scope.sync = !$scope.sync;

            if($scope.sync == true){
                ToolService.showTips("所有推广活动的下载地址将同步更新。",2000);
            }
        }
        var init = function(){
            if(infoId!=null){
                if($scope.isLog){
                    $scope.stepflag = 3;
                }
                else{
                    $scope.stepflag = 1;
                }
                var editPM = HttpService.getInfo("mng/app/find/"+infoId);
                ToolService.showLoading();
                editPM.then(function(data){
                    $scope.platform = data.platform;
                    $scope.name = oldName = data.name;
                    $scope.url = data.url;
                    $scope.appkey = data.appkey;
                    // $scope.sync = data.sync;
                    $scope.sync = false;
                    $scope.bundleid = boundOldID = data.bundleid;

                    $scope.appTagList = data.appTagList;
                    var stemp = [], ttemp = [], etemp = [];
                    if(data.tagType=="02"){
                        $scope.appTagList.filter(function(item) {
                            if(item.parentTagId == $scope.tagList.game[0].itemCode){
                               stemp.push(item.tagId);
                               $scope.typeinitIds = stemp.join(',');
                               $scope.typeIds = stemp.join(',');
                            }else if(item.parentTagId == $scope.tagList.game[1].itemCode){
                               ttemp.push(item.tagId);
                               $scope.themeinitIds = ttemp.join(',');
                               $scope.themeIds = ttemp.join(',');
                            }else if(item.parentTagId == $scope.tagList.game[2].itemCode){
                               etemp.push(item.tagId);
                               $scope.styleinitIds = etemp.join(',');
                               $scope.styleIds = etemp.join(',');
                            }
                        });
                        $scope.tagType = "game";
                    }else if(data.tagType=="04"){
                        $scope.secondinitId = $scope.appTagList[0].tagId;
                        $scope.tagList.app.filter(function(p) {
                            if($scope.appTagList[0].parentTagId == p.itemCode){
                               $scope.firstinitId = p.itemCode;
                            }
                        });
                        $scope.tagType = "app";
                    }else if(data.tagType=="00"){
                        $scope.tagType = "test";
                    }
                });
                if($scope.stepflag == 1){
                    $q.all([typePM,editPM]).then(function(data){
                        ToolService.hideLoading();
                        var info = data[1];
                        $scope.appGenreInit = info.appGenre;
                        $scope.gameGenreInit = info.gameGenre;
                    });
                }
            }else{
                $scope.stepflag = 1;
                $scope.platform = 'iOS';
                $scope.sync = false;
            }
        }

        $scope.nameHas = false;
        $scope.exixtName = function(){
            if(!$scope.tip){
                $scope.tip = {};
            }
            if($scope.judgeNameChange(oldName,$scope.name)){
                ToolService.showLoading();
                var existPM = HttpService.getInfo("mng/app/validname",{name:$scope.name});
                existPM.then(function(data){
                    ToolService.hideLoading();
                    if(data==true){
                        $scope.tip.name = {
                            status:true,
                            txt : "名称已存在"
                        };
                        $scope.nameHas = true;
                    }
                    else{
                        $scope.tip.name = {
                            status:false
                        };
                        $scope.nameHas = false;
                    }
                });
            }
            else{
                $scope.tip.name = {
                    status:false
                };
                $scope.nameHas = false;
            }
        }

        $scope.bundleHas = false;
        $scope.existBundleid = function(flag){
            if(!$scope.tip){
                $scope.tip = {};
            }
            if($scope.judgeNameChange(boundOldID,$scope.bundleid)){
                ToolService.showLoading();
                var existPM = HttpService.getInfo("mng/app/valid",{name:$scope.bundleid});
                existPM.then(function(data){
                    ToolService.hideLoading();
                    if(data==true){
                        $scope.tip.bundleid = {
                            status:true,
                            txt : "bundleid已存在"
                        };
                        $scope.bundleHas = true;
                    }
                    else{
                        $scope.tip.bundleid = {
                            status:false
                        };
                        $scope.bundleHas = false;
                    }
                });
            }
            else{
                $scope.tip.bundleid = {
                    status:false
                };
                $scope.bundleHas = false;
            }
        }

        $scope.save = function(){
            if($scope.nameHas || $scope.bundleHas){
                return false;
            }
            var appTagList = [], isnull = false, tag = "00";
           
            if($scope.tagType == 'game'){
                $scope.typenull = !$scope.typeIds;
                $scope.themenull = !$scope.themeIds;
                $scope.stylenull = !$scope.styleIds;
                if($scope.typenull || $scope.themenull || $scope.stylenull){
                   isnull = true;
                }else{
                   tag = "02";
                   $scope.typeIds.split(",").filter(function(item){
                       appTagList.push({tagId:item});
                   });
                   $scope.themeIds.split(",").filter(function(item){
                       appTagList.push({tagId:item});
                   });
                   $scope.styleIds.split(",").filter(function(item){
                       appTagList.push({tagId:item});
                   });
                }

            }
            else if($scope.tagType == 'app'){
                $scope.firstnull = !$scope.firstId;
                if($scope.firstId){
                  $scope.secondnull = !$scope.secondId;
                }
                if($scope.firstnull || $scope.secondnull){
                   isnull = true;
                }else{
                   tag = "04";

                   $scope.secondId.split(",").filter(function(item){
                      appTagList.push({tagId:item});
                   });
                }
            }
            var par = {
                    platform: $scope.platform,
                    name: $scope.name,
                    appGenre: $scope.appGenre,
                    sync: $scope.sync,
                    url: $scope.url,
                    appTagList: appTagList,
                    tagType: tag
                };
                if($scope.appGenre == gameTypeId){
                    par.gameGenre = $scope.gameGenre;
                }else{
                    par.gameGenre = -1;
                }

            var verPar = {
                name: {
                    key: 'nameFormat',
                    val: $scope.name
                },
                url: {
                    key: 'url',
                    val: $scope.url,
                    txt:"以http://或https://开头的合法url"
                }
            };

            if($scope.platform=='iOS'){
                par["bundleid"] = $scope.bundleid;
                verPar.bundleid = {
                    key : "num",
                    min : 9,
                    max : 10,
                    val : $scope.bundleid,
                    txt : '请输入9-10位数字'
                }
            }

            $scope.tip = formJudge(verPar);
            if ($scope.tip.succ != true) {
                ToolService.showTips($scope.formTipMsg);
                return false;
            }

            var savePM = null,txtTips = "添加成功";
            if(infoId!=null){
                par.id = infoId;
                savePM = HttpService.putInfo("mng/app/update",par);
                txtTips = "修改成功";
            }else{
                savePM = HttpService.postInfo("mng/app/create",par);
            }
            ToolService.showLoading();
            savePM.then(function(data){
                if(infoId!=null){
                    ToolService.hideLoading();
                    ToolService.showTips(txtTips);
                    $scope.cancel();
                }else{
                    $scope.$emit("f5Applist",1);
                    $scope.id = data.id;
                    $scope.name = data.name;
                    $scope.appkey = data.appkey;
                    ToolService.hideLoading();
                    $scope.stepflag = 2;
                    $rootScope.operSubmitData("新建");
                }
            });
        }

        $scope.cancel = function(){
            $scope.$emit("f5Applist",true);
            $state.go("collect.app");
        }

        $scope.changeStep = function(){
            if($scope.stepflag == 3){
                $scope.stepflag = 2;
            }
        }

        $scope.deviceList = [{'id':1,name:"全部设备"}];
        $scope.deviceInit = $scope.deviceList[0].id;
        $scope.$on("deviceId",function(e,msg){
            if(msg.info.id == 1){
                $scope.deviceTxt = "";
            }
            else{
                $scope.deviceTxt = msg.info.id;
            }
        });

        var getV = function(v){
            if(UtilService.isNullStr(v)){
                return "";
            }
            else{
                return v;
            }
        }
        $scope.queryLogInfo = function(){
            $scope.logFlag = 0;
            ToolService.showLoading();
            var testPM = HttpService.getInfo("mng/app/debug/event/list/"+$scope.id),
                logPM = HttpService.getInfo("mng/app/debug/log/list/"+$scope.id),
                totalPM = HttpService.getInfo("mng/app/debug/device/list/"+$scope.id);

            $scope.hasZeroEvt = 0;
            $q.all([testPM,logPM,totalPM]).then(function(data){
                $scope.testInfos = data[0];
                $scope.testInfos.filter(function(item){
                    if($scope.platform=="H5"){
                        if(['pageview'].indexOf(item.eventName)>-1 && item.eventNumber==0){
                            $scope.hasZeroEvt ++;
                        }
                    }else{
                        if(['startup','install'].indexOf(item.eventName)>-1 && item.eventNumber==0){
                            $scope.hasZeroEvt ++;
                        }
                    }

                });
                var logs = data[1];
                logs.map(function(item){
                    item.xcontext = JSON.parse(item.xcontext);

                    item.xcontext.osname = getV(item.xcontext._ryos || item.xcontext._os) + '' + getV(item.xcontext._ryosversion);
                    item.xcontext.channel = item.xcontext._campaignid || item.xcontext.channelid;
                    item.deviceId = item.xcontext._deviceid;

                    item._network_type = item.xcontext._network_type || item.xcontext._network;
                    item._model = item.xcontext._model || item.xcontext._devicetype;
                });
                $scope.logInfos = logs;
                $scope.totalInfos = data[2];

                var devList = [{'id':1,name:"全部设备"}];
                $scope.totalInfos.filter(function(item){
                    devList.push({id:item.deviceId,name:item.deviceId});
                });
                $scope.deviceList = devList;
                $rootScope.operSubmitData("下一步");
                ToolService.hideLoading();
            });
        }
        $scope.getPlatClass = function(plat){
            var plat = $filter("lowercase")(plat);
            return {'ios':'apple','android':'android','h5':'web'}[plat];
        }
        $scope.nextStep = function(){
            $scope.cancel();
            // $scope.stepflag = 3;
            // $scope.queryLogInfo();
        }
        $scope.lookEvents = function(info){
            $scope.eventDetails = [
                {name:'时间',key:'xwhen'},
                {name:'设备ID',key:'_deviceid',second:true},
                {name:'APPKEY',key:'',value:$scope.appkey},
                {name:'应用名称',key:'',value:$scope.name},
                {name:'分包渠道',key:'channel',second:true},
                {name:'系统',key:'osname',second:true},
                {name:'机型',key:'_model'},
                {name:'分辨率',key:'_resolution',second:true},
                {name:'网络',key:'_network_type'},
                {name:'SDK版本',key:'_lib_version',second:true},
                {name:'事件ID',key:'xwhat',isevent:true},
                {name:'事件名称',key:'eventName'}
            ];
            $scope.curEvtLogInfo = info;

            $scope.logFlag = 1;
            ToolService.showAlp();
            angular.element(document).on("click",function(){
                $scope.$apply(function(){
                    $scope.hideDetails();
                });
            });
        }
        $scope.commonParams = null;
        $scope.lookParams = function(info){
            var getEventParams = function(){
                var xcontext = $scope.curEvtLogInfo.xcontext;
                var myparams = [];
                for(var k in xcontext){
                    var temp = {'name':k,'value':xcontext[k],sortId:100};
                    if(k.indexOf("_")==0){
                        var ccc = $scope.commonParams[k];
                        if(ccc){
                            temp.name = ccc.alias;
                            temp.sortId = ccc.sortId;
                        }
                        myparams.push(temp);
                    }
                    else{
                        myparams.push(temp);
                    }
                }
                UtilService.sortArray(myparams);
                $scope.paramsList = myparams;
                $scope.logFlag = 2;
            }
            if($scope.commonParams != null){
                getEventParams();
            }
            else{
                ToolService.showLoading();
                var evtPM = HttpService.getInfo("mng/app/debug/find/common");
                evtPM.then(function(data){
                    ToolService.hideLoading();
                    var json = {};
                    data.filter(function(item){
                        json[item.param] = item;
                    });
                    $scope.commonParams = json;
                    getEventParams();
                });
            }
        }

        $scope.hideDetails = function(){
            ToolService.hideAlp();
            $scope.logFlag = 0;
        }
        $scope.finisStep = function(){
            ToolService.showLoading();
            var finshPM = HttpService.putInfo("mng/app/debug/complete/"+$scope.id);
            finshPM.then(function(data){
                $scope.cancel();
                $rootScope.operSubmitData("调试完成");
            });
        }
        $timeout(function(){
            var clipboard = new Clipboard('.sdkAppid');
            clipboard.on('success', function(e) {
                $scope.$apply(function(){
                    ToolService.showTips("复制成功");
                });
            });
            clipboard.on('error', function(e) {
                $scope.$apply(function(){
                    ToolService.showTips("复制失败");
                });
            });
        },200);
    }
})();