var TOiRReportWindow = null;
var TOiRReport_result = null;

var MileageSpeedWindow;
var MileageSpeed_result;
 var data=new Array();
  
 var car=new Array();
 var driver=new Array();
 var customer=new Array();
 var route=new Array();
 var time=new Array();
 var mileage=new Array();
 var after_Counts=new Array();
 
 Ext.define('TOiR_StatusRoutesModel', {
	    extend: 'Ext.data.Model',
	    fields: ['id' , 'name']
	});
 
 var TOiR_StatusRoutesStore = new Ext.data.Store(
  {     
		//autoLoad: true,
		//autoDestroy: true,
        model: 'TOiR_StatusRoutesModel',
        data: [{'id': 1, 'name': report_toir.executed},
    	       {'id': 0, 'name': report_toir.not_executed}]
       
});

 var reportTypeStore = new Ext.data.Store({	
		fields: ['id', 'name'],
		data : [{'id': 1, 'name': 'Внеплановые работы'},
		        {'id': 2, 'name': 'Плановые работы'}
		        ],
	}); 

function show_TOiR_report_Window() {
	TOiR_UsersRequestStoreMy.load();
    
	//Data_MileageSpeed_panel.load();
	//Data_Groups_MileageSpeed_panel.load();
	
	var TOiRReportWorkers_sm = Ext.create('Ext.selection.CheckboxModel');
	var TOiRReport_gridId = "TOiRReport_gridId";
	var TOiRReport_Workers_panel_Grid = new Ext.grid.GridPanel({
	   
	    id: TOiRReport_gridId,
		border: false,
	    store: TOiR_UsersRequestStoreMy,
	    autoScroll: true,
	    height: 180,
		selModel: TOiRReportWorkers_sm,  
		
		columns : [	     
	        {
	            //text : 'Бригада',
				text : report_toir.brigade,
	            //text : reports.name, 
	            dataIndex : 'name',
	            width:'97%',
	            sortable: true,
	            hideable: false
	            
	        }	        
	    ] 
		});
	
	var TOiRReportStatus_sm = Ext.create('Ext.selection.CheckboxModel');
	var TOiRReport_status_grid	= new Ext.grid.GridPanel({
	    //id: TOiRReport_gridId,
		border: false,
	    store: TOiR_StatusRoutesStore,
	    autoScroll: true,
	    height: 70,
		selModel: TOiRReportStatus_sm,  
		
		columns : [	     
	        {
	            //text : 'Статус',
				text : plan_toir.status,
	            //text : reports.name, 
	            dataIndex : 'name',
	            width: '97%',
	            sortable: true,
	            hideable: false
	            
	        }	        
	    ] 
		});
	//-----------grid Результату формування звіту--------------------------------------------------
	    var MileageSpeed_groupingFeature = Ext.create('Ext.grid.feature.Grouping',{
	        //groupHeaderTpl: 'Cuisine: {name} ({rows.length} Item{[values.rows.length > 1 ? "s" : ""]})'
	    });
		
		
	//---------------------------------------------------------------------------------------	
	//---------------Поля вибору дати-----------------------------------------
	var TOiRReport_date_fields = {
	//defaultType: 'datefield',
	bodyStyle: 'padding: 3 0 0 3',
	border: false,
	//width: '100%',
	height: 110,
	        items: [
				{
	            xtype: 'fieldset',
	            //title: 'Период c',
	            title: date.from,
	            defaultType: 'numberfield',
	            //defaults: { width: 280 },
	            items: [
				{
	                xtype: 'datefield',	format: 'Y-m-d',  altFormats: 'Y-m-d',  startDay: 1,/*fieldLabel: 'Период с',*/ labelAlign: 'top', style:'float:left; margin-left:0px;', id: 'TOiRReport_startdt', width: 99, value: new Date(), maxValue: new Date(), listeners:{ change: function(newValue, oldValue, eOpts){ Ext.getCmp('TOiRReport_enddt').setMinValue( this.getValue() ) }}
	            },
				{
	               xtype: 'numberfield', id: 'TOiRReport_hours_from', /*fieldLabel: 'Часы',*/ labelAlign: 'top', minValue: 0, maxValue: 23, step: 1, style:'float:left; margin-left:5px;', labelStyle: 'width: 30', width:50, value:0 
	            },
	            {
	               xtype: 'numberfield', id: 'TOiRReport_minets_from', /*fieldLabel: 'Мин.',*/ labelAlign: 'top', style:'float:left; margin-left:5px;', labelStyle: 'width: 30', minValue: 0, maxValue: 59, step: 1, width:50, value:0
	            },
	            {
	               xtype: 'numberfield', id: 'TOiRReport_seconds_from', /*fieldLabel: 'Сек.',*/ labelAlign: 'top', style:'float:left; margin-left:5px;', labelStyle: 'width: 30', minValue: 0, maxValue: 59, step: 1, width:50, value:0
	            }
				]},
				{
	            xtype: 'fieldset',
	            //title: 'Период по',
	            title: date.to,
	            defaultType: 'numberfield',
	            //defaults: { width: 280 },
	            items: [
	            {
	               xtype: 'datefield', format: 'Y-m-d', altFormats: 'Y-m-d', startDay: 1,/*fieldLabel: 'Период по',*/ labelAlign: 'top', id: 'TOiRReport_enddt', style:'float:left; margin-left:0px;', width: 99, value: new Date()
	            },
				{
	               xtype: 'numberfield', id: 'TOiRReport_hours_to', /*fieldLabel: 'Часы',*/ labelAlign: 'top', minValue: 0, maxValue: 23, step: 1, style:'float:left; margin-left:5px;', labelStyle: 'width: 30', width:50, value:23 
	            },
	            {
	               xtype: 'numberfield', id: 'TOiRReport_minets_to', /*fieldLabel: 'Мин.',*/ labelAlign: 'top', style:'float:left; margin-left:5px;', labelStyle: 'width: 30', minValue: 0, maxValue: 59, step: 1, width:50, value:59
	            },
	            {
	               xtype: 'numberfield', id: 'TOiRReport_seconds_to', /*fieldLabel: 'Сек.',*/ labelAlign: 'top', style:'float:left; margin-left:5px;', labelStyle: 'width: 30', minValue: 0, maxValue: 59, step: 1, width:50, value:59
	            }
				]}			
				
	        ]
	}	
	//-----------------------------------------------------------------------
	var TOiRReport_treePanel = {
	        //id: 'CarsRun_tree-panel',
	        //title: 'Выбор бригад',
			title: report_toir.selecting_brigades,
	        region:'south',
	        split: true,
	        height: 185,
			width: '100%',
	        //autoScroll: true,
			items:[TOiRReport_Workers_panel_Grid]
	    };
	
	var TOiRReport_panel_reportType = {
		title: 'Тип отчета',
		region:'north',
		height: 70,
		width: '100%',
		items: [{
			xtype: 'combo',
			store: reportTypeStore,
			margin: '8',
			queryMode: 'local',
			width: 180,
    		//labelWidth: 130,    	
    		id: 'select_report_type_id',
    		//fieldLabel: 'Показывать файлы за ',    		
    		displayField: 'name',
    		valueField: 'id',
    		value: 1,
    		listeners: {
    			select: function( combo, records, eOpts) {
    				if (records[0].get('id') == 2) {
    					TOiRReport_status_grid.hide();
    					TOiRReport_Workers_panel_Grid.hide();
    					
    				} else if (records[0].get('id') == 1) {
    					TOiRReport_status_grid.show();
    					TOiRReport_Workers_panel_Grid.show();
    				}
    			}
    		}
		}]
	};
	
	var TOiRReport_treePanel2 = {
	        //id: 'CarsRun_tree-panel2',
	        //title: 'Выбор статуса',
			title: 'Параметры отчета',
			//title: report_toir.select_status,
	       // title: reports.selecting_a_group_cars,
	        region:'south',
	        split: true,
	        height: 100,
			width: '100%',
			collapsible: true,
	        autoScroll: true,
			items:[TOiRReport_status_grid]
	};
	
	var TOiRReport_detailsPanel = {
	        //id: 'CarsRun_details-panel',
	        //title: 'Выбор периода',
			title: report_toir.select_the_period,
	        //title: reports.selection_period_and_maximum_speed,
	        region: 'center',
			split: true,
			height: 130,
			width: '100%',
	        //bodyStyle: 'padding-bottom:15px;background:#eee;',
	        autoScroll: true,
			items:[TOiRReport_date_fields]
	    };
	      

	
	if (!TOiRReportWindow){
        Ext.getBody().mask(all.loading);
        TOiRReportWindow = new Ext.Window({
            //layout : 'fit', 
            //title : 'Отчет',
			title : TOiR.report,
			//title : reports.report_overspeed,
			//iconCls: 'report',
            closeAction: 'destroy',
             
            width : ReportWindow.Width ,
            height : ReportWindow.Height,
            //minimizable: true,
            maximizable:true,
			constrainHeader: false,
            x : 2,
            y : 29,
			layout:'border',
            defaults: {
            collapsible: true,
            split: true,
              //bodyStyle: 'padding:15px'
            },
            listeners : {
                destroy : function(){
                	TOiRReportWindow = null;    
                }
            },
			//---------- bottom toolbar with two buttons Сформировать and Отмена-------------
			dockedItems: [
			{xtype: 'toolbar',
            dock: 'bottom',
            ui: 'footer',
            layout: {
                pack: 'center'
            },
                items: [{
                minWidth: 100,
                //text: 'Сформировать',
                text: all.generate,
				handler: function(){
                    
					var date_to =Ext.getCmp('TOiRReport_enddt').getRawValue();
                    var date_from =Ext.getCmp('TOiRReport_startdt').getRawValue();
                    var hours_from=Ext.getCmp('TOiRReport_hours_from').getValue(); 
                    var minuts_from=Ext.getCmp('TOiRReport_minets_from').getValue(); 
                    var seconds_from=Ext.getCmp('TOiRReport_seconds_from').getValue();
                    var hours_to=Ext.getCmp('TOiRReport_hours_to').getValue(); 
                    var minuts_to=Ext.getCmp('TOiRReport_minets_to').getValue(); 
                    var seconds_to=Ext.getCmp('TOiRReport_seconds_to').getValue();
                    
					if (hours_from<10) hours_from='0'+hours_from;
                    if (minuts_from<10) minuts_from='0'+minuts_from;
                    if (seconds_from<10) seconds_from='0'+seconds_from;
                    if (hours_to<10) hours_to='0'+hours_to;
                    if (minuts_to<10) minuts_to='0'+minuts_to;
                    if (seconds_to<10) seconds_to='0'+seconds_to;

                    date_from=date_from+' '+hours_from+':'+minuts_from+':'+seconds_from;
                    date_to=date_to+' '+hours_to+':'+minuts_to+':'+seconds_to;
								
					
                    
                    //TOiRReport_status_grid
                    var arrOfStatus = TOiRReport_status_grid.getSelectionModel().getSelection();
                    var arrOfWorkers = TOiRReport_Workers_panel_Grid.getSelectionModel().getSelection();
                    
                    var reportType = Ext.getCmp('select_report_type_id').getValue();
                    
                    var strOfStatusID = '';
                    var strOfWorkersID = '';
                     
                     
                     
                     $.each(arrOfWorkers,function(key,value)
                     {                    	 
                    	 strOfWorkersID += value.data.id + ',';
                     })
                     
                      $.each(arrOfStatus,function(key,value)
                     {
                    	  strOfStatusID += value.data.id + ',';
                     })
                     
                     strOfWorkersID = strOfWorkersID.slice(0, -1);
                     strOfStatusID = strOfStatusID.slice(0, -1);
                     
                     if((reportType == 2) || (strOfWorkersID  && strOfStatusID)){
					 
					 
                    	/* var myMask = new Ext.LoadMask(MileageSpeedWindow, {msg: all.msg_load_data});
					 myMask.show();*/
					 
                     $.post("app/TOiR_report.php",{func:'getResult',date_to: date_to, date_from: date_from, strOfWorkersID: strOfWorkersID,
                    	 strOfStatusID:strOfStatusID, reportType: reportType},function(data)  
                     {
                     
                         var ObjReportTOiR = eval("(" + data + ")");
                         console.log(ObjReportTOiR);
                         var grid_field=eval("(" + ObjReportTOiR.BodyReport + ")");
                         var model=eval("(" + ObjReportTOiR.ModelReport + ")");
                         var store_data=eval("(" + ObjReportTOiR.StoreReport + ")"); 
                         
                         Ext.define('TOirReport', {
                            extend: 'Ext.data.Model',
                            fields: model
                          });
                         var TOiRReportStore = Ext.create('Ext.data.Store', {
                                                         model: 'TOirReport',
                                                         data : store_data
                                                            });   
                           
                                  if(TOiRReport_result){ 
								Ext.getCmp('TOiRReport_result_id').remove(TOiRReport_result, true);
								Ext.getCmp('TOiRReport_result_id').doLayout();
								TOiRReport_result = null;
								}
								  
								  var grid_TOiRReport_result = "grid_MileageSpeed_result";
								  TOiRReport_result = new Ext.grid.GridPanel({
                                  //frame: true,
                                  forceFit: false,
                                  	// features: [MileageSpeed_groupingFeature],
                                    columnLines: true,
                                    border: false,
                                    width: '100%',
                                    store:TOiRReportStore,    
                                    id: grid_TOiRReport_result,
                                    autoScroll: true,
                                    dockedItems: [ {
                                    xtype: 'toolbar',
                                     border: false,
                                     items: [{                                        
                                    	 text: all.print,
                                         tooltip: all.print,
                                         iconCls:'print',
                                         handler:function() 
                                        {
                                            var ArrData = new Array();  
                                            ArrData = save_table_data_ReportTOiR(ObjReportTOiR.CountColumns); 
                                            export_print_ReportTOiR(ArrData, reportType);
                                        }
                                     }, '-', {                                        
                                        text: all.export_xls,
                                        tooltip: all.export_xls,
                                        iconCls:'xls',
                                        handler:function() 
                                        {
                                            var ArrData=new Array();  
                                            ArrData=save_table_data_ReportTOiR(ObjReportTOiR.CountColumns); 
                                            export_xls_ReportTOiR(ArrData, reportType);
                                        }
                                     },'-',{                                        
                                    	 text: all.export_csv,
                                         tooltip: all.export_csv,
                                        iconCls:'csv',
                                        handler:function() 
                                        {
                                            var ArrData = new Array(); 
                                            ArrData = save_table_data_ReportTOiR(ObjReportTOiR.CountColumns); 
                                            export_csv_ReportTOiR(ArrData, reportType);
                                        }
                                     }, {
                                    	 text: 'Создать заявку',
                                    	 tooltip: 'Создание заявки из отчета',
                                    	 id: 'create_request_button_id',
                                    	 hidden: true,
                                    	 listeners: {
                                    		beforerender: function () {
                                    			if (Ext.getCmp('select_report_type_id').getValue() == 2) {
                                       			 	Ext.getCmp('create_request_button_id').show();
                                       		 	}
                                    		} 
                                    	 }, 
                                    	 handler: function() {
                                    		 select = Ext.getCmp(grid_TOiRReport_result).getView().getSelectionModel().getSelection()[0];
                                    		 if (select) {
                                    			 var equipment_id = parseInt(select.get('result_15'));
                                    			 var id_client = parseInt(select.get('result_16'));
                                    			 var id_outlet = parseInt(select.get('result_17'));
                                    			 var region = select.get('result_12');
                                    			 var city = select.get('result_13');
                                    			 var address = select.get('result_14');
                                    			 var contact_number = select.get('result_18');
                                    			 var contact_name = select.get('result_19');
                                    			 var type_TT = select.get('result_20');
                                    			 var sales_contact_number = select.get('result_21');
												 
												 var tow = select.get('result_6');
												 var tonext = select.get('result_22');
												 
                                    			 show_TOiR_request_WindowAddEdit();
                                    			 Ext.getCmp('client_combo_id').setValue(id_client);
                                    			 TOiR_OutletStoreRequest.load({
                     								params: {
                     									clientID: id_client
                     								}
                     							 });
                                    			 TOiR_EquipmentStoreRequest.load({
                     								params: {
                     									outletID: id_outlet
                     								}
                     							 });
												 
												 TOiR_NextTypeTOStore.load({
                     								params: {
                     									type: tonext
                     								}
                     							 });
                                    		 	
                                    			 Ext.getCmp('outlet_combo_id').setValue(parseInt(id_outlet));
                                    			 Ext.getCmp('equipment_combo_id').setValue(parseInt(equipment_id));
                                    			 Ext.getCmp('request_id_region').setValue(region);
                                    			 Ext.getCmp('request_id_sity').setValue(city);
                                    			 Ext.getCmp('request_id_address').setValue(address);
                                    			 Ext.getCmp('request_id_client_number').setValue(contact_number);
                                    			 Ext.getCmp('request_id_contact_man').setValue(contact_name);
                                    			 Ext.getCmp('request_id_outlet_type').setValue(type_TT);
                                    			 Ext.getCmp('request_id_sales_man').setValue(sales_contact_number);
                                    			 
												 Ext.getCmp('request_id_typeeq').setDisabled( false );
												 Ext.getCmp('request_id_typeeq').setValue( tow );
												 
                                    			 
                                    			 var form = Ext.getCmp("TOiR_RequestFormId").getForm().getFields();
                                    			 form.each(function(item){
                                    				 item.enable(true);
                                    			 });
                                    			 
                                    		 } else {
                                    			 Ext.Msg.alert('Ошибка', 'Выберите строку для создания заявки');
                                    		 }
                                    		 console.log(select);
                                    	 }
                                     }]
                                    }],
                                    listeners: {
                                    	itemclick: function() {
                                    		
                                    	}
                                    },
                                    columns:grid_field 
    });
                                  //myMask.hide();								  
                                  Ext.getCmp('TOiRReport_result_id').add(TOiRReport_result);
                     });                 
                }else{ Ext.MessageBox.alert(all.error, report_toir.select_a_brigade_and_the_execution_status); }           
								 
				}
			    },{
                minWidth: 100,               
                text: all.cancel,
				handler: function(){
					TOiRReportWindow.destroy();                   
                        }
				}
			    ]}],
			//----------------------------------------------------------------------------------
                 items:[
				 {
                 //title: 'Параметры формирования отчета',
				 title: report_toir.parameters_of_the_report,
                 //title: 'Выбор автомобилей',
                 //title: reports.choosing_cars,
				 layout: 'border',
				 //border: false,
                 split:true,
				 region:'west',
                 margins: '5 0 5 5',
                 //cmargins: '5 5 5 5',
                 width: 325,
                 //minSize: '40%',
                 //maxSize: '40%',
                 items:[TOiRReport_panel_reportType, TOiRReport_treePanel, TOiRReport_treePanel2, TOiRReport_detailsPanel]			
			     },
				 {
                 //title: 'Результаты отчета',
                 title: reports.report_results,
                 layout: 'fit',
			     collapsible: false,
                 region:'center',
                 margins: '5 5 5 0',
                 id:'TOiRReport_result_id'
                 //items:[grid_MileageSpeed_result]
			     }
			     ],
            
        });
        TOiRReportWindow.show();
        Ext.getBody().unmask(all.loading);    
    }
   else { 
	   TOiRReportWindow.show();
    Ext.getBody().unmask(all.loading);
   }

}

function save_table_data_ReportTOiR(ColumsCount)
{
    var ColumnsArray=new Array(); 
    var i=0;
    TOiRReport_result.store.each
    (
        function(rec)
        {
            j=1;
            Str='';
            while (j<=(ColumsCount-8))
            {
                Str+=rec.get('result_'+j)+'/n';
                j++;  
            }
            ColumnsArray[i]=Str;
            i++;
        }
    )
    return ColumnsArray; 
}

    function export_xls_ReportTOiR(ArrayData, reportType)
    {
        
        $.post("app/TOiR_report.php",{func:'export_xls','ColumnsArray[]':ArrayData, reportType: reportType}, function(data){
                // alert(data);
                var newWin = window.open('app/TOiR_report.php?func=save_export_xls', '_blank');
                if(!newWin || newWin.closed || typeof newWin.closed=='undefined') 
				{ 
					Ext.MessageBox.alert(all.error, general.you_have_blocked_popups_allow_in_your_browser_settings_for_correct_operation);
				}
				//alert('Данные сохранены');
                    });                                   
            
    }
    
     function export_csv_ReportTOiR(ArrayData, reportType)
    {
        
        $.post("app/TOiR_report.php",{func:'export_csv','ColumnsArray[]':ArrayData, reportType: reportType}, function(data){
                // alert(data);
                 var newWin = window.open('app/TOiR_report.php?func=save_export_csv', '_blank');
                 if(!newWin || newWin.closed || typeof newWin.closed=='undefined') 
				{ 
					Ext.MessageBox.alert(all.error, general.you_have_blocked_popups_allow_in_your_browser_settings_for_correct_operation);
				}
				 //alert('Данные сохранены');
                    });                                   
            
    }
    
      function export_print_ReportTOiR(ArrayData, reportType)
    {
        
        $.post("app/TOiR_report.php",{func:'export_print','ColumnsArray[]':ArrayData, reportType: reportType}, function(data){
                // alert(data);
                 var newWin = window.open('app/TOiR_report.php?func=save_export_print', '_blank');
                 if(!newWin || newWin.closed || typeof newWin.closed=='undefined') 
				{ 
					Ext.MessageBox.alert(all.error, general.you_have_blocked_popups_allow_in_your_browser_settings_for_correct_operation);
				}
				 //alert('Данные сохранены');
                    });                                   
            
    }
