import Vue from "vue";
// import {checkGoogleCode, baseUrl} from "../api/public.js";
import transCodeImg from "./codeImg";
// import ElementUI from "element-ui";
import md5 from "js-md5";
// import i18n from "@/locale/index.js"; //引入语言包
// import CryptoJS from "crypto-js";
import {store} from "../store";

const keyStr = "bi_ecology_qwert"; //加密的秘钥
// Vue.use(ElementUI);
// Vue.use(ElementUI, {
//   i18n: (key, value) => i18n.t(key, value) //重点！！在注册Element时设置i18n的处理方法（这里有个小坑）
// });
// let vue = new Vue({
//   i18n: i18n
// });
let Public = new Object();
Public.imgUpload = "/api/authentication/shangchuan"; //图片上传地址
Public.img_host = "https://jyh.hashtron.top/";
Public.kf = 'https://1539049.s2.udesk.cn/im_client/?web_plugin_id=28350';
Public.captchaId = "7057166a15d74781a0d8620b925436c9"; // 网易滑块
// 加法
Public.UserInfo = {};
Public.getLocalTime = function (nS) {
  var h, m, s;
  var date = new Date(nS * 1000);
  h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  m =
    (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
    ":";
  s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return h + m + s;
};
Public.Addition = function (a, b) {
  var c, d, e;
  try {
    c = a.toString().split(".")[1].length;
  } catch (f) {
    c = 0;
  }
  try {
    d = b.toString().split(".")[1].length;
  } catch (f) {
    d = 0;
  }
  return (e = Math.pow(10, Math.max(c, d))), (mul(a, e) + mul(b, e)) / e;
};
// 减法
Public.Subtraction = function (a, b) {
  var c, d, e;
  try {
    c = a.toString().split(".")[1].length;
  } catch (f) {
    c = 0;
  }
  try {
    d = b.toString().split(".")[1].length;
  } catch (f) {
    d = 0;
  }
  return (e = Math.pow(10, Math.max(c, d))), (mul(a, e) - mul(b, e)) / e;
};
// 参数val为内容，num为需要保留的位数 bl为true则去除无效零
Public.toIntercept = function (_val, num, bl, debug) {
  var val = String(_val)
  if (val == undefined) return 0; //
  // var _num = Number(val).toFixed(num + 1); // 补零
  var de = val.indexOf('.')
  var arr = val.split('.')

  if (de > -1) { // 小数
    var rs = arr[1]
    if (rs.length >= num) { // 小数位多余需保留位数
      rs = rs.substring(0, num)
      arr[1] = rs
    } else {
      // 补零
      for (var i = 0; i < num; i++) {
        rs[i] === undefined ? rs = rs + '0' : ''
      }
      arr[1] = rs
    }
    return bl ? parseFloat(Number(arr.join('.'))) : arr.join('.')
  } else {// 整数
    return bl ? val : Number(val).toFixed(num)
  }
};
// 数组去重 根据数组中的对象
Public.repeat = function (arr, key) {
  console.log(arr)
  const res = new Map();
  return arr.filter((a) => !res.has(a[key]) && res.set(a[key], 1))
},
  // 乘法
  Public.Multiplication = function (arg1, arg2) {
    var arg1 = isNaN(Number(arg1)) ? 0 : Number(arg1);
    var arg2 = isNaN(Number(arg2)) ? 0 : Number(arg2);
    var r1, r2, m, n, q;
    if (parseInt(arg1) == arg1) {
      r1 = 0;
    } else {
      r1 = arg1.toString().split(".")[1].length;
    }
    if (parseInt(arg2) == arg2) {
      r2 = 0;
    } else {
      r2 = arg2.toString().split(".")[1].length;
    }
    m = Math.pow(10, r1);
    n = Math.pow(10, r2);
    q = m * n;
    var sum = (arg1 * m * (arg2 * n)) / q;
    return sum;
  };
Public.toPercent = function (val) {
  return Number(val) * 100 + "%";
};
// 除法
Public.Division = function (a, b) {
  var a = a == "" || isNaN(Number(a)) ? 0 : Number(a);
  var b = b == "" || isNaN(Number(b)) ? 0 : Number(b);
  var c,
    d,
    e = 0,
    f = 0;
  try {
    e = a.toString().split(".")[1].length;
  } catch (g) {
  }
  try {
    f = b.toString().split(".")[1].length;
  } catch (g) {
  }
  return (
    (c = Number(a.toString().replace(".", ""))),
      (d = Number(b.toString().replace(".", ""))),
      mul(c / d, Math.pow(10, f - e))
  );
};
Public.toLowFixed1 = function (num, n) {
  var c, e;
  try {
    c = num.toString().split(".")[1].length;
  } catch (f) {
    c = 0;
  }
  e = Math.pow(10, Math.max(0, n));
  let str = mul(num, e) / e;
  str = str + "";
  if (str.indexOf(".") == -1) {
    str = str + ".0000000000";
  } else {
    str = str + "00000000";
  }
  return str.substring(0, str.indexOf(".") + n + 1);
};
Public.formatSeconds = function (value) {
  var theTime = parseInt(value);// 需要转换的时间秒
  var theTime1 = 0;// 分
  var theTime2 = 0;// 小时
  var theTime3 = 0;// 天
  if (theTime > 60) {
    theTime1 = parseInt(theTime / 60);
    theTime = parseInt(theTime % 60);
    if (theTime1 > 60) {
      theTime2 = parseInt(theTime1 / 60);
      theTime1 = parseInt(theTime1 % 60);
      if (theTime2 > 24) {
        //大于24小时
        theTime3 = parseInt(theTime2 / 24);
        theTime2 = parseInt(theTime2 % 24);
      }
    }
  }
  var result = '';
  if (theTime > 0) {
    result = "" + parseInt(theTime) + "秒";
  }
  if (theTime1 > 0) {
    result = "" + parseInt(theTime1) + "分" + result;
  }
  if (theTime2 > 0) {
    result = "" + parseInt(theTime2) + "小时" + result;
  }
  if (theTime3 > 0) {
    result = "" + parseInt(theTime3) + "天" + result;
  }
  return result;
}
// 保留小数位  btc btc_usdt btc/usdt   字母不区分大小写
Public.cutDot = function (num, type) {
  if (type.indexOf("_") != -1) {
    type = type.split("_")[0];
  }
  if (type.indexOf("/") != -1) {
    type = type.split("/")[0];
  }
  type = type.toUpperCase();
  if (type == "BTC") {
    return this.toLowFixed1(parseFloat(num), 6);
  } else if (type == "XRP") {
    return this.toLowFixed1(parseFloat(num), 4);
  } else if (type == "ETH") {
    return this.toLowFixed1(parseFloat(num), 6);
  } else if (type == "LTC") {
    return this.toLowFixed1(parseFloat(num), 2);
  } else if (type == "EOS") {
    return this.toLowFixed1(parseFloat(num), 4);
  } else if (type == "BCH") {
    return this.toLowFixed1(parseFloat(num), 2);
  } else if (type == "ETC") {
    return this.toLowFixed1(parseFloat(num), 4);
  } else if (type == "TRX") {
    return this.toLowFixed1(parseFloat(num), 6);
  } else if (type == "ZEC") {
    return this.toLowFixed1(parseFloat(num), 2);
  } else if (type == "DASH") {
    return this.toLowFixed1(parseFloat(num), 2);
  } else if (type == "USDT") {
    return this.toLowFixed1(parseFloat(num), 4);
  } else if (type == "CNY") {
    return this.toLowFixed1(parseFloat(num), 2);
  } else if (type == "NUM") {
    return this.toLowFixed1(parseFloat(num), 6);
  } else if (type == "UDR") {
    // 涨跌幅
    return this.toLowFixed1(parseFloat(num), 2);
  } else {
    return this.toLowFixed1(parseFloat(num), 8);
  }
};
// 百分数转小数
Public.toPoint = function (percent) {
  if (percent == 0) {
    return 0;
  }
  var str = percent.replace("%", "");
  str = str / 100;
  return str;
};
// 验证正整数
Public.integer = function (value) {
  var reg = /^\+?[1-9][0-9]*$/;
  if (!reg.test(value)) {
    return false;
  } else {
    return true;
  }
};
// 验证小数最多8位
Public.integerDecimal = function (value) {
  var reg = /^\d{1}$|^\d{1}(\.?\d{1,8})$/;
  if (!reg.test(value)) {
    return false;
  } else {
    return true;
  }
};
// 时间戳转化
Public.timestampToTime = function (timestamp, mat) {
  var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y, M, D, h, m, s;
  var format = '-'
  if (mat) format = mat
  Y = date.getFullYear() + format;
  M =
    (date.getMonth() < 9 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) +
    format;
  D = (date.getDate() < 9 ? "0" + date.getDate() : date.getDate()) + " ";
  h = (date.getHours() < 9 ? "0" + date.getHours() : date.getHours()) + ":";
  m =
    (date.getMinutes() < 9 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
  s = date.getSeconds() < 9 ? "0" + date.getSeconds() : date.getSeconds();

  return Y + M + D + h + m + s;
};
// 时间戳转化
Public.timestampToTimeshian = function (timestamp) {
  var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y, M, D, h, m, s;
  Y = date.getFullYear() + "-";
  M =
    (date.getMonth() < 9 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) +
    "-";
  D = (date.getDate() < 9 ? "0" + date.getDate() : date.getDate()) + " ";
  h = (date.getHours() < 9 ? "0" + date.getHours() : date.getHours()) + ":";
  m =
    (date.getMinutes() < 9 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
  s = date.getSeconds() < 9 ? "0" + date.getSeconds() : date.getSeconds();
  return Y + M + D;
};
Public.timestampToTimeshian1 = function (timestamp) {
  var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y, M, D, h, m, s;
  Y = date.getFullYear() + "-";
  M =
    (date.getMonth() < 9 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) +
    "-";
  D = (date.getDate() < 9 ? "0" + date.getDate() : date.getDate()) + " ";
  h = (date.getHours() < 9 ? "0" + date.getHours() : date.getHours()) + ":";
  m =
    (date.getMinutes() < 9 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
  s = date.getSeconds() < 9 ? "0" + date.getSeconds() : date.getSeconds();
  return h + m + s;
};

// 函数节流
// throttle(fn, 1000) 函数foo每次执行间隔最小为1000ms
// 第一个参数也可以为数组：throttle([fn, arg1, arg2...], 1000)
// 同一页面多个节流时需要传mark(String类型) 区分全局变量防止冲突
Public.throttle = function (obj, t, mark) {
  var windowVar = (function () {
    if (mark == undefined) return "$$THROTTLE_CTRL";
    if (mark.constructor === String || mark.constructor === Number)
      return "$$THROTTLE_CTRL" + "_" + mark;
    else return "$$THROTTLE_CTRL";
  })();
  if (!window[windowVar]) {
    window[windowVar] = true;

    if (obj.constructor === Function) obj();
    if (obj.constructor !== Function && obj.constructor !== Array)
      throw new TypeError(
        "throttle(option , time) 'option' Musb be a Function or Array"
      );
    if (obj.constructor === Array) {
      var fn = obj[0];
      if (fn.constructor !== Function)
        throw new TypeError("throttle(arr , time) 'arr[0]' Musb be a Function");
      obj.splice(0, 1);
      fn.apply(null, obj);
    }
    window.setTimeout(function () {
      window[windowVar] = null;
    }, t);
  }
};
//密码格式
Public.pwd = function (val) {
  var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/;
  return reg.test(val);
};
//邮箱验证
Public.email = function (em) {
  // var ema = /^[A-Za-z0-9\u4e00-\u9fa5_]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  // if (!ema.test(em)) {
  //   return false;
  // } else {
  //   return true;
  // }
  var exist = em.indexOf('@') > -1;
  if (exist) {
    return true;
  } else {
    return false;
  }

};
// 手机正则
Public.checkMobile = function (sMobile) {

  var phone = sMobile.trim();
  // var reg = /^1\d{10}$/;
  // return reg.test(phone);
  if (isNaN(Number(phone))) {
    return false
  }
  return true


};
//身份证号验证
Public.isCardID = function (sId) {
  if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(sId)) {
    return false;
  } else {
    return true;
  }
};
//银行卡号验证
Public.bank_car = function (val) {
  if (!isNaN(val) && val.length > 10 && val.length < 20) {
    return true;
  } else {
    return false;
  }
};
Public.Eliminate = function (str) {
  var rs = "";
  for (var i = 0; i < str.length; i++) {
    rs = rs + str.substr(i, 1).replace(/^\s+/, "");
  }
  return rs;
};
//验证码格式验证
Public.code = function (val) {
  var reg = /^\d{6}$/;
  return reg.test(val);
};
Public.name = function (val) {
  var reg1 = /^([\u4e00-\u9fa5]){2,7}$/; //只能是中文，长度为2-7位
  var reg2 = /^[a-zA-Z\/ ]{2,20}$/; //英文
  if (reg1.test(val) || reg2.test(val)) {
    return true;
  } else {
    return false;
  }
  //return reg2.test(val);
};
//验证是否为大于0的非空纯数字
Public.Ints = function (val) {
  if (!val) {
    return false;
  } else if (val <= 0) {
    return false;
  } else {
    return true;
  }
};
// 正数
// Public.validateNums = function (num) {
//  var reg = /^\d+$|^\d+\.\d+$/g
//   if(reg.test(num)) return true;
//   return false ;
// }
Public.isInteger = function (obj) {
  var obj = Number(obj);
  return Math.floor(obj) === obj;
};
//倒计时执行函数封装
Public.setTime = function (_this) {
  _this.btnCode = {
    time: 59,
    disabled: true
  };
  _this.$message({
    // message: _this.$t('header.tips[1]'),
    message: "验证码发送成功",
    type: "success"
  });
  var path = _this.$route.path;
  var set = setInterval(function () {
    if (_this.$route.path != path) clearInterval(set);
    _this.btnCode.time--;
    if (_this.btnCode.time <= 0) {
      _this.btnCode = {
        time: "重获验证码",
        disabled: false
      };
      clearInterval(set);
    }
  }, 1000);
};

//密码加密
Public.transPwd = function (msg, type, _this) {


};
//提示信息封装
Public.msg = function (msg, type, _this) {
  // _this.$message({
  //   showClose: true,
  //   message: msg,
  //   type: type,
  //   time: 2100000
  // });
  const h = _this.$createElement;
  _this.$notify[type]({
    message: msg,
  });

};
//传一个手机号 返回手机号的前3位和后四位 其他的显示* (手机号加密)
Public.telStart = function (num, type) {
  let _num = String(num)
  //获得手机号的前3位
  if (!_num) {
    return false;
  }
  var a = _num.slice(0, 3);
  var b = _num.slice(7);
  var ok = a + "****" + b;
  if (type === 'bank') {

    var reg = /^(\d{4})\d+(\d{4})$/;
    _num = _num.replace(reg, "$1 **** **** $2");
    return _num
  }
  return ok;
};
Public.Trim = function (str) {
  return str.replace(/(^\s*)|(\s*$)/g, "");
};
Public.codeImg = function (id) {
  // 生成验证码
  function yanzhenma(window, document) {
    var size = 4; //设置验证码长度
    function GVerify(options) {
      //创建一个图形验证码对象，接收options对象为参数
      this.options = {
        //默认options参数值
        id: "", //容器Id
        canvasId: "verifyCanvas", //canvas的ID
        width: "200", //默认canvas宽度
        height: "44", //默认canvas高度
        type: "blend", //图形验证码默认类型blend:数字字母混合类型、number:纯数字、letter:纯字母
        code: ""
      };
      if (Object.prototype.toString.call(options) == "[object Object]") {
        //判断传入参数类型
        for (var i in options) {
          //根据传入的参数，修改默认参数值
          this.options[i] = options[i];
        }
      } else {
        this.options.id = options;
      }
      this.options.numArr = "0,1,2,3,4,5,6,7,8,9".split(",");
      this.options.letterArr = getAllLetter();
      this._init();
      this.refresh();
    }

    GVerify.prototype = {
      /**版本号**/
      version: "1.0.0",
      /**初始化方法**/
      _init: function () {
        var con = document.getElementById(this.options.id);
        var canvas = document.createElement("canvas");
        this.options.width = con.offsetWidth > 0 ? con.offsetWidth : "200";
        this.options.height = con.offsetHeight > 0 ? con.offsetHeight : "44";
        canvas.id = this.options.canvasId;
        canvas.width = this.options.width;
        canvas.height = this.options.height;
        canvas.style.cursor = "pointer";
        canvas.innerHTML = "您的浏览器版本不支持canvas";
        con.appendChild(canvas);
        var parent = this;
        canvas.onclick = function () {
          parent.refresh();
        };
      },
      /**生成验证码**/
      refresh: function () {
        this.options.code = "";
        var canvas = document.getElementById(this.options.canvasId);
        if (canvas.getContext) {
          var ctx = canvas.getContext("2d");
        } else {
          return;
        }
        ctx.textBaseline = "middle";
        ctx.fillStyle = randomColor(180, 240);
        ctx.fillRect(0, 0, this.options.width, this.options.height);
        if (this.options.type == "blend") {
          //判断验证码类型
          var txtArr = this.options.numArr.concat(this.options.letterArr);
        } else if (this.options.type == "number") {
          var txtArr = this.options.numArr;
        } else {
          var txtArr = this.options.letterArr;
        }
        for (var i = 1; i <= size; i++) {
          var txt = txtArr[randomNum(0, txtArr.length)];
          this.options.code += txt;
          ctx.font =
            randomNum(this.options.height, this.options.height) + "px SimHei"; //随机生成字体大小
          ctx.fillStyle = randomColor(50, 160); //随机生成字体颜色
          ctx.shadowOffsetX = randomNum(-3, 3);
          ctx.shadowOffsetY = randomNum(-3, 3);
          ctx.shadowBlur = randomNum(-3, 3);
          ctx.shadowColor = "rgba(0, 0, 0, 0.3)";
          var x = (this.options.width / (size + 1)) * i;
          var y = this.options.height / 2;
          var deg = randomNum(-30, 30);
          /**设置旋转角度和坐标原点**/
          ctx.translate(x, y);
          ctx.rotate((deg * Math.PI) / 180);
          ctx.fillText(txt, 0, 0);
          /**恢复旋转角度和坐标原点**/
          ctx.rotate((-deg * Math.PI) / 180);
          ctx.translate(-x, -y);
        }
        /**绘制干扰线**/
        for (var i = 0; i < 4; i++) {
          ctx.strokeStyle = randomColor(40, 180);
          ctx.beginPath();
          ctx.moveTo(
            randomNum(0, this.options.width),
            randomNum(0, this.options.height)
          );
          ctx.lineTo(
            randomNum(0, this.options.width),
            randomNum(0, this.options.height)
          );
          ctx.stroke();
        }
        /**绘制干扰点**/
        for (var i = 0; i < this.options.width / 4; i++) {
          ctx.fillStyle = randomColor(0, 255);
          ctx.beginPath();
          ctx.arc(
            randomNum(0, this.options.width),
            randomNum(0, this.options.height),
            1,
            0,
            2 * Math.PI
          );
          ctx.fill();
        }
      },
      /**验证验证码**/
      validate: function (code) {
        var code = code.toLowerCase();
        var v_code = this.options.code.toLowerCase();
        if (code == v_code) {
          return true;
        } else {
          this.refresh();
          return false;
        }
      }
    };

    /**生成字母数组**/
    function getAllLetter() {
      var letterStr =
        "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
      return letterStr.split(",");
    }

    /**生成一个随机数**/
    function randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    }

    /**生成一个随机色**/
    function randomColor(min, max) {
      var r = randomNum(min, max);
      var g = randomNum(min, max);
      var b = randomNum(min, max);
      return "rgb(" + r + "," + g + "," + b + ")";
    }

    window.GVerify = GVerify;
  }

  yanzhenma(window, document);
  new GVerify(id);
};
//页面路由跳转封装
Public.go = function (url, time, _this) {
  _this.$router.push({
    path: url
  });
};
Public.scrollTop = function () {
  document.body.scrollTop = document.documentElement.scrollTop = 0;
};

function mul(a, b) {
  var c = 0,
    d = a.toString(),
    e = b.toString();
  try {
    c += d.split(".")[1].length;
  } catch (f) {
  }
  try {
    c += e.split(".")[1].length;
  } catch (f) {
  }
  return (
    (Number(d.replace(".", "")) * Number(e.replace(".", ""))) / Math.pow(10, c)
  );
}

//判断是否登录执行函数
Public.isLogin = function (_this) {
  if (!sessionStorage.account || !sessionStorage.token) {
    _this.$public.msg(_this.$t("confirm[4]"), "warning", _this);
    _this.$public.go("login", 1000, _this);
  }
};
//提示信息封装
Public.confirm = function (msg, what, _this) {
  _this
    .$confirm(msg, _this.$t("confirm[0]"), {
      confirmButtonText: _this.$t("confirm[1]"),
      cancelButtonText: _this.$t("confirm[2]"),
      type: "warning"
    })
    .then(() => {
      _this.$public.go(what, 800, _this);
    })
    .catch(() => {
      _this.$message({
        type: "info",
        message: _this.$t("confirm[3]")
      });
    });
  return false;
};

//提示没有设置资金密码
Public.confirm_fund_pwd = function (msg, what, _this) {
  _this
    .$confirm(msg, _this.$t("confirm[0]"), {
      confirmButtonText: _this.$t("confirm[1]"),
      cancelButtonText: _this.$t("confirm[2]"),
      type: "warning"
    })
    .then(() => {
      _this.$public.go(what, 800, _this);
    })
    .catch(() => {
      _this.$message({
        type: "info",
        message: _this.$t("confirm[3]")
      });
    });
  return false;
};

// 币种图标
Public.transCodeImg = function (code) {
  return transCodeImg(code);
};
//清除对象值
Public.clearObj = function (obj, save) {
  for (var i in obj) {
    if (i !== save) {
      obj[i] = undefined;
    }
  }
};
//谷歌验证
Public.googleVerify = function (isLogin) {
  //直接调用 不用额外判断用户谷歌开关状态 内部统一处理
  return new Promise((resolve, reject) => {
    if (isLogin || store.getters.googleState == 1) {
      //谷歌验证已开启的用户
      // '请输入谷歌验证码', '谷歌验证'
      vue
        .$prompt(
          vue.$t("googleDialog.tips[0]"),
          vue.$t("googleDialog.tips[1]"),
          {
            confirmButtonText: vue.$t("center.baseInfo[33]"),
            cancelButtonText: vue.$t("center.baseInfo[34]"),
            customClass: "prompt_googleVerify",
            inputType: "password",
            inputPattern: /^\d{6}$/,
            inputErrorMessage: vue.$t("googleDialog.tips[2]")
          }
        )
        .then(data => {
          // 请求谷歌验证码接口，成功返回true 失败false
          let _data = {
            code: data.value,
            stockUserId: store.getters.Id
          };
          checkGoogleCode(_data).then(res => {
            if (res.data.code == 200) {
              resolve(true);
            } else {
              resolve(false);
            }
          });
        })
        .catch(() => {
          reject("取消输入");
        });
    } else {
      //谷歌验证关闭的用户
      resolve(true);
    }
  });
};
// 保留位数
Public.savePoint = function (code) {
  if (!code) {
    return 2;
  }
  var _code = code;
  if (_code.indexOf("/") > -1) {
    _code = _code.replace("/", "_");
  }
  _code = _code.toLowerCase();

  var obj = {
    btc_usdt: 2,
    eth_usdt: 2,
    bch_usdt: 2,
    etc_usdt: 4,
    xrp_usdt: 5,
    ltc_usdt: 2,
    eos_usdt: 4,
    dash_usdt: 2,
    ht_usdt: 4,
    atom_usdt: 4,
    trx_usdt: 6,
    imc_usdt: 4,

    link_usdt: 4,
    bsv_usdt: 4,
    trx_usdt: 6,
    ada_usdt: 6,
    xlm_usdt: 6,
    xmr_usdt: 2,
    neo_usdt: 2,
    xem_usdt: 4,
    iota_usdt: 4,
    zec_usdt: 2,
    omg_usdt: 4,
    ont_usdt: 4,
    defalut: 2
  };
  var num = obj[_code] ? obj[_code] : obj.defalut;
  return num;
};
Public.cpTime = function (endTime) {
  let start = new Date().getTime()
  let end = new Date(endTime).getTime()
  let time = end - start;
  if (time >= 0) {
    let day = Math.floor(time / 86400000);
    time = time - day * 86400000;
    let hours = Math.floor(time / 3600000);
    time = time - hours * 3600000;
    let min = Math.floor(time / 60000);
    time = time - min * 60000;
    let second = Math.floor(time / 1000);
    let obj = {
      day,
      hours,
      min,
      second
    };
    //   let obj = {
    //     day:day<10?'0'+day:day,
    //     hours:hours<10?'0'+hours:hours,
    //     min:min<10?'0'+min:min,
    //     second:second<10?'0'+second:second
    // };
    obj.hours = obj.day * 24 + obj.hours * 1
    obj.hours < 10 ? obj.hours = '0' + obj.hours : ''
    obj.min < 10 ? obj.min = '0' + obj.min : ''
    obj.second < 10 ? obj.second = '0' + obj.second : ''
    return `${obj.hours}:${obj.min}:${obj.second}`
  } else {
    return false
  }
},
// 保留位数 下单数量
  Public.savePoint_order = function (code) {
    if (!code) {
      return 6;
    }
    var _code = code;
    if (_code.indexOf("/") > -1) {
      _code = _code.replace("/", "_");
    }
    _code = _code.toLowerCase();

    var obj = {
      btc_usdt: 6,
      eth_usdt: 4,
      bch_usdt: 4,
      etc_usdt: 4,
      xrp_usdt: 2,
      ltc_usdt: 4,
      eos_usdt: 4,
      dash_usdt: 4,
      atom_usdt: 4,
      ht_usdt: 4,
      imc_usdt: 4,
      link_usdt: 4,
      bsv_usdt: 4,
      trx_usdt: 4,
      ada_usdt: 4,
      xlm_usdt: 4,
      xmr_usdt: 4,
      neo_usdt: 4,
      xem_usdt: 4,
      iota_usdt: 4,
      zec_usdt: 4,
      omg_usdt: 4,
      ont_usdt: 4,

      defalut: 2
    };
    var num = obj[_code] ? obj[_code] : obj.defalut;
    return num;
  };
Public.transPrice_order = function (val, code, bl) {
  //按需将价格位数保留
  if (val == undefined) return 0; //
  var num = this.savePoint_order(code);
  var _num = Number(val).toFixed(num + 1);
  if (bl) {
    return parseFloat(Number(_num.substr(0, _num.length - 1)));
  }
  return _num.substr(0, _num.length - 1);
};


Public.CryptographicLand = function (argument) {
  //登录密码加密
  return md5(argument);

};
Public.ungzip = function (msg, call) {


  let reader = new FileReader();
  reader.onload = () => {
    let result = JSON.parse(
      this.$pako.inflate(reader.result, {to: "string"})
    );
  };
  let blob = msg.data;
  try {
    reader.readAsBinaryString(blob);
  } catch (err) {
    console.log(err);
  }


};

Public.Cryptographiccapital = function (argument) {
  //资金密码加密
  return md5(argument);
};
Public.transPrice = function (val, code, bl) {
  //按需将价格位数保留
  if (val == undefined) return 0; //
  var num = this.savePoint(code);
  var _num = Number(val).toFixed(num + 1);
  if (bl) {
    return parseFloat(_num.substr(0, _num.length - 1));
  }
  return _num.substr(0, _num.length - 1);
};


Public.CryptographicLand = function (argument) {
  //登录密码加密
  return md5(argument);
};

Public.Cryptographiccapital = function (argument) {
  //资金密码加密
  return md5(argument);
};
// 加密
Public.encrypt = function (word) {
  return word
  // return vue.$jse.encrypt(String(word))
  var key = CryptoJS.enc.Utf8.parse(keyStr);
  var srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    // padding: CryptoJS.pad.Pkcs7
    padding: CryptoJS.pad.ZeroPadding
  }); // 加密模式为ECB，补码方式为PKCS5Padding（也就是PKCS7）

  return encrypted.toString();
};
// 解密
Public.decrypt = function (word) {
  var key = CryptoJS.enc.Utf8.parse(keyStr);
  var decrypt = CryptoJS.AES.decrypt(word, key, {
    mode: CryptoJS.mode.ECB,
    // padding: CryptoJS.pad.Pkcs7
    padding: CryptoJS.pad.ZeroPadding
  });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
};
// 獲取 cookie
Public.getCookie = function (name) {
  var arr,
    reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if ((arr = document.cookie.match(reg))) return unescape(arr[2]);
  else return null;
};

//获取浏览器查询字符串
Public.GetQueryString = function (name) {
  //截取url
  var reg = new RegExp("(^|&|)" + name + "=([^&?]*)(&|$|)", "i");
  var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
  var context = "";
  if (r != null) context = r[2];
  reg = null;
  r = null;
  return context == null || context == "" || context == "undefined"
    ? ""
    : context;
};

Public.webSocket = function (url) {
  let _webSocket;
  if ("WebSocket" in window) {
    _webSocket = new WebSocket(url);
  } else if ("MozWebSocket" in window) {
    _webSocket = new MozWebSocket(url);
  } else {
    _webSocket = new SockJS(url);
  }
  return _webSocket;
};
export default Public;
