(function()
{
	//-------------------------------------------------
	//#region 获取模板路径，并加到helper中
	var __p = $('script:last').attr('src');
	__p = __p.substr(0, __p.lastIndexOf('/js/module.js') + 1);
	_helper.addInit(__p, init);
	//#endregion 获取模板路径，并加到helper中
	//-------------------------------------------------
	
	//-------------------------------------------------
	//#region 辅助函数
	//词典中，获取关键字对应的值
	function w(k){return _helper.dict(__p, k);}
	//获取对象名称
	function o(f){return f.toString().match(/^function (\w+)\(/)[1];}
	//获取页面变量值
	function v(p, n){return $('>section', p).data(n);}
	//#endregion 辅助函数
	//-------------------------------------------------

	//-------------------------------------------------
	//#region 初始化
	function init(instance, page, panel)
	{
		if (page == 'stock_out_list')
		{
		}
	}
	//#endregion 初始化
	//-------------------------------------------------

	//-------------------------------------------------
	//#region 出库单
	function StockOut(instance, panel)
	{
		var __object = o(arguments.callee),
			__goods = [],
			__goodsIndex = 0;

		this.init = function()
		{
			//ToType
			$('[name=ToType]').val(v(panel, 'toType'));
				
			//商品
			$('.ali-grid-body:first tr', panel).each(function()
			{
				var tds = $('td', this);
				
				var goods = {};
				goods.element = $(this);
				goods.goodsName = tds.eq(0).text();
				goods.goodsNo = tds.eq(1).text();
				goods.goodsBarCode = tds.eq(2).text();
				goods.goodsSpec = tds.eq(3).text();
				goods.price = tds.eq(4).text();
				goods.amount = tds.eq(5).text();
				goods.memo = $(':text', tds[6]).val();
				goods.id = $(this).data('id');

				__goods.push(goods);
			});
		}

		this.add = function()
		{
			__goods = [];

			var data = prepareData(this);
			if (data == null)
				return false;
			
			data += '&WarehouseID=' + v(panel, 'warehouseId');			

			var guid = _helper.post({instance:instance,object:__object,operation:'Add',data:data,silent:true});
			if (guid)
			{
				var id = _helper.post({instance:instance,object:__object,operation:'GetInnerIDFromGuid',data:data,params:'ID=' + guid,silent:true});

				setGoods(guid);
			}

			return false;
		};
		
		this.modify = function()
		{
			var data = prepareData(this);
			if (data == null)
				return false;

			var id = v(panel, 'id');
			_helper.post({instance:instance,object:__object,operation:'Modify',data:data,params:'ID=' + id,silent:true});
			setGoods(v(panel, 'guid'));

			return false;
		};

		this.onSelectToClick = function()
		{
			var type = $('[name=ToType]', panel).val();
			if (type == 'Shop')
			{
				ali.dialog({name:'SelectShop',modal:true,appendTo:panel,width:400,height:200,resizable:false,url:_helper.toAbsPanel(panel, 'shop_select.aspx'),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			}
			else
			{
				alert('//TODO');
			}
			return false;
		};
		
		this.onShopClick = function()
		{
			$('[name=ToName]', panel).val($(this).data('name'));
			$('[name=ToID]', panel).val($(this).data('id'));
			$('[name=ToNo]', panel).val($(this).data('no'));
			$('[name=ReceiverAddress]', panel).val($(this).data('address'));
			$('[name=ReceiverPhone]', panel).val($(this).data('phone') + ' ' + $(this).data('mobile'));
			$('[name=ReceiverZip]', panel).val($(this).data('zip'));

			ali.dialog($(this).closest('.ali-dialog-body').children(), 'close');
			
			return false;
		};
		
		this.onSelectGoodsClick = function()
		{
			ali.dialog({name:'SelectGoods',modal:true,appendTo:panel,width:1000,height:500,resizable:false,url:_helper.toAbsPanel(panel, 'goods_select.aspx'),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onAddGoodsClick = function()
		{
			var row = $(this).closest('tr'),
				from = row.closest('.ali-grid').prev(),
				to = $('.grid1:first', panel),
				amount = $(':text', row);
			
			//获取当前行数据
			var newRow = ali.grid(from, 'getRow', row[0].rowIndex);

			//检查数量是否是数字
			if (!newRow.amount.match(/^\d+$/))
			{
				ali.error(w('amount_must_be_number'), $.proxy(function(){amount[0].select();}, this));
				return false;
			}
			
			//检查数量不能超过库存
			if (parseInt(newRow.amount) > parseInt(newRow.totalAmount))
			{
				ali.error(w('amount_exceed_stock'), $.proxy(function(){amount[0].select();}, this));
				return false;
			}
			
			//如果已经添加过，则退出
			var rows = $('tbody tr', to.next());
			for (var i = 0; i < rows.length; i++)
			{
				if (rows.eq(i).find('td:eq(1)').text() == newRow.goodsNo)
					return;
			}

			//调整数据
			newRow.memo = '<input type="text" size="10" class="ali-input">';
			newRow.operation = '<a class="ali-button">' + w('delete') + '</a>';
			
			//添加新行
			row = ali.grid(to, 'addRow', newRow);
			ali.button($('.ali-button', row));
			
			return false;
		};
		
		this.onDeleteGoodsClick = function()
		{
			ali.grid($(this).closest('.ali-grid').prev(), 'deleteRow', $(this).closest('tr')[0].rowIndex);

			return false;
		};

		this.onDeliverClick = function()
		{
			ali.dialog({name:'Deliver',modal:true,appendTo:panel,width:500,height:300,resizable:false,url:_helper.toAbsPanel(panel, 'deliver.aspx?StockOutID=' + $(this).closest('tr').data('id')),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onDeliverSubmit = function()
		{
			if (this.LogisticsID.value == '')
			{
				ali.error(w('logistics_empty'));
				return false;
			}
		
			if (this.WaybillNo.value == '')
			{
				ali.error(w('waybill_no_empty'));
				return false;
			}
		
			if (this.Waybill.value == '')
			{
				ali.error(w('waybill_empty'));
				return false;
			}
	
			if (!this.DeliverTime.value.match(/^(\d{1,4})(-|\/)(\d{1,2})(-|\/)(\d{1,2})( (\d{1,2}):(\d{1,2}):(\d{1,2}))?$/))
			{
				ali.error(w('deliver_time_incorrect'), function(){this.DeliverTime.select();}, this);
				return false;
			}

			var data = _helper.serialize(this);
			
			var form = this;
			var id = $(form).data('stockOutId');

			//上传发货凭据			
			var upload = $(this.Waybill);
			if (ali.uploader(upload.next(), 'needUpload'))
			{
				ali.uploader(upload.next(), 'upload', {status:w('uploading_waybill'),params:'Instance=' + instance + '&Lang=' + _lang + '&Object=StockOut&Operation=UploadWaybill&ID=' + id,onComplete:function()
				{
					if (arguments[0] != 0)
					{
						ali.error(arguments[1]);
					}
					else
					{
						upload.val(arguments[1]);
						data += '&Waybill=' + encodeURIComponent(arguments[1]);
			
						//提交数据
						_helper.post({instance:instance,object:'StockOut',operation:'Deliver',data:data,params:'ID=' + id});

						//关闭接单对话框
						ali.dialog($(form).closest('.ali-dialog-body').children(), 'close');
						
						//刷新列表
						$('.search1', panel).submit();
					}
				}});
			}
			else
			{
				//提交数据
				_helper.post({instance:instance,object:'StockOut',operation:'Deliver',data:data,params:'ID=' + id});

				//关闭接单对话框
				ali.dialog($(form).closest('.ali-dialog-body').children(), 'close');
				
				//刷新列表
				$('.search1', panel).submit();
			}

			return false;
		};
		
		this.onSelectLogisticsClick = function()
		{
			ali.dialog({name:'SelectLogistics',modal:true,appendTo:panel,width:400,height:200,resizable:false,url:_helper.toAbsPanel(panel, 'logistics_select.aspx'),onBeforeLoad:_helper.onDialogBeforeLoad,onShow:_helper.onDialogShow});
			return false;
		};
		
		this.onLogisticsClick = function()
		{
			$('[name=LogisticsName]', panel).val($(this).data('name'));
			$('[name=LogisticsID]', panel).val($(this).data('id'));

			ali.dialog($(this).closest('.ali-dialog-body').children(), 'close');

			return false;
		};
		
		function prepareData(form)
		{
			if ($.trim(form.No.value) == '')
			{
				ali.error(w('stock_out_no_empty'), $.proxy(function(){form.No.select();}, this));
				return null;
			}
		
			if (form.ToID.value == '')
			{
				ali.error(w('to_id_empty'));
				return null;
			}
		
			if ($.trim(form.ReceiverName.value) == '')
			{
				ali.error(w('receiver_name_empty'), $.proxy(function(){form.ReceiverName.select();}, this));
				return null;
			}
		
			if ($.trim(form.ReceiverAddress.value) == '')
			{
				ali.error(w('receiver_address_empty'), $.proxy(function(){form.ReceiverAddress.select();}, this));
				return null;
			}
		
			if ($.trim(form.ReceiverPhone.value) == '')
			{
				ali.error(w('receiver_phone_empty'), $.proxy(function(){form.ReceiverPhone.select();}, this));
				return null;
			}
		
			if ($.trim(form.ReceiverZip.value) == '')
			{
				ali.error(w('receiver_zip_empty'), $.proxy(function(){form.ReceiverZip.select();}, this));
				return null;
			}
			
			//#region 准备商品列表
			var goodsRows = $('.ali-grid-body:first tr', panel);
			if (goodsRows.length == 0)
			{
				ali.error(w('no_goods'));
				return null;
			}

			var goodsList = __goods;
			__goodsIndex = 0;
			__goods = [];
			
			goodsRows.each(function()
			{
				var tds = $('td', this);
				
				var goods = {};
				goods.element = $(this);
				goods.goodsName = tds.eq(0).text();
				goods.goodsNo = tds.eq(1).text();
				goods.goodsBarCode = tds.eq(2).text();
				goods.goodsSpec = tds.eq(3).text();
				goods.price = tds.eq(4).text();
				goods.amount = tds.eq(5).text();
				goods.memo = $(':text', tds[6]).val();

				goods.id = $(this).data('id');
				if (!goods.id)
				{
					goods.operation = 'Add';
				}
				else
				{
					var j = 0;
					for (; j < goodsList.length; j++)
					{
						if (goods.id == goodsList[j].id && (goods.memo != goodsList[j].memo))
							break;
					}
					
					if (j < goodsList.length)
						goods.operation = 'Modify';
				}
	
				__goods.push(goods);
			});
	
			for (var i = 0; i < goodsList.length; i++)
			{
				var j = 0;
				for (; j < goodsRows.length; j++)
				{
					if (goodsList[i].id == goodsRows.eq(j).data('id'))
						break;
				}
	
				if (j >= goodsRows.length)
				{
					goodsList[i].operation = 'Delete';
					__goods.push(goodsList[i]);
				}
			}
			//#endregion
		
			var data = _helper.serialize(form);
			
			return data;
		}
			
		function setGoods(guid)
		{
			if (__goodsIndex >= __goods.length)
			{
				for (var i = __goods.length - 1; i >= 0; i--)
				{
					if (__goods[i].operation == 'Delete')
						__goods.splice(i, 1);
				}
				
				ali.success(_lang_operation_success);
				ali.working();
				return;
			}
	
			var object = 'StockOut.Detail';
			var goods = __goods[__goodsIndex];
			if (goods.operation == 'Add')
			{
				var data = 'StockOutID=' + guid;
				data += '&GoodsName=' + encodeURIComponent(goods.goodsName);
				data += '&GoodsNo=' + encodeURIComponent(goods.goodsNo);
				data += '&GoodsBarCode=' + encodeURIComponent(goods.goodsBarCode);
				data += '&GoodsSpec=' + encodeURIComponent(goods.goodsSpec);
				data += '&Price=' + encodeURIComponent(goods.price);
				data += '&Amount=' + encodeURIComponent(goods.amount);
				data += '&Memo=' + encodeURIComponent(goods.memo);
				
				goods.id = _helper.post({instance:instance,object:object,operation:'Add',data:data,silent:true});
				if (typeof(_id) != 'undefined')
				{
					goods.id = _helper.post({instance:instance,object:object,operation:'GetInnerIDFromGuid',params:'ID=' + goods.id,silent:true});
					goods.element.data('id', goods.id);
				}
			}
			else if (goods.operation == 'Modify')
			{
				var data = 'Memo=' + encodeURIComponent(goods.memo);
				
				_helper.post({instance:instance,object:object,operation:'Modify',data:data,params:'ID=' + goods.id,silent:true});
			}
			else if (goods.operation == 'Delete')
			{
				_helper.post({instance:instance,object:object,operation:'Delete',params:'ID=' + goods.id,silent:true});
			}
		
			__goodsIndex++;
			setGoods(guid);
		}
	}
	//#endregion 出库单
	//-------------------------------------------------
})();
////@ sourceURL=AliShop.ShopModule.js