define([ 'toaster', 'charts', 'ngTable', 'common/services', 'service/Purc', 'ui.router', 'ui.bootstrap' ], function() {
	'use strict';
	var app = angular.module('myApp', [ 'toaster', 'angularCharts', 'ngTable', '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 : "",
			views : {
				"left-view" : {
					templateUrl : "static/tpl/index/home/left.html"
				},
				"right-view" : {
					templateUrl : "static/tpl/index/home/right.html"
				}
			}
		}).state('home', {
			url : "/",
			views : {
				"left-view" : {
					templateUrl : "static/tpl/index/home/left.html"
				},
				"right-view" : {
					templateUrl : "static/tpl/index/home/right.html"
				}
			}
		}).state('sale', {
			url : "/sale",
			views : {
				"left-view" : {
					templateUrl : "static/tpl/index/sale/left.html"
				},
				"right-view" : {
					templateUrl : "static/tpl/index/sale/right.html"
				}
			},
			controller: function($rootScope) {
				$rootScope.active = null;
			}
		}).state('sale.index', {
			url : "",
			templateUrl : "static/tpl/index/sale/index.html",
			controller: function($rootScope) {
				$rootScope.active = null;
			}
		}).state('sale.home', {
			url : "/",
			templateUrl : "static/tpl/index/sale/index.html",
			controller: function($rootScope) {
				$rootScope.active = null;
			}
		}).state('sale.todo', {
			url : "/todo",
			templateUrl : "static/tpl/index/sale/todo.html",
			controller: function($rootScope) {
				$rootScope.active = null;
			}
		}).state('sale.todo.inquiry', {
			url : "/inquiry",
			templateUrl : "static/tpl/index/sale/inquiry.html",
			controller: 'SaleInquiryCtrl'
		}).state('sale.todo.order', {
			url : "/order",
			templateUrl : "static/tpl/index/sale/order.html",
			controller: 'SaleOrderCtrl'
		}).state('sale.todo.change', {
			url : "/change",
			templateUrl : "static/tpl/index/sale/change.html",
			controller: 'SaleChangeCtrl'
		}).state('sale.todo.notice', {
			url : "/notice",
			templateUrl : "static/tpl/index/sale/notice.html",
			controller: 'SaleNoticeCtrl'
		}).state('sale.inquiry', {
			url : "/inquiry",
			templateUrl : "static/tpl/index/sale/inquiry.html",
			controller: 'SaleInquiryCtrl'
		}).state('sale.quotation', {
			url : "/quotation",
			templateUrl : "static/tpl/index/sale/quotation.html",
			controller: 'SaleInquiryCtrl'
		}).state('sale.order', {
			url : "/order",
			templateUrl : "static/tpl/index/sale/order.html",
			controller: 'SaleOrderCtrl'
		}).state('sale.change', {
			url : "/change",
			templateUrl : "static/tpl/index/sale/change.html",
			controller: 'SaleChangeCtrl'
		}).state('sale.notice', {
			url : "/notice",
			templateUrl : "static/tpl/index/sale/notice.html",
			controller: 'SaleNoticeCtrl'
		}).state('sale.send', {
			url : "/send",
			templateUrl : "static/tpl/index/sale/send.html",
			controller: 'SaleSendCtrl'
		}).state('sale.forecast', {
			url : "/forecast",
			templateUrl : "static/tpl/index/sale/forecast.html",
			controller: 'SaleForecastCtrl'
		}).state('sale.accept', {
			url : "/accept",
			templateUrl : "static/tpl/index/sale/accept.html",
			controller: 'SaleAcceptCtrl'
		}).state('sale.returns', {
			url : "/returns",
			templateUrl : "static/tpl/index/sale/returns.html",
			controller: 'SaleReturnsCtrl'
		}).state('user', {
			url : "/user",
			views : {
				"left-view" : {
					templateUrl : "static/tpl/index/user/left.html"
				},
				"right-view" : {
					templateUrl : "static/tpl/index/user/right.html"
				}
			}
		}).state('qc', {
			url : "/qc",
			views : {
				"left-view" : {
					templateUrl : "static/tpl/index/qc/left.html"
				},
				"right-view" : {
					templateUrl : "static/tpl/index/qc/right.html"
				}
			}
		}).state('qc.badIn', {
			url : "/badIn",
			templateUrl : "static/tpl/index/qc/badIn.html",
			controller: 'SaleBadInCtrl'
		}).state('qc.badOut', {
			url : "/badOut",
			templateUrl : "static/tpl/index/qc/badOut.html",
			controller: 'SaleBadOutCtrl'
		}).state('qc.MRB', {
			url : "/MRB",
			templateUrl : "static/tpl/index/qc/MRB.html",
			controller: 'SaleMRBCtrl'
		}).state('fa', {
			url : "/fa",
			views : {
				"left-view" : {
					templateUrl : "static/tpl/index/fa/left.html"
				},
				"right-view" : {
					templateUrl : "static/tpl/index/fa/right.html"
				}
			}
		}).state('fa.apBill', {
			url : "/apBill",
			templateUrl : "static/tpl/index/fa/apBill.html",
			controller: 'SaleApBillCtrl'
		});
	});
	
	/**
	 * 表示符号
	 */
	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('TodoCtrl', function($scope, SnapshotService){
		SnapshotService.getTodo(function(data){
			$scope.todo = data;
		});
	});
	app.controller('DataCtrl', function($scope) {
		$scope.charts = {
			product : {
				chartType : 'pie',
				datas : {
					data : [ {
						x : "JDI 5寸液晶玻璃",
						y : [ 100000 ],
						tooltip : "JDI 5寸液晶玻璃: ￥100000"
					}, {
						x : "液晶显示屏",
						y : [ 60000 ],
						tooltip : "液晶显示屏: ￥60000"
					}, {
						x : "触摸屏",
						y : [ 48000 ],
						tooltip : "触摸屏: ￥48000"
					}, {
						x : "松下连接器",
						y : [ 36000 ],
						tooltip : "松下连接器: ￥36000"
					}, {
						x : "罗姆IC",
						y : [ 18000 ],
						tooltip : "罗姆IC: ￥18000"
					} ]
				},
				config : {
					labels : false,
					title : "产品月销量排行榜",
					legend : {
						display : true,
						position : 'right'
					},
					colors : [ '#4D9934', '#33D6EA', '#98E1CC', '#8060E4', '#9999CC' ],
					click : function(d) {

					},
					mouseover : function(d) {

					},
					mouseout : function(d) {

					},
					innerRadius : 0,
					lineLegend : 'lineEnd'
				}
			},
			sale : {
				chartType : 'pie',
				datas : {
					data : [ {
						x : "通达电子",
						y : [ 1800000 ],
						tooltip : "通达电子: ￥1800000"
					}, {
						x : "天派科技",
						y : [ 1600000 ],
						tooltip : "天派科技: ￥1600000"
					}, {
						x : "凯瑞德",
						y : [ 900000 ],
						tooltip : "凯瑞德: ￥900000"
					}, {
						x : "松下电器",
						y : [ 360000 ],
						tooltip : "松下电器: ￥360000"
					}, {
						x : "易商电子",
						y : [ 180000 ],
						tooltip : "易商电子: ￥180000"
					} ]
				},
				config : {
					labels : false,
					title : "客户月采购量排行榜",
					legend : {
						display : true,
						position : 'right'
					},
					colors : [ '#4D9934', '#33D6EA', '#98E1CC', '#8060E4', '#9999CC' ],
					click : function(d) {

					},
					mouseover : function(d) {

					},
					mouseout : function(d) {

					},
					innerRadius : 0,
					lineLegend : 'lineEnd'
				}
			},
			seller : {
				chartType : 'pie',
				datas : {
					data : [ {
						x : "刘青松",
						y : [ 5000000 ],
						tooltip : "刘青松: ￥5000000"
					}, {
						x : "凌海洋",
						y : [ 2000000 ],
						tooltip : "凌海洋: ￥2000000"
					}, {
						x : "聂洋",
						y : [ 980000 ],
						tooltip : "聂洋: ￥980000"
					}, {
						x : "李小敏",
						y : [ 900000 ],
						tooltip : "李小敏: ￥900000"
					}, {
						x : "张韶刚",
						y : [ 800000 ],
						tooltip : "张韶刚: ￥800000"
					} ]
				},
				config : {
					labels : false,
					title : "业务员月销量排行榜",
					legend : {
						display : true,
						position : 'right'
					},
					colors : [ '#4D9934', '#33D6EA', '#98E1CC', '#8060E4', '#9999CC' ],
					click : function(d) {

					},
					mouseover : function(d) {

					},
					mouseout : function(d) {

					},
					innerRadius : 0,
					lineLegend : 'lineEnd'
				}
			}
		};
	});
	app.controller('NoticeCtrl', function($scope, SnapshotService){
		SnapshotService.getNotice(5, function(data){
			$scope.notices = data;
		});
	});
	var getState = function(active) {
		var fn = 'get';
		switch(active) {
		case 'done':
			fn = 'getDone';break;
		case 'todo':
			fn = 'getTodo';break;
		case 'end':	
			fn = 'getEnd';break;
		}
		return fn;
	};
	app.controller('SaleOrderCtrl', function($scope, $rootScope, $filter, PurcOrderItem, ngTableParams, 
		toaster, ReportService, BaseService, PurcOrderItemHis){
		$rootScope.active = 'order';
		$scope.active = 'todo';
		$scope.dateZoneText = '一个月内';
		$scope.condition = {dateZone: 1};
		$scope.changeDateZone = function(zone) {
			$scope.condition.dateZone = zone;
			$scope.dateZoneText = typeof zone == 'undefined' ? '半年前' : (zone == 1 ? '一个月内' : '半年内');
			$scope.condition.$dateZoneOpen = false;
		};
		$scope.setActive = function(state) {
			if($scope.active != state) {
				$scope.active = state;
				if($scope.tableParams.page() == 1)
					$scope.tableParams.reload();
				else
					$scope.tableParams.page(1);
			}
		};
		var getService = function() {
			return $scope.condition.dateZone ? PurcOrderItem : PurcOrderItemHis;
		};
		$scope.tableParams = new ngTableParams({
			page : 1,
			count : 5,
			sorting: {
                date: 'desc'
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				getService()[getState($scope.active)].call(null, BaseService.parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				}, function(response){
					$scope.loading = false;
					toaster.pop('error', '加载失败', response.data);
				});
			}
		});
		
		$scope.getOrderTotal = function(items) {
			var sum = 0;
			angular.forEach(items, function(item){
				sum += item.qty * item.price;
			});
			return sum;
		};
		
		$scope.openDatePicker = function($event, item, openParam) {
			$event.preventDefault();
		    $event.stopPropagation();
		    item[openParam] = !item[openParam];
		};
		
		$scope.parseDate = function(dateStr) {
			if(dateStr)
				return Date.parse(dateStr, 'yyyy-MM-dd');
			return new Date();
		};
		
		$scope.onReplyClick = function(item) {
			if(item.reply) {
				if(!item.reply.qty) {
					toaster.pop('warning', '提示', '请填写回复数量！');
					return;
				}
				var reply = angular.copy(item.reply);
				if(reply.delivery) {
					if(typeof reply.delivery == 'object')
						reply.delivery = reply.delivery.getTime();
				} else
					reply.delivery = item.delivery;
				$scope.loading = true;
				PurcOrderItem.reply({orderItemId: item.id}, reply, function(){
					$scope.loading = false;
					toaster.pop('info', '提示', '回复成功');
					$scope.tableParams.reload();
				}, function(response){
					$scope.loading = false;
					toaster.pop('error', '回复失败', response.data);
				});
			}
		};
		
		$scope.print = function(order) {
			ReportService.print(order.vendUU, 'purchase', '{purc_orders.pu_id}=' + order.id, '销售订单-' + order.code);
		};
		
		$scope.getReply = function(item) {
			if(!item.replies) {
				PurcOrderItem.getReply({orderItemId: item.id}, function(replies){
					item.replies = replies;
				}, function(response){
					toaster.pop('error', '无法查看回复记录', response.data);
				});
			}
		};
	});
	app.controller('SaleChangeCtrl', function($scope, $rootScope, $filter, PurcChange, ngTableParams, toaster, BaseService, PurcChangeHis){
		$rootScope.active = 'change';
		$scope.active = 'todo';
		$scope.agreedText = '全部';
		$scope.dateZoneText = '一个月内';
		$scope.condition = {dateZone: 1};
		$scope.changeAgreed = function(agreed) {
			$scope.condition.agreed = agreed;
			$scope.agreedText = typeof agreed == 'undefined' ? '全部' : (agreed == 1 ? '已同意' : '不同意');
			$scope.condition.$agreedOpen = false;
		};
		$scope.changeDateZone = function(zone) {
			$scope.condition.dateZone = zone;
			$scope.dateZoneText = typeof zone == 'undefined' ? '半年前' : (zone == 1 ? '一个月内' : '半年内');
			$scope.condition.$dateZoneOpen = false;
		};
		$scope.setActive = function(state) {
			if($scope.active != state) {
				$scope.active = state;
				if($scope.tableParams.page() == 1)
					$scope.tableParams.reload();
				else
					$scope.tableParams.page(1);
			}
		};
		var getService = function() {
			return $scope.condition.dateZone ? PurcChange : PurcChangeHis;
		};
		$scope.tableParams = new ngTableParams({
			page : 1, 
			count : 5,
			sorting: {
                date: 'desc' 
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				getService()[getState($scope.active)].call(null, BaseService.parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				}, function(response){
					$scope.loading = false;
					toaster.pop('error', '加载失败', response.data);
				});
			}
		});
		
		$scope.openDatePicker = function($event, item, openParam) {
			$event.preventDefault();
		    $event.stopPropagation();
		    item[openParam] = !item[openParam];
		};
		
		$scope.onReplyClick = function(change) {
			if(change.agreed) {
				var reply = {id: change.id, agreed: Number(change.$agreed), replyRemark: change.replyRemark};
				$scope.loading = true;
				PurcChange.reply({changeId: change.id}, reply, function(){
					$scope.loading = false;
					toaster.pop('info', '提示', '回复成功');
					$scope.tableParams.reload();
				}, function(response){
					$scope.loading = false;
					toaster.pop('error', '回复失败', response.data);
				});
			}
		};
	});
	app.controller('SaleInquiryCtrl', function($scope, $rootScope, $filter, PurcInquiry, ngTableParams, toaster, BaseService, PurcInquiryHis){
		$rootScope.active = 'inquiry';
		$scope.active = 'todo';
		$scope.agreedText = '全部';
		$scope.dateZoneText = '一个月内';
		$scope.condition = {dateZone: 1};
		$scope.changeAgreed = function(agreed) {
			$scope.condition.agreed = agreed;
			$scope.agreedText = typeof agreed == 'undefined' ? '全部' : (agreed == 1 ? '已采纳' : '未采纳');
			$scope.condition.$agreedOpen = false;
		};
		$scope.changeDateZone = function(zone) {
			$scope.condition.dateZone = zone;
			$scope.dateZoneText = typeof zone == 'undefined' ? '半年前' : (zone == 1 ? '一个月内' : '半年内');
			$scope.condition.$dateZoneOpen = false;
		};
		$scope.setActive = function(state) {
			if($scope.active != state) {
				$scope.active = state;
				if($scope.tableParams.page() == 1)
					$scope.tableParams.reload();
				else
					$scope.tableParams.page(1);
			}
		};
		var getService = function() {
			return $scope.condition.dateZone ? PurcInquiry : PurcInquiryHis;
		};
		$scope.tableParams = new ngTableParams({
			page : 1, 
			count : 5,
			sorting: {
                'inquiry.date': 'desc',
                'inquiry.enterprise.enName': 'asc',
                'inquiry.code': 'asc'
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				getService()[getState($scope.active)].call(null, BaseService.parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				}, function(response){
					$scope.loading = false;
					toaster.pop('error', '加载失败', response.data);
				});
			}
		});
		
		$scope.getMinDate = function(item) {
			return $filter('date')(item.inquiry.date, 'yyyy-MM-dd');
		};
		
		$scope.addStep = function(inquiryItem) {
			if(inquiryItem.replies.length >= 10) {
				toaster.pop('warning', '提示', '最多支持10个分段！');
			} else
				inquiryItem.replies.push({});
		};
		
		$scope.removeStep = function(inquiryItem, stepIndex) {
			inquiryItem.replies.splice(stepIndex, 1);
		};
		
		$scope.openDatePicker = function($event, item, openParam) {
			$event.preventDefault();
		    $event.stopPropagation();
		    item[openParam] = !item[openParam];
		};
		
		$scope.getHistory = function(item) {
			if(!item.history) {
				PurcInquiry.getHistory({itemId: item.id}, function(data){
					item.history = data;
				});
			}
		};
		
		$scope.isValid = function(item, withSteps) {
			var bool = item.replies && item.replies[0].price > 0;
			if(!withSteps || !bool)
				return bool;
			angular.forEach(item.replies, function(r, i){
				bool = (i > 0 ? r.lapQty : 1) && r.price;
			});
			return bool;
		};
		
		$scope.onReplyClick = function(item, withSteps) {
			if(item.vendFromDate instanceof Date) {
  				item.vendFromDate = item.vendFromDate.getTime();
  			}
  			if(item.vendToDate instanceof Date) {
  				item.vendToDate = item.vendToDate.getTime();
  			}
  			if(item.vendFromDate > item.vendToDate) {
  				toaster.pop('warning', '警告', '有效开始日期不能超过有效截止日期');
  				return;
  			}
			var replies = [];
			angular.forEach(item.replies, function(r, i){
				if((i > 0 ? r.lapQty : 1) || r.price)
					replies.push(r);
			});
			item.replies = replies;
			$scope.loading = true;
			if(withSteps) {
				PurcInquiry.reply({itemId: item.id}, item, function(){
					$scope.loading = false;
					toaster.pop('info', '提示', '报价成功');
					$scope.tableParams.reload();
				}, function(response){
					$scope.loading = false;
					toaster.pop('error', '报价失败', response.data);
				});
			} else {
				PurcInquiry.saveItem({itemId: item.id}, item, function(){
					$scope.loading = false;
					toaster.pop('info', '提示', '保存成功');
					$scope.tableParams.reload();
				}, function(response){
					$scope.loading = false;
					toaster.pop('error', '保存失败', response.data);
				});
			}
		};
	});
	app.controller('SaleNoticeCtrl', function($scope, $rootScope, $filter, PurcNotice, ngTableParams, toaster, BaseService, PurcNoticeHis){
		$rootScope.active = 'notice';
		$scope.active = 'todo';
		$scope.dateZoneText = '一个月内';
		$scope.condition = {dateZone: 1};
		$scope.changeDateZone = function(zone) {
			$scope.condition.dateZone = zone;
			$scope.dateZoneText = typeof zone == 'undefined' ? '半年前' : (zone == 1 ? '一个月内' : '半年内');
			$scope.condition.$dateZoneOpen = false;
		};
		$scope.setActive = function(state) {
			if($scope.active != state) {
				$scope.active = state;
				if($scope.tableParams.page() == 1)
					$scope.tableParams.reload();
				else
					$scope.tableParams.page(1);
			}
		};
		var getService = function() {
			return $scope.condition.dateZone ? PurcNotice : PurcNoticeHis;
		};
		$scope.tableParams = new ngTableParams({
			page : 1, 
			count : 5,
			sorting: {
                'date': 'desc'
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				getService()[getState($scope.active)].call(null, BaseService.parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				}, function(response){
					$scope.loading = false;
					toaster.pop('error', '加载失败', response.data);
				});
			}
		});
		
		$scope.openDatePicker = function($event, item, openParam) {
			$event.preventDefault();
		    $event.stopPropagation();
		    item[openParam] = !item[openParam];
		};
		
		$scope.onReplyClick = function(notice) {
			if(!notice.send || !notice.send.qty || notice.send.qty > notice.qty - (notice.endQty || 0)) {
				toaster.pop('warning', '警告', '数量填写错误！');
			} else if(!notice.send.code) {
				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;
					toaster.pop('info', '提示', '发货成功');
					$scope.tableParams.reload();
				}, function(response){
					$scope.loading = false;
					toaster.pop('error', '失败', response);
				});
			}
		};
	});
	/**
	 * 发货单
	 */
	app.controller('SaleSendCtrl', function($scope, $rootScope, $filter, PurcChange, ngTableParams, toaster, BaseService, PurcChangeHis){
		$rootScope.active = 'change';
		$scope.active = 'todo';
		$scope.agreedText = '全部';
		$scope.dateZoneText = '一个月内';
		$scope.condition = {dateZone: 1};
		$scope.changeAgreed = function(agreed) {
			$scope.condition.agreed = agreed;
			$scope.agreedText = typeof agreed == 'undefined' ? '全部' : (agreed == 1 ? '已同意' : '不同意');
			$scope.condition.$agreedOpen = false;
		};
		$scope.changeDateZone = function(zone) {
			$scope.condition.dateZone = zone;
			$scope.dateZoneText = typeof zone == 'undefined' ? '半年前' : (zone == 1 ? '一个月内' : '半年内');
			$scope.condition.$dateZoneOpen = false;
		};
		$scope.setActive = function(state) {
			if($scope.active != state) {
				$scope.active = state;
				if($scope.tableParams.page() == 1)
					$scope.tableParams.reload();
				else
					$scope.tableParams.page(1);
			}
		};
		var getService = function() {
			return $scope.condition.dateZone ? PurcChange : PurcChangeHis;
		};
		$scope.tableParams = new ngTableParams({
			page : 1, 
			count : 5,
			sorting: {
                date: 'desc' 
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				getService()[getState($scope.active)].call(null, BaseService.parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				});
			}
		});
		
		$scope.openDatePicker = function($event, item, openParam) {
			$event.preventDefault();
		    $event.stopPropagation();
		    item[openParam] = !item[openParam];
		};
		
		$scope.onReplyClick = function(change) {
			if(change.agreed) {
				var reply = {id: change.id, agreed: Number(change.$agreed), replyRemark: change.replyRemark};
				$scope.loading = true;
				PurcChange.reply({changeId: change.id}, reply, function(){
					$scope.loading = false;
					toaster.pop('info', '提示', '回复成功');
					$scope.tableParams.reload();
				}, function(response){
					$scope.loading = false;
					toaster.pop('error', '回复失败', response.data);
				});
			}
		};
	});
	
	/**
	 * 客户采购预测
	 */
	app.controller('SaleForecastCtrl', function($scope, $rootScope, $filter, PurcForecast, ngTableParams, toaster, BaseService, Symbol){
		$rootScope.active = 'forecast';
		$scope.active = 'all';
		$scope.agreedText = '全部';
		$scope.dateZoneText = '一个月内';
		$scope.condition = {dateZone: 1};
		$scope.currency = Symbol.currency;//将币别转化为对应的符号
		$scope.changeAgreed = function(agreed) {
			$scope.condition.agreed = agreed;
			$scope.agreedText = typeof agreed == 'undefined' ? '全部' : (agreed == 1 ? '已同意' : '不同意');
			$scope.condition.$agreedOpen = false;
		};
		$scope.changeDateZone = function(zone) {
			$scope.condition.dateZone = zone;
			$scope.dateZoneText = typeof zone == 'undefined' ? '半年前' : (zone == 1 ? '一个月内' : '半年内');
			$scope.condition.$dateZoneOpen = false;
		};
		$scope.setActive = function(state) {
			if($scope.active != state) {
				$scope.active = state;
				if($scope.tableParams.page() == 1)
					$scope.tableParams.reload();
				else
					$scope.tableParams.page(1);
			}
		};
		var getService = function() {
			return PurcForecast;
		};
		
		$scope.tableParams = new ngTableParams({
			page : 1, 
			count : 5,
			sorting: {
				orderDate: 'desc'
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				getService()[getState($scope.active)].call(null, BaseService.parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				});
			}
		});
		
		$scope.openDatePicker = function($event, item, openParam) {
			$event.preventDefault();
		    $event.stopPropagation();
		    item[openParam] = !item[openParam];
		};
		
	});
	
	/**
	 * 客户采购验收
	 */
	app.controller('SaleAcceptCtrl', function($scope, $rootScope, $filter, PurcAccept, ngTableParams, toaster, BaseService, Symbol){
		$rootScope.active = 'accept';
		$scope.active = 'all';
		$scope.agreedText = '全部';
		$scope.dateZoneText = '一个月内';
		$scope.condition = {dateZone: 1};
		$scope.currency = Symbol.currency;//将币别转化为对应的符号
		$scope.changeAgreed = function(agreed) {
			$scope.condition.agreed = agreed;
			$scope.agreedText = typeof agreed == 'undefined' ? '全部' : (agreed == 1 ? '已同意' : '不同意');
			$scope.condition.$agreedOpen = false;
		};
		$scope.changeDateZone = function(zone) {
			$scope.condition.dateZone = zone;
			$scope.dateZoneText = typeof zone == 'undefined' ? '半年前' : (zone == 1 ? '一个月内' : '半年内');
			$scope.condition.$dateZoneOpen = false;
		};
		$scope.setActive = function(state) {
			if($scope.active != state) {
				$scope.active = state;
				if($scope.tableParams.page() == 1)
					$scope.tableParams.reload();
				else
					$scope.tableParams.page(1);
			}
		};
		var getService = function() {
			return PurcAccept;
		};
		
		$scope.tableParams = new ngTableParams({
			page : 1, 
			count : 5,
			sorting: {
                date: 'desc' 
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				getService()[getState($scope.active)].call(null, BaseService.parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				});
			}
		});
		
		$scope.openDatePicker = function($event, item, openParam) {
			$event.preventDefault();
		    $event.stopPropagation();
		    item[openParam] = !item[openParam];
		};
		
	});
	
	/**
	 * 客户采购验退
	 */
	app.controller('SaleReturnsCtrl', function($scope, $rootScope, $filter, PurcReturn, ngTableParams, toaster, BaseService, Symbol){
		$rootScope.active = 'returns';
		$scope.active = 'all';
		$scope.agreedText = '全部';
		$scope.dateZoneText = '一个月内';
		$scope.condition = {dateZone: 1};
		$scope.currency = Symbol.currency;//将币别转化为对应的符号
		$scope.changeAgreed = function(agreed) {
			$scope.condition.agreed = agreed;
			$scope.agreedText = typeof agreed == 'undefined' ? '全部' : (agreed == 1 ? '已同意' : '不同意');
			$scope.condition.$agreedOpen = false;
		};
		$scope.changeDateZone = function(zone) {
			$scope.condition.dateZone = zone;
			$scope.dateZoneText = typeof zone == 'undefined' ? '半年前' : (zone == 1 ? '一个月内' : '半年内');
			$scope.condition.$dateZoneOpen = false;
		};
		$scope.setActive = function(state) {
			if($scope.active != state) {
				$scope.active = state;
				if($scope.tableParams.page() == 1)
					$scope.tableParams.reload();
				else
					$scope.tableParams.page(1);
			}
		};
		var getService = function() {
			return PurcReturn;
		};
		$scope.tableParams = new ngTableParams({
			page : 1, 
			count : 5,
			sorting: {
                date: 'desc' 
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				getService()[getState($scope.active)].call(null, BaseService.parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				});
			}
		});
		
		$scope.openDatePicker = function($event, item, openParam) {
			$event.preventDefault();
		    $event.stopPropagation();
		    item[openParam] = !item[openParam];
		};
		
	});
	
	/**
	 * 客户不良品入库
	 */
	app.controller('SaleBadInCtrl', function($scope, $rootScope, $filter, PurcBadIn, ngTableParams, toaster, BaseService, Symbol){
		$rootScope.active = 'badIn';
		$scope.active = 'all';
		$scope.agreedText = '全部';
		$scope.dateZoneText = '一个月内';
		$scope.condition = {dateZone: 1};
		$scope.currency = Symbol.currency;//将币别转化为对应的符号
		$scope.changeAgreed = function(agreed) {
			$scope.condition.agreed = agreed;
			$scope.agreedText = typeof agreed == 'undefined' ? '全部' : (agreed == 1 ? '已同意' : '不同意');
			$scope.condition.$agreedOpen = false;
		};
		$scope.changeDateZone = function(zone) {
			$scope.condition.dateZone = zone;
			$scope.dateZoneText = typeof zone == 'undefined' ? '半年前' : (zone == 1 ? '一个月内' : '半年内');
			$scope.condition.$dateZoneOpen = false;
		};
		$scope.setActive = function(state) {
			if($scope.active != state) {
				$scope.active = state;
				if($scope.tableParams.page() == 1)
					$scope.tableParams.reload();
				else
					$scope.tableParams.page(1);
			}
		};
		var getService = function() {
			return PurcBadIn;
		};
		$scope.tableParams = new ngTableParams({
			page : 1, 
			count : 5,
			sorting: {
                date: 'desc' 
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				getService()[getState($scope.active)].call(null, BaseService.parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				});
			}
		});
		
		$scope.openDatePicker = function($event, item, openParam) {
			$event.preventDefault();
		    $event.stopPropagation();
		    item[openParam] = !item[openParam];
		};
		
	});
	
	/**
	 * 客户不良品出库
	 */
	app.controller('SaleBadOutCtrl', function($scope, $rootScope, $filter, PurcBadOut, ngTableParams, toaster, BaseService, Symbol){
		$rootScope.active = 'badOut';
		$scope.active = 'all';
		$scope.agreedText = '全部';
		$scope.dateZoneText = '一个月内';
		$scope.condition = {dateZone: 1};
		$scope.currency = Symbol.currency;//将币别转化为对应的符号
		$scope.changeAgreed = function(agreed) {
			$scope.condition.agreed = agreed;
			$scope.agreedText = typeof agreed == 'undefined' ? '全部' : (agreed == 1 ? '已同意' : '不同意');
			$scope.condition.$agreedOpen = false;
		};
		$scope.changeDateZone = function(zone) {
			$scope.condition.dateZone = zone;
			$scope.dateZoneText = typeof zone == 'undefined' ? '半年前' : (zone == 1 ? '一个月内' : '半年内');
			$scope.condition.$dateZoneOpen = false;
		};
		$scope.setActive = function(state) {
			if($scope.active != state) {
				$scope.active = state;
				if($scope.tableParams.page() == 1)
					$scope.tableParams.reload();
				else
					$scope.tableParams.page(1);
			}
		};
		var getService = function() {
			return PurcBadOut;
		};
		$scope.tableParams = new ngTableParams({
			page : 1, 
			count : 5,
			sorting: {
                date: 'desc' 
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				getService()[getState($scope.active)].call(null, BaseService.parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				});
			}
		});
		
		$scope.openDatePicker = function($event, item, openParam) {
			$event.preventDefault();
		    $event.stopPropagation();
		    item[openParam] = !item[openParam];
		};
		
	});
	
	/**
	 * 客户MRB
	 */
	app.controller('SaleMRBCtrl', function($scope, $rootScope, $filter, PurcMRB, ngTableParams, toaster, BaseService, Symbol){
		$rootScope.active = 'MRB';
		$scope.active = 'all';
		$scope.agreedText = '全部';
		$scope.dateZoneText = '一个月内';
		$scope.condition = {dateZone: 1};
		$scope.currency = Symbol.currency;//将币别转化为对应的符号
		$scope.changeAgreed = function(agreed) {
			$scope.condition.agreed = agreed;
			$scope.agreedText = typeof agreed == 'undefined' ? '全部' : (agreed == 1 ? '已同意' : '不同意');
			$scope.condition.$agreedOpen = false;
		};
		$scope.changeDateZone = function(zone) {
			$scope.condition.dateZone = zone;
			$scope.dateZoneText = typeof zone == 'undefined' ? '半年前' : (zone == 1 ? '一个月内' : '半年内');
			$scope.condition.$dateZoneOpen = false;
		};
		$scope.setActive = function(state) {
			if($scope.active != state) {
				$scope.active = state;
				if($scope.tableParams.page() == 1)
					$scope.tableParams.reload();
				else
					$scope.tableParams.page(1);
			}
		};
		var getService = function() {
			return PurcMRB;
		};
		$scope.tableParams = new ngTableParams({
			page : 1, 
			count : 5,
			sorting: {
                date: 'desc' 
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				getService()[getState($scope.active)].call(null, BaseService.parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				});
			}
		});
		
		$scope.openDatePicker = function($event, item, openParam) {
			$event.preventDefault();
		    $event.stopPropagation();
		    item[openParam] = !item[openParam];
		};
		
	});
	
	/**
	 * 客户应付发票
	 */
	app.controller('SaleApBillCtrl', function($scope, $rootScope, $filter, PurcApBill, ngTableParams, toaster, BaseService, Symbol){
		$rootScope.active = 'apBill';
		$scope.active = 'all';
		$scope.agreedText = '全部';
		$scope.dateZoneText = '一个月内';
		$scope.condition = {dateZone: 1};
		$scope.currency = Symbol.currency;//将币别转化为对应的符号
		$scope.changeAgreed = function(agreed) {
			$scope.condition.agreed = agreed;
			$scope.agreedText = typeof agreed == 'undefined' ? '全部' : (agreed == 1 ? '已同意' : '不同意');
			$scope.condition.$agreedOpen = false;
		};
		$scope.changeDateZone = function(zone) {
			$scope.condition.dateZone = zone;
			$scope.dateZoneText = typeof zone == 'undefined' ? '半年前' : (zone == 1 ? '一个月内' : '半年内');
			$scope.condition.$dateZoneOpen = false;
		};
		$scope.setActive = function(state) {
			if($scope.active != state) {
				$scope.active = state;
				if($scope.tableParams.page() == 1)
					$scope.tableParams.reload();
				else
					$scope.tableParams.page(1);
			}
		};
		var getService = function() {
			return PurcApBill;
		};
		
		$scope.tableParams = new ngTableParams({
			page : 1, 
			count : 5,
			sorting: {
                date: 'desc' 
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				getService()[getState($scope.active)].call(null, BaseService.parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				});
			}
		});
		
		$scope.openDatePicker = function($event, item, openParam) {
			$event.preventDefault();
		    $event.stopPropagation();
		    item[openParam] = !item[openParam];
		};
		
	});
	
	/**
	 * 计算时间差
	 */
	app.filter('timespan', function(){
		return function(time) {
			if(time == null)
				return '9999年';
			var now = new Date().getTime(), span = time - now, 
				d = Math.ceil(span/86400000), h = Math.ceil(span/3600000), 
				m = Math.ceil(span/60000);
			if(span < 0)
				return '0天';
			if(d > 0)
				return d + '天';
			if(h > 0)
				return h + '小时';
			if(m > 0)
				return m + '分钟';
			return '0天';
		};
	});
	return app;
});