var reportQuestionWindow = new Windows(SFA.ReportQuestion,900,620);
FormConstructor = new Forms();
var resultReportQuestion; 
/*var CarsStop_result;
var data=new Array();
var car_name=new Array();
var driver=new Array();
var employer=new Array();
var route=new Array();
var time_start_route=new Array();
var time_route=new Array();
var mileage=new Array();
var time_not_work=new Array();
var time_holiday=new Array();
var time_start_stop=new Array();
var time_stop=new Array(); 
check = 0;*/

Ext.Loader.setPath('Ext.ux', '../js/ext-4.1-pr1/docs/output');
Ext.require([
	'Ext.selection.CheckboxModel'
]);
/*Ext.define('CarsStop_panel', {
    extend: 'Ext.data.Model',
    fields: [ {name: 'Name'},
	          {name: 'imei'}//,
			  //{name: 'check', type: 'bool'}
			]
});
      var Data_CarsStop_panel = new Ext.data.Store({
        model: 'CarsStop_panel',
           proxy: {
              type: 'ajax',
              url: 'scripts/Cars.php',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });
   Data_CarsStop_panel.load();*/
   
   
//-----------------window-----------------------------------------------------   
function show_SFA_ReportQuestion_Window()
{
      Ext.define('init', {
    extend: 'Ext.data.Model',
    fields: [ 'id','addressTP']
});


var dataInit = new Ext.data.Store({
           autoLoad:true, 
           model: 'init',
           proxy: {
              type: 'ajax',
              url: 'app/SFA_ReportQuestion.php?func=initData',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });
   
   dataInit.load(); 
   
    
    Ext.define('typeTP', {
    extend: 'Ext.data.Model',
    fields: [ 'id','addressTP']
});


var dataTP = new Ext.data.Store({
          autoLoad:true,
           model: 'typeTP',
           proxy: {
              type: 'ajax',
              url: 'app/SFA_ReportQuestion.php?func=tradePoint',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });
   
   dataTP.load(); 
   
   Ext.define('typeCity', 
   {
    extend: 'Ext.data.Model',
    fields: [ 'id','name']
   }); 
   
   var dataCity = new Ext.data.Store({
           autoLoad:true,
           model: 'typeCity',
           proxy: {
              type: 'ajax',
              url: 'app/SFA_ReportQuestion.php?func=city',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });
   
   dataCity.load();  
   
   
   Ext.define('typeNetwork', 
   {
    extend: 'Ext.data.Model',
    fields: [ 'id','name']
   }); 
   
   var dataNetwork = new Ext.data.Store({
           autoLoad:true,
           model: 'typeNetwork',
           proxy: {
              type: 'ajax',
              url: 'app/SFA_ReportQuestion.php?func=network',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });
   
   dataNetwork.load(); 
   
   
   Ext.define('typeRegion', 
   {
    extend: 'Ext.data.Model',
    fields: [ 'id','name']
   }); 
   
   var dataRegion = new Ext.data.Store({
           autoLoad:true,
           model: 'typeRegion',
           proxy: {
              type: 'ajax',
              url: 'app/SFA_ReportQuestion.php?func=region',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });
   
   dataRegion.load();
    
    Year = new Date().getFullYear();
    Month = new Date().getMonth();
    Day = new Date().getDate();
    Hours=new Date().getHours();
    Minutes=new Date().getMinutes();
    Seconds=new Date().getSeconds();
    Month=Month+1; 
    
    if (Month<10) Month='0'+Month;
    if (Day<10) Day='0'+Day;
    if (Hours<10) Hours='0'+Hours;
    if (Minutes<10) Minutes='0'+Minutes;
    if (Seconds<10) Seconds='0'+Seconds; 

    FromDate=Year+'-'+Month+'-'+Day;
        
    PrevDay=FromDate.replace(/-/g,"/");
    var converted = Date.parse(PrevDay);
    PrevDay=converted-24*60*60*1000;
    Start = new Date(PrevDay);
    
    dateFromReportQuestion = FormConstructor.CreateDateFieldLabelTop('Дата с:','',Start);
    hourseFromReportQuestion = FormConstructor.CreateNumberFieldLabelTop('Часы:',50,Hours,0,23);      
    minutsFromReportQuestion = FormConstructor.CreateNumberFieldLabelTop('Мин.:',50,Minutes,0,60);      
    secondsFromReportQuestion = FormConstructor.CreateNumberFieldLabelTop('Сек.:',50,Seconds,0,60);
    
    dateToReportQuestion=FormConstructor.CreateDateFieldLabelTop('Дата по:');
    hourseToReportQuestion=FormConstructor.CreateNumberFieldLabelTop('Часы:',50,Hours,0,23);      
    minutsToReportQuestion=FormConstructor.CreateNumberFieldLabelTop('Мин.:',50,Minutes,0,60);      
    secondsToReportQuestion=FormConstructor.CreateNumberFieldLabelTop('Сек.:',50,Seconds,0,60);
    
    selectTPQuestion = FormConstructor.CreateComboboxFieldProxy('Адресс ТТ','top',dataTP,'addressTP','id');
    selectTPQuestion.on('change',function(combo, newValue, oldValue, eOpts)
    {
         if (selectTPQuestion.getValue() != selectTPQuestion.getRawValue())
         {
            $.post("app/SFA_ReportQuestion.php",{func:'setAddress',idTP:newValue},function(data)
            {
             
            })
         }
    })
    
    selectCityQuestion = FormConstructor.CreateComboboxFieldProxy('Город','top',dataCity,'name','id');
    selectCityQuestion.on('change',function(combo, newValue, oldValue, eOpts)
    {
         if (selectCityQuestion.getValue() != selectCityQuestion.getRawValue())
         {
            $.post("app/SFA_ReportQuestion.php",{func:'setCity',idCity:newValue},function(data)
            {
                 
            })
         }
    })
    //selectEmployerQuestion = FormConstructor.CreateComboboxFieldLocal('Сотрудник','top',dataEmployer,'name','id');
    selectNetworkQuestion = FormConstructor.CreateComboboxFieldProxy('Сеть','top',dataNetwork,'name','id');
    selectNetworkQuestion.on('change',function(combo, newValue, oldValue, eOpts)
    {
         if (selectNetworkQuestion.getValue() != selectNetworkQuestion.getRawValue())
         {
            $.post("app/SFA_ReportQuestion.php",{func:'setNetwork',idNetwork:newValue},function(data)
            {
                //dataCity.load();   
            })
         }
    })
    
    selectRegionQuestion = FormConstructor.CreateComboboxFieldProxy('Регион','top',dataRegion,'name','id');
    selectRegionQuestion.on('change',function(combo, newValue, oldValue, eOpts)
    {
         if (selectRegionQuestion.getValue() != selectRegionQuestion.getRawValue())
         {
            $.post("app/SFA_ReportQuestion.php",{func:'setRegion',idRegion:newValue},function(data)
            {
                     
            })
         }
    })
    
    CreateReportQuestion = FormConstructor.CreateButtonTooltipText('Построить отчет','Кликните что бы построить отчет');
    CreateReportQuestion.handler=function()
                        { 
                            BuildReportQuestion();         
                        }

    dateTimeQuestionForm = Ext.create('Ext.form.Panel', 
    {                
        layout: 'fit',
        layout:{type: 'vbox',align: 'left'},
        items:[{
                    xtype: 'fieldcontainer',
                    layout: {type: 'hbox',align: 'bottom'},
                    defaults:{margin: "5 5"},
                    items: [dateFromReportQuestion/*,hourseFromReportQuestion,minutsFromReportQuestion,secondsFromReportQuestion*/,selectCityQuestion,selectTPQuestion]
               },
               {
                    xtype: 'fieldcontainer',
                    layout: {type: 'hbox',align: 'bottom'},
                    defaults:{margin: "5 5"},
                    items: [dateToReportQuestion/*,hourseToReportQuestion,minutsToReportQuestion,secondsToReportQuestion*/,selectNetworkQuestion,selectRegionQuestion]
               },
               {
                    xtype: 'fieldcontainer',
                    layout: {type: 'hbox',align: 'bottom'},
                    defaults:{margin: "5 5"},
                    items: [CreateReportQuestion]
               }]
    })   
    
    PanelInfoReportQuestion=FormConstructor.CreatePanelRegionCollaps('Параметры','north',190);
    PanelInfoReportQuestion.add(dateTimeQuestionForm);
    //alert(reportQuestionWindow.Width-200)
    resultQuestionForm = Ext.create('Ext.form.Panel', 
    {                
        autoScroll: true,
        width:'100%',
        title:'Результат отчета',
        
    })   
    reportQuestionForm = Ext.create('Ext.form.Panel', 
    {                
        items:[PanelInfoReportQuestion,resultQuestionForm]
    })
   
   reportQuestionWindow.CreateWindowSympleDestroy(reportQuestionWindow,reportQuestionForm); 
    reportQuestionWindow.Window.show(); 
   
   // reportQuestionWindow.CreateWindowSympleDestroyLayout(reportQuestionWindow,reportQuestionForm); 
    
}

function BuildReportQuestion()
{
    dateFrom = dateFromReportQuestion.getRawValue()/*+' '+hourseFromReportQuestion.getValue()+':'+minutsFromReportQuestion.getValue()+':'+secondsFromReportQuestion.getValue()*/;
    dateTo = dateToReportQuestion.getRawValue()/*+' '+hourseToReportQuestion.getValue()+':'+minutsToReportQuestion.getValue()+':'+secondsToReportQuestion.getValue()*/;
    reportQuestionWindow.Window.mask('Обработка...');
    resultQuestionForm.remove(resultReportQuestion); 
    $.post("app/SFA_ReportQuestion.php",{func:'getResult',dateTo:dateTo,dateFrom:dateFrom},function(data)  
    { 
          var ObjReport = eval("(" + data + ")");   
          var grid_field = eval("(" + ObjReport.tableRezult + ")");
          var model = eval("(" + ObjReport.model + ")");
          //var store = eval("(" + ObjReport.store + ")"); 
          
           Ext.define('ReportQuestion', 
           {
                extend: 'Ext.data.Model',
                fields: model
           });
           /*var dataReportQuestion = Ext.create('Ext.data.Store', 
           {
                model: 'ReportQuestion',
                data : store
           });*/
           //alert(1)
           var dataReportQuestion = new Ext.data.Store(
           {
            model: 'ReportQuestion',
            buffered: true,
            remoteGroup: true,
            leadingBufferZone: 300,
            pageSize: 100,
            proxy: 
            {
              type: 'ajax',
              url: 'app/SFA_ReportQuestion.php?func=getData&dateTo=' + dateTo + '&dateFrom=' + dateFrom,
              reader: 
              {
                  type: 'json',
                  root: 'rows',
                  totalProperty: 'totalCount'
              },
              simpleSortMode: true,
              simpleGroupMode: true,
              groupParam: 'sort',
              groupDirectionParam: 'dir'
            },
            sorters: 
            [{
                property: 'threadid',
                direction: 'ASC'
            }],
            autoLoad: true,
            listeners: {

            // This particular service cannot sort on more than one field, so if grouped, disable sorting
            groupchange: function(store, groupers) {
                var sortable = !store.isGrouped(),
                    headers = grid.headerCt.getVisibleGridColumns(),
                    i, len = headers.length;
                
                for (i = 0; i < len; i++) {
                    headers[i].sortable = (headers[i].sortable !== undefined) ? headers[i].sortable : sortable;
                }
            },

            // This particular service cannot sort on more than one field, so if grouped, disable sorting
            beforeprefetch: function(store, operation) {
                if (operation.groupers && operation.groupers.length) {
                    delete operation.sorters;
                }
            }
        }
            
          });
          
           dataReportQuestion.load();
           
           resultReportQuestion = new Ext.grid.GridPanel(
           {
                columnLines: true,
                layout: 'fit',
                store:dataReportQuestion,
                border: false,
                columns:grid_field,
                selType: 'rowmodel',    
                autoScroll: true,
                dockedItems: [ 
                {
                    xtype: 'toolbar',
                    items: [{
                                    itemId: 'CarsStop_xls',
                                    text:'Экспорт в xls',
                                    tooltip:'Экспорт в xls',
                                    iconCls:'xls',
                                    handler:function() 
                                    {
                                        var ArrData = new Array();
                                        ArrData = GetDataQuestion(ObjReport.countColumn); 
                                        ExportxlsQuestion(ArrData);  
                                    }
                           }]
                 }],
                 columns:grid_field
    });

    
           reportQuestionForm.remove(resultQuestionForm);
           
           resultQuestionForm = Ext.create('Ext.form.Panel', 
           {                
                //autoScroll: true,
                width:'100%',
                title:'Результат отчета',
				layout: {
				type: 'hbox',
				align: 'stretch'
				},
				defaults: { flex: 1 },
                items:[resultReportQuestion]
           })
           //alert(resultQuestionForm.getVeiw().getWidth());   
           //resultReportQuestion.setWidth(900-15);
           //resultReportQuestion.setHeight(620-205);
           reportQuestionForm.add(resultQuestionForm);
            
           reportQuestionWindow.Window.unmask('Обработка...');   
    })
}


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

    return  ColumnsArray; 
}

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

    
function alertObj(obj) 
{ 
    var str = ""; 
    for(k in obj) { 
        str += k+": "+ obj[k]+"\r\n"; 
    } 
    alert(str); 
}
