if (!Ext.ModelManager.isRegistered('DropOrder')){
Ext.define('DropOrder', {
	extend : 'Ext.form.Panel',
	alias  : 'widget.DropOrder',
	
	initComponent : function() {
		var customsLoaded = function(store, records, options) {
			var unreg = Ext.create('Custom', {
				id: 9999999,
				Username : '未注册用户',
				Mobile : '手机号码未知'
			});
			this.customs.insert(0,unreg);
		};
		
		this.customs = Ext.create('Ext.data.Store', {
			autoDestroy: true,
			model: 'Custom',
			pageSize: 10,
			proxy: {
				type: 'jsonp',
				url: 'customs.php',
				reader: {
					type: 'json',
					root: 'customs',
					totalProperty: 'total',
					id: 'id'
				}
			},
			autoLoad: true,
			listeners: {
				'load': customsLoaded,
				scope: this
			}
		});
		
		var cityDataInitialization = function(store, records, options){
			if(records && records.length){
				this.getForm().findField('cityid').setValue(records[0].data.id);
				this.cityid = records[0].data.id;
				this.restaurants.getProxy().extraParams.cityid = records[0].data.id;
				this.restaurants.loadPage(1);
			}
		};
		
		this.cities = Ext.create('Ext.data.Store',{
			autoDestroy: true,
			model: 'City',
			pageSize: 100,
			proxy: {
				type: 'ajax',
				url: 'cities.php',
				reader: {
					type: 'json',
					root: 'cities',
					totalProperty: 'total',
					id: 'id'
				}
			},
			autoLoad: true,
			listeners: {
				'load': cityDataInitialization,
				scope: this
			}
		});

		this.restaurants = Ext.create('Ext.data.Store', {
			autoDestroy: true,
			model: 'Restaurant',
			pageSize: 10,
			proxy: {
				type: 'ajax',
				url: 'restaurants.php',
				extraParams: {cityid: this.cityid},
				reader: {
					type: 'json',
					root: 'restaurants',
					totalProperty: 'total',
					id: 'id'
				}
			},
			listeners: {
				scope: this,
				'load': function(store, records, operation, successful, operation, eopts){
					var field = this.getForm().findField('restaurantid');
					if(records && records.length==1) {
						if(field){
							field.setValue(records[0].data.id);
						}
						this.restaurantid = records[0].data.id;
						this.restaurant = records[0].data.name;
						this.restaurantmobile = records[0].data.mobile;
						this.dishStore.getProxy().extraParams.restaurantid = records[0].data.id;
						this.dishStore.loadPage(1);
					}
					if(field) {
						field.validate() ;
					}
				}
			}
		});
		
		var customAddressLoaded = function(store, records, options) {
			var form = this.getForm();
			var addressField = form.findField('address');
			if(records && records.length){
				addressField.setValue(records[0].data.Address);
			}
		};
		
		this.addresses = Ext.create('Ext.data.Store', {
			autoDestroy: true,
			model: 'CustomAddress',
			pageSize: 10,
			proxy: {
				type: 'ajax',
				url: 'customaddress.php',
				reader: {
					type: 'json',
					root: 'addresses',
					totalProperty: 'total',
					id: 'id'
				}
			},
			autoLoad: false,
			listeners: {
				'load': customAddressLoaded,
				scope: this
			}
		});
		
		Ext.apply(this, {
			id : 'widget.DropOrder',
			title : '手工下单',
			closable : true,
			autoScroll : true,
			bodyPadding: 10,
	        fieldDefaults : {
	            msgTarget: 'side',
	            labelWidth: 40,
	            labelAlign: 'right'
	        },
			items: [{
            	xtype: 'fieldset',
            	title: '订单',
    			defaultType: 'textfield',
    			padding: 10,
    			items: [{
	    			fieldLabel: '客户',
					name: 'customid',
					xtype: 'combo',
					width: 400,
					store: this.customs,
					typeAhead: true,
					displayField: 'Username',
					valueField: 'id',
					value: 9999999,
					selectOnFocus : true,
					pageSize: 10,
					listConfig: {
						loadingText: '正在搜索...',
						emptyText: '无数据',
						getInnerTpl: function() {
							return '<div>用户名：{Username} ({Mobile})</div>';
						}
					},
					listeners: {
						scope: this,
						'select' : function(combobox, value){
							var form = this.getForm();
							var mobileField = form.findField('mobile');
							if(value[0].data.Mobile && value[0].data.Mobile.length>0){
								mobileField.setValue(value[0].data.Mobile);
							}
							if(value[0].data.id && value[0].data.id!=9999999){
								this.addresses.getProxy().extraParams.customid = value[0].data.id;
								this.addresses.load();
							}
						}
					}
	    		},{
	    			fieldLabel: '城市',
					name: 'cityid',
					xtype: 'combo',
					editable: false,
					queryMode: 'local',
					store: this.cities,
					displayField: 'name',
					valueField: 'id',
					listeners: {
						scope: this,
						'select' : function(combobox, records){
							this.cityid = records[0].data.id;
							this.restaurants.getProxy().extraParams.cityid = records[0].data.id;
							this.restaurants.loadPage(1);
						}
					}
	    		},{
	    			fieldLabel: '餐馆',
					name: 'restaurantid',
					xtype: 'combo',
					width: 400,
					store: this.restaurants,
					typeAhead: true,
					minChars : 2,
					displayField: 'name',
					valueField: 'id',
					selectOnFocus : true,
					blankText : '必须选择一个餐馆',
					allowBlank: false,
					pageSize: 10,
					listConfig: {
						loadingText: '正在搜索...'
					},
					listeners: {
						scope: this,
						'select' : function(combobox, value){
							if(value[0].data.id){
								this.restaurantid = value[0].data.id;
								this.restaurant = value[0].data.name;
								this.restaurantmobile = value[0].data.mobile;
								this.dishStore.getProxy().extraParams.restaurantid = value[0].data.id;
								this.dishStore.loadPage(1);
							}
						}
					}
	    		},{
	    			fieldLabel: '手机',
					name	  : 'mobile',
					allowBlank: false,
					blankText : '手机号码不能为空',
	            	regex : /^((\+86)?|(86)?)(13[0-9]{9}|15[0|1|2|3|5|6|7|8|9]\d{8}|18[0|5|6|7|8|9]\d{8})$/,
	            	regexText : '请填写有效的手机号码'
	    		},{
					xtype: 'combo',
	    			fieldLabel: '地址',
					name	  : 'address',
					store: this.addresses,
					minChars : 2000, //为的是不触动查找。
					displayField: 'Address',
					valueField: 'Address',
					width: 500,
					allowBlank: false,
					blankText : '地址不能为空'
	    		},{
					xtype: 'textarea',
	    			fieldLabel: '要求',
					name	  : 'notes',
					width: 500,
					height: 50
	    		}]
			},
			{
				xtype: 'fieldset',
            	title: '餐饮',
    			padding: 10,
    			layout:'column',
				items:[
					this.createDishGrid(),
					{
						frame: false,
						width: 10
					},
					this.createSelectedDishGrid()
				]
			},
			{
				xtype: 'panel',
				border: false,
				frame: false,
				buttonAlign: 'left',
				buttons: [{
		            text: '保存',
		            handler: this.submitForm,
		            scope: this
		        },{
		            text: '重置',
		            handler: function() {this.getForm().reset();},
		            scope: this
		        }]
			}]
		});
		this.callParent(arguments);
	},
	
	createDishGrid : function () {
		this.dishStore = Ext.create('Ext.data.Store',{
			autoDestroy: true,
			model: 'Dish',
			pageSize: 100,
			groupField: 'section',
			proxy: {
				type: 'ajax',
				url: 'dishes.php',
				reader: {
					type: 'json',
					root: 'dishes',
					totalProperty: 'total',
					id: 'id'
				}
			},
			autoLoad: false
		});

		this.dishGrid = Ext.create("Ext.grid.Panel", {
			title : '餐品列表',
			height: 300,
			columnWidth: .5,
			autoScroll : true,
	        viewConfig: {
	            stripeRows: true
	        },
	        store : this.dishStore,
	        features: [{ftype:'grouping'}],
			columns: [
	            {
	                text     : '餐品名称',
	                width    : 200,
	                sortable : true,
	                dataIndex: 'name'
	            },
	            {
	                text     : '分类',
	                width    : 100,
	                sortable : true,
	                dataIndex: 'section'
	            },
	            {
	                text     : '注释',
	                width    : 100,
	                sortable : true,
	                dataIndex: 'annotation'
	            },
	            {
					xtype: 'numbercolumn',
	                text     : '单价',
	                width    : 100,
	                sortable : true,
	                dataIndex: 'price',
	                decimalSeparator : '.',
					format: '￥0.00'
	            },
	            {
					xtype: 'checkcolumn',
	                text     : '不接受订餐',
	                editable : false, //由我扩展，哈哈。
	                sortable : true,
	                width    : 80,
	                dataIndex: 'denyorder'
	            }
	        ],
	        dockedItems: [{
				xtype: 'pagingtoolbar',
				store: this.dishStore,   // same store GridPanel is using
				dock: 'bottom',
				displayInfo: true
			}],
			selType: 'rowmodel',
			listeners: {
				scope: this,
				'itemclick' : this.selectDish
			}
		});
		
		return this.dishGrid;
	},
	
	selectDish : function(gird, record){
		var selected = this.selectedDishStore.findRecord('DishID', record.data.id);
		if(selected){
			selected.data.Count = selected.data.Count+1;
			selected.commit();
		}
		else {
			var r = Ext.create('OrderItem', {
				DishID: record.data.id,
				Name: record.data.name,
				section: record.data.section,
				annotation: record.data.annotation,
				Price: record.data.price,
				Count: 1,
				RestaurantID: this.restaurantid,
				Restaurant: this.restaurant
			});
			this.selectedDishStore.add(r);
		}
	},
	
	createSelectedDishGrid : function() {
		this.selectedDishStore = Ext.create('Ext.data.ArrayStore', {
			autoDestroy: true,
			model: 'OrderItem'
		});
		this.selectedDishGrid = Ext.create("Ext.grid.Panel", {
			title : '选择的餐饮',
			height: 300,
			columnWidth: .5,
			autoScroll : true,
	        viewConfig: {
	            stripeRows: true
	        },
	        store : this.selectedDishStore,
	        features: [{ftype:'grouping'}],
			columns: [
	            {
	                text     : '餐品名称',
	                width    : 200,
	                sortable : true,
	                dataIndex: 'Name'
	            },
	            {
	                text     : '分类',
	                width    : 100,
	                sortable : true,
	                dataIndex: 'section'
	            },
	            {
	                text     : '注释',
	                width    : 100,
	                sortable : true,
	                dataIndex: 'annotation'
	            },
	            {
					xtype: 'numbercolumn',
	                text     : '单价',
	                width    : 100,
	                sortable : true,
	                dataIndex: 'Price',
	                decimalSeparator : '.',
					format: '￥0.00'
	            },
	            {
	                text     : '数量',
	                sortable : true,
	                width    : 80,
	                dataIndex: 'Count'
	            }
	        ],
			selType: 'rowmodel',
			listeners: {
				scope: this,
				'itemclick' : this.deleteSelectedDish
			}
		});
		
		return this.selectedDishGrid;
	},
	
	deleteSelectedDish : function(gird, record){
		var count = record.data.Count;
		if(count>1){
			record.data.Count--;
			record.commit();
		}
		else {
			this.selectedDishStore.remove(record);
		}
	},
	
	getSelectedDishParams : function() {
		var dishes = new Array();
		var names = new Array();
		var prices = new Array();
		var count = new Array();
		var store = this.selectedDishStore;
		store.each(function(record){
			dishes.push(record.data.DishID);
			names.push(record.data.Name);
			prices.push(record.data.Price);
			count.push(record.data.Count);
		});
		return {
			dishes : dishes.join(","),
			names : names.join(","),
			prices : prices.join(","),
			count : count.join(","),
			restaurant : this.restaurant,
			restaurantmobile : this.restaurantmobile
		}
	},
	
	submitForm : function() {
		var form = this.getForm();
		if (form.isValid()) {
				console.log(this.selectedDishStore);
			this.submit({
				url:'drop_order.php',
				waitTitle : '请稍候',
				params: this.getSelectedDishParams(),
				waitMsg : '正在保存订单信息...',
				method : 'POST',
		        success: this.dropOrderSuccess,
		        failure: this.dropOrderFailure,
		        scope: this
		    });
		}
		else {
			showErrorMsg('某些输入项不符合规定，请检查各字段的输入。','输入有误。');
		}
	},
	
	dropOrderSuccess : function (form, action) {
		showSuccessMsg('手工下单成功。');
	},
	
	dropOrderFailure : function (form, action) {
		showFormFailureMsg( action, '手工下单失败');
	}
});
}