util.js 10.1 KB
import Vue from 'vue'
/* import {
	ToastPlugin,
	LoadingPlugin,
	AlertPlugin
} from 'vux'

Vue.use(ToastPlugin)
Vue.use(LoadingPlugin)
Vue.use(AlertPlugin) */

import {
  Toast,
  Notify,
  Dialog
} from 'vant';

export const Util = {

  /**
   * 简单alert
   * title 标题
   * message 内容
   * className 自定义class
   * showCancelButton 是否展示取消按钮
   * confirmButtonText 确认按钮文案
   * cancelButtonText 取消按钮文案
   * confirmButtonColor 确认按钮颜色
   * cancelButtonColor 取消按钮颜色
   */
  msg: function(options) {
    Dialog({
      title: options.title || '',
      message: options.message || '',
      className: options.className || '',
      showCancelButton: options.showCancelButton || false,
      confirmButtonText: options.confirmButtonText || '确认',
      cancelButtonText: options.cancelButtonText || '取消',
      confirmButtonColor: options.confirmButtonColor || '#1989fa',
      cancelButtonColor: options.cancelButtonColor || '#000',
      beforeClose: options.beforeClose
    });

    /* Vue.$vux.alert.show({
    	title: options.title||'',
    	content: options.message||'',
    	onShow() {
    		options.onShow?(options.onShow)():'';
    	},
    	onHide() {
    		options.onHide?(options.onHide)():'';
    	}
    }) */
  },

  /**
   * 提示框
   */
  Info: function(options) {
    Notify({
      message: options.message || '提示',
      duration: options.time || 2000,
      background: options.background || '#f44'
    });
    /* Vue.$vux.toast.show({
    	text: options.message || '提示',
    	position: options.position || 'default',
    	width: options.width || '12em',
    	type: options.type || 'text',
    	time: options.time || 2000
    }) */
  },

  /**
   * 轻提示
   */
  Tips: function(options) {
    Toast({
      message: options.message || '提示',
      duration: options.duration || 3000,
      type: options.type || 'text',
      icon: options.icon || ''
    })
  },

  /**
   * loading
   */
  loading: function(message) {
    Toast.loading({
      mask: true,
      message: message || '加载中...'
    });
    /* Vue.$vux.loading.show({
    	text: message || '加载中...',
    }) */
  },

  /**
   * 关闭loading
   */
  closeLoading: function() {
    Toast.clear();
  },

  /**
   * 校验手机号码格式
   */
  checkPhone: function(mobile) {
    var myreg = /^(13[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9]|14[0-9])[0-9]{8}$/;
    return myreg.test(mobile);
  },

  /**
   * 是否特殊字符
   */
  isSpecialLetter: function(str) {
    var reg = new RegExp("[`~!@#$^&*=|{}':;',\\[\\]<>?~!@#¥……&*——|{}【】‘;:”“'。,、? ]");
    return reg.test(str);
  },

  /**
   * 身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X
   */
  isCardId: function(sId) {
    var iSum = 0;
    var info = "";
    var sBirthday = '';
    var aCity = {
      11: "北京",
      12: "天津",
      13: "河北",
      14: "山西",
      15: "内蒙古",
      21: "辽宁",
      22: "吉林",
      23: "黑龙江",
      31: "上海",
      32: "江苏",
      33: "浙江",
      34: "安徽",
      35: "福建",
      36: "江西",
      37: "山东",
      41: "河南",
      42: "湖北",
      43: "湖南",
      44: "广东",
      45: "广西",
      46: "海南",
      50: "重庆",
      51: "四川",
      52: "贵州",
      53: "云南",
      54: "西藏",
      61: "陕西",
      62: "甘肃",
      63: "青海",
      64: "宁夏",
      65: "新疆",
      71: "台湾",
      81: "香港",
      82: "澳门",
      91: "国外"
    };
    if (!/^\d{17}(\d|x)$/i.test(sId)) {
      //return "你输入的身份证长度或格式错误"; 
      return false;
    }
    sId = sId.replace(/x$/i, "a");
    if (aCity[parseInt(sId.substr(0, 2))] == null) {
      //return "你的身份证地区非法"; 
      return false;
    }
    sBirthday = sId.substr(6, 4) + "-" + Number(sId.substr(10, 2)) + "-" + Number(sId.substr(12, 2));
    var d = new Date(sBirthday.replace(/-/g, "/"));
    if (sBirthday != (d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate())) {
      //return "身份证上的出生日期非法"; 
      return false;
    }
    for (var i = 17; i >= 0; i--) {
      iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
    }
    if (iSum % 11 != 1) {
      //return "你输入的身份证号非法";
      return false;
      //aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女");
      //此次还可以判断出输入的身份证号的人性别
    }
    return true;
  },

  /**
   * 获取当前时间
   */
  getCurrentDate: function() {
    let time = new Date();
    let y = time.getFullYear();
    let m = time.getMonth() + 1;
    let d = time.getDate();

    return {
      date: y + '/' + m + '/' + d
    }

  },

  /**
   * 获取浏览器参数
   */
  getUrlParams: function(name) {
    var vars = [],
      hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars[name];
  },

  /**
   * 根据当前时间,计算往后30天的日期
   */
  getAfterDate: function(day) {
    let date1 = new Date();
    let date2 = new Date(date1);
    let time = 30;
    if (day) {
      time = day;
    }
    date2.setDate(date1.getDate() + time);

    let _date = date2.getFullYear() + "-" + (date2.getMonth() + 1) + "-" + date2.getDate();

    return {
      date: _date,
      year: date2.getFullYear(),
      month: date2.getMonth() + 1,
      day: date2.getDate()
    };
  },
  /**
   * 设置cookie
   */
  setCookie: function(c_name, value, expiredays) {
    var exdate = new Date()
    var time = 1;
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = c_name + "=" + escape(value) +
      ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
  },

  /**
   * 取回cookie
   */
  getCookie: function(c_name) {
    if (document.cookie.length > 0) {
      c_start = document.cookie.indexOf(c_name + "=")
      if (c_start != -1) {
        c_start = c_start + c_name.length + 1
        c_end = document.cookie.indexOf(";", c_start)
        if (c_end == -1) c_end = document.cookie.length
        return unescape(document.cookie.substring(c_start, c_end))
      }
    }
    return ""
  },


  /**
   * 校验银行卡号
   */
  checkBankCard: function(bankno) {
    if (!bankno) {
      return false;
    };

    let lastNum = bankno.substr(bankno.length - 1, 1); //取出最后一位(与luhn进行比较)
    let first15Num = bankno.substr(0, bankno.length - 1); //前15或18位
    let newArr = new Array();
    for (let i = first15Num.length - 1; i > -1; i--) { //前15或18位倒序存进数组
      newArr.push(first15Num.substr(i, 1));
    }
    let arrJiShu = new Array(); //奇数位*2的积 <9
    let arrJiShu2 = new Array(); //奇数位*2的积 >9
    let arrOuShu = new Array(); //偶数位数组

    for (var j = 0; j < newArr.length; j++) {
      if ((j + 1) % 2 == 1) { //奇数位
        if (parseInt(newArr[j]) * 2 < 9) {
          arrJiShu.push(parseInt(newArr[j]) * 2);
        } else {
          arrJiShu2.push(parseInt(newArr[j]) * 2);
        }
      } else {
        //偶数位
        arrOuShu.push(newArr[j]);
      }
    }

    var jishu_child1 = new Array(); //奇数位*2 >9 的分割之后的数组个位数
    var jishu_child2 = new Array(); //奇数位*2 >9 的分割之后的数组十位数

    for (var h = 0; h < arrJiShu2.length; h++) {
      jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
      jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
    }

    var sumJiShu = 0; //奇数位*2 < 9 的数组之和
    var sumOuShu = 0; //偶数位数组之和
    var sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和
    var sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和
    var sumTotal = 0;
    for (var m = 0; m < arrJiShu.length; m++) {
      sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
    }

    for (var n = 0; n < arrOuShu.length; n++) {
      sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
    }

    for (var p = 0; p < jishu_child1.length; p++) {
      sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
      sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
    }
    //计算总和
    sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);

    //计算luhn值
    var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
    var luhn = 10 - k;

    if (lastNum == luhn) {
      return true;
    } else {
      return false;
    }
  },

  /**
   * vant
   * 压缩图片
   */
  compressionImg: function(file) {
    return new Promise(function(resolve, reject){
      var img = new Image();
      img.src = file.content;
      img.onload = function() {
        var that = this;
        var w = that.width / 3,
          h = that.height / 3;
        // 默认按比例压缩
        var quality = 0.7; // 默认图片质量为0.7
        //生成canvas
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        var anw = document.createAttribute('width');
        anw.nodeValue = w;
        var anh = document.createAttribute('height');
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        ctx.drawImage(that, 0, 0, w, h);
        // quality值越小,所绘制出的图像越模糊
        var base64 = canvas.toDataURL('image/jpeg', quality);

        var m = Util.convertBase64UrlToBlob(base64);
        resolve(m);
      };
    })
  },

  /**
   * 将以base64的图片url数据转换为Blob
   * 用url方式表示的base64图片数据
   */
  convertBase64UrlToBlob: function(urlData) {
    var arr = urlData.split(',');
    var mime = arr[0].match(/:(.*?);/)[1];
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
      type: mime
    });
  }

};