define([ 'toaster', 'charts', 'ngTable', 'common/services', 'service/Purc', 'ui.router', 'ui.bootstrap' ], function() {
	'use strict';
	var app = angular.module('myApp', ['ngAnimate', 'toaster', 'ui.router', 'common.services', 'PurcServices', 'ui.bootstrap' ]);
	app.init = function() {
		angular.bootstrap(document, [ 'myApp' ]);
	};
	app.config(function($stateProvider, $urlRouterProvider) {
		$urlRouterProvider.otherwise('/index');
		$stateProvider.state('index', {
			url : "/index",
			templateUrl : "static/tpl/index_mobile/home/index.html"
		}).state('saleOrder', {
			url : "/sale/order/:code",
			templateUrl : "static/tpl/index_mobile/sale/saleOrder.html"
		}).state('saleChange', {
			url: '/sale/change/:code',
			templateUrl: 'static/tpl/index_mobile/sale/saleChange.html'
		}).state('saleInquiry', {
			url: '/sale/inquiry/:itemId',
			templateUrl: 'static/tpl/index_mobile/sale/saleInquiry.html'
		}).state('saleNotice', {
			url: '/sale/notice/:id',
			templateUrl: 'static/tpl/index_mobile/sale/saleNotice.html'
		});
	});
	
	app.factory('StatusCode', function(){
		var statusConfig = {
				'101' : '已提交',
				'102' : '已审核',
				'103' : '未通过',
				'313' : '已激活',
				'316' : '已过账', 
				'311' : '申请中',
				'312' : '未激活',
				'200' : '未回复',
				'203' : '已下载',
				'201' : '已回复'
		};
		return {
			get: function(code) {
				return statusConfig[code];
			}
		};
	}).filter('status', function(StatusCode){
		return function(data) {
			return StatusCode.get(data);
		}
	});
	
	app.factory('Symbol', function(){
		return {
			currency: function(cur) {
				if(cur == 'RMB') return '¥';
				else if(cur == 'USD') return '$';
				else if(cur == 'EUR') return '€';
				else return cur;
			}
		};
	});
	
	app.controller('MyCtrl', function($scope, $rootScope) {
		$rootScope.$on('$locationChangeSuccess', function(evt, newUrl) {
			var routeState = newUrl.substr(newUrl.indexOf('#/') + 2);
			if (routeState.indexOf('/') > -1)
				routeState = routeState.substring(0, routeState.indexOf('/'));
			if (routeState.indexOf('.') > -1)
				routeState = routeState.substring(0, routeState.indexOf('.'));
			$scope.routeState = routeState || 'home';
		});
	});
	app.controller('AuthCtrl', function($scope, $window, AuthenticationService) {
		$scope.isAuthed = AuthenticationService.isAuthed();
		$scope.userInfo = {};
		AuthenticationService.getAuthentication().success(function(data) {
			$scope.userInfo = data;
			if (data == null || !data.uu)
				$scope.isAuthed = false;
		});
		$scope.logout = function() {
			AuthenticationService.logout().success(function() {
				$window.location.reload();
			});
		};
	});
	app.controller('SaleOrderCtrl', function($scope, $filter, $stateParams, toaster, PurcOrder, PurcOrderItem, Symbol){
		$scope.loading = true;
		$scope.symbol = Symbol.currency;
		
		$scope.getOrderTotal = function(items) {
			var sum = 0;
			angular.forEach(items, function(item){
				sum += item.qty * item.price;
			});
			return parseFloat(sum).toFixed(2);//四舍五入取两位小数
		};
		
		PurcOrder.get({id: $stateParams.code}, function(data) {
			$scope.purcOrder = data;
			$scope.loading = false;
		});
		
		/**
		 * 展开回复
		 */
		$scope.expandReply = function(orderItem) {
			if(!orderItem.replys) {
				PurcOrderItem.getReply({orderItemId: orderItem.id}, function(data){
					orderItem.replys = data;
				}, function(){
					orderItem.replysError = true;
				});
			}
			angular.forEach($scope.purcOrder.orderItems, function(item, index){
				if(item.number != orderItem.number) item.expand = false;
			});
			orderItem.expand = !orderItem.expand;
		};
		
		/**
		 * 全选
		 */
		$scope.checkAll = function(value) {
			angular.forEach($scope.purcOrder.orderItems, function(item, index){
				item.checked = value;
			});
		};
		
		/**
		 * 选中一个
		 */
		$scope.checkOne = function(value) {
			if(value) {
//				angular.forEach($scope.purcOrder.orderItems, function(item, index){
//					if(item.checked == false) {
//						$scope.check_all = false; return ;
//					}
//				});
			} else {
				$scope.check_all = false;
			}
		};
		
		$scope.open = function($event, orderItem) {
    		$event.preventDefault();
    		$event.stopPropagation();
    		orderItem.opened = !orderItem.opened;
  		};
		
		
		$scope.reply = function(item) {
			$scope.loading = true;
			if(item.reply) {
				var reply = angular.copy(item.reply), 
					dateFilter = $filter('date');
				if(reply.delivery) {
					reply.delivery = reply.delivery.getTime();
				}
				PurcOrderItem.reply({orderItemId: item.id}, reply, function(){
					PurcOrder.get({id: $stateParams.code}, function(data) {
						$scope.purcOrder = data;
						$scope.loading = false;
						toaster.pop('success', '提示', '回复成功');
					});
				}, function(response){
					$scope.loading = false;
					toaster.pop('error', '回复失败', response.data);
				});
			}
		};
		
		$scope.replyByBatch = function() {
			$scope.loading = true;
			var str = '';
			angular.forEach($scope.purcOrder.orderItems, function(item) {
				if(item.checked == true) {
					str += item.id + ",";
				}
			});
			if(!(str == '')) {
				str = str.substr(0, str.length-1);
				PurcOrderItem.replyByBatch(str, function(){
					$scope.loading = false;
					PurcOrder.get({id: $stateParams.code}, function(data) {
						$scope.purcOrder = data;
						$scope.loading = false;
						toaster.pop('success', '提示', '回复成功');
					});
				}, function(data){
					$scope.loading = false;
					toaster.pop('error', '回复失败', data);
				});
			};
			
		};
	});
	
	/**
	 * 销售变更
	 */
	app.controller('SaleChangeCtrl', function($scope, $stateParams, toaster, PurcChange){
		$scope.loading = true;
		$scope.remark = '';
		
		//获取变更单
		PurcChange.get({id: $stateParams.code}, function(data){
			$scope.purcChange = data;
			$scope.remark = data.replyRemark;
			$scope.loading = false;
		}, function(response){
			console.log(response);
		});
		
		$scope.onReplyClick = function(change) {
			$scope.loading = true;
			var reply = {id: change.id, agreed: Number(change.agreed), replyRemark: change.replyRemark};
			PurcChange.reply({changeId: change.id}, reply, function(){
				toaster.pop('info', '提示', '回复成功');
				PurcChange.get({id: $stateParams.code}, function(data){
					$scope.purcChange = data;
					$scope.remark = data.replyRemark;
					$scope.loading = false;
				}, function(response){
					console.log(response);
				});
			}, function(response){
				$scope.loading = false;
				toaster.pop('error', '回复失败', response.data);
			});
		};
	});
	
	app.controller('SaleInquiryCtrl', function($scope, $stateParams, toaster, PurcInquiry, Symbol){
		$scope.loading = true;
		$scope.vendFromDateOpen = false;
		$scope.vendToDateOpen = false;
		
		$scope.symbol = Symbol.currency;//把币别转化为符号
		
		PurcInquiry.getItem({itemId: $stateParams.itemId}, function(data){
			$scope.purcInquiry = data;
			$scope.loading = false;
		}, function(data){
			toaster.pop('error', '加载失败', response.data);
		});
		
		$scope.openF = function($event) {
    		$event.preventDefault();
    		$event.stopPropagation();
    		$scope.vendFromDateOpen = !$scope.vendFromDateOpen;
  		};
  		
  		$scope.openT = function($event) {
    		$event.preventDefault();
    		$event.stopPropagation();
    		$scope.vendToDateOpen = !$scope.vendToDateOpen;
  		};
  		
  		$scope.addNewReply = function(reply) {
  			$scope.purcInquiry.replies.push({price: null, lapQty: null, id: null, editing: true});
  			reply.editing = false;
  		};
  		
  		$scope.save = function(item) {
  			$scope.loading = true;
  			if(item.vendFromDate instanceof Date) {
  				item.vendFromDate = item.vendFromDate.getTime();
  			}
  			if(item.vendToDate instanceof Date) {
  				item.vendToDate = item.vendToDate.getTime();
  			}
  			PurcInquiry.saveItem({itemId: item.id}, item, function(data) {
  				toaster.pop('info', '提示', '保存成功');
  				PurcInquiry.getItem({itemId: $stateParams.itemId}, function(data){
					$scope.purcInquiry = data;
					$scope.loading = false;
				}, function(data){
					$scope.loading = false;
					toaster.pop('error', '加载失败', response.data);
				});
  			}, function(response){
  				$scope.loading = false;
				toaster.pop('error', '保存失败', response.data);
  			});
  		};
  		
  		$scope.reply = function(item) {
  			$scope.loading = true;
  			if(item.vendFromDate instanceof Date) {
  				item.vendFromDate = item.vendFromDate.getTime();
  			}
  			if(item.vendToDate instanceof Date) {
  				item.vendToDate = item.vendToDate.getTime();
  			}
  			PurcInquiry.reply({itemId: item.id}, item, function(data) {
  				toaster.pop('info', '提示', '回复成功');
  				PurcInquiry.getItem({itemId: $stateParams.itemId}, function(data){
					$scope.purcInquiry = data;
					$scope.loading = false;
				}, function(data){
					$scope.loading = false;
					toaster.pop('error', '加载失败', response.data);
				});
  			}, function(response){
  				$scope.loading = false;
				toaster.pop('error', '回复失败', response.data);
  			});
  		};
	});
	
	app.controller('SaleNoticeCtrl', function($scope, $stateParams, toaster, PurcNotice, Symbol){
		$scope.loading = true;
		$scope.symbol = Symbol.currency;//把币别转化为符号
		$scope.logShow = false;
		
		$scope.notice = PurcNotice.get({id: $stateParams.id}, function(data){
			$scope.loading = false;
		}, function(response){
			toaster.pop('error', '加载失败', response.data);
		});
		
		$scope.getSends = function(){
			if(! $scope.notice.sendLogs) {
				$scope.loading = true;
				$scope.notice.sendLogs = PurcNotice.getSends({id: $stateParams.id}, function(data){
					$scope.loading = false;
				}, function(response){
					$scope.loading = false;
					toaster.pop('error', '加载失败', response.data);
				});
			}
		};
		
		$scope.onReplyClick = function(notice) {
			if(notice.send.qty > notice.qty - (notice.endQty || 0)) {
				toaster.pop('warning', '警告', '本次发货数量超出！');
			} else {
				var send = {code: notice.send.code, sendItems: [{qty: notice.send.qty}]};
				$scope.loading = true;
				PurcNotice.save({id: notice.id}, send, function(){
					$scope.loading = false;
					$scope.notice = PurcNotice.get({id: $stateParams.id}, function(data){
					}, function(response){
						toaster.pop('error', '加载失败', response.data);
					});
					toaster.pop('success', '提示', '发货成功');
				}, function(response){
					$scope.loading = false;
					toaster.pop('error', '失败', response);
				});
				$scope.logShow = false;
			}
		};
		
		
	});
	return app;
});