var WindowCategory;
var GridCategory;
var StoreCategory;


var WindowBrand;
var GridBrand;
var id_category;
var StoreBrand;


var WindowProduct;
var GridProduct;
var id_category_brand;
var id_category;
var id_brand;

 //--- category
Ext.define('ModelCategory', {
    extend: 'Ext.data.Model',
    fields: ['id', 'name']
});

var StoreCategory = new Ext.data.Store({
        model: 'ModelCategory',
           proxy: {
              type: 'ajax',
              url: 'app/SFA_CRUDCategory.php?func=show',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });
 //--- brand
 Ext.define('ModelBrand', {
    extend: 'Ext.data.Model',
    fields: ['id', 'name']
});

var StoreBrand = new Ext.data.Store({
        model: 'ModelBrand',
           proxy: {
              type: 'ajax',
              url: 'app/SFA_CRUDBrand.php?func=show',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });
//--product
Ext.define('ModelProduct', {
    extend: 'Ext.data.Model',
    fields: ['id', 'article', 'name', 'id_brand', 'id_category', 'barcode', 'info', 'price', 'unit', 'begin_date', 'end_date', 'delivery_period', 'balance_stock', 'photo']
});
var StoreProduct = new Ext.data.Store({
        model: 'ModelProduct',
           proxy: {
              type: 'ajax',
              url: 'app/SFA_CRUDProduct.php?func=show',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });




   
function show_SFA_Category_Window()
{

  if (!WindowCategory || WindowCategory.Window==null)
  {
    
    createGridCategory();
    WindowCategory = new Windows('Категории продукции',400,300);       // create window
    WindowCategory.CreateWindowMaximizableDestroy(WindowCategory,GridCategory);

    // ------------------------------ create button ------------------------------------------  
    var ButtonAddCategory = Ext.create('Ext.button.Button', 
    { 
      text: 'Добавить',
      iconCls: 'adduser',
      handler: function(){showFormCategory();}
    });
    var ButtonCorrectCategory = Ext.create('Ext.button.Button', 
    { 
      text: 'Редактировать',
      iconCls: 'createtask',
      handler: function()
      {
        if (!id_row){msg('Выбрано 0 записей.', 'Выберите запись!');}
        else
        {
          showFormCategory(id_row);
          id_row=0;
        }
      }
    });
    var ButtonDeleteCategory = Ext.create('Ext.button.Button', 
    { 
      text: 'Удалить',    
      iconCls: 'deluser',
      disabled: true,
      itemId: 'delete',
      id: 'delete_category',
      handler: function()
      {
        if (!id_row){msg('Выбрано 0 записей', 'Выберите запись!');}
        else{
          deleteRow('Удаление', 'Вы точно хотите удалить данную категорию продуктов !?',id_row, 'Category');
        }
      }
    });
    
    var ButtonImportCategory = Ext.create('Ext.button.Button', 
    { 
      text: 'Импортировать',    
      iconCls: 'deluser',
      itemId: 'import',
      id: 'import_category',
      handler: function()
      {
        $.post('app/UploadProducts.php', {}, function(data)
        {
            StoreCategory.load();    
        })
      }
    });
    WindowCategory.Window.addDocked(
      {
        xtype: 'toolbar',
        dock: 'top',
        items:[ButtonAddCategory,ButtonCorrectCategory,ButtonDeleteCategory,ButtonImportCategory]
    });
  }

  WindowCategory.Window.show();
}

function createGridCategory()
{
    Ext.define('ModelCategory', 
    {
        extend: 'Ext.data.Model',
        fields: ['id', 'name']
    });
    
    StoreCategory = new Ext.data.Store({
        model: 'ModelCategory',
           proxy: {
              type: 'ajax',
              url: 'app/SFA_CRUDCategory.php?func=show',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
    });
   
   StoreCategory.load();
   
  GridCategory = Ext.create('Ext.grid.Panel',{
    selType: 'rowmodel',
    columnLines: true,
    store: StoreCategory,
    loadMask: true,
    border: false,
    autoScroll: true,
    columns : [
      {
        text : '№', 
        xtype:'rownumberer',
        width: 50
      },
      {
        text : 'Категория', 
        dataIndex : 'name',
        width:300,
        sortable: true,
        hideable: false/*,
        editor: 'textfield'*/

      }
    ],
    listeners:{
      itemclick: function(View,record,item,index,e,eOpts )
      {
        id_row = record.get('id');
        id_row =parseInt(id_row);
        var deleteButton = Ext.getCmp('delete_category');
        deleteButton.setDisabled(false);
      },
      itemdblclick: function(View,record,item,index,e,eOpts )
      {
        var selectCategory = record.get('id');
        ShowBrand(selectCategory);
      }
    }
  });
}

function showFormCategory(id_row)
{
  var idSelectingRow= id_row;

  $.post('app/SFA_CRUDCategory.php', {func:'edit',id:idSelectingRow}, function(data){
    var arrayDataCategory  = data.split('/t');

    id = parseInt(arrayDataCategory[0]);
    var name = arrayDataCategory[1];

    var FormConstructor = new Forms();
    var fieldName = FormConstructor.CreateTextFieldWidthPercent('Название','top','95%',name);
   
    var formCategory = Ext.create('Ext.form.Panel', 
      {
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        width: '100%',
        autoScroll: true,
        fieldDefaults: 
        {
          labelAlign: 'top',
          msgTarget: 'side'
        },                
        items:[fieldName]
    });
    
    var windowFormCategory = new Windows('Данные категории продукции',400,140);
    windowFormCategory.CreateWindowModal(windowFormCategory,formCategory);

    var saveDataCategory = Ext.create('Ext.button.Button', { 
      text: 'Сохранить',    
      iconCls: 'save',
      handler: function()
      {
        var name = fieldName.getValue();
      
        if (name=='')
        {
          msg('Ошибка!', 'Проверьте данные!');
          if (name==''){fieldName.markInvalid('Проверьте данные!');}
        }
        else 
        {
          $.post("app/SFA_CRUDCategory.php",{func:'update',id:id, name:name}, function(data){
            windowFormCategory.Window.destroy();
            GridCategory.store.load();
            GridCategory.getView().refresh();
            var deleteButton = Ext.getCmp('delete');
            deleteButton.setDisabled(true);
          });
        }
      }
    });
    var cancelInputDataCategory = Ext.create('Ext.button.Button', { 
      text: 'Отмена',    
      handler: function(){
        windowFormCategory.Window.destroy();
        GridCategory.store.load();
        GridCategory.getView().refresh();
        var deleteButton = Ext.getCmp('delete');
        deleteButton.setDisabled(true);
      }
    });
    windowFormCategory.Window.addDocked(
      {
        xtype: 'toolbar',
        dock: 'bottom',
        items:['->',saveDataCategory,'-',cancelInputDataCategory]
      });

    windowFormCategory.Window.show();
  });
}







//---------------- brand window

function ShowBrand(id_category_product)
{
  id_category = id_category_product;
  if (!WindowBrand || WindowBrand.Window==null)
  {
    StoreBrand.load({params:{id_category:id_category}});
    createGridBrand();
    WindowBrand = new Windows('Бренды продукции',362,300);       // create window
    WindowBrand.CreateWindowModal(WindowBrand,GridBrand);

    // ------------------------------ create button ------------------------------------------  
    var ButtonAddBrand = Ext.create('Ext.button.Button', 
    { 
      text: 'Добавить',
      iconCls: 'adduser',
      handler: function(){showFormBrand();}
    });
    var ButtonCorrectBrand = Ext.create('Ext.button.Button', 
    { 
      text: 'Редактировать',
      iconCls: 'createtask',
      handler: function()
      {
        if (!id_row){msg('Выбрано 0 записей.', 'Выберите запись!');}
        else
        {
          showFormBrand(id_row);
          id_row=0;
        }
      }
    });
    var ButtonDeleteBrand = Ext.create('Ext.button.Button', 
    { 
      text: 'Удалить',    
      iconCls: 'deluser',
      disabled: true,
      itemId: 'deleteBrand',
      id: 'deleteBrand',
      handler: function()
      {
        if (!id_row){msg('Выбрано 0 записей', 'Выберите запись!');}
        else{
          deleteRow('Удаление', 'Вы точно хотите удалить данный бренд продуктов !?',id_row, 'Brand', id_category);
        }
      }
    });
    WindowBrand.Window.addDocked(
      {
        xtype: 'toolbar',
        dock: 'top',
        items:[ButtonAddBrand,ButtonCorrectBrand,ButtonDeleteBrand]
    });
  }

  WindowBrand.Window.show();
}


   
function createGridBrand()
{
  GridBrand = Ext.create('Ext.grid.Panel',{
    selType: 'rowmodel',
    columnLines: true,
    store: StoreBrand,
    loadMask: true,
    border: false,
    autoScroll: true,
    columns : [
      {
        text : '№', 
        xtype:'rownumberer',
        width: 50
      },
      {
        text : 'Бренд', 
        dataIndex : 'name',
        width:300,
        sortable: true,
        hideable: false,
        editor: 'textfield'

      }
    ],
    listeners:{
      itemclick: function(View,record,item,index,e,eOpts )
      {
        id_row = record.get('id');
        //id_row =parseInt(id_row);
        var deleteButton = Ext.getCmp('deleteBrand');
        deleteButton.setDisabled(false);
      },
      itemdblclick: function(View,record,item,index,e,eOpts )
      {
        var selectBrand = record.get('id');
        ShowWindowProduct(id_category,selectBrand);
      }
    }
  });
}

function showFormBrand(id_row)
{
  var idSelectingRow= id_row;

  $.post('app/SFA_CRUDBrand.php', {func:'edit',id:idSelectingRow}, function(data){
    var arrayDataBrand  = data.split('/t');

    id = parseInt(arrayDataBrand[0]);
    var name = arrayDataBrand[1];

    var FormConstructor = new Forms();
    var fieldName = FormConstructor.CreateTextFieldWidthPercent('Название','top','95%',name);
    var fieldCode = FormConstructor.CreateTextFieldWidthPercent('Код','top','95%',name);
   
    var formBrand = Ext.create('Ext.form.Panel', 
      {
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        width: '100%',
        autoScroll: true,
        fieldDefaults: 
        {
          labelAlign: 'top',
          msgTarget: 'side'
        },                
        items:[fieldCode,fieldName]
    });
    
    var windowFormBrand = new Windows('Данные бренда продукции',400,180);
    windowFormBrand.CreateWindowModal(windowFormBrand,formBrand);

    var saveDataBrand = Ext.create('Ext.button.Button', { 
      text: 'Сохранить',    
      iconCls: 'save',
      handler: function()
      {
        var code = fieldCode.getValue();
        var name = fieldName.getValue();
      
        if (name=='' || code == '')
        {
          msg('Ошибка!', 'Проверьте данные!');
          if (name==''){fieldName.markInvalid('Проверьте данные!');}
          if (code==''){fieldCode.markInvalid('Проверьте данные!');}
        }
        else 
        {
          $.post("app/SFA_CRUDBrand.php",{func:'update',id:id, name:name, id_category:id_category, code:code}, function(data){
            windowFormBrand.Window.destroy();
            GridBrand.store.load({params:{id_category:id_category}});
            GridBrand.getView().refresh();
            var deleteButton = Ext.getCmp('deleteBrand');
            deleteButton.setDisabled(true);
          });
        }
      }
    });
    var cancelInputDataBrand = Ext.create('Ext.button.Button', { 
      text: 'Отмена',    
      handler: function(){
        windowFormBrand.Window.destroy();
        GridBrand.store.load({params:{id_category:id_category}});
        GridBrand.getView().refresh();
        var deleteButton = Ext.getCmp('deleteBrand');
        deleteButton.setDisabled(true);
      }
    });
    windowFormBrand.Window.addDocked(
      {
        xtype: 'toolbar',
        dock: 'bottom',
        items:['->',saveDataBrand,'-',cancelInputDataBrand]
      });

    windowFormBrand.Window.show();
  });
}




// ----- product

function ShowWindowProduct(id_category_product,id_brand_product)
{
  id_category = id_category_product;
  id_brand = id_brand_product;
  if (!WindowProduct || WindowProduct.Window==null)
  {
    StoreProduct.load({params:{id_category:id_category, id_brand:id_brand}});
    createGridProduct();
    WindowProduct = new Windows('Продукты',715,400);       // create window
    WindowProduct.CreateWindowModal(WindowProduct,GridProduct);

    // ------------------------------ create button ------------------------------------------  
    var ButtonAddProduct = Ext.create('Ext.button.Button', 
    { 
      text: 'Добавить',
      iconCls: 'adduser',
      handler: function(){showFormProduct();}
    });
    var ButtonCorrectProduct = Ext.create('Ext.button.Button', 
    { 
      text: 'Редактировать',
      iconCls: 'createtask',
      handler: function()
      {
        if (!id_row){msg('Выбрано 0 записей.', 'Выберите запись!');}
        else
        {
          showFormProduct(id_row);
          id_row=0;
        }
      }
    });
    var ButtonDeleteProduct = Ext.create('Ext.button.Button', 
    { 
      text: 'Удалить',    
      iconCls: 'deluser',
      disabled: true,
      itemId: 'deleteProduct',
      id: 'deleteProduct',
      handler: function()
      {
        if (!id_row){msg('Выбрано 0 записей', 'Выберите запись!');}
        else{
          deleteRow('Удаление', 'Вы точно хотите удалить данный продукт !?',id_row, 'Product', id_category, id_brand);
        }
      }
    });
    WindowProduct.Window.addDocked(
      {
        xtype: 'toolbar',
        dock: 'top',
        items:[ButtonAddProduct,ButtonCorrectProduct,ButtonDeleteProduct]
    });
  }

  WindowProduct.Window.show();
}

function createGridProduct()
{
  GridProduct = Ext.create('Ext.grid.Panel',{
    selType: 'rowmodel',
    columnLines: true,
    store: StoreProduct,
    loadMask: true,
    border: false,
    autoScroll: true,
    columns : [
      {
        text : '№', 
        xtype:'rownumberer',
        width: 50
      },
      {
        text : 'Артикль', 
        dataIndex : 'article',
        width:100,
        sortable: true,
        hideable: false,
      },
      {
        text : 'Название', 
        dataIndex : 'name',
        width:100,
        sortable: true,
        hideable: false,
      },
      {
        text : 'Штрихкод', 
        dataIndex : 'barcode',
        width:100,
        sortable: true,
        hideable: false,
      },
      {
        text : 'Цена', 
        dataIndex : 'price',
        width:100,
        sortable: true,
        hideable: false,
      },
      {
        text : 'Срок доставки', 
        dataIndex : 'delivery_period',
        width:100,
        sortable: true,
        hideable: false,
      },{
        text : 'Остаток на складе', 
        dataIndex : 'balance_stock',
        width:150,
        sortable: true,
        hideable: false,
      }
    ],
    listeners:{
      itemclick: function(View,record,item,index,e,eOpts )
      {
        id_row = record.get('id');
        id_row =parseInt(id_row);
        var deleteButton = Ext.getCmp('deleteProduct');
        deleteButton.setDisabled(false);
      },
      itemdblclick: function(View,record,item,index,e,eOpts )
      {
        var selectProduct = record.get('id');
        showFormProduct(selectProduct);
      }
    }
  });
}

function showFormProduct(id_row)
{
  var idSelectingRow= id_row;

  $.post('app/SFA_CRUDProduct.php', {func:'edit',id:idSelectingRow}, function(data){
    var arrayDataProduct  = data.split('/t');

    id = parseInt(arrayDataProduct[0]);
    var article = arrayDataProduct[1];
    var name = arrayDataProduct[2];
    id_category_brand = parseInt(arrayDataProduct[3]);
    var barcode = arrayDataProduct[4];
    var info = arrayDataProduct[5];
    var price = arrayDataProduct[6];
    var unit = arrayDataProduct[7];
    var begin_date = arrayDataProduct[8];
    var end_date = arrayDataProduct[9];
    var delivery_period = parseInt(arrayDataProduct[10]);
    var balance_stock = parseInt(arrayDataProduct[11]);

    var FormConstructor = new Forms();
    var fieldArticle = FormConstructor.CreateTextFieldWidthPercent('Артикль','top','95%',article);
    var fieldName = FormConstructor.CreateTextFieldWidthPercent('Название','top','95%',name);
    //StoreCategory.load();
    //var fieldId_category = FormConstructor.CreateComboboxFieldProxyWidthPercent('Категория продукта','top',StoreProductCategory,'name','id','95%',id_category);
    var fieldBarcode = FormConstructor.CreateTextFieldWidthPercent('Штрихкод','top','95%',barcode);
    var fieldInfo = FormConstructor.CreateTextAreaFieldWidthPercent('Дополнительная информация','top','95%',2,info);
    var fieldPrice = FormConstructor.CreateTextFieldWidthPercent('Цена','top','95%',price);
    var fieldUnit = FormConstructor.CreateTextFieldWidthPercent('Единица измерения','top','95%',unit);
    var fieldBegin_date = FormConstructor.CreateDateField('Дата начала продаж','top','120',begin_date,'Y-m-d');
    var fieldEnd_date = FormConstructor.CreateDateField('Дата конца продаж','top','120',end_date,'Y-m-d');
    var fieldDelivery_period = FormConstructor.CreateNumberFieldStepRead('Срок доставки','top',120,130,delivery_period,1,30,1,false);
    var fieldВalance_stock = FormConstructor.CreateTextFieldWidthPercent('Остаток на складе','top','95%',balance_stock);
   
    var formProduct = Ext.create('Ext.form.Panel', 
      {
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        width: '100%',
        autoScroll: true,
        fieldDefaults: 
        {
          labelAlign: 'top',
          msgTarget: 'side'
        },                
        items:[{
                              xtype: 'fieldcontainer',
                              anchor: '100%',
                              layout:'column',
                              items:[{
                                  xtype: 'fieldcontainer',
                                  columnWidth:.5,
                                  layout: 'anchor',
                                  items: [fieldArticle,fieldName,fieldBarcode,fieldInfo,fieldPrice]
                                },
                                {
                                  xtype: 'container',
                                  columnWidth:.5,
                                  layout: 'anchor',
                                  items: [fieldUnit,fieldBegin_date,fieldEnd_date,fieldDelivery_period,fieldВalance_stock]
                              }]
                          }]
    });
    
    var windowFormProduct = new Windows('Данные продукции',600,370);
    windowFormProduct.CreateWindowModal(windowFormProduct,formProduct);

    var saveDataProduct = Ext.create('Ext.button.Button', { 
      text: 'Сохранить',    
      iconCls: 'save',
      handler: function()
      {
        var article = fieldArticle.getValue();
        var name = fieldName.getValue();
        //var id_category = fieldId_category.getValue();
        var barcode = fieldBarcode.getValue();
        var info = fieldInfo.getValue();
        var price = fieldPrice.getValue();
        var unit = fieldUnit.getValue();
        var begin_date = fieldBegin_date.getRawValue();
        var end_date = fieldEnd_date.getRawValue();
        var delivery_period = fieldDelivery_period.getValue();
        var balance_stock = fieldВalance_stock.getValue();
      
        if (name=='')
        {
          msg('Ошибка!', 'Проверьте данные!');
          if (name==''){fieldName.markInvalid('Проверьте данные!');}
        }
        else 
        {
          $.post("app/SFA_CRUDProduct.php",{func:'update',id:id, article:article,  name:name, id_category_brand:id_category_brand, barcode:barcode, info:info, price:price, unit:unit, begin_date:begin_date, end_date:end_date, delivery_period:delivery_period, balance_stock:balance_stock, id_category:id_category, id_brand:id_brand}, function(data){
            windowFormProduct.Window.destroy();
            GridProduct.store.load({params:{id_category:id_category, id_brand:id_brand}});
            GridProduct.getView().refresh();
            var deleteButton = Ext.getCmp('deleteProduct');
            deleteButton.setDisabled(true);
          });
        }
      }
    });
    var cancelInputDataProduct = Ext.create('Ext.button.Button', { 
      text: 'Отмена',    
      handler: function(){
        windowFormProduct.Window.destroy();
        GridProduct.store.load({params:{id_category:id_category, id_brand:id_brand}});
        GridProduct.getView().refresh();
        var deleteButton = Ext.getCmp('delete');
        deleteButton.setDisabled(true);
      }
    });
    windowFormProduct.Window.addDocked(
      {
        xtype: 'toolbar',
        dock: 'bottom',
        items:['->',saveDataProduct,'-',cancelInputDataProduct]
      });

    windowFormProduct.Window.show();
  });
}