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"
				}
			}
		}).state('sale.index', {
			url : "",
			views : {
				"sale-view" : {
					templateUrl : "static/tpl/index/sale/index.html"
				}
			}
		}).state('sale.home', {
			url : "/",
			views : {
				"sale-view" : {
					templateUrl : "static/tpl/index/sale/index.html"
				}
			}
		}).state('sale.inquiry', {
			url : "/inquiry",
			views : {
				"sale-view" : {
					templateUrl : "static/tpl/index/sale/inquiry.html"
				}
			}
		}).state('sale.order', {
			url : "/order",
			views : {
				"sale-view" : {
					templateUrl : "static/tpl/index/sale/order.html"
				}
			}
		}).state('sale.order.reply', {
			url : "/reply",
			views : {
				"sale-view" : {
					templateUrl : "static/tpl/index/sale/order.html"
				}
			}
		}).state('sale.change', {
			url : "/change",
			views : {
				"sale-view" : {
					templateUrl : "static/tpl/index/sale/change.html"
				}
			}
		}).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('fa', {
			url : "/fa",
			views : {
				"left-view" : {
					templateUrl : "static/tpl/index/fa/left.html"
				},
				"right-view" : {
					templateUrl : "static/tpl/index/fa/right.html"
				}
			}
		});
	});
	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('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'
				}
			}
		};
	});
	var isNumber = function(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    };
	var parseParams = function(requestParams) {
        // parse url params
        for (var key in requestParams) {
            if (key.indexOf('[') >= 0) {
                var params = key.split(/\[(.*)\]/), value = requestParams[key], lastKey = '';
                angular.forEach(params.reverse(), function(name) {
                    if (name != '') {
                        var v = value;
                        value = {};
                        value[lastKey = name] = isNumber(v) ? parseFloat(v) : v;
                    }
                });
                requestParams[lastKey] = angular.extend(requestParams[lastKey] || {}, value[lastKey]);
                delete requestParams[key];
            } else {
                requestParams[key] = isNumber(requestParams[key]) ? parseFloat(requestParams[key]) : requestParams[key];
            }
        }
        return requestParams;
	};
	app.controller('SaleOrderCtrl', function($scope, $filter, PurcOrderItem, ngTableParams, 
		toaster, ReportService){
		$scope.tableParams = new ngTableParams({
			page : 1, // show first page
			count : 5, // count per page
			sorting: {
                date: 'desc' 
            },
            filter: {
            	'status' : 200
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				PurcOrderItem.get(parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				});
			}
		});
		
		$scope.getOrderTotal = function(items) {
			var sum = 0;
			angular.forEach(items, function(item){
				sum += item.qty * item.price;
			});
			return sum;
		};
		
		$scope.openDatePicker = function($event, item) {
			$event.preventDefault();
		    $event.stopPropagation();
		    item.$opened = !item.$opened;
		};
		
		$scope.parseDate = function(dateStr) {
			if(dateStr)
				return Date.parse(dateStr, 'yyyy-MM-dd');
			return new Date();
		};
		
		$scope.onReplyClick = function(item) {
			if(item.reply) {
				var reply = angular.copy(item.reply); 
				if(reply.delivery && typeof reply.delivery == 'object') {
					reply.delivery = reply.delivery.getTime();
				}
				PurcOrderItem.reply({orderItemId: item.id}, reply, function(){
					toaster.pop('info', '提示', '回复成功');
					$scope.tableParams.reload();
				}, function(response){
					toaster.pop('error', '回复失败', response.data);
				});
			}
		};
		
		$scope.print = function(order) {
			ReportService.print(order.vendUU, 'purchase', '{purc_orders.pu_id}=' + order.id, '销售订单-' + order.code);
		};
	});
	app.controller('SaleChangeCtrl', function($scope, $filter, PurcChange, ngTableParams, toaster){
		$scope.tableParams = new ngTableParams({
			page : 1, 
			count : 5,
			sorting: {
                date: 'desc' 
            },
            filter: {
            	'status' : 200
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				PurcChange.get(parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				});
			}
		});
		
		$scope.getOrderTotal = function(items) {
			var sum = 0;
			angular.forEach(items, function(item){
				sum += item.newQty * item.newPrice;
			});
			return sum;
		};
		
		$scope.onReplyClick = function(change) {
			if(change.agreed) {
				var reply = {id: change.id, agreed: Number(change.agreed), replyRemark: change.replyRemark};
				PurcChange.reply({changeId: change.id}, reply, function(){
					toaster.pop('info', '提示', '回复成功');
					$scope.tableParams.reload();
				}, function(response){
					toaster.pop('error', '回复失败', response.data);
				});
			}
		};
	});
	app.controller('SaleInquiryCtrl', function($scope, $filter, PurcInquiry, ngTableParams, toaster){
		$scope.tableParams = new ngTableParams({
			page : 1, 
			count : 5,
			sorting: {
                'inquiry.date': 'desc'
            },
            filter: {
            	'status' : 200
            }
		}, {
			total : 0, 
			counts: [5, 10, 25, 50],
			getData : function($defer, params) {
				$scope.loading = true;
				PurcInquiry.get(parseParams(params.url()), function(page){
					$scope.loading = false;
					if(page) {
						params.total(page.totalElements);
						$defer.resolve(page.content);
					}
				});
			}
		});
		
		$scope.onReplyClick = function() {
			
		};
	});
	return app;
});