


Ext.define('ModelJob', {
    extend: 'Ext.data.Model',
    fields: ['id', 'date', 'job', 'name_created', 'name_performer', 'state']
});

var StoreJob = new Ext.data.Store({
        model: 'ModelJob',
		pageSize: 100,
		remoteSort: true,
           proxy: {
              type: 'ajax',
              url: 'app/SFA_CRUDJob.php?func=show',
              reader: {
                  type: 'json',
                  root: 'rows',
				  totalProperty: 'total'
              },
		  sorters: [{
            property: 'name',
            direction: 'ASC'
        }]
			  
          }
   });
// ----------------------------------Window ------------------------------------
var WindowJob;       // variable creating window declaration

function show_SFA_Job_Window()
{
  
  if (!WindowJob || WindowJob.Window==null)
  {
    WindowJob = new Windows('Задания',725,380);
    StoreJob.load();
    createGridJob();
    WindowJob.CreateWindowMaximizableDestroy(WindowJob,GridJob);
   

  // ------------------------------ create button ------------------------------------------  
    var addJob = Ext.create('Ext.button.Button', { 
          text: 'Добавить',
          iconCls: 'adduser',
          handler: function(){showFormJob();}
    });
    var correctJob = Ext.create('Ext.button.Button', { 
          text: 'Редактировать',
          iconCls: 'createtask',
          handler: function(){
                    if (!select){msg('Выбрано 0 записей.', 'Выберите запись!');}
                    else{
                    showFormJob(select);
                    select=0;
                    }
          }
    });
    var deleteJob = Ext.create('Ext.button.Button', { 
        text: 'Удалить',    
        iconCls: 'deluser',
        disabled: true,
        itemId: 'delete',
        id: 'delete_job',
        handler: function(){
                       if (!select){msg('Выбрано 0 записей', 'Выберите задачу!');}
                       else{
                       msguam_job('Удаление', 'Вы точно хотите удалить выбранную задачу!?',select);
                       }
                  }
    });
    WindowJob.Window.addDocked(
    {
      xtype: 'toolbar',
      dock: 'top',
      items:[addJob,correctJob,deleteJob]
    });
  }
  
//---------------------------------------------------------------------------------------- 
 
  WindowJob.Window.show();
  
   
}

// ------------------------------------- create Grid --------------------------------------    
function createGridJob()
{
  
  var PagingToolbar = Ext.create('Ext.PagingToolbar', {
			//width: 400,
			border:false,
			frame:false,
			store: StoreJob,
            displayInfo: true,
            displayMsg: 'Показано {0} - {1} с {2}',
            emptyMsg: "Нет даных"/*,
			items:[
			],
			listeners: {
              change: function(){
			  
			  }
			}*/
}); 
  
  
  var IdGridJob = "grid_id_job";
  GridJob = new Ext.grid.GridPanel({
  selType: 'rowmodel',
  columnLines: true,
  //plugins: [rowEditing_report],
  id: 'IdGridJob',
  store: StoreJob,
  columns:[
  {
    text : '№', 
    dataIndex : 'id',
    width:40,
    sortable: true,
    //id: 'id_uam'
  },
  {
    text : 'Назначил', 
    dataIndex : 'name_created',
    width: 140,
    sortable: true,
    //id: 'login_uam'
  },
  {
    text : 'Дата', 
    dataIndex : 'date',
    width:140,
    sortable: true/*,
    id: 'firstName_uam'*/
  },
  {
    text : 'Задание', 
    dataIndex : 'job',
    width: 140,
    sortable: true/*,
    id: 'lastName_uam'*/
  },
  {
    text : 'Исполнитель', 
    dataIndex : 'name_performer',
    width: 125,
    sortable: true/*,
    id: 'role_uam'*/
  },
  {
    text : 'Статус', 
    dataIndex : 'state',
    width: 125,
    sortable: true,
    xtype: 'booleancolumn', 
    trueText: 'Выполнена', 
    falseText: 'Открыта'
  }
  ],
  bbar: [
		PagingToolbar
  ],
  listeners:
  {
    itemclick: function(View,record,item,index,e,eOpts )
    {
      select = record.get('id');
      select =parseInt(select);
      var deleteButton = Ext.getCmp('delete_job');
      deleteButton.setDisabled(false);
    },
    itemdblclick: function(View,record,item,index,e,eOpts )
    {
      select = record.get('id');
      select=parseInt(select);
      //showUsers_adm_menFormEdit(select);
      showFormJob(select);
      select=0;
    }
  }
  });
}

// ------------------------------- Create Form for Add and Correct User Data ------------------------

function showFormJob(select)
{
  id_job=select;

  $.post('app/SFA_CRUDJob.php', {func:'editJob',id_job:id_job}, function(data){
  data_edit_row = data.split('/t');

      id_job = parseInt(data_edit_row[0]);
      id_user_created = parseInt(data_edit_row[1]);
      date = data_edit_row[2];
      job = data_edit_row[3];
      id_user_performer = parseInt(data_edit_row[4]);
      state = parseInt(data_edit_row[5]);
      
  
  
  var FormConstructor = new Forms();

  Data_boss_id.load();
  var formCreatedJob = FormConstructor.CreateComboboxFieldProxyWidthPercent('Назначил','top',Data_boss_id,'FIO_B','id','95%',id_user_created);
  //Data_boss_id.load();
  var formPerformer = FormConstructor.CreateComboboxFieldProxyWidthPercent('Исполнитель','top',Data_boss_id,'FIO_B','id','95%',id_user_performer);
  var formDate = FormConstructor.CreateDateFieldLabelTop('Дата','95%',date,'Y-m-d');
  var formState = FormConstructor.CreateCheckBox('Выполнено','95%',state);
  
  var formJobText = FormConstructor.CreateTextAreaFieldWidthPercent('Задание','top','95%',6,job);
  
  
  

/*var formLogin = FormConstructor.CreateTextFieldWidthPercent('Логин','top','95%',date);
var formNewPassword = FormConstructor.CreateTextFieldWidthPercent('Новый пароль','top','95%','');
var formConfirmPassword = FormConstructor.CreateTextFieldWidthPercent('Подтверждение пароля','top','95%','');
StoreRolenames.load();
var formRole = FormConstructor.CreateComboboxFieldProxyWidthPercent('Права пользователя','top',StoreRolenames,'name','id','95%',formRoleValue);
var formFirstName = FormConstructor.CreateTextFieldWidthPercent('Фамилия','top','95%',id_user_performer);
var formLastName = FormConstructor.CreateTextFieldWidthPercent('Имя','top','95%',formLastNameValue);
var formMiddleName = FormConstructor.CreateTextFieldWidthPercent('Отчество','top','95%',formMiddleNameValue);
var formPosition = FormConstructor.CreateTextFieldWidthPercent('Должность','top','95%',formPositionValue);

var formEmail = FormConstructor.CreateTextFieldWidthPercent('e-mail','top','95%',formEmailValue);
var formTel = FormConstructor.CreateTextFieldWidthPercent('Телефон','top','95%',formTelValue);
var formAddress = FormConstructor.CreateTextFieldWidthPercent('Адрес','top','95%',formAddressValue);
var formComments = FormConstructor.CreateTextFieldWidthPercent('Дополнительная информация','top','95%',formCommentsValue);*/


var formJob = 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: [formCreatedJob, formPerformer, formDate, formState]
                                },
                                {
                                  xtype: 'container',
                                  columnWidth:.5,
                                  layout: 'anchor',
                                  items: [formJobText]
                              }]
                          }]
                        });
    var windowFormJob = new Windows('Данные задания',600,410);
    windowFormJob.CreateWindowModal(windowFormJob,formJob);
    
    var saveJobData = Ext.create('Ext.button.Button', { 
      text: 'Сохранить',    
      iconCls: 'save',
      handler: function(){
            var id = id_job;
            var id_user_created = formCreatedJob.getValue();
            var date = formDate.getRawValue();
            var job = formJobText.getValue();
            var id_user_performer = formPerformer.getValue();
            var state = formState.getValue();
            
            /*
            var login = formLogin.getValue();
            var password2 = formNewPassword.getValue();
            var password3 = formConfirmPassword.getValue();
            var role = formRole.getValue();
            var firstName = formFirstName.getValue();
            var lastName = formLastName.getValue();
            var middleName = formMiddleName.getValue();
            var position = formPosition.getValue();
            var bossID = formBossId.getValue();
            var email = formEmail.getValue(); 
            var tel = formTel.getValue(); 
            var address = formAddress.getValue();
            var comments = formComments.getValue(); */
                                                 
            if (id_user_created=='' || date=='' || job == '' || id_user_performer == '')
            {
              msg('Ошибка!', 'Проверьте данные!');
              if (id_user_created==''){formCreatedJob.markInvalid('Проверьте данные!');}
              if (date==''){formDate.markInvalid('Проверьте данные!');}
              if (job==''){formJobText.markInvalid('Проверьте данные!');}
              if (id_user_performer==''){formPerformer.markInvalid('Проверьте данные!');}
            }
            else 
            {
              $.post("app/SFA_CRUDJob.php",{func:'CreateUpdateJob',id:id,id_user_created:id_user_created,date:date,job:job,id_user_performer:id_user_performer, state:state}, function(data){
                          //alert(data);
                          windowFormJob.Window.destroy();
                          GridJob.store.load();
                          GridJob.getView().refresh();
                          var deleteButton = Ext.getCmp('delete_job');
                          deleteButton.setDisabled(true);
                          });
            }
            }
  });
  var cancelInputUserData = Ext.create('Ext.button.Button', { 
      text: 'Отмена',    
      handler: function(){
                windowFormJob.Window.destroy();
                GridJob.store.load();
                GridJob.getView().refresh();
                var deleteButton = Ext.getCmp('delete_job');
                deleteButton.setDisabled(true);
            }
  });
  windowFormJob.Window.addDocked(
  {
    xtype: 'toolbar',
    dock: 'bottom',
    items:['->',saveJobData,'-',cancelInputUserData]
  });
    
    windowFormJob.Window.show();
  });
  
}
