var LogistMobile_orders_Window = null;
var LogistMobile_orders_WindowAddEdit = null;


var LOG = "";
var strl = "";
function addToLog(strl)
{
    LOG += strl + "\n";
    console.log(LOG);
}

function OpenSocket(json)
{	
	$.ajax({
		type: 'POST',
		url: 'http://localhost:5113/TSCPrinterService/',
		//url: 'http://localhost/testPrint/jsonp.php',
		data: {json},
		//jsonp: false,
		//contentType:'text/html; charset=UTF-8',
		dataType: 'json',
		//processData: false,
		crossDomain: true,
	}).done(function(response){
		//console.log(response);
	}).fail(function(error){
		//console.log(error.statusText);
	});
}




	
	Ext.define('stateLogistMobileModel', {
	    extend: 'Ext.data.Model',
		fields: ['id','value']
	});
	var stateLogistMobileStore = new  Ext.data.Store({   
	        model: 'stateLogistMobileModel',
	        proxy: 
	        {
	          type: 'ajax',
	          url: 'app/LogistMobile_CRM_orders.php?func=state',
	          reader: 
	          {
	            type: 'json',
	            root: 'rows'
	          }
	        }
	});

    var arrCount = [];
    for (var i = 1; i <= 32; i++){
        arrCount.push({"value":i});
    }
    var count_store =Ext.create('Ext.data.Store', {
        autoLoad: true,
        fields: ['value'],
        data: arrCount
    });
	
	Ext.define('cargoLogistMobileModelDef', {
    extend: 'Ext.data.Model',
    fields: ['id','value']
	});
	
	var cargoLogistMobileStoreDef = new Ext.data.Store({
        model: 'cargoLogistMobileModelDef',
           proxy: {
              type: 'ajax',
			  limitParam: null,
              url: 'app/LogistMobile_CRM_orders.php?func=cargo',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
	});
	
	Ext.define('clientLogistMobileModelDef', {
    extend: 'Ext.data.Model',
    fields: ['id','value']
	});
	
	var clientLogistMobileStoreDef = new Ext.data.Store({
        model: 'clientLogistMobileModelDef',
           proxy: {
              type: 'ajax',
			  limitParam: null,
              url: 'app/LogistMobile_CRM_orders.php?func=client',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
	});
	
/* store & model --> */	
	Ext.define('ordersLogistMobileModel', {
	    extend: 'Ext.data.Model',
		fields: ['id','Name',{name: 'Date', type: 'date', dateFormat: 'Y-m-d'},{name: 'Time', type: 'date', dateFormat:'H:i'},'State','NameClient','clientId','stateId',{name: 'indoor', type: 'bool'}]
	});
	var ordersLogistMobileStore = new  Ext.data.Store({   
			//autoLoad: true,	
	        pageSize: 50,
			model: 'ordersLogistMobileModel',
	        proxy: 
	        {
	          type: 'ajax',
	          url: 'app/LogistMobile_CRM_orders.php?func=show',
	          reader: 
	          {
	            type: 'json',
	            root: 'rows',
				totalProperty: 'total'
	          }
	        },listeners: {
				load: function(store, records, successful, operation, eOpts) {
					
					store.each(function(record){
						//if( record.get('indoor') == true ){
							//Ext.getCmp('ordersLogistMobileBtnBlockAll').setText(available_orders.btnunblockordersnapshotall);
							//Ext.getCmp('ordersLogistMobileBtnBlockAll').toggle(true);
						//}
					});
				}
			}
	});
/* store & model --> */


function show_LogistMobile_CRM_orders_Window() {
	
	ordersLogistMobileStore.load();
	stateLogistMobileStore.load();
	
	if (!LogistMobile_orders_Window) {

	    Xcoord = 40;
	    Ycoord = 60;  
	    Wwidth = 700;  
	    Wheight = 400;
			
/* grid --> */
		var PagingToolbarLogistMobile_orders = Ext.create('Ext.PagingToolbar', {
        border: false,
        frame: false,
        store: ordersLogistMobileStore,
        displayInfo: true
		});
		
	    var ordersRowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
        clicksToEdit: 1,
		autoCancel: true,
		errorSummary: false,
		saveBtnText: 'Сохранить',
		cancelBtnText: 'Отмена',
		listeners: {
			edit: function(editor, ctx, e, eOpts, record) {
				//alert(ctx.record.get('id'));
				//alert(ctx.record.get('State'));
				console.log(record);
				console.log(editor);
				
				var form = editor.editor.getForm();
				var Date = form.findField("Date").getRawValue();
				var Time = form.findField("Time").getRawValue();
				
				changeStateOrder(ctx.record.get('id'),ctx.record.get('State'),Date,Time);
			},
			canceledit: function(rowEditing, context) {
				//if (context.record.phantom) {
				//	context.store.remove(context.record);
				//}
			}
		}
		});
		
		var ordersLogistMobileGrid = new Ext.grid.Panel({
	    	selType: 'rowmodel',
	        columnLines: true,
			plugins: [ordersRowEditing],
	        layout: 'fit',
	        store:  ordersLogistMobileStore,
	        loadMask: true,
			id: 'LogistMobile_ordersGridId',
	        border: false,
	        autoScroll: true,
	        viewConfig: {
	        	preserveScrollOnRefresh: true,
	        },
			bbar:[PagingToolbarLogistMobile_orders],
	        columns:[
			{
				xtype: 'checkcolumn', 
				width: 30, 
				dataIndex: 'indoor', 
				hideable: false, 
				sortable: false,
				listeners:
                {
                    checkchange:function(CheckColumn, rowIndex, checked, eOpts )
                    {
						
					}
				}
			},
			{
	        	xtype: 'rownumberer',
				width: 30,	
	        },
			{
	        	text: 'Наряд',
	        	//text: available_orders.trip, 
	            dataIndex: 'Name',            
	            width: 200,
	            sortable: true,
	        },
			{        	
	        	text: 'Дата',
	        	//text: available_orders.start_trip, 
	            dataIndex: 'Date',
	            width: 90,
				sortable: true,
				xtype: 'datecolumn',
				format: 'Y-m-d',
				editor: {
					xtype:'datefield',
                    name: 'Date',
					format: 'Y-m-d',
                    altFormats: 'Y-m-d',
					startDay: 1,
					anchor:'100%',
					//minValue: new Date(),
				}
	        },
			{        	
	        	text: 'Время',
	        	//text: available_orders.start_trip, 
	            dataIndex: 'Time',
	            width: 70,
				sortable: true,
				xtype: 'datecolumn',
				format: 'H:i',
				editor: {
					xtype:'timefield',				
					name: 'Time',
					format: 'H:i',
					altFormats: 'H:i'
				}
	        },
			{        	
	        	text: 'Клиника',
	        	//text: available_orders.start_trip, 
	            dataIndex: 'NameClient',
	            width: 120,
				sortable: true,
	        },
			{
	        	text: 'Статус',
	        	//text: available_orders.end_trip,
	            dataIndex: 'State',
	            width: 120,
				sortable: true,
				editor: {
                    xtype: 'combo',
					name: 'State',
					store: stateLogistMobileStore,
					queryMode: 'local',
                    displayField: 'value',
                    valueField: 'id',
					typeAhead: false,
                    triggerAction: 'all',
					//forceSelection: true,
                    lazyRender: true,
					listeners:{
						//change: function(val, value, eOpts, editor){
							
						//}
					}
				}
	        }
			], 
	        listeners: {
	        	itemclick: function(cmp, records) {
					
	        	},
				itemdblclick: function(cmp, records) {
		    		show_LogistMobile_orders_WindowAddEdit(records.get('id'),records);
		    	}				
	        },
			tbar:[
				{
	    		xtype: 'button',
	    		//text: 'Создать',
				iconCls: 'add',
				tooltip: 'Создать',
	    		handler: function() {
					show_LogistMobile_orders_WindowAddEdit();
				}
				},
				{
	    		xtype: 'button',
	    		//text: 'Редактировать',
				iconCls: 'edit',
				tooltip: 'Редактировать',
	    		handler: function() {
						var select = Ext.getCmp('LogistMobile_ordersGridId').getView().getSelectionModel().getSelection()[0];
						if(select){
							show_LogistMobile_orders_WindowAddEdit(select.get('id'),select);
						}else {
							Ext.Msg.alert(all_toir.attention, 'Выберите строку'); 	
						}
					
				}
				},
				{
		        xtype: 'button',
			    //text: 'Удалить',
				iconCls: 'delete',
				tooltip: 'Удалить',
		        handler: function(){
							var arrayId=[];									
							ordersLogistMobileStore.each(function(record)   
							{
								if(record.get('indoor') == true){
									arrayId.push(record.get('id'));
								}
								
							});
							
							if (arrayId.length==0){
								Ext.Msg.alert(all_toir.error, 'Выберите строку(и)');
							} else {
								Ext.MessageBox.confirm(all_toir.attention, 'Вы действительно хотите удалить выбранную строку(и)',  function(btn){
								if(btn=='yes'){
									
								var myMask = new Ext.LoadMask(LogistMobile_orders_Window, {msg: all.loading});
								myMask.show();
								$.post("app/LogistMobile_CRM_orders.php",{'delete':true, 'arrayId[]':arrayId}, function(data){
										if(data){
											var obj = Ext.decode(data);
											if(obj.success == true){
												Ext.MessageBox.alert(all_toir.attention, 'Удалено');
												ordersLogistMobileStore.load();
												myMask.hide();
											}else{
												myMask.hide();
												Ext.MessageBox.alert(all_toir.error, obj.message);
											}
				
										}else{
											Ext.MessageBox.alert(all_toir.error, '');
											myMask.hide();
										}
								});
								}
								});
							}
				}
				},
				{
							xtype: 'button',
							iconCls: 'print',
							margin: '0 0 0 3',
							text: 'Печать шк. заказа',
							//tooltip: 'Печать',
							handler: function(){
								var select = Ext.getCmp('LogistMobile_ordersGridId').getView().getSelectionModel().getSelection()[0];
								if(select){
									var myMask = new Ext.LoadMask(LogistMobile_orders_Window, {msg: all.loading});
									myMask.show();
									$.post("app/LogistMobile_CRM_orders.php",{'printOrder':true, 'id':select.get('id')}, function(data){
										if(data){
											console.log(data);
											
											OpenSocket(data);
											
											myMask.hide();
											/*var obj = Ext.decode(data);
											if(obj.state == 0){
												Ext.MessageBox.alert(all_toir.attention, 'Выполнено');
												myMask.hide();
											}else{
												myMask.hide();
												Ext.MessageBox.alert(all_toir.error, obj.err);
											}*/
										}else{
											Ext.MessageBox.alert(all_toir.error, '');
											myMask.hide();
										}
									});
								}else {
									Ext.Msg.alert(all_toir.attention, 'Выберите строку'); 	
								}
							}
				},
				{
							xtype: 'button',
							iconCls: 'print',
							margin: '0 0 0 3',
							text: 'Печать шк. товаров',
							//tooltip: 'Печать',
							handler: function(){
								var select = Ext.getCmp('LogistMobile_ordersGridId').getView().getSelectionModel().getSelection()[0];
								if(select){
									var myMask = new Ext.LoadMask(LogistMobile_orders_Window, {msg: all.loading});
									myMask.show();
									$.post("app/LogistMobile_CRM_orders.php",{'printOrderCargo':true, 'id':select.get('id')}, function(data){
										if(data){
											console.log(data);
											
											var obj = Ext.decode(data);
											
											for(key in obj){
												console.log( Ext.encode(obj[key]) );
												OpenSocket(Ext.encode(obj[key]));
											}
											
											
											myMask.hide();
											
											/*var obj = Ext.decode(data);
											if(obj.state == 0){
												Ext.MessageBox.alert(all_toir.attention, 'Выполнено');
												myMask.hide();
											}else{
												myMask.hide();
												Ext.MessageBox.alert(all_toir.error, obj.err);
											}*/
				
										}else{
											Ext.MessageBox.alert(all_toir.error, '');
											myMask.hide();
										}
									});
								}else {
									Ext.Msg.alert(all_toir.attention, 'Выберите строку'); 	
								}
							}
				}
			]
	    	
	    });
/* <-- grid */		    
	    
		
		
	        Ext.getBody().mask(all.loading);
	        LogistMobile_orders_Window = new Ext.Window({
	            layout : 'fit',
	            title: 'Заказы',
	            //title : available_orders.orders_in_trip,
	            closeAction : 'destroy',
	            width : parseInt(Wwidth),
	            height : parseInt(Wheight),
	            maximizable:true,
				constrain : true,
				resizable: true,
	            defaults: {
	            },
				listeners : {
	            	destroy : function(){
	            		LogistMobile_orders_Window = null;	
	            	}
	            },
	            items: [ordersLogistMobileGrid]
			})      
		LogistMobile_orders_Window.show(); 
		Ext.getBody().unmask(all.loading);

	}


}


function show_LogistMobile_orders_WindowAddEdit(id,records){
	
	cargoLogistMobileStoreDef.load();
	clientLogistMobileStoreDef.load();
	
	
	if(id){
	title= 'Редактирование заказа';
	}else{
	title= 'Создание заказа';
	id = "";
	}
	
/* grid --> */
	Ext.define('orderscargoLogistMobileModel', {
	    extend: 'Ext.data.Model',
		fields: ['id','NameGroup','NameCargo', 'barcode', 'count','Comments',{name: 'indoor', type: 'bool'}]
	});
	var orderscargoLogistMobileStore = new  Ext.data.Store({   
			//autoLoad: true,	
	        model: 'orderscargoLogistMobileModel',
			groupField: 'NameGroup',
	        proxy: 
	        {
	          type: 'ajax',
	          url: 'app/LogistMobile_CRM_orders.php?func=showcargo&id='+id,
	          reader: 
	          {
	            type: 'json',
	            root: 'rows'
	          }
	        }
	});
	orderscargoLogistMobileStore.load();
	var orderscargoLogistMobileGrid = new Ext.grid.Panel({
	    	selType: 'rowmodel',
	        columnLines: true,
	        layout: 'fit',
	        store:  orderscargoLogistMobileStore,
	        loadMask: true,
	        border: false,
	        autoScroll: true,
			id: 'orderscargoGridId',
	        viewConfig: {
	        	preserveScrollOnRefresh: true,
	        },
			features: [{
	  					  ftype: 'groupingsummary',
	  					  groupHeaderTpl: '{name}',
	  					  hideGroupedHeader: false,
	  					  enableGroupingMenu: false
	  				  }],
	        columns:[
			{
				xtype: 'checkcolumn', 
				width: 30, 
				dataIndex: 'indoor', 
				hideable: false, 
				sortable: false,
				listeners:
                {
                    checkchange:function(CheckColumn, rowIndex, checked, eOpts )
                    {
						var record  = orderscargoLogistMobileGrid.getView().getRecord(orderscargoLogistMobileGrid.getView().getNode(rowIndex));

                        if(checked){
                            record.set('count', 1);
                        }else{
                            record.set('count', '');
                        }
					}
				}
			},
			{
	        	xtype: 'rownumberer',
				width: 30,	
	        },
			{
	        	text: 'Название',
	            dataIndex: 'NameCargo',            
	            flex: 1,
	            sortable: true,
	        },
			{
	        	text: 'Штрих-код',
	            dataIndex: 'barcode',            
	            width: 70,
	            sortable: true,
	        },
            {
                 text: 'Кол-во',
                 dataIndex: 'count',
                 width: 70,
                 sortable: false,
                 /*editor: {
                    xtype: 'textfield',
                    allowBlank: false
                 }*/
                editor: {
                    xtype:'combobox',
                    name: 'count',
                    allowBlank: true,
                    store: count_store,
                    queryMode: 'local',
                    displayField: 'value',
                    valueField: 'value',
                    typeAhead: false,
                    triggerAction: 'all',
                    value: 1,
                    lazyRender: true,
                    editable: true,
                    minChars: 1,
                    enableKeyEvents: true
                }
			}	
			], 
			selModel: 'cellmodel',
            plugins: {
                ptype: 'cellediting',
                clicksToEdit: 1
            },
	        listeners: {
	        	itemclick: function(cmp, records) {
	        	},
				itemdblclick: function(cmp, records) {
		    	}
	        },
			tbar:[]
	});
/* <-- grid */
	
	
	if(!LogistMobile_orders_WindowAddEdit){
        LogistMobile_orders_WindowAddEdit = new Ext.Window({
            width:600,
            height:320,
            title: title,
            closeAction: 'destroy',
            listeners: {
                destroy: function()
				{
                    LogistMobile_orders_WindowAddEdit = null;
                }
            },
            layout: 'fit',
            resizable: true,
            constrainHeader: true,
            modal: true,
            items:[
                {
                    xtype: 'form',
                    autoScroll: true,
                    bodyPadding: '5 5 5 5',
                    id: "LogistMobile_orders_formId",
                    border: false,
                    frame: true,
                    autoHeight: true,
                    layout: 'anchor',
                    items:
                    [
				
				// -- CONTAINER -->
				{
				xtype: 'container',
				anchor: '100%',
				layout:'column',
				//layout: 'anchor',
				items:[
				// -- COLUMN 1 -->
				{
                xtype: 'container',
                columnWidth:.5,
                layout: 'anchor',
                items: [
					{
                    xtype: 'textfield',
                    fieldLabel: 'Наряд',
                    name: 'orderName',
					anchor:'96%',
					labelWidth: 60,
					allowBlank: false,
					},
					{
                    xtype: 'combo',
					fieldLabel: 'Статус',
					store: stateLogistMobileStore,
					queryMode: 'local',
                    displayField: 'value',
                    valueField: 'id',
					typeAhead: false,
                    triggerAction: 'all',
					//forceSelection: true,
                    lazyRender: true,
					editable: true,
					allowBlank: false,
                    name: 'orderState',
					anchor:'96%',
					labelWidth: 60,
					readOnly: true,
					value: 1
					},
					{
                    xtype: 'combo',
					fieldLabel: 'Клиника',
					store: clientLogistMobileStoreDef,
					queryMode: 'local',
                    displayField: 'value',
                    valueField: 'id',
					typeAhead: false,
                    triggerAction: 'all',
					//forceSelection: true,
                    lazyRender: true,
					editable: true,
					allowBlank: false,
                    name: 'orderClient',
					anchor:'96%',
					labelWidth: 60,
					}
				]
				},
				// <-- COLUMN 1 --
				// -- COLUMN 2 -->
				{
                xtype: 'container',
                columnWidth:.5,
                layout: 'anchor',
                items: [
					{
                    xtype:'datefield',
                    format: 'Y-m-d',
                    altFormats: 'Y-m-d',
					startDay: 1,
					editable: false,
					fieldLabel: 'Дата',
                    name: 'orderDate',
					allowBlank: false,
					anchor:'100%',
					labelWidth: 60,
					minValue: new Date(),
					value: new Date()
					},
					{
					xtype:'timefield',				
					format: 'H:i',
					name: 'orderTime',
					altFormats: 'H:i',              
					fieldLabel: 'Время',
					allowBlank: false,
					value: '00:00',
					anchor:'100%',
					labelWidth: 60,
					editable: false,
					}
				]
				}
				// <-- COLUMN 2 --
				
					
					
					
				
				]
				}
				// <-- CONTAINER --
		,orderscargoLogistMobileGrid
		/*,{
            xtype: 'itemselector',
			height:170,
			autoScroll:true,
            name: 'orderCargo',
			fromTitle: 'Товары',
            toTitle: 'Товары заказа',
			validateOnChange: false,
			id: 'LogistMobile_orderCargo',
			buttons: ['add', 'remove'],
            autoScroll: true,
			imagePath: '../ux/images/',
			allowBlank: true,
			store: cargoLogistMobileStoreDef,
            displayField: 'value',
            valueField: 'id',
            msgTarget: 'side',
			value: []
        }*/
			
			
			
			/*,new Ext.create('Ext.container.Container', {
            xtype: 'multi-selector',
            //width: 300,
            //height: 300,
            requires: ['Ext.view.MultiSelector'],
            layout: 'fit',
            items: [{
                xtype: 'multiselector',
                id: 'orderMultiSelector',
				title: 'Товары заказа',
                fieldName: 'value',
                viewConfig: {
                    deferEmptyText: false,
                    emptyText: 'Нет выбраных товаров'
                },
                search: {
                    field: 'value',
                    store: cargoLogistMobileStoreDef,
                    search: function(text) {
                        var me = this,
                            filter = me.searchFilter,
                            filters = me.getSearchStore().getFilters();

                        if (text) {
                            filters.beginUpdate();

                            if (filter) {
                                filter.setValue(text);
                            } else {
                                me.searchFilter = filter = new Ext.util.Filter({
                                    id: 'search',
                                    property: me.field,
                                    value: text,
                                    anyMatch: true
                                });
                            }
                            filters.add(filter);
                            filters.endUpdate();
                        } else if (filter) {
                            filters.remove(filter);
                        }
                    },
                }
            }]
        })*/
			
			
				
					]
				}
			],
			buttons:[
					{ 
                    text:'Сохранить',
					iconCls:'save',
					handler: function() {
						var form = Ext.getCmp('LogistMobile_orders_formId').getForm();
						
						//var item_cargo = Ext.getCmp('LogistMobile_orderCargo').getValue();    
							var item_cargo=[];
							var item_cargo_count = [];
                            orderscargoLogistMobileStore.each(function(record)
							{
								if(record.get('indoor') == true){
									item_cargo.push(record.get('id'));
									item_cargo_count.push(record.get('count'));
								}
								
							});
                            console.log(item_cargo);
                            console.log(item_cargo_count);

						if(form.isValid()){
						
						form.submit({
							url: 'app/LogistMobile_CRM_orders.php',
							waitMsg: 'Сохранение...',
							wait: true,
							scope: this,
							method: 'post',
							//timeout : 60000,
							params: {addedit:true,'item_cargo[]':item_cargo,'item_cargo_count[]':item_cargo_count,id:id},
							success: function(fp, o) {
								Ext.MessageBox.alert(all_toir.attention, 'Сохранено');
								LogistMobile_orders_WindowAddEdit.destroy();
								ordersLogistMobileStore.load();
							},
							failure: function(fp, o) {
								Ext.MessageBox.alert('Ошибка', o.result.message);
							}
						});
						}
					}
					},
					{ 
                    text:'Отмена',
					iconCls: 'cancel',
					handler: function() {
						LogistMobile_orders_WindowAddEdit.destroy();
					}
					}
			]
		});
	}
	LogistMobile_orders_WindowAddEdit.show();
	
	var form = Ext.getCmp("LogistMobile_orders_formId").getForm();
    if (id) {
		form.findField("orderName").setValue( records.get('Name') );
		form.findField("orderState").setValue( records.get('stateId') );
		form.findField("orderClient").setValue( records.get('clientId') );
		
		form.findField("orderDate").setMinValue( new Date(records.get('Date')) )
		form.findField("orderDate").setValue( records.get('Date') );
		form.findField("orderTime").setValue( records.get('Time') );
    }
	
}

function changeStateOrder(id,state,date,time){
	
	var myMask = new Ext.LoadMask(LogistMobile_orders_Window, {msg: all.loading});
	myMask.show();
	
	
	Ext.Ajax.request({
		url: 'app/LogistMobile_CRM_orders.php',
		method: 'POST',
		wait: true,
		params: {"updatestate":true,id:id,state:state,date:date,time:time},
		success: function(response) {
			var data = response.responseText;
			//alert(data);
			var obj = Ext.decode(data);
			if(obj.success == true){
				Ext.MessageBox.alert(all_toir.attention, 'Сохранено');
				ordersLogistMobileStore.load();
			}else{
				Ext.MessageBox.alert(all_toir.error, obj.message);
			}
		    myMask.hide();
		},
		failure: function(response) {
			//alert(data);
			var obj = Ext.decode(data);
			Ext.MessageBox.alert(all_toir.error, obj.message);
			myMask.hide();
		}
	});
}
