前端一套非常好用的工具.js

2020-12-15  本文已影响0人  武汉前端阿杰1001

import Cookies from "js-cookie";
import axios from "axios";
if(!location.href.includes('http://localhost:8899/')){
  axios.defaults.baseURL=window.baseUrl
  axios.defaults.withCredentials = true;
}
import qs from "qs";
const isLocalhost = Boolean(
  window.location.hostname === "localhost" ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === "[::1]" ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);
// 支持跨域请求携带cookie
axios.defaults.withCredentials = true;

// 生成默认header
const genDefaultHeaders = function(){
  return {}
}

const errFn = (error, self, isGet) => {
  if (error.response) {
    // 接口返回80001的时候跳转登录
    if (error.response.data.error_code === 80001) {
      // 非get请求或者工作台操作都验证
      const pathname = window.location.pathname
      if (!isGet || pathname.indexOf("/zxns") >= 0 ) {
        self.goLogin(window.location.href);
      }
    }
    return error.response.data;
  } else {
    return {
      errCode: error.errCode,
      errMessage: error.errMessage
    };
  }
};

const lz = {
  errFn,
  isLocalhost,
  xhrGateWay(data) {
    let res = data;
    if (typeof data !== "object") {
      res = {};
    }
    return res;
  },
  assemblingData(data) {
    if (typeof data === "object") {
      data._xsrf = Cookies.get("_xsrf");
    } else {
      data = {};
      data._xsrf = Cookies.get("_xsrf");
    }
    return data;
  },
  post(url, data = {}) {
    data = this.xhrGateWay(data);
    data = this.assemblingData(data);
    return axios
      .post(url, data, {
        headers: {
          "Content-Type": "application/json"
        }
      })
      .then(res => {
        return res.data;
      })
      .catch(err => {
        return errFn(err, this);
      });
  },
  get(url, data = {}) {
    data = this.xhrGateWay(data);
    return axios
      .get(url, {
        params: data,
        headers: {
          ...genDefaultHeaders(),
          // "Content-Type": "application/json"
        }
      })
      .then(res => {
        return res.data;
      })
      .catch(err => {
        return errFn(err, this, true);
      });
  },
  request(config) {
    return axios
      .request(config)
      .then(res => {
        return res.data;
      })
      .catch(err => {
        return errFn(err, this, true);
      });
  },
  getJson(url, data = {}) {
    data = this.xhrGateWay(data);
    return axios
      .get(url + "?ts=" + new Date().getTime(), {
        params: data,
        headers: {
          ...genDefaultHeaders(),
          // "Content-Type": "application/json"
        }
      })
      .then(res => {
        return res.data;
      })
      .catch(err => {
        return errFn(err, this, true);
      });
  },
  deleteJson(url, data = {}, options = {}) {
    data = this.xhrGateWay(data);
    data = this.assemblingData(data);
    return axios
      .delete(
        url,
        {
          params: data
        },
        {
          headers: {
            ...genDefaultHeaders(),
            "Content-Type":
              options.contentType || "application/x-www-form-urlencoded"
          }
        }
      )
      .then(res => {
        return res.data;
      })
      .catch(err => {
        return errFn(err, this);
      });
  },
  putJson(url, data = {}, options = {}) {
    data = this.xhrGateWay(data);
    data = this.assemblingData(data);
    return axios
      .put(url, qs.stringify(data), {
        headers: {
          ...genDefaultHeaders(),
          "Content-Type":
            options.contentType || "application/x-www-form-urlencoded"
        }
      })
      .then(res => {
        return res.data;
      })
      .catch(err => {
        return errFn(err, this);
      });
  },
  postJson(url, data = {}, options = {}) {
    data = this.xhrGateWay(data);
    data = this.assemblingData(data);
    if (options.contentType !== "application/json") {
      data = qs.stringify(data);
    }
    return axios
      .post(url, data, {
        headers: {
          ...genDefaultHeaders(),
          "Content-Type":
            options.contentType || "application/x-www-form-urlencoded"
        }
      })
      .then(res => {
        return res.data;
      })
      .catch(err => {
        return errFn(err, this);
      });
  },
  postJsonIM(url, data = {}, options = {}) {
    data = this.xhrGateWay(data);
    return axios
      .post(url, JSON.stringify(data), {
        headers: {
          ...genDefaultHeaders(),
          "Content-Type": options.contentType || "application/json"
        }
      })
      .then(res => {
        return res.data;
      })
      .catch(err => {
        return errFn(err);
      });
  },
  postFile(url, data) {
    data.append("_xsrf", Cookies.get("_xsrf"));
    let config = {
      headers: {
        ...genDefaultHeaders(),
        "Content-Type": "multipart/form-data"
      }
    };
    return axios
      .post(url, data, config)
      .then(res => {
        return res.data;
      })
      .catch(err => {
        return errFn(err, this);
      });
  },
  postFileProgress(url, data, callback, source) {
    data.append("_xsrf", Cookies.get("_xsrf"));
    let config = {
      headers: {
        ...genDefaultHeaders(),
        "Content-Type": "multipart/form-data"
      },
      onUploadProgress: callback,
      cancelToken: source.token
    };
    return axios
      .post(url, data, config)
      .then(res => {
        return res.data;
      })
      .catch(err => {
        if (axios.isCancel(err)) {
          console.log("Request canceled", err.message);
        } else {
          return errFn(err);
        }
      });
  },
  getUploadFilePath(){
    const relpath = '/api/file/v1/uploadFileElement'
    if (isLocalhost) {
      return relpath
    }
    return window.location.host + relpath
  },
  /**
   * 获取文字的字符数量(中文及中文符号转化为2个字符)
   * @param val{String}文字信息
   */
  getCharLen(val) {
    if (val) {
      return val.replace(/[^\\x00-\\xff]/g, "xx").length;
    } else {
      return 0;
    }
  },
  /* 计算两个Date类型时间差,以hh:mm:ss格式返回 */
  getDiff(start, end) {
    let diffStr = "";
    let difference = end.getTime() - start.getTime();
    if (difference > 0) {
      let hour = Math.floor(difference / (1000 * 60 * 60));
      let minute = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
      let second = Math.floor(
        ((difference % (1000 * 60 * 60)) % (1000 * 60)) / 1000
      );
      if (parseInt(hour, 10) < 10) {
        hour = "0" + parseInt(hour, 10);
      }
      if (parseInt(minute, 10) < 10) {
        minute = "0" + parseInt(minute, 10);
      }
      if (parseInt(second, 10) < 10) {
        second = "0" + parseInt(second, 10);
      }
      diffStr = hour + ":" + minute + ":" + second;
    }
    return diffStr;
  },
  /**
   * 获取url参数
   */
  getQueryString(name, path) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let search = path || decodeURI(window.location.search);
    var r = search.substr(1).match(reg);
    if (r != null) {
      return unescape(r[2]);
    }
    return null;
  },

  /**
   * 获取uuid 方法
   */
  getUuid() {
    return window.location.pathname.match(/[0-9a-f]{16,16}/g);
  },

  /**
   * 转换后端传回的日期串
   * @param {*} val 值
   * @param {*} type 格式
   * @param {*} isMillisecond 是否是毫秒
   */
  getDate(val, type, isMillisecond = true) {
    let time = new Date();
    if (val) {
      time = isMillisecond
        ? new Date(val * 1000)
        : new Date(val.toString().replace(/-/g, "/"));
    }
    let year = time.getFullYear();
    let cmonth = time.getMonth() + 1;
    let month = cmonth < 10 ? "0" + cmonth : cmonth;
    let date = time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
    let hour = time.getHours();
    hour = hour < 10 ? "0" + hour : hour;
    let minutes = time.getMinutes();
    minutes = minutes < 10 ? "0" + minutes : minutes;
    let seconds = time.getSeconds();
    seconds = seconds < 10 ? "0" + seconds : seconds;
    let result = "";
    switch (type) {
      case "y.m": // 2016.11
        result = year + "." + month;
        break;
      case "ym": // 2016.11.23
        result = year + "." + month + "." + date;
        break;
      case "md": // 11.23
        result = month + "." + date;
        break;
      case "hm": // 10:56
        result = hour + ":" + minutes;
        break;
      case "mdhm": // 11-23 10:56
        result = month + "-" + date + " " + hour + ":" + minutes;
        break;
      case "hms": // 10:56:09
        result = hour + ":" + minutes + ":" + seconds;
        break;
      case "m": // 06
        result = minutes;
        break;
      case "m-d": // 11-23
        result = month + "-" + date;
        break;
      case "ymhs": // 2016.11.23 10:56
        result = year + "." + month + "." + date + " " + hour + ":" + minutes;
        break;
      case "ymhss": // 2016.11.23 10:56:00
        result =
          year +
          "." +
          month +
          "." +
          date +
          " " +
          hour +
          ":" +
          minutes +
          ":" +
          seconds;
        break;
      case "ymdhms": // 20161123105600
        result =
          year +
          "" +
          month +
          "" +
          date +
          "" +
          hour +
          "" +
          minutes +
          "" +
          seconds;
        break;
      case "y-mhs": // 2016-11-23 10:56
        result = year + "-" + month + "-" + date + " " + hour + ":" + minutes;
        break;
      case "ymdhm": // 2016-11-23
        result = year + "-" + month + "-" + date;
        break;
      case "mdyr": // 11月23日
        result = month + "月" + date + "日 ";
        break;
      case "ymd": // 2013年11月23日
        result = year + "年" + month + "月" + date + "日 ";
        break;
      case "year": // 2016
        result = year;
        break;
      case "task":
        let now = new Date().getTime();
        let day = new Date().getDate();
        let diff = now - time;
        result = year + "-" + month + "-" + date + " " + hour + ":" + minutes;
        if (diff < 86400000) {
          result =
            time.getDate() - day === 0
              ? "今天 " + hour + ":" + minutes
              : "昨天 " + hour + ":" + minutes;
        } else if (diff < 86400000 * 2) {
          result =
            day - time.getDate() === 1
              ? "昨天 " + hour + ":" + minutes
              : result;
        }
        break;
      default:
        result = year + "-" + month;
    }
    return result;
  },

  /**
   * 格式化金钱, 加千位分隔符
   * @param {*} val 金额
   * @param {*} isWan 是否显示万
   */
  getMoney(val, isWan) {
    if (isWan && val >= 10000) {
      return val / 10000 + "万";
    } else {
      return val ? val.toString().replace(/(\d)(?=(?:\d{3})+$)/g, "$1,") : val;
    }
  },

  /**
   * 数字格式化
   * @param {*} value 金额
   */
  formatNum(value) {
    let newValue = ["", "", ""];
    let fr = 1000;
    let num = 3;
    while (value / fr >= 1) {
      fr *= 10;
      num += 1;
      console.log("数字", value / fr, "num:", num);
    }
    if (num <= 4) {
      // 千
      newValue[1] = "千";
      newValue[0] = parseInt(value / 1000) + "";
    } else if (num <= 8) {
      // 万
      const text1 = parseInt(num - 4) / 3 > 1 ? "千万" : "万";
      const fm = "万" === text1 ? 10000 : 10000000;
      newValue[1] = text1;
      newValue[0] = value / fm + "";
    } else if (num <= 16) {
      // 亿
      let text1 = (num - 8) / 3 > 1 ? "千亿" : "亿";
      text1 = (num - 8) / 4 > 1 ? "万亿" : text1;
      text1 = (num - 8) / 7 > 1 ? "千万亿" : text1;
      let fm = 1;
      if ("亿" === text1) {
        fm = 100000000;
      } else if ("千亿" === text1) {
        fm = 100000000000;
      } else if ("万亿" === text1) {
        fm = 1000000000000;
      } else if ("千万亿" === text1) {
        fm = 1000000000000000;
      }
      newValue[1] = text1;
      newValue[0] = parseInt(value / fm) + "";
    }
    if (value < 1000) {
      newValue[1] = "";
      newValue[0] = value + "";
    }
    return newValue.join("");
  },

  /**
   *
   * @param {*获取附件size} val
   */
  getSize(val) {
    if (val < 1048576) {
      return (val / 1024).toFixed(2) + "KB";
    } else {
      return (val / 1048576).toFixed(2) + "MB";
    }
  },
  /**
   * 获取下标
   */
  findIndex(arr, key, val) {
    let idx = -1;
    if (Object.prototype.toString.call(arr) === "[object Array]") {
      arr.forEach((item, i) => {
        if (item[key] === val) {
          idx = i;
        }
      });
    }
    return idx;
  },
  /**
   * 获取当前日期字符串
   */
  getNowDateStr(type = "") {
    let res = "";
    let now = new Date();
    let getyear = now.getFullYear();
    let getmonth = now.getMonth() + 1;
    let getdate = now.getDate();
    if (getmonth < 10) {
      getmonth = "0" + getmonth.toString();
    }
    if (getdate < 10) {
      getdate = "0" + getdate.toString();
    }

    switch (type) {
      case "yyyy-mm-dd":
        res = `${getyear.toString()}-${getmonth.toString()}-${getdate}`;
        break;
      case "ymd":
        res = `${getyear.toString()}年${getmonth.toString()}月${getdate}日`;
        break;
      default:
        res = `${getyear.toString()}/${getmonth.toString()}/${getdate}`;
    }
    return res;
  },
  /**
   * 是否为数组
   * @param o js对象
   */
  isArray(o){
    return Object.prototype.toString.call(o) === '[object Array]';
  },
  /**
   * 添加事件
   * @param {Object} obj 被添加事件的对象
   * @param {String} xEvent  事件名称
   * @param {Function} fn 事件执行函数
   */
  addEvent(obj, xEvent, fn) {
    if (obj.attachEvent) {
      obj.attachEvent("on" + xEvent, fn);
    } else {
      obj.addEventListener(xEvent, fn, false);
    }
  },
  // 移除事件
  removeEvent(obj, xEvent, fn) {
    if (obj.detachEvent) {
      obj.detachEvent("on" + xEvent, fn);
    } else {
      obj.removeEventListener(xEvent, fn, false);
    }
  },
  /**
   * 注销事件
   * @param {*} obj
   * @param {*} xEvent
   */
  offEvent(obj, xEvent) {
    obj.removeEventListener(xEvent, this);
  },
  /**
   * 验证登录态
   */
  loginRequired: function(profile, func) {
    if (profile && profile.id) {
      return func;
    }
    let path = window.location.href;
    if (window.isInIframe) {
      path = window.top.location.href;
    }
    lz.goLogin(path);
    return () => {};
  },


  /**
   * 跳转登录
   */
  goLogin(path) {
    const _path = path || (window.location.pathname + window.location.search)
    window.location.href = "/login?redirect=" + _path;
  },
  /**
   * 深度克隆
   * @param {Object} data
   */
  deepCopy(obj, deep) {
    let self = this;
    // 类型判断
    let isArray = item => {
      return Object.prototype.toString.call(obj) === "[object Array]";
    };

    if (
      obj === null ||
      (typeof obj !== "object" && typeof obj !== "function")
    ) {
      return obj;
    }

    if (typeof obj === "function") {
      return new Function("return " + obj.toString())();
    } else {
      var target = isArray(obj) ? [] : {};
      let value = null;

      for (const name of Object.keys(obj)) {
        value = obj[name];
        if (value === obj) {
          continue;
        }

        if (deep && (isArray(value) || typeof value === "object")) {
          target[name] = self.deepCopy(value, deep);
        } else {
          target[name] = value;
        }
      }
      return target;
    }
  },
  /** 检查身份证合法性 */
  checkIdentify(code) {
    // let tip = "";
    let pass = true;
    if (code.length !== 18 && code.lenth !== 16) {
      // tip = "身份证位数不正确";
      pass = false;
    } else if (
      !code ||
      !/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(
        code
      )
    ) {
      // tip = "身份证号格式错误";
      pass = false;
    }
    return pass;
  },
  /**
   * 节流函数
   * @param {Function} fn 被执行行数
   * @param {Number} wait 需要等待的时间(毫秒)
   * @param {Number} mustRun 多少毫秒必须执行一次
   */
  throttle(fn, wait = 100, mustRun = 1000) {
    let timeout = null;
    let start = new Date();
    return function() {
      let ctx = this;
      let args = arguments;
      let curTime = new Date();
      if (timeout) {
        clearTimeout(timeout);
      }
      // 如果达到了规定的触发时间间隔,触发 handler
      if (curTime - start >= mustRun) {
        fn.apply(ctx, args);
        start = curTime;
      } else {
        // 没达到触发间隔,重新设定定时器
        timeout = setTimeout(fn, wait);
      }
    };
  },
  /**
   * 延迟函数
   * @param {Function} fn 被执行函数
   * @param {Number} delay 延迟时间(毫秒)
   */
  debounce(fn, delay = 100) {
    let timer = null;
    return function(...args) {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => fn.apply(this, args), delay);
    };
  },


  /** 设置倒计时 */
  downTime(time, before, type) {
    const now = new Date().getTime();
    time = new Date(time.toString().replace(/-/gi, "/")).getTime();
    let oneDay = 24 * 1000 * 60 * 60;
    if (Math.abs(time - now) > oneDay) {
      let diffDay = Math.floor(Math.abs(time - now) / oneDay);
      if (before) {
        if (Math.abs(time - now) > oneDay * 5) {
          return this.getDate(time / 1000, type || "ymd", true);
        } else {
          return `${diffDay}天前`;
        }
      }
      return "<b>" + diffDay + "</b>天";
    } else {
      var h, m;
      let leftTime = Math.abs(time - now);
      if (leftTime >= 0) {
        h = Math.floor((leftTime / 1000 / 60 / 60) % 24);
        m = Math.floor((leftTime / 1000 / 60) % 60);
      }
      if (before) {
        if (h <= 0) {
          if (m < 1) {
            return "刚刚";
          }
          return `${m}分钟前`;
        }
        return `${h}小时前`;
      }
      return `<b>${h}</b>小时<b>${m}</b>分`;
    }
  },

  localStorage: {
    setItem: (...args) => {
      window.localStorage.setItem(...args)
    },
    getItem: (...args) => {
      return window.localStorage.getItem(...args)
    }
  }

};

export default lz;
上一篇 下一篇

猜你喜欢

热点阅读