/**
 * Created by yaobo on 2018/3/2.
 * 存放一些公用的全局方法
 */
import Vue from 'vue';

Vue.prototype.resetFormX = (formName) => {
  this.$refs[formName].resetFields();
}

// 浮点运算
Vue.prototype.floatComputed = (arg1, arg2, sign) => {
  if (!arg1) {
    arg1 = 0;
  }
  if (!arg2) {
    arg2 = 0;
  }
  let val1 = arg1 + '';
  let val2 = arg2 + '';
  let rate = 1;
  let rate1 = 1;
  let rate2 = 1;
  if (val1.indexOf('.') < 0) {
    rate1 = 0;
  } else {
    rate1 = val1.length - val1.indexOf('.') - 1;
  }
  if (val2.indexOf('.') < 0) {
    rate2 = 0;
  } else {
    rate2 = val2.length - val2.indexOf('.') - 1;
  }
  rate = rate2;
  val2 = val2.replace('.', '');
  val1 = val1.replace('.', '');
  if (rate1 > rate2) {
    rate = rate1;
    for (let i = 0; i < rate1 - rate2; i++) {
      val2 = val2 + '0'
    }
  } else {
    for (let i = 0; i < rate2 - rate1; i++) {
      val1 = val1 + '0';
    }
  }
  let rateNum = Math.pow(10, rate);
  if (sign === '-') {
    return (Number(val1) - Number(val2)) / rateNum
  }
  if (sign === '+') {
    return (Number(val1) + Number(val2)) / rateNum
  }
  if (sign === '*') {
    return (Number(val1) * Number(val2)) / (rateNum * rateNum)
  }
  if (sign === '/') { // 默认保留4位
    let num = (Number(val1) / Number(val2)) + '';
    let numArr = num.split('.');
    if (numArr.length > 1) {
      if (numArr[1].length > 4) {
        num = (+num).toFixed(4);
      }
    }
    return num;
  }
  return null;
}
// 原生ul指令origin-ul
Vue.directive('origin-ul', {
  inserted: function (el, binding) {
    var inputTarget = $(el).find('input');
    var ulTarget = $(el).find('ul');
    setUl();
    setUlEvent(inputTarget, ulTarget);
  }
})

function setUl () {
  $('body').unbind('mousewheel');
  $('body').unbind('mousedown');
  var Func = function (e) {
    var originUlTarget = $('.origin-ul');
    for (var i = 0; i < originUlTarget.length; i++) {
      var ulTarget = $(originUlTarget[i]).find('ul');
      if (!$(ulTarget).is(':hidden') && $(ulTarget).length > 0) {
        var inputTarget = $(originUlTarget[i]).find('input');
        if (e.clientX < $(ulTarget).offset().left || e.clientX > ($(ulTarget).offset().left + $(ulTarget).outerWidth())) {
          $(ulTarget).hide();
          $(inputTarget).blur();
        }
        if (e.clientY < $(ulTarget).offset().top || e.clientY > ($(ulTarget).offset().top + $(ulTarget).outerHeight())) {
          $(ulTarget).hide();
          $(inputTarget).blur();
        }
      }
    }
  }
  $('body').bind('mousewheel', Func);
  $('body').bind('mousedown', Func);
}

function setUlEvent (inputTarget, ulTarget) {
  $(inputTarget).focus(function () {
    setUlPosition(inputTarget, ulTarget)
  });
  $(inputTarget).keyup(function () {
    setUlPosition(inputTarget, ulTarget)
  });
}

function setUlPosition (inputTarget, ulTarget) {
  var top = $(inputTarget).offset().top;
  var left = $(inputTarget).offset().left;
  var height = $(inputTarget).outerHeight();
  var MaxH = $('body').outerHeight();
  var ulH = $(ulTarget).outerHeight();
  var ulTop = top + height + 'px';
  if ((top + height + ulH) > MaxH) {
    ulTop = (top - ulH) + 'px';
  }
  $(ulTarget).css({
    'top': ulTop,
    'position': 'fixed',
    'left': ''
  });
  $(ulTarget).show();
}

// 表格固定指令
Vue.directive('origin-table', {
  inserted: function (el, binding) {
    $(el).css({
      'position': 'relative'
    });
    $(el).find('th').css({
      'position': 'relative',
      'webkit-user-select': 'none',
      'padding': '6px'
    });
    var thead = $(el).find('thead')[0];
    var drag = $(thead).attr('drag');
    if (typeof (drag) !== 'undefined') {
      setDrag(el);
    }
    setResize(el);
    setScroll(el);
  },
  update: function (el, binding) {
    var target = $(el);
    // initScroll(target);
    $(target).find('.body-wrapper').unbind();
    $(target).find('.body-wrapper').scroll(function () {
      setTbodyWidth(target);
    });
  },
  componentUpdated: function (el, binding) {
    var bodyTr = $(el).find('tbody tr');
    var tdTempArr = [];
    var theadTr = $(el).find('thead:eq(0) tr');
    var theadTrL = $(theadTr).length;
    for (var i = bodyTr.length - 1; i >= 0; i--) {
      if ($(bodyTr[i]).hasClass('origin-set')) {
        break;
      }
      var tdTarget = $(bodyTr[i]).find('td');
      for (var j = 0; j < tdTarget.length; j++) {
        var td = tdTarget[j];
        var newtdW = $($(bodyTr[i]).find('td')[j]).css('width');
        $(td).unbind();
        $(td).find('.set-cell').css({
          'display': 'inline-block',
          // 'line-height': '18px',
          // 'height': '27px',
          'width': (parseFloat(newtdW) - 5) + 'px'
        });
        // setTableShow(el, tdTempArr, $(td), j);
        var attrTips = $(td).attr('showTips');
        if (typeof (attrTips) !== 'undefined') {
          // if ($(td).find('input').is(':hidden') || $(td).find('input').length === 0) {
          $(td).find('.set-cell').css({
            'text-overflow': 'ellipsis',
            'white-space': 'nowrap',
            'overflow': 'hidden',
            'display': 'inline-block'
            // 'line-height': '18px',
            // 'height': '27px'
          });
          // } else {
          //   $(td).css({
          //     'text-overflow': '',
          //     'white-space': '',
          //     'overflow': '',
          //     'display': '',
          //     'line-height': '',
          //     'height': ''
          //   });
          // }
          hoverTips(el, td);
        }
      }
      $(bodyTr[i]).addClass('origin-set');
      setScroll($(el));
      remarkTable(el);
    }
  }
})

function setResize (el) {
  $(window).unbind('resize');
  $(window).resize(function () {
    setScroll($(el));
    remarkTable(el);
  });
}

function remarkTable (el) {
  var bodyTr = $(el).find('tbody tr');
  var tdTempArr = [];
  var theadTr = $(el).find('thead:eq(0) tr');
  var theadTrL = $(theadTr).length;
  var seqflag = false;
  for (var ii = 0; ii < theadTrL; ii++) {
    var th = $(theadTr[ii]).find('th');
    for (var jj = 0; jj < th.length; jj++) {
      var rospan = $(th[jj]).attr('rowspan');
      var t = rospan ? parseInt(rospan) : 1;
      if ((t + ii) === theadTrL) {
        if ($(th[jj]).attr('seq')) {
          seqflag = true;
        }
        tdTempArr.push($(th[jj]));
      }
    }
  }
  if (seqflag) {
    tdTempArr.sort(function (a, b) {
      return parseInt($(a).attr('seq')) - parseInt($(b).attr('seq'));
    });
  } else {
    tdTempArr.sort(function (a, b) {
      return $(a).offset().left - $(b).offset().left;
    });
    for (let seq = 0; seq < tdTempArr.length; seq++) {
      $(tdTempArr[seq]).attr('seq', seq);
    }
  }

  for (var i = 0; i < bodyTr.length; i++) {
    var tdTarget = $(bodyTr[i]).find('td');
    for (var j = 0; j < tdTarget.length; j++) {
      var td = tdTarget[j];
      if (j < tdTarget.length - 1) {
        setTableShow(el, tdTempArr, $(td), j);
      }
    }
  }
}

function setTableShow (el, tdTempArr, setTdTarget, index) {
  var setTdTargetX = $(setTdTarget).offset().left;
  var setTdTargetW = $(setTdTarget).outerWidth();
  var thTargetX = $(tdTempArr[index]).offset().left;
  var thTargetW = $(tdTempArr[index]).outerWidth();
  // console.log('index :' + index + ' setTdTargetX:' + setTdTargetX + ' setTdTargetW:' + setTdTargetW + ' thTargetX:' + thTargetX + ' thTargetW:' + thTargetW)
  if ((setTdTargetX + setTdTargetW - thTargetX - thTargetW) !== 0) {
    var setTdTargetStW = parseFloat($(setTdTarget).css('width'));
    $(setTdTarget).css({
      'width': setTdTargetStW + ((thTargetX + thTargetW) - (setTdTargetX + setTdTargetW)) + 'px'
    });
    $(setTdTarget).find('.set-cell').css({
      'width': setTdTargetStW + ((thTargetX + thTargetW) - (setTdTargetX + setTdTargetW)) - 5 + 'px'
    });
  }
}
function setDrag (el) {
  var theadTr = $(el).find('thead:eq(0) tr');
  var theadTrL = $(theadTr).length;
  for (var i = 0; i < theadTrL; i++) {
    var th = $(theadTr[i]).find('th');
    for (var j = 0; j < th.length; j++) {
      var rospan = $(th[j]).attr('rowspan');
      var t = rospan ? parseInt(rospan) : 1;
      if ((t + i) === theadTrL) {
        bindDrag(el, $(th[j]));
      }
    }
  }
}

function bindDrag (el, thTarget) {
  var id = new Date().getTime() + Math.round(Math.random() * 999999999999);
  var _div = '<div id = "' + id + '"class="dragdiv" style="cursor:col-resize;position:absolute;display:inline-block;height:100%;width:12px;right:-6px;top:0px;">' +
             '</div>';
  $(thTarget).append(_div);
  $(thTarget).find('.dragdiv').unbind();
  document.getElementById(id).addEventListener('mousedown', function (event) {
    $(event.target).addClass('drag-set');
    $(event.target).data('dragStart', event.pageX)
    document.body.style.cursor = 'col-resize';
    el.removeEventListener('mousemove', elMouseMove);
    el.addEventListener('mousemove', elMouseMove);
    el.removeEventListener('mouseup', elMouseUp);
    el.addEventListener('mouseup', elMouseUp);
  });
}

function elMouseMove (event) {
  setDragLine(event);
}

function setDragLine (event) {
  let target = event.target;
  while (target && !$(target).hasClass('origin-table')) {
    target = target.parentNode;
  }
  var left = $(target).offset().left - $(target).find('table').offset().left;
  if ($('.dragLine').length === 0) {
    var divLine = '<div class="dragLine" style="z-index:9999;overflow:hidden;position:absolute;height:' + ($(target).outerHeight() - 20) + 'px;width:1px;background-color:#fff;"></div>';
    $(target).append(divLine);
  }
  $('.dragLine').css({
    'top': 0,
    'left': event.pageX - 6 - $(target).offset().left + left
  });
}

function elMouseUp (event) {
  setMouseUp(event);
}

function setMouseUp (event) {
  let target = event.target;
  while (target && !$(target).hasClass('origin-table')) {
    target = target.parentNode;
  }
  document.body.style.cursor = '';
  target.removeEventListener('mousemove', elMouseMove);
  target.removeEventListener('mouseup', elMouseUp);
  var dragSetTarget = $('.drag-set');
  confirmDrag(dragSetTarget, event.pageX);
  $('.dragLine').remove();
  $(dragSetTarget).removeClass('drag-set');
  if (window.navigator.userAgent.indexOf('MSIE') > -1 || window.navigator.userAgent.indexOf('Edge') > -1) {
    remarkTable(target);
  }
}

function confirmDrag (dragSetTarget, endX) {
  var startX = $(dragSetTarget).data('dragStart');
  var targetTH = $(dragSetTarget).parent();
  var targetTHX = $(targetTH).offset().left;
  let target = event.target;
  while (target && !$(target).hasClass('origin-table')) {
    target = target.parentNode;
  }
  var targetTHW = $(targetTH).outerWidth();
  var changeWidth = endX - startX;
  if ((targetTHW - 35) < (startX - endX)) {
    changeWidth = 35 - targetTHW;
  }
  var tableTarget = $(target).find('table');
  for (let i = 0; i < tableTarget.length; i++) {
    var trTarget = $(tableTarget[i]).find('tr');
    for (let j = 0; j < trTarget.length; j++) {
      var tdTarget = $(trTarget[j]).find('td');
      for (let m = 0; m < tdTarget.length; m++) {
        let tdX = $(tdTarget[m]).offset().left;
        if (Math.abs(targetTHX - tdX) <= 4) {
          var tdW = parseFloat($(tdTarget[m]).css('width'));
          $(tdTarget[m]).css({
            'width': (tdW + changeWidth) + 'px'
          });
          $(tdTarget[m]).find('.set-cell').css({
            'width': (tdW + changeWidth - 5) + 'px'
          });
          break;
        }
      }
    }
  }
  var thW = parseFloat($(targetTH).css('width'));
  $(targetTH).css({
    'width': (thW + changeWidth) + 'px'
  });
  for (let i = 0; i < tableTarget.length; i++) {
    var width = parseFloat($(tableTarget[i]).css('width'));
    $(tableTarget[i]).css({
      'width': (width + changeWidth) + 'px',
      'max-width': (width + changeWidth) + 'px'
    });
  }
}

function hoverTips (el, target) {
  var elL = $(el).offset().left;
  var elW = $(el).outerWidth();
  $(target).hover(function () {
    var that = $(this);
    if ($(that).find('input').length !== 0 && !$(that).find('input').is(':hidden')) {
      $('body').find('.tdTips').remove();
      return;
    }
    hoverIn(elL, elW, that)
  }, function () {
    $('body').find('.tdTips').remove();
  });
}

function hoverIn (elL, elW, target) {
  var tipContent = $(target).attr('showTips');
  if (tipContent === '') {
    return;
  }
  var left = $(target).offset().left;
  var top = $(target).offset().top;
  var tgH = $(target).outerHeight();
  var tgW = $(target).outerWidth();
  var style = 'position:absolute;' +
              'text-align:center;' +
              'display:none;' +
              'background-color:#303133;' +
              'padding:10px;' +
              'color:#FFFFFF;' +
              'border-radius:4px;' +
              'z-index:9999;' +
              'max-width:1000px;' +
              'top:' + (top - tgH - 20) + 'px;' +
              'left:' + elL + 'px;';
  var arrowSty = 'width:0;' +
                  'height:0;' +
                  'border: 6px solid transparent;' +
                  'border-top-color: #303133;' +
                  'position:absolute;' +
                  'top:33px;';
  var _div = '<div class="tdTips" style="' + style + '"><span>' + tipContent + '</span><div class="tipArrow" style="' + arrowSty + '"></div></div>';
  $('body').append(_div);
  setTipPos(elL, elW, target, tipContent);
}

function setTipPos (elL, elW, target, tipContent) {
  $('body').find('.tdTips span')[0].innerText = tipContent;
  var tdTipsW = $('body').find('.tdTips').outerWidth();
  var tdTipsH = $('body').find('.tdTips').outerHeight();
  var tdtop = $(target).offset().top;
  var tdleft = $(target).offset().left;
  var tdtgW = $(target).outerWidth();
  var tdtgH = $(target).outerHeight();
  if ((elL + elW) < (tdleft + tdTipsW)) {
    $('body').find('.tdTips').css({
      'left': (elL + elW - tdTipsW) + 'px'
    });
    $('body').find('.tipArrow').css({
      'right': ((elL + elW) - tdleft - 10) + 'px'
    });
    if ((elL + elW) > (tdleft + tdtgW)) {
      $('body').find('.tipArrow').css({
        'right': ((elL + elW) - tdleft - 8 - (tdtgW / 2)) + 'px'
      });
    }
  } else {
    $('body').find('.tdTips').css({
      'left': ((tdtgW / 2 + tdleft) - (tdTipsW / 2)) + 'px'
    });
    $('body').find('.tipArrow').css({
      'left': (tdTipsW / 2 - 6) + 'px'
    });
  }
  $('body').find('.tdTips').css({
    'top': (tdtop - 10 - tdTipsH) + 'px'
  });
  $('body').find('.tipArrow').css({
    'top': $('body').find('.tdTips').outerHeight() + 'px'
  });
  if ($('body').find('.tdTips').outerWidth() > ($(target).outerWidth() + 10)) {
    $('body').find('.tdTips').show();
  }
}

function initScroll (target) {
  var theadTrTarget = $(target).find('table').find('thead tr');
  var fixedRFlag = false;
  for (var i = 0; i < theadTrTarget.length; i++) {
    var thTarget = $(theadTrTarget[i]).find('th');
    for (var p = thTarget.length - 1; p > 0; p--) {
      var fixed = $(thTarget[p]).attr('fixed');
      if (fixed === 'right') {
        fixedRFlag = true;
        break;
      }
    }
  }
  if (fixedRFlag) {
    var interValFun = setInterval(function () {
      var tdTarget = $(target).find('table').find('tbody tr td');
      if (tdTarget.length > 0) {
        clearInterval(interValFun);
        setScroll(target);
      }
    }, 200);
  }
}

function setTbodyWidth (target) {
  $(target).find('.head-wrapper').scrollLeft($(target).find('.body-wrapper').scrollLeft())
}

function setScroll (target) {
  var theadTrTarget = $(target).find('table').find('thead tr');
  setTrScroll(theadTrTarget, 'th');
  var targetTr = $(target).find('table').find('tbody tr');
  setTrScroll(targetTr, 'td');
  setSticky(target);
}

function setTrScroll (theadTrTarget, domName) {
  for (var m = 0; m < theadTrTarget.length; m++) {
    var trThTarget = $(theadTrTarget[m]).find(domName);
    var setLFlag = false;
    var setRFlag = false;
    for (var p = 0; p < trThTarget.length; p++) {
      var fixed = $(trThTarget[p]).attr('fixed');
      if (fixed === 'left') {
        setLFlag = true;
      }
      if (fixed === 'right') {
        setRFlag = true;
      }
    }
    if (setLFlag) {
      for (var j = 0; j < trThTarget.length; j++) {
        var thFixed = $(trThTarget[j]).attr('fixed');
        $(trThTarget[j]).addClass('set-fixed-left');
        if (thFixed === 'left') {
          break;
        }
      }
    }
    if (setRFlag) {
      for (var rj = trThTarget.length - 1; rj > 0; rj--) {
        var rthFixed = $(trThTarget[rj]).attr('fixed');
        $(trThTarget[rj]).addClass('set-fixed-right');
        if (rthFixed === 'right') {
          break;
        }
      }
    }
  }
}

function setSticky (target) {
  var left = $(target).find('table').offset().left;
  var setFixedLeftT = $(target).find('table .set-fixed-left');
  var setFixedRightT = $(target).find('table .set-fixed-right');
  for (var i = 0; i < setFixedLeftT.length; i++) {
    if ($(setFixedLeftT[i]).css('left') !== 'auto' && $(setFixedLeftT[i]).css('left') !== '0px') {
      continue;
    }
    var setLeft = $(setFixedLeftT[i]).offset().left;
    var _left = setLeft - left + 'px';
    if (setLeft - left === 0) {
      $(setFixedLeftT[i]).css({
        'border-left': '1px solid #CCCCCC'
      });
    }
    $(setFixedLeftT[i]).css({
      'z-index': 999,
      'position': 'sticky',
      'background-color': '#fff',
      'left': _left
    });
  }
  for (var j = 0; j < setFixedRightT.length; j++) {
    if ($(setFixedRightT[j]).css('right') !== 'auto' && $(setFixedRightT[j]).css('right') !== '0px') {
      continue;
    }
    var setRight = $(target).find('table').outerWidth() - ($(setFixedRightT[j]).offset().left - $(target).find('table').offset().left) - $(setFixedRightT[j]).outerWidth();
    var _right = setRight + 'px';
    $(setFixedRightT[j]).css({
      'z-index': 999,
      'position': 'sticky',
      'background-color': '#fff',
      'right': _right
    });
  }
}
// 高亮当前行指令
Vue.directive('highlight-row', {
  bind (el) {
    el.onclick = function () {
      $(this).siblings().removeClass('zhb-highlighet-row');
      $(this).addClass('zhb-highlighet-row');
    }
  }
})
// 车间页面左右布局表格，左边表格宽度拖动指令，拖动表格的父级div为相对定位，且id为heat-left，右表格父级盒子加上id heat-right
Vue.directive('table-drag', {
  bind (el) {
    $(el).append('<div class="drag-line" style="width: 5px;height: 100%;background: transparent;position: absolute;top: 0;left: 100%;cursor: col-resize">')
    let oDrag = $(el).find('div.drag-line').get(0)
    oDrag.onmousedown = function () {
      document.onmousemove = function (ev) {
        // console.log('执行拖动', ev.clientX)
        $('body').css('cursor', 'col-resize')
        let w = ev.clientX - 22 + 'px'
        if (ev.clientX < 22) {
          $('#heat-left').css('width', '20px')
          $('.drag-line').css('left', '20px')
          $('#heat-right').css('width', `calc(100% - 20px`)
        } else {
          $('#heat-left').css('width', w)
          $('.drag-line').css('left', w)
          $('#heat-right').css('width', `calc(100% - ${w}`)
        }
      }
      document.onmouseup = function () {
        document.onmousedown = null
        document.onmousemove = null
        $('body').css('cursor', 'auto')
      }
    }
  }
})
