'use strict';

/**
 * 0.1.1
 * Deferred load js/css file, used for ui-jq.js and Lazy Loading.
 * 
 * @ flatfull.com All Rights Reserved.
 * Author url: #user/flatfull
 */

angular.module('ui.load', [])
	.service('uiLoad', ['$document', '$q', '$timeout', function ($document, $q, $timeout) {

		var loaded = [];
		var promise = false;
		var deferred = $q.defer();

		/**
		 * Chain loads the given sources
		 * @param srcs array, script or css
		 * @returns {*} Promise that will be resolved once the sources has been loaded.
		 */
		this.load = function (srcs) {
			srcs = angular.isArray(srcs) ? srcs : srcs.split(/\s+/);
			var self = this;
			if(!promise){
				promise = deferred.promise;
			}
      angular.forEach(srcs, function(src) {
      	promise = promise.then( function(){
      		return src.indexOf('.css') >=0 ? self.loadCSS(src) : self.loadScript(src);
      	} );
      });
      deferred.resolve();
      return promise;
		}

		/**
		 * Dynamically loads the given script
		 * @param src The url of the script to load dynamically
		 * @returns {*} Promise that will be resolved once the script has been loaded.
		 */
		this.loadScript = function (src) {
			if(loaded[src]) return loaded[src].promise;

			var deferred = $q.defer();
			var script = $document[0].createElement('script');
			script.src = src;
			script.onload = function (e) {
				$timeout(function () {
					deferred.resolve(e);
				});
			};
			script.onerror = function (e) {
				$timeout(function () {
					deferred.reject(e);
				});
			};
			$document[0].body.appendChild(script);
			loaded[src] = deferred;

			return deferred.promise;
		};

		/**
		 * Dynamically loads the given CSS file
		 * @param href The url of the CSS to load dynamically
		 * @returns {*} Promise that will be resolved once the CSS file has been loaded.
		 */
		this.loadCSS = function (href) {
			if(loaded[href]) return loaded[href].promise;

			var deferred = $q.defer();
			var style = $document[0].createElement('link');
			style.rel = 'stylesheet';
			style.type = 'text/css';
			style.href = href;
			style.onload = function (e) {
				$timeout(function () {
					deferred.resolve(e);
				});
			};
			style.onerror = function (e) {
				$timeout(function () {
					deferred.reject(e);
				});
			};
			$document[0].head.appendChild(style);
			loaded[href] = deferred;

			return deferred.promise;
		};
}]);

app.service('MessageService', function (ngDialog) {

        return {

            httpRequestFailed: function (url) {
                ngDialog.openConfirm({
                    template: 'dialogs/alert.html' + urlTimeStamp(),
                    width: 600,
                    cache: false,
                    data: url,
                    controller: ['$scope', function ($scope) {
                        $scope.msgText = $scope.ngDialogData;
                        $scope.confirmYes = function() {
                            $scope.closeThisDialog();
                        }
                    }]
                });
            },
            showAlert: function (msg) {
                ngDialog.openConfirm({
                    template: 'dialogs/alert.html' + urlTimeStamp(),
                    width: 400,
                    cache: false,
                    data: msg,
                    controller: ['$scope', function ($scope) {
                        $scope.msgText = $scope.ngDialogData;
                        $scope.confirmYes = function() {
                            $scope.closeThisDialog();
                        }
                    }]
                });
            }

        }
    })
	.service('HttpService',['$http','MessageService',function ($http,MessageService){
		return{
			getUserListData:function(success){
                $http({
                    method: 'GET',
                    url: "../admin/getUserList"+urlTimeStamp()
                }).then(function successCallback(response) {
					success(response.data)
                },function(err){
                    console.log(err)
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
			getAllActiveRoleList:function(success){
                $http({
                    method: 'GET',
                    url: "../admin/getAllActiveRoleList"+urlTimeStamp()
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    console.log(err)
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
			addUser:function(data,success){
				var body = JSON.stringify(data);
                $http({
                    method: 'POST',
                    url: "../admin/userAdd" + urlTimeStamp(),
                    data: body,
                    headers: {'Content-Type': 'application/json'}
                }).then(function successCallback(response) {
					success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            getPermissionListData:function(success){
                $http({
                    method: 'GET',
                    url: "../admin/getPermissionList"+urlTimeStamp()
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            getAllActivePermissionList:function(success) {
                $http({
                    method: 'GET',
                    url: "../admin/getAllActivePermissionList"+urlTimeStamp()
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            getRoleListData:function(success){
                $http({
                    method: 'GET',
                    url: "../admin/getRoleList"+urlTimeStamp()
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            userDelete:function(id,success){
                $http({
                    method: 'GET',
                    url: "../admin/userDel"+urlTimeStamp(),
                    params:{
                        userId:id
                    }
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            userOpen:function(id,success){
                $http({
                    method: 'GET',
                    url: "../admin/userBack"+urlTimeStamp(),
                    params:{
                        userId:id
                    }
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            getUserById:function(id,success){
                $http({
                    method: 'GET',
                    url: "../admin/getUserById"+urlTimeStamp(),
                    params:{
                        userId:id
                    }
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            updateUser:function(data,success){
                var body = JSON.stringify(data);
                $http({
                    method: 'POST',
                    url: "../admin/userUpdate" + urlTimeStamp(),
                    data: body,
                    headers: {'Content-Type': 'application/json'}
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })

            },
            delPermission:function(id,success){
                $http({
                    method: 'GET',
                    url: "../admin/permissionDel"+urlTimeStamp(),
                    params:{
                        permissionId:id
                    }

                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            openPermission:function(id,success){
                $http({
                    method: 'GET',
                    url: "../admin/permissionOpen"+urlTimeStamp(),
                    params:{
                        permissionId:id
                    }
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            addPermission:function(data,success){
                var body = JSON.stringify(data);
                $http({
                    method: 'POST',
                    url: "../admin/permissionAdd" + urlTimeStamp(),
                    data: body,
                    headers: {'Content-Type': 'application/json'}
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            getPermsById:function(id,success){
                $http({
                    method: 'GET',
                    url: "../admin/getPermsById"+urlTimeStamp(),
                    params:{
                        permissionId:id
                    }
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            updatePerm:function(data,success){
                var body = JSON.stringify(data);
                $http({
                    method: 'POST',
                    url: "../admin/permissionUpdate" + urlTimeStamp(),
                    data: body,
                    headers: {'Content-Type': 'application/json'}
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            logout:function(success){
                $http({
                    method: 'GET',
                    url: "../user/logout"+urlTimeStamp()
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            rolesAdd:function(data,success){
                var body = JSON.stringify(data);
                $http({
                    method: 'POST',
                    url: "../admin/roleAdd" + urlTimeStamp(),
                    data: body,
                    headers: {'Content-Type': 'application/json'}
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            getRoleById:function(id,success){
                $http({
                    method: 'GET',
                    url: "../admin/getRoleById"+urlTimeStamp(),
                    params:{
                        roleId:id
                    }
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            updateRole:function(data,success){
                var body = JSON.stringify(data);
                $http({
                    method: 'POST',
                    url: "../admin/roleUpdate" + urlTimeStamp(),
                    data: body,
                    headers: {'Content-Type': 'application/json'}
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            getTypeListByTaskStateId:function(state,success){
                $http({
                    method: 'GET',
                    url: "../user/getTypeListByTaskStateId" + urlTimeStamp(),
                    params:{
                        taskStateId:state
                    }
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            getCityListByCardType:function(cardType,state,success){
                $http({
                    method: 'GET',
                    url: "../user/getCityListByCardType" + urlTimeStamp(),
                    params:{
                        state:state,
                        cardType:cardType
                    }
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            getGroupNoByTaskListId:function(taskStateId,success){
                $http({
                    method: 'GET',
                    url: "../user/getGroupNoByTaskListId" + urlTimeStamp(),
                    params:{
                        taskStateId:taskStateId
                    }
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            getCountyListByTaskListId:function(taskStateId,success){
                $http({
                    method: 'GET',
                    url: "../user/getCountyListByTaskListId" + urlTimeStamp(),
                    params:{
                        taskStateId:taskStateId
                    }
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            updateProductionTask:function(taskId,state,success){
                $http({
                    method: 'GET',
                    url: "../user/updateProductionTask" + urlTimeStamp(),
                    params:{
                        taskId:taskId,
                        state:state
                    }
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            findFailedinfo:function(state,workShop,success){
                $http({
                    method: 'GET',
                    url: "../user/findFailedinfo" + urlTimeStamp(),
                    params:{
                        workShop:workShop,
                        state:state
                    }
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            getReceiptData:function(startTime, endTime,success){
                $http({
                    method: 'GET',
                    url: "../user/getConnectList" + urlTimeStamp(),
                    params:{
                        startTime:startTime,
                        endTime:endTime
                    }
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            },
            getprintReceipt:function(startTime, endTime,success){
                $http({
                    method: 'GET',
                    url: "../user/getConnectList" + urlTimeStamp(),
                    params:{
                        startTime:startTime,
                        endTime:endTime
                    }
                }).then(function successCallback(response) {
                    success(response.data)
                },function(err){
                    var errA = {Error:true, ReturnCode:err.status, ReturnMsg:"API访问返回错误"}
                    MessageService.httpRequestFailed(JSON.stringify(errA))
                })
            }


		}
	}])