const compContainer = $(`#${comp.code}`);
const workContainer = compContainer.find(`.workflow-work-container`);
const tableContainer = workContainer.find(`.workflow-table-container`);
const paginatorContainer = workContainer.find(`.workflow-paginator-container`);

const getProgressBar = value => `<div class="work-progress-container"><div class="work-progress" style="width: ${value}%;">${value}%</div></div>`;

const Paginator = {
  countInPart: 15,
  rows: 0,
  currentPage: 1,
  pages: 0,

  update: function(){
    this.pages = Math.ceil(this.rows / this.countInPart),
    this.label.text(this.currentPage + ' / ' + this.pages);

    if(this.pages == 0) {
      this.bPrevious.attr('disabled', 'disabled');
      this.bNext.attr('disabled', 'disabled');
    } else {
      if(this.currentPage == 1) {
        this.bPrevious.attr('disabled', 'disabled');
        if (this.currentPage == this.pages) {
          this.bNext.attr('disabled', 'disabled');
        } else {
          this.bNext.removeAttr('disabled');
        }
      } else {
        this.bPrevious.removeAttr('disabled');
        if (this.currentPage == this.pages) {
          this.bNext.attr('disabled', 'disabled');
        } else {
          this.bNext.removeAttr('disabled');
        }
      }
    }
  },

  addListeners: function(){
    this.bNext.click(() => {
      this.currentPage++;
      this.update();
      WorkTable.createBody();
    });

    this.bPrevious.click(() => {
      this.currentPage--;
      this.update();
      WorkTable.createBody();
    });

    this.label.on('dblclick', e => {
      e.preventDefault();
      this.input.show();
      this.label.hide();

      this.input.on('blur', () => {
        this.label.show();
        this.input.hide();
      });

      this.input.val("" + this.currentPage);

      this.input.on('keypress', e => {
        if (e.which != 8 && e.which != 0 && e.which != 46 && (e.which < 48 || e.which > 57)) return false;
      });

      this.input.on('keydown', e => {
        if(e.which === 13) {
          let inputVal = +this.input.val();
          if(inputVal && inputVal != this.currentPage && inputVal <= this.pages && inputVal >= 1){
            this.currentPage = inputVal;
            this.update();
            WorkTable.createBody();
          }
          this.label.show();
          this.input.hide();
          this.input.off();
        }
      });
      this.input.focus();
    });
  },

  render: function(){
    this.container = $('<div class="workflow-pt-container">');
    this.paginator = $('<div class="workflow-pt-paginator">');
    this.pContent = $('<div class="workflow-pt-paginator-content">');
    this.bPrevious = $(`<button class="workflow-pt-previous" disabled="disabled" title="${i18n.tr('Назад')}">`);
    this.bNext = $(`<button class="workflow-pt-next" disabled="disabled" title="${i18n.tr('Вперед')}">`);
    this.label = $('<label>');
    this.input = $('<input type="text">');

    paginatorContainer.empty().append(this.container);

    this.pContent.append(this.label).append(this.input);
    this.paginator.append(this.bPrevious).append(this.pContent).append(this.bNext);
    this.container.append(this.paginator);
  },

  reset: function(countInPart){
    this.countInPart = countInPart;
    this.rows = countInPart;
    this.currentPage = 1;
    this.pages = 0;
  },

  init: function(countInPart = 15){
    const {rowsPerPage = countInPart} = localStorage;
    this.render();
    this.reset(rowsPerPage);
    this.addListeners();
  }
};

const WorkTable = {
  filterType: 'OWN_WORKS',
  filterId: null,
  objectId: null,

  search: null,
  periodType: null,

  isAscSort: true,
  sortColumn: null,

  table: null,
  tHead: null,
  tBody: null,

  selectedItems: [],

  priorities: null,

  getUrl: function(){
    let url = `api/workflow/works/list_ext?userID=${AS.OPTIONS.currentUser.userid}&filterType=${this.filterType}`;

    const startRecord = Paginator.currentPage * Paginator.countInPart - Paginator.countInPart;
    url += `&startRecord=${startRecord}&recordsCount=${Paginator.countInPart}`;

    if(this.filterId) url += `&filterID=${this.filterId}`;
    if(this.objectId) url += `&objectID=${this.objectId}`;
    if(this.search) url += `&search=${this.search}`;
    if(this.periodType) url += `&hasExtSearchParams=true&periodType=${this.periodType}`;
    if(this.sortColumn) url += `&sortColumn=${this.sortColumn}&isAscSort=${this.isAscSort}`;

    url += `&locale=${AS.OPTIONS.locale}`;
    return url;
  },

  sortable: function(th) {
    if(th.attr('columnid') == 'checkbox' || th.hasClass("uk-checkbox")) return;
    this.tHead.find('th').not(th).removeClass('sortable sortable__down sortable__up');
    if (th.hasClass("sortable__down") || th.hasClass("sortable__up")) {
      th.toggleClass("sortable__down sortable__up");
    } else {
      th.addClass("sortable sortable__down");
    }
    this.sortColumn = th.attr('columnid');
    this.isAscSort = th.hasClass("sortable__down") ? true : false;
    this.createBody();
  },

  createHeader: function() {
    this.tHead.empty();
    this.isAscSort = true;
    this.sortColumn = null;

    const tr = $('<tr>');
    const th = $('<th columnid="checkbox" style="width: 40px;"></th>');
    const checkbox = $('<input/>')
    .addClass('uk-checkbox')
    .attr('type', 'checkbox')
    .on('change', e => {
      this.tBody.find('td > [type="checkbox"]').each((k, x) => {
        x.checked = !!e.target.checked;
      });
      this.tBody.find('td > [type="checkbox"]').each((k, x) => {
        $(x).trigger('change');
      });
    });
    th.append(checkbox);
    tr.append(th);

    tr.append(`<th columnid="name" class="uk-table-expand">${i18n.tr('Название')}</th>`);
    if(this.filterType == 'OWN_WORKS') {
      tr.append(`<th columnid="author" class="uk-width-small">${i18n.tr('Поставил')}</th>`);
    } else {
      tr.append(`<th columnid="responsible" class="uk-width-small">${i18n.tr('Ответственный')}</th>`);
    }
    tr.append(`<th columnid="left" class="uk-width-small">${i18n.tr('Осталось')}</th>`);
    tr.append(`<th columnid="percent" class="uk-width-small">${i18n.tr('Прогресс')}</th>`);

    tr.on('click', e => this.sortable($(e.target)));

    this.tHead.append(tr);
  },

  createRow: function(item) {
    const {actionID, name, is_new, is_expired, is_soon_expired, user, author, remained_label, percent} = item;
    const tr = $('<tr>');
    const checkbox = $('<input/>').addClass('uk-checkbox').attr('type', 'checkbox');
    const tmpTd = $('<td>');

    if(this.selectedItems.indexOf(actionID) !== -1) checkbox.prop('checked', true);
    tmpTd.append(`<span class="mobile-table-header">Выбор</span>`).append(checkbox);
    tr.append(tmpTd);

    if(this.priorities) {
      const priority = this.priorities.find(x => x.id == item.priority);
      if(priority) tmpTd.css({
        'background': priority.color
      });
    }

    checkbox.on('change', e => {
      if(e.target.checked) {
        if(this.selectedItems.indexOf(actionID) === -1) {
          this.selectedItems.push(actionID);
        }
      } else {
        const index = this.selectedItems.indexOf(actionID);
        if(index !== -1) this.selectedItems.splice(index, 1);
      }
      // if(this.selectedItems.length > 0) {
      //   $('.action-menu-item').removeClass('uk-disabled');
      //   if($('.action-menu-item.item-delete').length) {
      //     if(!this.isDelete) $('.action-menu-item.item-delete').addClass('uk-disabled');
      //   }
      // } else {
      //   $('.action-menu-item').addClass('uk-disabled');
      // }
    });

    if(is_new && is_new == "true") tr.addClass('new_work');
    if(is_expired && is_expired == "true") {
      tr.addClass('expired_work');
    } else if (is_soon_expired && is_soon_expired == "true") {
      tr.addClass('soon_expired_work');
    }

    tr.append(`<td title="${name}">${name}</td>`);
    if(this.filterType == 'OWN_WORKS') {
      tr.append(`<td title="${author.name}">${author.name}</td>`);
    } else {
      tr.append(`<td title="${user.name}">${user.name}</td>`);
    }
    tr.append(`<td>${remained_label}</td>`);
    tr.append(`<td>${getProgressBar(percent)}</td>`);

    let timeoutId;

    tr.on('click', e => {
      if($(e.target).is("input")) return;
      timeoutId = setTimeout(() => {
        if(!timeoutId) return;
        this.tBody.find('tr').removeAttr('selected');
        tr.attr('selected', true);
        fire({type: 'worklist_item_click', ...item}, comp.code);
      }, 200);
    });

    tr.on('dblclick', e => {
      if($(e.target).is("input")) return;
      clearTimeout(timeoutId);
      timeoutId = null;
      fire({type: 'worklist_item_dbl_click', ...item}, comp.code);
    });

    return tr;
  },

  createBody: function(rowsCount) {
    Cons.showLoader();
    rest.synergyGet(this.getUrl(), res => {
      this.tBody.empty();
      res.data.forEach(item => this.tBody.append(this.createRow(item)));
      Paginator.rows = res.totalCount;
      Paginator.update();
      Cons.hideLoader();
    });
  },

  render: function() {
    compContainer.find(`.jsx-parser`).css({
      'width': '100%',
      'height': '100%'
    });
    this.table = $('<table class="workflow-table-list uk-table uk-table-small uk-table-responsive">');
    this.tHead = $('<thead>');
    this.tBody = $('<tbody>');
    this.table.append(this.tHead).append(this.tBody);
    tableContainer.empty().append(this.table);
  },

  reset: function(){
    this.search = null;
    this.periodType = null;
    this.isAscSort = true;
    this.sortColumn = null;
    this.selectedItems = [];
  },

  init: function() {
    const {systemSettings} = Cons.getAppStore();
    if(systemSettings) this.priorities = systemSettings.current_priorities;

    this.render();
    this.createHeader();
    Paginator.init();
    this.createBody();
  }

};

WorkTable.init();

addListener('worklist_filter_arbitrary_change', comp.code, filterData => {
  const {filterType, filterId, objectId} = filterData;

  WorkTable.filterType = filterType;
  WorkTable.filterId = filterId;
  WorkTable.objectId = objectId;
  WorkTable.reset();
  WorkTable.createHeader();
  WorkTable.createBody();
  Paginator.init();
});

addListener('worklist_translate', comp.code, () => {
  WorkTable.createHeader();
  WorkTable.reset();
  WorkTable.createBody();
  Paginator.init();
});


addListener('worklist_search', comp.code, e => {
  const {value = null} = e;
  WorkTable.search = value;
  WorkTable.createBody();
  Paginator.init();
});

addListener('worklist_row_count_on_page', comp.code, e => {
  const {rowsPerPage = null} = e;
  WorkTable.search = null;
  Paginator.init(rowsPerPage);
  WorkTable.createBody();
});

addListener('worklist_update', comp.code, e => {
  const {countInPart} = Paginator;
  Paginator.init(countInPart);
  WorkTable.createBody();
});
