var windowReportReportTrip = null;

Ext.define('modelReportReportTrip', {
    extend: 'Ext.data.Model',
	fields: ['Name','Address','Driver','StartWorkTime','EndWorkTime','DELIVERY_DATE_FACT','DELIVERY_OUTDATE_FACT','PointState',{name: 'SumCargo', type: 'float'},'DriverComments',{name: 'FuelVal', type: 'float'},{name: 'StartOdom', type: 'float'},{name: 'EndOdom', type: 'float'},{name: 'DiffOdom', type: 'float'},'InTime'] //{name: 'indoor', type: 'bool'}
	//fields: ['result_1', 'result_2', 'result_3', 'result_4', 'result_5', 'result_6', 'result_7', 'result_8', 'result_9', 'result_10', 'result_11', 'result_12', 'result_13', 'result_14', 'result_15', {name: 'result_16', type: 'float'},{name: 'result_17', type: 'float'},{name: 'result_18', type: 'float'},{name: 'result_19', type: 'float'},{name: 'result_20', type: 'float'},'result_21','result_22','result_23']
});

var storeReportReportTrip =  new Ext.data.Store({		        
			    pageSize: 30,
				groupField: 'DriverId',
		        model: 'modelReportReportTrip',
		        proxy: 
		        {
		          type: 'ajax',
		          url: 'app/LogistMobile_ReportTrip.php?load=1',
		          reader: 
		          {
		            type: 'json',
		            root: 'rows',
					totalProperty: 'total'
		          }
		        }
		});

   
//-----------------window-----------------------------------------------------   
function show_LogistMobile_ReportTrip_Window()
{
	
	
	if(!windowReportReportTrip){
	
	//storeReportReportTrip.load();
	
	var pagingToolbarReportReportTrip = Ext.create('Ext.PagingToolbar', {
        border: false,
        frame: false,
        store: storeReportReportTrip,
        displayInfo: true
    });
	
	
	var gridReportReportTrip = new Ext.create('Ext.grid.Panel',{
		    selType: 'rowmodel',
		    columnLines: true,
		    store: storeReportReportTrip,
		    loadMask: true,
			id: 'ReportTrip_GridId',
		    border: false,
		    autoScroll: true,
			bbar:[pagingToolbarReportReportTrip],
			features: [{
				ftype: 'groupingsummary',
				//groupHeaderTpl: '{[values.rows.trade_point]} {name}',//{[values.rows[0].trade_point]}
				groupHeaderTpl: '{[values.rows[0].data["Driver"]]}',
				hideGroupedHeader: false,
				//startCollapsed: true,
				enableGroupingMenu: false
			},
					{
							ftype: 'summary',
							dock: 'bottom'
					}
			],
			tbar:[
				/*{
							tooltip: 'Обновить данные',
							iconCls: 'refresh',
	    		    		handler: function(){
								
							}
				},'-',*/{
                            xtype: 'datefield',
                            format: 'Y-m-d',
                            altFormats: 'Y-m-d',
                            startDay: 1,
                            fieldLabel: 'Период с',
                            labelAlign: 'left',
                            labelWidth: 60,
                            style:' margin-left:3px;',
                            id: 'ReportTrip_startdt',
                            width: 165,
                            value: new Date(),
                            maxValue: new Date(),
                            listeners:{
                                change: function(newValue, oldValue, eOpts){

                                }
                            }
                },
                {
                             xtype: 'datefield',
                             format: 'Y-m-d',
                             altFormats: 'Y-m-d',
                             startDay: 1,
                             fieldLabel: 'Период по',
                             labelAlign: 'left',
                             labelWidth: 60,
                             id: 'ReportTrip_enddt',
                             style:'margin-left:3px;',
                             width: 165,
                             value: new Date()
                },
                {
                            text: "Сформировать",
                            //iconCls: 'left-right',
                            //id:'filter_data',
                            handler:function(){
                               
							   Ext.getCmp('ReportTrip_GridId').store.load({
									params: {
									reportQues_startdt: Ext.getCmp('ReportTrip_startdt').getRawValue(),
									reportQues_enddt: Ext.getCmp('ReportTrip_enddt').getRawValue()
									}
								});
								
								storeReportReportTrip.setProxy({
									type: 'ajax',
									url: 'app/LogistMobile_ReportTrip.php?load=1&reportQues_startdt='+Ext.getCmp('ReportTrip_startdt').getRawValue()+'&reportQues_enddt='+Ext.getCmp('ReportTrip_enddt').getRawValue(),
									reader: 
									{
										type: 'json',
										root: 'rows',
										totalProperty: 'total'
									}
								});
							   
                            }
                },'-',
				{
	  						  text: all.export_xls,
	  						  tooltip: all.export_xls,
	  						  iconCls:'xls',
	  						  handler:function() 
	  						  {
								var ArrData=new Array(); 
								var columnCount = modelReportReportTrip.fields.length;
								//if(Ext.getCmp('ReportTrip_GridId').store.getCount() > 0){
								if(Ext.getCmp('ReportTrip_GridId').store.getTotalCount() > 0){
									ArrData = save_table_data(columnCount); 
									export_xls(ArrData,Ext.getCmp('ReportTrip_startdt').getRawValue(),Ext.getCmp('ReportTrip_enddt').getRawValue());
								}
	  						  }
	  			}
			],
			columns:[
			/*{
				xtype: 'checkcolumn', 
				width: 30, 
				dataIndex: 'indoor', 
				hideable: false, 
				sortable: false,
				listeners:
                {
                    checkchange:function(CheckColumn, rowIndex, checked, eOpts )
                    {
						
					}
				}
			},*/
			{
	        	xtype: 'rownumberer',
				width: 30
	        },
			{
	        	text: 'Название',
	            dataIndex: 'Name',            
	            width: 200,
	            sortable: true,
				summaryRenderer: function(value, summaryData, dataIndex) { return ('Итого:'); }
	        },
			{
	        	text: 'Адрес доставки',
	            dataIndex: 'Address',
	            width: 200,
				sortable: true
	        },
			{
	        	text: 'Курьер',
	            dataIndex: 'Driver',  
				width: 80,
	            sortable: true
	        },
			{
	        	text: 'Начало работы',
	            dataIndex: 'StartWorkTime',  
				width: 100,
	            sortable: true
	        },
			{
	        	text: 'Конец работы',
	            dataIndex: 'EndWorkTime',
	            width: 100,
				sortable: true
	        },
			{
	        	text: 'Время прибытия',
	            dataIndex: 'DELIVERY_DATE_FACT',
	            width: 120,
				sortable: true
	        },
			{
	        	text: 'Время отбытия',
	            dataIndex: 'DELIVERY_OUTDATE_FACT',
	            width: 120,
				sortable: true
	        },
			{
	        	text: 'Состояние резерва',
	            dataIndex: 'PointState',
	            width: 130,
				sortable: true
	        },
			{
	        	text: 'Сумма оплаты',
	            dataIndex: 'SumCargo',
	            width:90,
				sortable: true,
				xtype: 'numbercolumn',
				format:0.00,
				//summaryType: 'sum'
				summaryType: function(records){
							var i = 0,
							length = records.length,
							total = 0,
							record;
							for (; i < length; ++i) {
								record = records[i];
								total += record.get('SumCargo');
							}
	                
							total = total.toFixed(2);
							return total;
				}
	        },
			{
	        	text: 'Комментарий курьера',
	            dataIndex: 'DriverComments',
	            width:200,
				sortable: true
	        },
			{
	        	text: 'Заправка',
	            dataIndex: 'FuelVal',
	            width:80,
				sortable: true,
				xtype: 'numbercolumn',
				format:0.00,
				renderer:function(){
				return '-';
				},
				summaryType: function(records){
							//return records[0].get('FuelVal');
							var i = 0,
							length = records.length,
							total = 0,
							record;
							for (; i < length; ++i) {
								record = records[i];
								total = record.get('FuelVal');
							}
							return total;
				}
	        },
			{
	        	text: 'Показатели одометра 9:00',
	            dataIndex: 'StartOdom',
	            width:80,
				sortable: true,
				xtype: 'numbercolumn',
				format:0.00,
				renderer:function(){
				return '-';
				},
				summaryType: function(records){
							//return records[0].get('StartOdom');
							var i = 0,
							length = records.length,
							total = 0,
							record;
							for (; i < length; ++i) {
								record = records[i];
								total = record.get('StartOdom');
							}
							return total;
				}
	        },
			{
	        	text: 'Показатели одометра 18:00',
	            dataIndex: 'EndOdom',
	            width:80,
				sortable: true,
				xtype: 'numbercolumn',
				format:0.00,
				renderer:function(){
				return '-';
				},
				summaryType: function(records){
							//return records[0].get('EndOdom');
							var i = 0,
							length = records.length,
							total = 0,
							record;
							for (; i < length; ++i) {
								record = records[i];
								total = record.get('EndOdom');
							}
							return total;
				}
	        },
			{
	        	text: 'Показатели одометра разница',
	            dataIndex: 'DiffOdom',
	            width:80,
				sortable: true,
				xtype: 'numbercolumn',
				format:0.00,
				renderer:function(){
				return '-';
				},
				summaryType: function(records){
							//return records[0].get('DiffOdom');
							var i = 0,
							length = records.length,
							total = 0,
							record;
							for (; i < length; ++i) {
								record = records[i];
								total = record.get('DiffOdom');
							}
							return total;
				}
	        },
			{
	        	text: 'Оценка',
	            dataIndex: 'InTime',
	            width:80,
				sortable: true
	        }
			],
			listeners: {
				beforeedit: function(editor, ctx, e, eOpts, record)
				{
           
				},
				edit: function(editor, ctx, e, eOpts, record) {
           
				},
				itemdblclick: function(cmp, records) {    		
    		
				}
			}
	});

	
	
        windowReportReportTrip = new Ext.Window({
                        width: 800,
                        height: 400,
                        title: LogistMobile.ReportTrip,
                        closeAction : 'destroy',
                        layout: 'fit',
                        resizable:true,
                        modal:false,
						constrainHeader: true,
						constrain: true,
						resizable: true,
						maximizable: true,
						listeners: {
							destroy: function(){
							windowReportReportTrip = null;
							}
						},
                        //bodyStyle:{'background-color': '#FFFFFF'},
                 items:[
					gridReportReportTrip
				 ]
                     

        });    
         
    }
    windowReportReportTrip.show();
	
	
function save_table_data(ColumsCount)
{
	var ColumnsArray = new Array(); 
	var i=0;
	console.log(modelReportReportTrip.fields);
	
	ColumsCount = ColumsCount - 1;
	
	Ext.getCmp('ReportTrip_GridId').store.each(function(rec){
				//var j=1;
				var k=0;
				Str='';
				while (k<ColumsCount)
				{
					console.log(modelReportReportTrip.fields[k].name);
					//Str += rec.get('result_'+j)+'/n';
					Str += rec.get(''+modelReportReportTrip.fields[k].name)+'/n';
					//j++;
					k++;
				}
				ColumnsArray[i]=Str;
				i++;
	});
	return ColumnsArray;
}

function export_xls(ArrayData,reportQues_startdt,reportQues_enddt)
{

	$.post("app/LogistMobile_ReportTrip.php",{func:'export_xls','ColumnsArray[]':ArrayData,reportQues_startdt:reportQues_startdt,reportQues_enddt:reportQues_enddt}, function(data){
		window.open('app/LogistMobile_ReportTrip.php?func=save_export_xls', '_blank');
	});                                   

}
	
}