(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);
            });
        }
        $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(id,flag){
            var url = "mng/app/enable/"+id,tipmsg = "启用成功";
            if(flag && flag==1){
                url = "mng/app/forbidden/"+id;
                tipmsg = "停用成功";
            }
            var userPM = HttpService.putInfo(url,{});
            ToolService.showLoading();
            userPM.then(function(data){
                ToolService.hideLoading();
                ToolService.showTips(tipmsg)
                $scope.$emit("f5Applist",true);
            });
        }

        $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){
            $rootScope.isweb = info.platform == 'H5';
            $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;

        var boundOldID = "",oldName = "";

        var gameTypeId = 38;

        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(){
        }
        $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.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;

                    if($scope.stepflag == 3){
                        ToolService.hideLoading();
                        $scope.queryLogInfo();
                    }
                });
                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;
            }
        }
        init();

        $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 par = {
                    platform: $scope.platform,
                    name: $scope.name,
                    appGenre: $scope.appGenre,
                    sync: $scope.sync,
                    url: $scope.url
                };
                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;
                }
            });
        }

        $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;
                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();
            });
        }
        $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);
    }
})();