var app = angular.module('pageCDN', ['ui.bootstrap','ngCookies','ngSanitize', 'localization'], angular.noop)

.config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('{[{');
    $interpolateProvider.endSymbol('}]}');
})

app.controller('pageCDNCtrl', ['$scope','$http','$log','$modal','$filter','$cookies','localize', function orderCtrl($scope,$http,$log,$modal,$filter,$cookies,$localize) {
    var _ = $localize.getLocalizedString;

    $scope.page = 1;           //当前页数
    $scope.pageSize = 10;   //分页大小
    $scope.pages = 1;       //总页数
    $scope.total = 0;      //总条数
 
	$scope.pageCDNs = []; //列表数据
    $scope.selected = '';  //选择类表项

    $scope.getPageCDN = function() {
		$http({
	         method: 'GET', 
	         url: '/api/rctrl/v1/cdn/',
	         params : {
	             action: 'list',
                 servicetype: 0,
	             pageIndex: $scope.page - 1,
	             pageSize: $scope.pageSize,
	         }
	     }).success(function(response) {
	     	$scope.pages = response.pages;
            $scope.total = response.total;
            $scope.selected = '';
	        $scope.pageCDNs = response.lists;
     
	     })
    }

    //翻页
     $scope.pageFirst = function() {
        $scope.page = 1;
    }
    $scope.pagePre = function() {
        $scope.page -= 1;
    }
    $scope.pageNext = function() {
        $scope.page += 1;
    }
    $scope.pageLast = function() {
        $scope.page = $scope.pages;
    }
    $scope.$watch('page',function(){
        $scope.getPageCDN();
    },true);

    //刷新列表
    $scope.$on("reload", function (event) {
        $scope.getPageCDN();
    });
    $scope.reload = function() {
        $scope.getPageCDN();
    }

    //获取选中列表条目的值
    $scope.select = function(pageCDN){
        $scope.selected = pageCDN;
    }
    //按钮禁用判断
     $scope.checkbox = function() {
        if ($scope.selected == "")
            return true;
        else
            return false;
    }
   
     $scope.power = function(){
         //选中时才打开模态框
        if($scope.checkbox() == false){
        var modalInstance = $modal.open({
            templateUrl: '/static/frontend/modals/pageCDN/power.html',
            controller: 'powerCtrl',
            resolve: {
                pageCDN: function() {
                    return $scope.selected;
                }
            }
        });
        } 

    }

    $scope.shutdown = function(){
        //选中时才打开模态框
       if($scope.checkbox() == false){
        var modalInstance = $modal.open({
            templateUrl: '/static/frontend/modals/pageCDN/shutdown.html',
            controller: 'shutdownCtrl',
            resolve: {
                pageCDN: function() {
                    return $scope.selected;
                }
            }
        });
    }

    }

    $scope.create = function(){
        var modalInstance = $modal.open({
            templateUrl: '/static/frontend/modals/pageCDN/create.html',
            controller: 'createCtrl',
            resolve: {
                pageCDN: function() {
                    return $scope.selected;
                }
            }
        });

    }

    $scope.modify = function(){
    	if($scope.selected){
	        var modalInstance = $modal.open({
	            templateUrl: '/static/frontend/modals/pageCDN/modify.html',
	            controller: 'modifyCtrl',
	            resolve: {
	                pageCDN: function() {
	                    return $scope.selected;
	                }
	            }
	        });
	    }
    }
    
    $scope.purgecache = function(){
    	if($scope.selected){
	        var modalInstance = $modal.open({
	            templateUrl: '/static/frontend/modals/pageCDN/purgeCache.html',
	            controller: 'purgeCacheCtrl',
	            resolve: {
	                pageCDN: function() {
	                    return $scope.selected;
	                }
	            }
	        });
	    }
    }

    $scope.delete = function(){
        if($scope.selected){
            var modalInstance = $modal.open({
                templateUrl: '/static/frontend/modals/pageCDN/delete.html',
                controller: 'deleteCtrl',
                resolve: {
                    pageCDN: function() {
                        return $scope.selected;
                    }
                }
            });
        }
    }

    $scope.isStable = function(cdn){
        return cdn.status == 'Speeding' || cdn.status == 'Disable'
    }

}]);

app.controller('powerCtrl', function ($scope,$http,$modalInstance,$cookies,pageCDN) {
    $scope.pageCDN = pageCDN;
    $scope.ok = function() {
        var last_status = pageCDN['status'];
        $scope.pageCDN['status'] = 'Updating';
        var data = {
            "action": "enable",
            "id": $scope.pageCDN.fakeid
        }
        
        $http({
            method: 'POST', 
            url: '/api/rctrl/v1/cdn/',
            headers:{'X-CSRFToken':$cookies.csrftoken,
                "Content-Type":"application/json;charset=utf-8"},
            data: data 
        }).success(function(response) {
            if (response.status == false){
                alert(response.message);
                $scope.pageCDN['status'] = last_status;
            }
            else{
                setAsyn(response.jobid, 'PageCDN', 'Enable')
                $modalInstance.close(undefined)
            }
        });
    };

    $scope.cancel = function() {
        //$scope.$root.$broadcast("reload");
        $modalInstance.close(undefined)
    }
});

app.controller('shutdownCtrl', function ($scope,$http,$modalInstance,$cookies,pageCDN) {
    $scope.pageCDN = pageCDN;
    $scope.ok = function() {
        var last_status = pageCDN['status'];
        $scope.pageCDN['status'] = 'Updating';
        var data = {
            "action": "disable",
            "id": $scope.pageCDN.fakeid
        }
        
        $http({
            method: 'POST', 
            url: '/api/rctrl/v1/cdn/',
            headers:{'X-CSRFToken':$cookies.csrftoken,
                "Content-Type":"application/json;charset=utf-8"},
            data: data 
        }).success(function(response) {
            if (response.status == false){
                alert(response.message)
                $scope.pageCDN['status'] = last_status;
            }
            else{
                setAsyn(response.jobid, 'PageCDN', 'Disable')
                $modalInstance.close(undefined)
            }
        });
    };

    $scope.cancel = function() {
        //$scope.$root.$broadcast("reload");
        $modalInstance.close(undefined)
    }
});

app.controller('createCtrl', function ($scope,$http,$modalInstance,$cookies,pageCDN) {
    $scope.pageCDN = pageCDN;
    $scope.value1 = "0"; //初始化服务区域


    $http({
        method: 'GET', 
        url: '/api/valuate/',
        params : {
            rtype: 'cdn'
        }
    }).success(function(response) {
        $scope.price = response.price.traffic;
    })
   
   


    $scope.ok = function() {
        
        var serviceareasValue = [];

        if($scope.value1 == "0"){
            serviceareasValue.push(0);
        }
        if($scope.value2 == "1"){
            serviceareasValue.push(1);
        }
        if($scope.value3 == "2"){
            serviceareasValue.push(2);
        }
        
        if(serviceareasValue == ""){
            return false;
        }
//        console.log(serviceareasValue.join());
        serviceareasValue = serviceareasValue.join();
        
        var data = {
            "action": "create",
            "domainname": $scope.domainname,
            "servicetype": 0,
            "serviceareas": serviceareasValue,
            "originips": $scope.originips
        }

        $http({
            method: 'POST', 
            url: '/api/rctrl/v1/cdn/',
            headers:{'X-CSRFToken':$cookies.csrftoken,
                "Content-Type":"application/json;charset=utf-8"},
            data: data 
        }).success(function(response) {
            if (response.status == false){
                alert(response.message)
            }
            else{
                setAsyn(response.jobid, 'PageCDN', 'Create')
                $modalInstance.close(undefined)
            }
        });

    };

    $scope.cancel = function() {
        //$scope.$root.$broadcast("reload");
        $modalInstance.close(undefined)
    }
});

app.controller('modifyCtrl', function ($scope,$http,$modalInstance,$cookies,pageCDN) {
    $scope.pageCDN = pageCDN;
    //显示服务区域初始值

   for(var id in $scope.pageCDN.serviceareaids){
     var value = $scope.pageCDN.serviceareaids[id];
        if(value == 0){
            $scope.value1 = "0";
        }else if (value == 1){
            $scope.value2 = "1"
        }else if (value == 2){
            $scope.value3 = "2"
        }
   }
    $scope.ok = function() {

//        console.log($scope.vmSnapshot.vmid);
        
        var last_status = pageCDN['status'];
        $scope.pageCDN['status'] = 'Updating';

        var serviceareasValue = [];
        if($scope.value1 == "0"){
            serviceareasValue.push(0);
        }
        if($scope.value2 == "1"){
            serviceareasValue.push(1);
        }
        if($scope.value3 == "2"){
            serviceareasValue.push(2);
        }

        if(serviceareasValue == ""){
            return false;
        }
        serviceareasValue = serviceareasValue.join();
        console.log(serviceareasValue)
        var data = {
            "action": "edit",
            "id": $scope.pageCDN.fakeid,
            "serviceareas": serviceareasValue,
            "originips": $scope.pageCDN.originips
            
        }
        
        $http({
            method: 'POST', 
            url: '/api/rctrl/v1/cdn/',
            headers:{'X-CSRFToken':$cookies.csrftoken,
                "Content-Type":"application/json;charset=utf-8"},
            data: data 
        }).success(function(response) {
            if (response.status == false){
                alert(response.message)
                $scope.pageCDN['status'] = last_status;
            }
            else{
                setAsyn(response.jobid, 'PageCDN', 'Modify')
                $modalInstance.close(undefined)
            }

        });

    };

    $scope.cancel = function() {
        $scope.$root.$broadcast("reload");
        $modalInstance.close(undefined)
    }
});

app.controller('purgeCacheCtrl', function ($scope,$http,$modalInstance,$cookies,pageCDN) {
    $scope.pageCDN = pageCDN;

    $scope.ok = function() {
        var last_status = pageCDN['status'];
        $scope.pageCDN['status'] = 'Updating';
        if(!($scope.pageCDN.files || $scope.pageCDN.dirs)){
            return false;
        }
        var data = {
            "action": "purgeCache",
            "id": $scope.pageCDN.fakeid,
            "files": $scope.pageCDN.files,
            "dirs": $scope.pageCDN.dirs
        }
        
        $http({
            method: 'POST', 
            url: '/api/rctrl/v1/cdn/',
            headers:{'X-CSRFToken':$cookies.csrftoken,
                "Content-Type":"application/json;charset=utf-8"},
            data: data 
        }).success(function(response) {
            if (response.status == false){
                alert(response.message)
                $scope.pageCDN['status'] = last_status;
            }
            else{
                setAsyn(response.jobid, 'PageCDN', 'PurgeCache')
                $modalInstance.close(undefined)
            }

        });

    };

    $scope.cancel = function() {
        //$scope.$root.$broadcast("reload");
        $modalInstance.close(undefined)
    }
});

app.controller('deleteCtrl', function ($scope,$http,$modalInstance,$cookies,pageCDN) {
    $scope.pageCDN = pageCDN;
    $scope.changeCode = function() {
        $('#checkcode').attr('src','/api/code?'+Date.parse(new Date()));
    }

    $scope.ok = function() {
        var last_status = pageCDN['status'];
        $scope.pageCDN['status'] = 'Updating';

    	var code = $("input[name='code']").val(); 
        if ($.trim(code) == '' || $.trim(code).length != 4) {
            return false;
        }
        
         // if (confirm("确定删除「"+$scope.pageCDN.fakeid+"」?")) {
	        var data = {
	            "action": "delete",
	            "id": $scope.pageCDN.fakeid,
	            "code": $scope.code
	        }
	        
	        $http({
	            method: 'POST', 
	            url: '/api/rctrl/v1/cdn/',
	            headers:{'X-CSRFToken':$cookies.csrftoken,
	                "Content-Type":"application/json;charset=utf-8"},
	            data: data 
	        }).success(function(response) {
                if (response.status == false){
                    alert(response.message)
                    $scope.pageCDN['status'] = last_status;
                }
                else{
                    setAsyn(response.jobid, 'PageCDN', 'Delete')
                    $modalInstance.close(undefined)
                }
	            $scope.changeCode();
	        });
    	// }

    };

    $scope.cancel = function() {
        //$scope.$root.$broadcast("reload");
        $modalInstance.close(undefined)
    }
});

Array.prototype.remove = function(b) {
    var a = this.indexOf(b);
    if (a >= 0) {
        this.splice(a, 1);
        return true;
    }
    return false;
};
