import default_img from 'images/default.png'; // 默认图片地址

const install = function(Vue, opts) {
  /**
   * [returnPage 返回页码(列表删除操作，根据情况返回页码来重新请求数据]]
   * @param  {[type]} total        [总条数]
   * @param  {[type]} current_page [当前页码]
   * @param  {[type]} limit        [每页条数]
   * @return {[type]}              [description]
   */
  Vue.prototype.returnPage = function(total, current_page, limit) {
    total = Number(total);
    current_page = Number(current_page);
    limit = Number(limit);
    let toal_page = Math.ceil(total / limit); // 总页数
    if (toal_page == 1) {
      return toal_page;
    } else {
      if (current_page < toal_page) {
        return current_page;
      } else {
        return (current_page - 1);
      }
    }
  };

  /**
   * [tableCheckboxHandle 表格有复选框,处理刷新数据后，复选框勾选项重新勾选]
   * @param  {[Array]} list      [后端返回的列表数据]
   * @param  {[Array]} selection [表格勾选项数据]
   * @return {[type]}           [description]
   */
  Vue.prototype.tableCheckboxHandle = function(list, selection) {
    const ids = selection.map(obj => obj.id);
    list.forEach((item, i) => {
      item._checked = ids.includes(item.id);
    });
    return list;
  };

  /**
   * [deepClone 数组/对象深度拷贝]
   * @param  {[type]} source [数组/对象]
   * @return {[type]}        [description]
   */
  Vue.prototype.deepClone = function(source) {
    if (!source && typeof source !== 'object') {
      throw new Error('error arguments', 'shallowClone');
    }
    const targetObj = source.constructor === Array ? [] : {};
    for (const keys in source) {
      if (source.hasOwnProperty(keys)) {
        if (source[keys] && typeof source[keys] === 'object') {
          targetObj[keys] = source[keys].constructor === Array ? [] : {};
          targetObj[keys] = deepClone(source[keys]);
        } else {
          targetObj[keys] = source[keys];
        }
      }
    }
    return targetObj;
  };

  /**
   * [imgEvent 判断图片路径是否有效，有效返回src,无效返回空，此用法用于图片上传处]
   * @param  {[type]} src [图片路径]
   * @return {[type]}     [description]
   */
  Vue.prototype.imgEvent = function(src) {
    let img = new Image();
    img.src = src;

    return new Promise(function(resolve, reject) {
      img.onerror = function(event) {
        reject(event);
      };

      img.onload = function() {
        resolve(src);
      };
    });
  };

  /**
   * [imgError 用于图片onerror时，返回默认图片]
   * @param  {[type]} event [description]
   * @return {[type]}       [description]
   */
  Vue.prototype.imgError = function(event, src) {
    const target = event.srcElement || event.target;
    target.src = src || default_img;

    // 如果默认图片出错，控制不要一直跳动
    target.onerror = null;
  };

  /**
   * [getByteLength 使用字符unicode判断，获取字符字节长度]
   * @param  {[type]} char [字符]
   * @return {[type]}      [description]
   */
  Vue.prototype.getByteLength = function(char) {
    char = char.toString().trim();
    let char_len = 0;
    for (let i = 0, len = char.length; i < len; i++) {
      let code = char[i].charCodeAt();
      if (code >= 0 && code <= 128) {
        char_len += 1;
      } else {
        char_len += 2;
      }
    }
    return char_len;
  };

  /**
   * [scrollTop 翻页数据页面滚动]
   * @return {[type]} [description]
   */
  Vue.prototype.scrollTop = function() {
    if (document.getElementById('layout')) {
      document.getElementById('layout').scrollTo(0, 0);
    } else {
      window.scrollTo(0, 0);
    }
  };

  /**
   * [haveJurisdiction 操作按钮判断,用在js页面渲染]
   * @param  {[type]} name [description]
   * @return {[type]}      [description]
   */
  Vue.prototype.haveJurisdiction = function(name) {
    const nodes = vm.$store.state.permissions.page_nodes;
    return nodes.includes(name);
  };

  /**
   * [操作按钮判断,用在页面渲染]
   */
  Vue.directive('has', {
    update(el, binding, vnode) {
      vhasHandle(el, binding, vnode);
    },
    bind(el, binding, vnode) {
      vhasHandle(el, binding, vnode);
    }
  });
};

/**
 * [vhasHandle v-has指令共用方法]
 * @param  {[type]} el      [description]
 * @param  {[type]} binding [description]
 * @param  {[type]} vnode   [description]
 * @return {[type]}         [description]
 */
function vhasHandle(el, binding, vnode) {
  setTimeout(() => {
    const nodes = vnode.context.$store.state.permissions.page_nodes;
    if (nodes.length) {
      if (!nodes.includes(binding.value)) {
        if (el.parentNode) {
          el.parentNode.removeChild(el);
        }
      } else {
        $(el).removeClass('ds-n');
      }
    } else {
      $(el).addClass('ds-n');
    }
  }, 500);
}

export default {
  install
};
