var reportSkuWindow = new Windows(SFA.ReportSku,900,620);
FormConstructor = new Forms();
var resultReportSku; 
/*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_ReportSku_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_ReportSku.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_ReportSku.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_ReportSku.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_ReportSku.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_ReportSku.php?func=region',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });
   
   dataRegion.load();
      
 /*   Ext.define('typeEmployer', 
   {
    extend: 'Ext.data.Model',
    fields: [ 'id','name']
   }); 
   
   var dataEmployer = new Ext.data.Store({
           model: 'typeEmployer',
           proxy: {
              type: 'ajax',
              url: 'app/SFA_ReportSku.php?func=employer',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });
   
   dataEmployer.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);
    
    dateFromReportSku = FormConstructor.CreateDateFieldLabelTop('Дата с:','',Start);
    /*hourseFromReportSku = FormConstructor.CreateNumberFieldLabelTop('Часы:',50,Hours,0,23);      
    minutsFromReportSku = FormConstructor.CreateNumberFieldLabelTop('Мин.:',50,Minutes,0,60);      
    secondsFromReportSku = FormConstructor.CreateNumberFieldLabelTop('Сек.:',50,Seconds,0,60);*/
    
    dateToReportSku=FormConstructor.CreateDateFieldLabelTop('Дата по:');
   /* hourseToReportSku=FormConstructor.CreateNumberFieldLabelTop('Часы:',50,Hours,0,23);      
    minutsToReportSku=FormConstructor.CreateNumberFieldLabelTop('Мин.:',50,Minutes,0,60);      
    secondsToReportSku=FormConstructor.CreateNumberFieldLabelTop('Сек.:',50,Seconds,0,60);*/
    
    selectTPSku = FormConstructor.CreateComboboxFieldProxy('Адресс ТТ','top',dataTP,'addressTP','id');
    selectTPSku.on('change',function(combo, newValue, oldValue, eOpts)
    {
         if (selectTPSku.getValue() != selectTPSku.getRawValue())
         {
            $.post("app/SFA_ReportSku.php",{func:'setAddress',idTP:newValue},function(data)
            {
             
            })
         }
    })
    
    selectCitySku = FormConstructor.CreateComboboxFieldProxy('Город','top',dataCity,'name','id');
    selectCitySku.on('change',function(combo, newValue, oldValue, eOpts)
    {
         if (selectCitySku.getValue() != selectCitySku.getRawValue())
         {
            $.post("app/SFA_ReportSku.php",{func:'setCity',idCity:newValue},function(data)
            {
                 
            })
         }
    })
    //selectEmployerSku = FormConstructor.CreateComboboxFieldLocal('Сотрудник','top',dataEmployer,'name','id');
    selectNetworkSku = FormConstructor.CreateComboboxFieldProxy('Сеть','top',dataNetwork,'name','id');
    selectNetworkSku.on('change',function(combo, newValue, oldValue, eOpts)
    {
         if (selectNetworkSku.getValue() != selectNetworkSku.getRawValue())
         {
            $.post("app/SFA_ReportSku.php",{func:'setNetwork',idNetwork:newValue},function(data)
            {
                //dataCity.load();   
            })
         }
    })
    
    selectRegionSku = FormConstructor.CreateComboboxFieldProxy('Регион','top',dataRegion,'name','id');
    selectRegionSku.on('change',function(combo, newValue, oldValue, eOpts)
    {
         if (selectRegionSku.getValue() != selectRegionSku.getRawValue())
         {
            $.post("app/SFA_ReportSku.php",{func:'setRegion',idRegion:newValue},function(data)
            {
                     
            })
         }
    })
    
    CreateReportSku = FormConstructor.CreateButtonTooltipText('Построить отчет','Кликните что бы построить отчет');
    CreateReportSku.handler=function()
                        { 
                           whereSku = CreateFiltreSku(selectTPSku.getRawValue(),selectCitySku.getValue(),selectNetworkSku.getValue(),selectRegionSku.getValue());
                           BuildReportSku(whereSku);         
                        }

    dateTimeSkuForm = 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: [dateFromReportSku,/*hourseFromReportSku,minutsFromReportSku,secondsFromReportSku,*/selectCitySku,selectTPSku]
               },
               {
                    xtype: 'fieldcontainer',
                    layout: {type: 'hbox',align: 'bottom'},
                    defaults:{margin: "5 5"},
                    items: [dateToReportSku,/*,hourseToReportSku,minutsToReportSku,secondsToReportSku*/selectNetworkSku,selectRegionSku]
               },
               {
                    xtype: 'fieldcontainer',
                    layout: {type: 'hbox',align: 'bottom'},
                    defaults:{margin: "5 5"},
                    items: [CreateReportSku]
               }]
    })   
    
    PanelInfoReportSku=FormConstructor.CreatePanelRegionCollaps('Параметры','north',190);
    PanelInfoReportSku.add(dateTimeSkuForm);
    //alert(reportSkuWindow.Width-200)
    resultSkuForm = Ext.create('Ext.form.Panel', 
    {                
        autoScroll: true,
        width:'100%',
        title:'Результат отчета',
        
    })   
    reportSkuForm = Ext.create('Ext.form.Panel', 
    {                
        items:[PanelInfoReportSku,resultSkuForm]
    })
   
   reportSkuWindow.CreateWindowSympleDestroy(reportSkuWindow,reportSkuForm); 
    reportSkuWindow.Window.show(); 
   
   // reportSkuWindow.CreateWindowSympleDestroyLayout(reportSkuWindow,reportSkuForm); 
    
}

function BuildReportSku(whereSku)
{
    var dateFrom = dateFromReportSku.getRawValue()/*+' '+hourseFromReportSku.getValue()+':'+minutsFromReportSku.getValue()+':'+secondsFromReportSku.getValue()*/;
    var dateTo = dateToReportSku.getRawValue()/*+' '+hourseToReportSku.getValue()+':'+minutsToReportSku.getValue()+':'+secondsToReportSku.getValue()*/;
   // alert(whereSku);
    reportSkuWindow.Window.mask('Обработка...');
    resultSkuForm.remove(resultReportSku); 
   
    $.post("app/SFA_ReportSku.php",{func:'getResult',dateTo:dateTo,dateFrom:dateFrom,whereSku:whereSku},function(data)  
    { 
           
          var ObjReport = eval("(" + data + ")"); 
          if (ObjReport.store.length > 1)
          {  
          var grid_field = eval("(" + ObjReport.tableRezult + ")");
          var model = eval("(" + ObjReport.model + ")");
          var store = eval("(" + ObjReport.store + ")"); 
          
           Ext.define('ReportSku', 
           {
                extend: 'Ext.data.Model',
                fields: model
           });
           var dataReportSku = Ext.create('Ext.data.Store', 
           {
                model: 'ReportSku',
                data : store
           });
           
           resultReportSku = new Ext.grid.GridPanel(
           {
                columnLines: true,
                layout: 'fit',
                store:dataReportSku,
                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 = GetDataSku(ObjReport.countColumn); 
                                        ExportxlsSku(ArrData);  
                                    }
                           }]
                 }],
                 columns:grid_field
           });
           
    
           reportSkuForm.remove(resultSkuForm);
           
           resultSkuForm = Ext.create('Ext.form.Panel', 
           {                
                //autoScroll: true,
                width:'100%',
                title:'Результат отчета',
                items:[resultReportSku]
           })   
           resultReportSku.setWidth(900-15);
           resultReportSku.setHeight(620-205);
           reportSkuForm.add(resultSkuForm);
           }
           else
           {
               alert('Данные отсутствуют');
           } 
           reportSkuWindow.Window.unmask('Обработка...');   
    })
}


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

    return  ColumnsArray; 
}

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

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

function CreateFiltreSku(idTP,idCity,idNetwork,idRegion)
{
    var where = '';
    if (idTP) {where += " AND address = '" + idTP + "'";}   
    if (idCity) {where += " AND id_city = '" + idCity + "'";}   
    if (idNetwork) {where += " AND id_network = " + idNetwork;}   
    if (idRegion) {where += " AND id_region = " + idRegion;} 
    
    return where;  
}
