function isString(str) {
  return (typeof str == 'string') && str.constructor == String;
}
function isArray(obj) {
  return (typeof obj == 'object') && obj.constructor == Array;
}


function sub_last(str){
  return str.substring(0, str.length - 1)
}
function trim(str) { return str.replace(/(^s*)|(s*$)/g, "");}
function e(e) {
    var r = ""; for (var t in e) r += (r ? "&" : "") + t + "=" + e[t]; return r;
}
//节流
let _throttle =function (fn, interval) {
  var enterTime = 0;//触发的时间
  var gapTime = interval || 300 ;//间隔时间，如果interval不传，则默认300ms
  return function() {
    var context = this;
    var backTime = new Date();//第一次函数return即触发的时间
    if (backTime - enterTime > gapTime) {
      fn.call(context,arguments);
      enterTime = backTime;//赋值给第一次触发的时间，这样就保存了第二次触发的时间
    }
  };
}.bind(this);

function _debounce(func, wait) {
  let timer;
  return function() {
    let context = this; // 注意 this 指向
    let args = arguments; // arguments中存着e
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args)
    }, wait)
  }
}
function utf16to8(str) {
  var out, i, len, c; out = ""; len = str.length;
  for (i = 0; i < len; i++) {
    c = str.charCodeAt(i);
    if ((c >= 0x0001) && (c <= 0x007F)) {
      out += str.charAt(i);
    } else if (c > 0x07FF) {
      out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
      out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
      out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
    } else {
      out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
      out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
    }
  }
  return out;
}

function utf8to16(str) {
  var out, i, len, c; var char2, char3;
  out = "";len = str.length; i = 0;
  while (i < len) {
    c = str.charCodeAt(i++);
    switch (c >> 4) {
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += str.charAt(i - 1);
        break;
      case 12: case 13:
        // 110x xxxx   10xx xxxx
        char2 = str.charCodeAt(i++);
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = str.charCodeAt(i++);
        char3 = str.charCodeAt(i++);
        out += String.fromCharCode(((c & 0x0F) << 12) |
          ((char2 & 0x3F) << 6) |
          ((char3 & 0x3F) << 0));
        break;
    }
  }
  return out;
}


function unserialize_o(ss) {
  var p = 0, ht = [], hv = 1,r = null;
  function unser_null() { p++; return null; }
  function unser_boolean() { p++; var b = (ss.charAt(p++) == '1');  p++; return b; }
  function unser_integer() {  p++;
    var i = parseInt(ss.substring(p, p = ss.indexOf(';', p))); p++; return i;}
  function unser_double() {
    p++;var d = ss.substring(p, p = ss.indexOf(';', p));
    switch (d) {
      case 'INF': d = Number.POSITIVE_INFINITY; break;
      case '-INF': d = Number.NEGATIVE_INFINITY; break;
      default: d = parseFloat(d);
    }
    p++; return d;
  }
  function unser_string() {
    p++;var l = parseInt(ss.substring(p, p = ss.indexOf(':', p)));
    p += 2;  var s = utf8to16(ss.substring(p, p += l));
    p += 2; return s;
  }
  function unser_array() {
    p++; var n = parseInt(ss.substring(p, p = ss.indexOf(':', p)));
    p += 2; var a = []; ht[hv++] = a;
    for (var i = 0; i < n; i++) {
      var k;
      switch (ss.charAt(p++)) {
        case 'i': k = unser_integer(); break;
        case 's': k = unser_string(); break;
        case 'U': k = unser_unicode_string(); break;
        default: return false;
      }
      a[k] = __unserialize();
    }
    p++; return a;
  }
  function unser_object() {
    p++;
    var l = parseInt(ss.substring(p, p = ss.indexOf(':', p)));
    p += 2;
    var cn = utf8to16(ss.substring(p, p += l));
    p += 2;
    var n = parseInt(ss.substring(p, p = ss.indexOf(':', p)));
    p += 2;
    if (eval(['typeof(', cn, ') == "undefined"'].join(''))) {
      eval(['function ', cn, '(){}'].join(''));
    }
    var o = eval(['new ', cn, '()'].join(''));
    ht[hv++] = o;
    for (var i = 0; i < n; i++) {
      var k;
      switch (ss.charAt(p++)) {
        case 's': k = unser_string(); break;
        case 'U': k = unser_unicode_string(); break;
        default: return false;
      }
      if (k.charAt(0) == '\0') {
        k = k.substring(k.indexOf('\0', 1) + 1, k.length);
      }
      o[k] = __unserialize();
    }
    p++;
    if (typeof (o.__wakeup) == 'function') o.__wakeup();
    return o;
  }
  function unser_custom_object() {
    p++;
    var l = parseInt(ss.substring(p, p = ss.indexOf(':', p)));
    p += 2;
    var cn = utf8to16(ss.substring(p, p += l));
    p += 2;
    var n = parseInt(ss.substring(p, p = ss.indexOf(':', p)));
    p += 2;
    if (eval(['typeof(', cn, ') == "undefined"'].join(''))) {
      eval(['function ', cn, '(){}'].join(''));
    }
    var o = eval(['new ', cn, '()'].join(''));
    ht[hv++] = o;
    if (typeof (o.unserialize) != 'function') p += n;
    else o.unserialize(ss.substring(p, p += n));
    p++;
    return o;
  }

  function unser_unicode_string() {
    p++; var l = parseInt(ss.substring(p, p = ss.indexOf(':', p)));
    p += 2; var sb = [];
    for (i = 0; i < l; i++) {
      if ((sb[i] = ss.charAt(p++)) == '\\') {
        sb[i] = String.fromCharCode(parseInt(ss.substring(p, p += 4), 16));
      }
    }
    p += 2; return sb.join('');
  }
  function unser_ref() {   p++; var r = parseInt(ss.substring(p, p = ss.indexOf(';', p)));  p++; return ht[r];}
  function __unserialize() {
    switch (ss.charAt(p++)) {
      case 'N': return ht[hv++] = unser_null();
      case 'b': return ht[hv++] = unser_boolean();
      case 'i': return ht[hv++] = unser_integer();
      case 'd': return ht[hv++] = unser_double();
      case 's': return ht[hv++] = unser_string();
      case 'U': return ht[hv++] = unser_unicode_string();
      case 'r': return ht[hv++] = unser_ref();
      case 'a': return unser_array();
      case 'O': return unser_object();
      case 'C': return unser_custom_object();
      case 'R': return unser_ref();
      default: return false;
    }
  }
  return __unserialize();
}

//---数组序列化的反转---
function unserialize(ss) {
  if (ss=="" || ss==undefined || ss==null) return '';
  //ss ='a:2:{i:0;s:60:"/public/upload/comment/8704/2017/10-14/15079840099736199.png";i:1;s:60:"/public/upload/comment/8704/2017/10-14/15079840132718554.jpg";}';
  ss=ss.substring(7);
  var arr = ss.split('i:'), rs=new Array();
  for (var i = 0; i < arr.length;i++){
    var ind0 = arr[i].indexOf('/public');
    var ind1 = arr[i].indexOf('";');
    var txt = arr[i].substring(ind0, ind1);
    rs.push(txt);
  }
  return rs;
}

//-----判断一个对象是不是空对象--------
function isEmptyObject(obj) {
   for (var key in obj) { return false };
   return true
};

function gettimestamp(){
  var timestamp = Date.parse(new Date());
  timestamp = timestamp / 1000;
  return timestamp;
}


function measureText(text, fontSize = 10) {
  text = String(text);
  var text = text.split('');
  var width = 0;
  text.forEach(function (item) {
    if (/[a-zA-Z]/.test(item)) {
      width += 7;
    } else if (/[0-9]/.test(item)) {
      width += 5.5;
    } else if (/\./.test(item)) {
      width += 2.7;
    } else if (/-/.test(item)) {
      width += 3.25;
    } else if (/[\u4e00-\u9fa5]/.test(item)) {  //中文匹配
      width += 10;
    } else if (/\(|\)/.test(item)) {
      width += 3.73;
    } else if (/\s/.test(item)) {
      width += 2.5;
    } else if (/%/.test(item)) {
      width += 8;
    } else {
      width += 10;
    }
  });
  return width * fontSize / 10;
}

//验证手机号
function check_mobile(phoneMobile){
  var myreg = /^(((11[0-9]{1})|(12[0-9]{1})|(13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(19[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
  var ob={code:1};
  if (phoneMobile.length === 0) {
      ob.title='输入的手机号为空';
      ob.code=-1;
  } else if (phoneMobile.length < 11) {
      ob.title ='手机号长度有误！';
      ob.code = -1;
  } else if (!myreg.test(phoneMobile)) {
    ob.title = '手机号格式有误！';
    ob.code = -1;
  }
  return ob;
}

//获取随机元素
function get_rand_item(arr){
   if(!arr) return null;
   if(arr.length<=0) return null;
   if(arr.length==1) return arr[0];
   var ind=Math.floor(Math.random()*arr.length);
   if(ind==arr.length) ind=arr.length-1;
   return arr[ind];
}


function getDistance(lat1, lng1, lat2, lng2){
    var radLat1 = lat1*Math.PI / 180.0;
    var radLat2 = lat2*Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
        Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
    s = s *6378.137 ;// EARTH_RADIUS;
    return s;
}

//画布画椭圆矩形
function draw_randon_rect(ctx,x,y,r,w,h){
	ctx.save();
	// 开始绘制
	ctx.beginPath();
	// 因为边缘描边存在锯齿，最好指定使用 transparent 填充
	// 这里是使用 fill 还是 stroke都可以，二选一即可
	ctx.setFillStyle('rgb(237,188,150)')
	// ctx.setStrokeStyle('transparent')
	// 左上角
	ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)

	// border-top
	ctx.moveTo(x + r, y)
	ctx.lineTo(x + w - r, y)
	ctx.lineTo(x + w, y + r)
	// 右上角
	ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)

	// border-right
	ctx.lineTo(x + w, y + h - r)
	ctx.lineTo(x + w - r, y + h)
	// 右下角
	ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)

	// border-bottom
	ctx.lineTo(x + r, y + h)
	ctx.lineTo(x, y + h - r)
	// 左下角
	ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)

	// border-left
	ctx.lineTo(x, y + r)
	ctx.lineTo(x + r, y)
	// 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
	ctx.fill();
}

/**
 * @param {Object} num 数量,最大5
 * @param {Object} x   中心坐标
 * @param {Object} y   y中心坐标
 * @param {Object} sp  圆的间隔
 * @param {Object} r   圆的半径
 */
function  get_box_arr(num,x,y,sp,r){
	if(num==1) return [{x:x,y:y}];
	if(num==2) return [{x:x-sp/2-r,y:y},{x:x+sp/2+r,y:y}];
	if(num==3) return [{x:x-sp-2*r,y:y},{x:x,y:y},{x:x+sp+2*r,y:y}];
	if(num==4) return [{x:x-sp/2-r-sp-2*r,y:y},{x:x-sp/2-r,y:y},{x:x+sp/2+r,y:y},{x:x+sp/2+r+sp+2*r,y:y}];
	if(num==5) return [{x:x-2*sp-4*r,y:y},{x:x-sp-2*r,y:y},{x:x,y:y},{x:x+sp+2*r,y:y},{x:x+2*sp+4*r,y:y}];
}

/**
 * @param {Object} ctx   画图句柄
 * @param {Object} x     x坐标
 * @param {Object} y     y坐标
 * @param {Object} img   画的图片
 * @param {Object} color 边框的颜色
 */

function draw_circle(ctx,x,y,r,img,color,unit){
	ctx.save();
	ctx.beginPath(); //开始绘制
	ctx.arc(x,y,r,0,2 * Math.PI);
	ctx.setLineWidth(4 * unit);
	ctx.setStrokeStyle('red');
	ctx.setFillStyle("white");
	ctx.fill();
	ctx.clip();
    ctx.drawImage(img,x-r,y-r,2*r,2*r);
	ctx.restore();
}

function null_promise(){
   var promise=new Promise(function(resolve, reject){ var ob={code:-1,data:null};  resolve(ob); });	return promise;
}

//---合并数组去掉重复项---
function mergeArray(arr1, arr2){
    for (var i = 0 ; i < arr1.length ; i ++ ){
        for(var j = 0 ; j < arr2.length ; j ++ ){
            if (arr1[i] === arr2[j]){
                arr1.splice(i,1); //利用splice函数删除元素，从第i个位置，截取长度为1的元素
            }
        }
    }
    //alert(arr1.length)
    for(var i = 0; i <arr2.length; i++){
        arr1.push(arr2[i]);
    }
    return arr1;
}

//一个数组是否包含另一个数组
function isContained(aa, bb) {
    if (!(aa instanceof Array) || !(bb instanceof Array) || ((aa.length < bb.length))) { return false; }
    var aaStr = aa.toString();
    for (var i = 0; i < bb.length; i++) { if (aaStr.indexOf(bb[i]) < 0) return false; }
    return true;
}

//---base64位编码---
function base64_encode (str) { // 编码，配合encodeURIComponent使用
    var c1, c2, c3;
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var i = 0, len = str.length, strin = '';
    while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
            strin += base64EncodeChars.charAt(c1 >> 2);
            strin += base64EncodeChars.charAt((c1 & 0x3) << 4);
            strin += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            strin += base64EncodeChars.charAt(c1 >> 2);
            strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            strin += base64EncodeChars.charAt((c2 & 0xF) << 2);
            strin += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        strin += base64EncodeChars.charAt(c1 >> 2);
        strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        strin += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
        strin += base64EncodeChars.charAt(c3 & 0x3F)
    }
    return strin
}

function ob_to_parm(ob){
  var parm="";
  for( var key in ob){
      parm+="&"+key+"="+ob[key];
  }
  parm = parm.substr(1);
  return parm;
}

function encodeUTF8(s) {
  var i, r = [], c, x;
  for (i = 0; i < s.length; i++)
    if ((c = s.charCodeAt(i)) < 0x80) r.push(c);
    else if (c < 0x800) r.push(0xC0 + (c >> 6 & 0x1F), 0x80 + (c & 0x3F));
    else {
      if ((x = c ^ 0xD800) >> 10 == 0) //对四字节UTF-16转换为Unicode
        c = (x << 10) + (s.charCodeAt(++i) ^ 0xDC00) + 0x10000,
          r.push(0xF0 + (c >> 18 & 0x7), 0x80 + (c >> 12 & 0x3F));
      else r.push(0xE0 + (c >> 12 & 0xF));
      r.push(0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
    };
  return r;
};
// 字符串加密成 hex 字符串
function sha1(s) {
  var data = new Uint8Array(encodeUTF8(s))
  var i, j, t;
  var l = ((data.length + 8) >>> 6 << 4) + 16, s = new Uint8Array(l << 2);
  s.set(new Uint8Array(data.buffer)), s = new Uint32Array(s.buffer);
  for (t = new DataView(s.buffer), i = 0; i < l; i++)s[i] = t.getUint32(i << 2);
  s[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
  s[l - 1] = data.length << 3;
  var w = [], f = [
    function () { return m[1] & m[2] | ~m[1] & m[3]; },
    function () { return m[1] ^ m[2] ^ m[3]; },
    function () { return m[1] & m[2] | m[1] & m[3] | m[2] & m[3]; },
    function () { return m[1] ^ m[2] ^ m[3]; }
  ], rol = function (n, c) { return n << c | n >>> (32 - c); },
    k = [1518500249, 1859775393, -1894007588, -899497514],
    m = [1732584193, -271733879, null, null, -1009589776];
  m[2] = ~m[0], m[3] = ~m[1];
  for (i = 0; i < s.length; i += 16) {
    var o = m.slice(0);
    for (j = 0; j < 80; j++)
      w[j] = j < 16 ? s[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1),
        t = rol(m[0], 5) + f[j / 20 | 0]() + m[4] + w[j] + k[j / 20 | 0] | 0,
        m[1] = rol(m[1], 30), m.pop(), m.unshift(t);
    for (j = 0; j < 5; j++)m[j] = m[j] + o[j] | 0;
  };
  t = new DataView(new Uint32Array(m).buffer);
  for (var i = 0; i < 5; i++)m[i] = t.getUint32(i << 2);
 
  var hex = Array.prototype.map.call(new Uint8Array(new Uint32Array(m).buffer), function (e) {
    return (e < 16 ? "0" : "") + e.toString(16);
  }).join("");
 
  return hex;
};
//将JS数组对象按其某个键值重组成Map对象
function convert_arr_key(list,key){
	let keyObs = {}
	list.forEach(item => {
	    keyObs[item[key]] = item
	})
	return keyObs;
}

function ajax_ok(res){
	if(res.data.code==0 && res.data.data && res.data.data.pageData && res.data.data.pageData.length>0){
		return 1;
	}	
	return 0;
}
function ajax_ok2(res){
	if(res.data.code==0 && res.data.data && res.data.data.length>0){
		return 1;
	}	
	return 0;
}

function wx_back() {
    var arr=getCurrentPages();
    if(arr.length<=2){
        getApp().goto("/pages/index/index/index");
    }else{
        wx.navigateBack();
    }
}


//-------------------计算物流---------------
function calculatewuliu(code, o_shipping_price, goods_weight, out_of_weight,
                          goods_piece, user_addr, back_data,rs) {
    var price = 0;
    price += parseFloat(o_shipping_price);
    if (user_addr == null) {
        return 0;
    }
    //如果是包邮
    if (back_data && back_data.is_by_all && !back_data.no_free_goods && out_of_weight >= 0) {
        return 0;
    }
    //计算物流的config  item;
    var item = null;

    //------------循环获取config-----------
    function get_wuliu_config(region_id, code, rs) {
        var item = null, rslist = rs.pageData;
        for (var i = 0; i < rslist.length; i++) {
            if (rslist[i].code == code && rslist[i].region_id == region_id) {
                item = rslist[i];
            }
        }
        return item;
    }
    //-------循环获取config,code default-------
    function get_wuliu_default(code, rs) {
        var item = null, rslist = rs.pageData;
        for (var i = 0; i < rslist.length; i++) {
            if (rslist[i].shipping_code == code && rslist[i].is_default == 1) {
                item = rslist[i];
            }
        }
        return item;
    }

    //先根据 镇 县 区找计算的config
    item = get_wuliu_config(user_addr.district, code, rs);
    if (item == null) item = get_wuliu_config(user_addr.city, code, rs);
    if (item == null) item = get_wuliu_config(user_addr.province, code, rs);
    if (item == null) item = get_wuliu_default(code, rs);
    if (item == null) return o_shipping_price;
    var fw_price = 0, fp_price = 0;
    item = item.config;
    if (item == null) return o_shipping_price;

    //------超出重量----------
    if (back_data && back_data.is_by_all &&  out_of_weight<0){
        goods_weight+=out_of_weight;
        if(goods_weight<=0) goods_weight=-1;
    }

    //------按重量----------
    if (goods_weight >= 0 && item['money']) {
        fw_price = parseFloat(item['money']);
        if (goods_weight > item['first_weight']) {
            var fw = goods_weight - item['first_weight'];
            var n = Math.ceil(fw / item['second_weight'])
            fw_price = fw_price + n * parseFloat(item['add_money']);
        }
    }

    //------按件数----------
    if (goods_piece > 0 && item['piecemoney']) {
        fp_price = parseFloat(item['piecemoney']);
        if (goods_piece > item['first_piece']) {
            var fp = goods_piece - item['first_piece'];
            var m = Math.ceil(fp / item['second_piece'])
            fp_price = fp_price + m * parseFloat(item['add_piecemoney']);
        }
    }

    var rspice = parseFloat(price + fw_price + fp_price);
    return rspice;
}

function format_content(str_con){
    str_con=str_con.replaceAll("display:block;", 'display:none;');
    str_con=str_con.replaceAll("display: block;", 'display:none;');

    str_con=str_con.replaceAll("position:absolute;", '');
    str_con=str_con.replaceAll("position: absolute", '');

    return str_con;
}

module.exports = {
    formatTime: function(e, r) {
        var t = e ? new Date(1e3 * e) : new Date(), n = t.getFullYear(), o = t.getMonth() + 1, a = t.getDate(), u = t.getHours(), i = t.getMinutes(), f = t.getSeconds(), s = function(e) {
            return (e = e.toString())[1] ? e : "0" + e;
        };
        return void 0 !== r && 0 == r ? [ n, o, a ].map(s).join("-") + " " + [ u, i ].map(s).join(":") : [ n, o, a ].map(s).join("-") + " " + [ u, i, f ].map(s).join(":");
    },

    format: function(e, r) {
        var t = new Date();
        if(e) t.setTime(1e3 * e);
        var n = {
            "M+": t.getMonth() + 1,
            "d+": t.getDate(),
            "h+": t.getHours(),
            "m+": t.getMinutes(),
            "s+": t.getSeconds(),
            "q+": Math.floor((t.getMonth() + 3) / 3),
            S: t.getMilliseconds()
        };
        void 0 === r && (r = "yyyy-MM-dd hh:mm:ss"), /(y+)/.test(r) && (r = r.replace(RegExp.$1, (t.getFullYear() + "").substr(4 - RegExp.$1.length)));
        for (var o in n) new RegExp("(" + o + ")").test(r) && (r = r.replace(RegExp.$1, 1 == RegExp.$1.length ? n[o] : ("00" + n[o]).substr(("" + n[o]).length)));
        return r;
    },

	formar_no_full(e,char){
		var t= new Date(1e3 * e);
		var c="-";
		if(char) c=char;
	    return t.getFullYear() +c+(t.getMonth() + 1)+c+t.getDate();
	},

    formar_day(e,char){
        var t= new Date();
        if(e) t=new Date(1e3 * e);

        var c="-";
        if(char) c=char;
        var ck=function (e){
            return e>=10? e : "0" + e;
        }
        return t.getFullYear() +c+ck(t.getMonth() + 1)+c+ck(t.getDate());
    },

    json2Form: function(e) {
        var r = [];
        for (var t in e) r.push(encodeURIComponent(t) + "=" + encodeURIComponent(e[t]));
        return r.join("&");
    },
    randomString: function(e) {
        e = e || 32;
        for (var r = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", t = r.length, n = "", o = 0; o < e; o++) n += r.charAt(Math.floor(Math.random() * (t + 1)));
        return n;
    },
    inArray: function(e, r) {
        for (var t = 0; t < r.length; t++) if (e == r[t]) return !0;
        return !1;
    },
    sortSize: function(e, r) {
        return void 0 === r && (r = 0), r ? e.sort(function(e, r) {
            return r - e;
        }) : e.sort(function(e, r) {
            return e - r;
        }), e;
    },
    convertRequestArray: function(e, r) {
        for (var t = {}, n = 0; n < r.length; n++) t[e + "[" + n + "]"] = r[n];
        return t;
    },
    remainTime: function(e) {
        var r = "", t = !1, n = Math.floor(e / 864e5);
        r = n ? n + "天" : "", t = !!n, e -= 864e5 * n;
        var o = Math.floor(e / 36e5);
        r += o ? o + "时" : t ? "0时" : "", t = !!o, e -= 36e5 * o;
        var a = Math.floor(e / 6e4);
        r += a ? a + "分" : t ? "0分" : "", e -= 6e4 * a;
        var u = Math.floor(e / 1e3);
        return r += u ? u + "秒" : "0秒";
    },
    transTime: function(e) {
        var r = {
            hour: 0,
            minute: 0,
            second: 0
        }, t = Math.floor(e / 36e5);
        r.hour = t || "0", e -= 36e5 * t;
        var n = Math.floor(e / 6e4);
        r.minute = n || "0", e -= 6e4 * n;
        var o = Math.floor(e / 1e3);
        return r.second = o || "0", r;
    },
    Obj2Str: e,
    JumpTo: function(r, t, n) {
        var o = e(t);
        n ? wx.redirectTo({
            url: r + o
        }) : wx.navigateTo({
            url: r + o
        });
    },

    //分享注册，跳转到授权
    new_user_go:function (stoid,first_leader) {
        if(!first_leader) return false;
        getApp().request.get("/api/weshop/users/get/" + stoid  + "/" + first_leader,{
            success: function(e) {
                if (e.data.code == 0  && e.data.data ) {
                    // 提示框
                    wx.showModal({
                        title: '邀请登录',
                        content: e.data.data.vipname+'邀请你登录成为会员？',
                        success: function (res) {
                            if (res.confirm) {
                                getApp().goto("/packageE/pages/togoin/togoin");
                            }
                        }
                    })
                }
            }
        })
    },
    //检验等级价格
    get_plus_name_price:function(sw_arr,th){
        var that=this;
        //---如果后台又开等级卡的开关---
        if (sw_arr.rank_switch && sw_arr.rank_switch == "2") {
            th.setData({
                rank_switch: true
            });
            //---回调卡的列表---
            th.getPlusCardType(function (ob) {
                th.setData({
                    card_list: ob.card_list
                });
                var ti = setInterval(function () {
                    var user = getApp().globalData.userInfo;
                    if (!user) return false;
                    clearInterval(ti);

                    if (user.card_field && user['card_expiredate']) {
                        var str = user['card_expiredate'].replace(/-/g, '/');
                        var end = new Date(str);
                        end = Date.parse(end) / 1000;
                        var now = that.gettimestamp();

                        //--- 判断是等级会员，且在有效期范围内 ---
                        if (user.card_field && now < end) {
                            var card_name = ob.name_map.get(user.card_field);
                            if (card_name && card_name.length > 6) card_name = card_name.substring(0, 6);
                            var is_near_date = 0;
                            if (end - now < 60 * 60 * 30 * 24) is_near_date = 1; //如果小于30天

                            th.setData({
                                card_field: user.card_field,
                                card_name: card_name,
                                card_list: ob.card_list,
                                is_near_date:is_near_date
                            });
                        }

                    }

                }, 500)
            })

        }
    },

    get_active_info:function(prom_type, prom_id,stoid,func) {
        var url = '/api/weshop/activitylist/getActInfo1/'+stoid+'/'+prom_type+'/'+prom_id;
        getApp().promiseGet(url, {}).then(res => {
            if(res.data.code==0){
                func(res.data.data);
            }
        })
    },

    //是不是富友的返回
    fy_back(url,is_need_back,func){
        var fy=getApp().globalData.fuiou_pay;
        console.log('cart2-show:'+fy);
        if(fy){
            getApp().globalData.fuiou_pay=0;
            wx.showToast({
                title:'取消支付',
                icon:'none',
                duration:2500
            })

            if(is_need_back){
                if(url){
                    setTimeout(()=>{
                        getApp().goto(url);
                    },2000);
                }else{
                    if(func) {
                        func();
                    }else{
                        //支付失败
                        setTimeout(function () {
                            wx.navigateBack({ delta: 1 })
                        }, 1000)
                    }
                }
            }else{
                if(func) func();
            }
            return true ;

        }
        return false
    },

    //-- 优惠促销的数据的格式话 --
    format_yh_act(fir_act){
        var more_arr = [];
        if(fir_act){
            //减价
            if (fir_act.money > 0){

                more_arr.push({
                    text:'减价' + fir_act.money + '元',
                    is_fir:1
                });
            }
            if (fir_act.sale > 0) {
                more_arr.push({
                    text:'打' + fir_act.sale + '折',
                    is_fir:1
                });
            }
            if (fir_act.past == 1) {
                more_arr.push({
                    text:'包邮',
                    is_fir:1
                });
            }
            if (fir_act.intValue > 0){
                more_arr.push({
                    text:'送' + fir_act.intValue + '积分',
                    is_fir:1
                });
            }
            if (fir_act.couponId > 0) {
                more_arr.push({
                    text:'送' + fir_act.couponMoney + '元优惠券',
                    is_quan:1
                });
            }

            if (fir_act.gift_id) {
                var is_more_gf = fir_act.gift_id.split(',')
                if (is_more_gf.length > 1) {
                    more_arr.push({
                        text:'送赠品',
                        is_gift:1,
                        prom_id:fir_act.prom_id
                    });
                } else {
                    more_arr.push({
                        text:'送' + fir_act.goods_name + ' x' + fir_act.zp_num,
                        is_gift:1,
                        prom_id:fir_act.prom_id,
                        is_no_goto:1,//不进行跳转的意思
                    });
                }
            }
            if (fir_act.lb_id){
                more_arr.push({
                    text:'送' + fir_act.lbtitle,
                    lb_id:fir_act.lb_id
                });
            }
            if (fir_act.zxlb_id){
                more_arr.push({
                    text:'送' + fir_act.zxlbtitle,
                    zxlb_id:fir_act.zxlb_id
                });
            }
            if (fir_act.monthgiftbag_id){
                more_arr.push({
                    text:'送' + fir_act.monthgiftbag_title,
                    monthgiftbag_id:fir_act.monthgiftbag_id
                });
            }
        }
        return more_arr
    },
    
    //-- 长的提示框 --
    m_toast(txt){
        wx.showToast({
            title: txt,
            icon: 'none',
            duration: 2500
        })
    },
    //-- 支付的结果判断是不是完成了,通联支付pos收银的返回 --
    /**
     * @param ok_order_sn 判断是不是有支付过
     * @param back_url 如果是地址，就跳转，如果是back，就返回。如果是func，就是要回调
     * @param err_url  如果是地址，就跳转，如果是back，就返回。如果是func，就是要回调，如果是none，就没有反应，提示而已
     * @param func  因为是物理键的返回，所以要调用结果，查询结果
     * @param success  //成功的回调函数， 当back_url是func
     * @param fail     //失败的回调函数， 当err_url是func
     * @param is_navigateTo  //跳转的页面是不是要is_re_to
     */
    is_pay_ok(ok_order_sn,back_url,err_url,func,success,fail,is_navigateTo){

        //如果不是通联支付，立即返回
        if(!getApp().globalData.is_tonglian_pay) return false;
        getApp().globalData.is_tonglian_pay=0;

        if(!ok_order_sn) {
            return false;
        }
        if(!err_url){
            err_url="/pages/index/index/index";
        }
        //-- getEnterOptionsSync的信息会一直存在，很恶心 --
        let options = wx.getEnterOptionsSync();

        console.log("is_pay_ok");
        console.log(options);

        if (options.scene == '1038' && options.referrerInfo.appId=='wxef277996acc166c3') {
            let extraData = options.referrerInfo.extraData;
            if (!extraData) {
                 if(func) func();
            } else {
                // "支付成功";
                if (extraData.code == 'success') {
                    this.m_toast("支付成功")
                    //支付失败
                    setTimeout(function () {
                        if(back_url=='back') {
                            wx.navigateBack();
                        }
                        else if(back_url=='func'){
                            success();
                        }
                        else if(back_url!='none'){

                            if(is_navigateTo){
                                getApp().goto(back_url)  //跳到tabbar页
                            }else{
                                wx.redirectTo({ url: back_url});
                            }


                        }
                    },2000)
                }
                // "支付已取消";
                else if (extraData.code == 'cancel') {
                    this.m_toast("取消支付")

                    console.log('err_url-11');
                    console.log(err_url);

                    //支付失败
                    setTimeout(function () {
                        if(err_url=='back'){
                            wx.navigateBack();
                        }
                        else if(err_url=='func'){
                            fail();
                        }
                        else if(err_url!='none'){
                            if(is_navigateTo){
                                getApp.goto({ url: err_url, })  //跳到tabbar页
                            }else {
                                wx.redirectTo({ url: err_url});
                            }
                        }

                    },2000)
                }
                // "支付失败：" + extraData.errmsg;
                else {
                    this.m_toast("支付失败：" + extraData.errmsg)
                    //支付失败
                    setTimeout(function () {
                        if(err_url=='back'){
                            wx.navigateBack();
                        }else{
                            getApp().goto(err_url);
                        }
                    },2000)
                }

            }

        }
    },

    unserialize: unserialize,
    _throttle:_throttle,
    unserialize_o: unserialize_o,
    trim: trim,                   //去空格
    isEmptyObject: isEmptyObject, //判断空对象
    gettimestamp: gettimestamp,  //获取时间戳
    isString: isString,
    isArray: isArray,
    sub_last: sub_last,//去掉末尾一个字符
    measureText: measureText,//画布需要的函数
    check_mobile: check_mobile,//验证手机
    get_rand_item:get_rand_item, //随机获取元素
    getDistance:getDistance,  //获取俩个经纬网度之间的距离
    draw_randon_rect:draw_randon_rect  ,//画图画圆角矩形
	null_promise:null_promise,//返回空的promise
	get_box_arr:get_box_arr,//返回圆的数组
	draw_circle:draw_circle,//绘制圆，
    mergeArray:mergeArray,    //数组合并
    isContained:isContained,  //是否包含
    base64_encode:base64_encode,  //64位加密
    ob_to_parm:ob_to_parm   ,//对象变成参数
	sha1:sha1,                //sha1进行签名
	convert_arr_key:convert_arr_key, //将JS数组对象按其某个键值重组成Map对象
	ajax_ok:ajax_ok, //将JS数组对象按其某个键值重组成Map对象
	ajax_ok2:ajax_ok2, //将JS数组对象按其某个键值重组成Map对象
    wx_back:wx_back,
    _debounce,
    calculatewuliu:calculatewuliu, //计算物流的函数进行抽象
    format_content,
    deep_cp:function(e){
        if(!e) return null;
        //判断e是不是对象类型
        var new_e = JSON.parse(JSON.stringify(e));
        return new_e;
    },
    getParams(url) {
        const search = url.split('?')[1];
        if (!search) return {};
        const paramArr = search.split('&');
        const paramObj = {};
        for (const param of paramArr) {
            const [key, value] = param.split('=');
            paramObj[key] = value;
        }
        return paramObj;
    },
    close_menu(){
        wx.hideShareMenu();
        try{
            wx.offCopyUrl()
            //替换掉复制链接
            wx.onCopyUrl(() => {
                setTimeout(()=>{
                    wx.setClipboardData({
                        data: '暂不支持分享',
                        success (res) { }
                    })
                },500)
                return { query: 'a=1&b=2' }
            })

        }catch(err){

        }
    }
};
