util.js 16.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
import {
  sopApi,
  commonApi,
  bigdatautilApi,
  equityApi
} from "../api/api";
import $router from "../router/index";
/**emoji正则 */
const emojiReg =
  /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac])/g;
/**
 * 日期格式化
 * let time = new Date().format('yyyy-MM-dd hh:mm:ss') //log   2020-07-31 10:00:00
 */
Date.prototype.format = function (fmt) {
  let o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    //季度
    "q+": Math.floor((this.getMonth() + 3) / 3),
    S: this.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  }
  return fmt;
};
const timeago = (dateTimeStamp) => {
  let result = "刚刚";
  let minute = 1000 * 60;
  let hour = minute * 60;
  let day = hour * 24;
  let now = new Date().getTime(); //获取当前时间毫秒
  let diffValue = now - dateTimeStamp; //时间差
  let todayValue = new Date();
  todayValue.setHours(0);
  todayValue.setMinutes(0);
  todayValue.setSeconds(0);
  todayValue.setMilliseconds(0);
  let todayTimeStamp = todayValue.getTime(); //获取当天零时毫秒
  if (diffValue < 0) {
    return result;
  }
  let diffTodayValue = todayTimeStamp - dateTimeStamp;
  //计算时间差的分,时,天,周,月
  let minC = diffValue / minute;
  let hourC = diffValue / hour;
  let dayC = diffTodayValue / day;

  if (diffTodayValue > 0) {
    if (dayC >= 2) {
      return new Date(dateTimeStamp).format("MM月dd日 hh:mm:ss");
    }
    if (dayC >= 1 && dayC < 2) {
      return "前天" + new Date(dateTimeStamp).format(" hh:mm:ss");
    }
    return "昨天" + new Date(dateTimeStamp).format(" hh:mm:ss");
  }
  if (hourC >= 1 && hourC <= 23) {
    return parseInt(hourC) + "小时前";
  }
  if (minC >= 1 && minC <= 59) {
    return parseInt(minC) + "分钟前";
  }
  if (diffValue >= 0 && diffValue <= minute) {
    return "刚刚";
  }
  return new Date(dateTimeStamp).format("MM月dd日 hh:mm:ss");
};

//用来判断评论时间
const commentTime = (dateTimeStamp) => {
  var result;
  let time = dateTimeStamp;
  let nowTime = new Date().getTime();
  let timeDifference = nowTime - time;

  let minTime = 60000;
  let hourTime = minTime * 60;
  let dayTime = hourTime * 24;
  let weektTime = dayTime * 7;
  let monthTime = dayTime * 30;
  let yearTime = dayTime * 365;

  if (parseInt(timeDifference / yearTime) >= 1) {
    result = parseInt(timeDifference / yearTime) + "年前";
  } else if (parseInt(timeDifference / monthTime) >= 1) {
    result = parseInt(timeDifference / monthTime) + "月前";
  } else if (parseInt(timeDifference / weektTime) >= 1) {
    result = parseInt(timeDifference / weektTime) + "周前";
  } else if (parseInt(timeDifference / dayTime) >= 1) {
    result = parseInt(timeDifference / dayTime) + "天前";
  } else if (parseInt(timeDifference / hourTime) >= 1) {
    result = parseInt(timeDifference / hourTime) + "小时前";
  } else if (parseInt(timeDifference / minTime) >= 1) {
    result = parseInt(timeDifference / minTime) + "分钟前";
    if (parseInt(timeDifference / minTime) <= 5) {
      //五分钟内就是刚刚
      result = "刚刚";
    }
  }
  return result;
};
/**
 * 防止重复点击
 */
const showLoading = (title = "") => {
  if (wx.showLoading) {
    // 基础库 1.1.0 微信6.5.6版本开始支持,低版本需做兼容处理
    wx.showLoading({
      title,
      mask: true,
    });
  } else {
    // 低版本采用Toast兼容处理并将时间设为20秒以免自动消失
    wx.showToast({
      title,
      icon: "loading",
      mask: true,
      duration: 20000,
    });
  }
};
const hideLoading = () => {
  if (wx.hideLoading) {
    // 基础库 1.1.0 微信6.5.6版本开始支持,低版本需做兼容处理
    wx.hideLoading();
  } else {
    wx.hideToast();
  }
};
const showToast = (val) => {
  let obj = {};
  if (val && typeof val === "string") {
    obj.title = val;
    obj.icon = "none";
  } else {
    obj = val;
  }
  return wx.showToast(obj);
};
/**获取节点信息
 * name(id获取class)
 * callBack 回调函数
 * isComponents是否在组件
 */
const getViewInfo = (name, callBack, isComponents) => {
  const query = !isComponents ?
    wx.createSelectorQuery() :
    wx.createSelectorQuery().in(isComponents);
  query
    .select(name)
    .boundingClientRect((res) => {
      callBack(res);
    })
    .exec();
};
/**触底加载 */
const onReachBottom = (obj, callBack) => {
  let _this = $router.getPageInstance();
  let {
    pageNum,
    total,
    pageSize,
    nothing
  } = obj;
  if (!total && !pageNum) {
    console.error("total&&pageNum为必传");
    return;
  }
  if (!pageSize) pageSize = 10;
  if (!nothing) nothing = "nothing";
  if (Math.ceil(total / pageSize) > pageNum) {
    _this.setData({
      pageNum: pageNum + 1,
    });
    callBack();
  } else {
    _this.setData({
      [nothing]: true,
    });
  }
};
/**过滤表情 */
const haveEmoji = (value) => {
  let val = false;
  value = value.replace(/\s/g, "").trimStart().trimEnd();
  if (emojiReg.test(value) && !/\s/g.test(value)) {
    showToast({
      icon: "error",
      title: "不能输入表情",
    });
    val = true;
  }
  return val;
};
/**替换表情 */
const replaceEmoji = (value) => {
  let val = value.replace(emojiReg, "");
  return val.trimStart().trimEnd();
};
/**节流 */
const throttle = (fn, gapTime) => {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500;
  }
  let _lastTime = null;
  // 返回新的函数
  return function () {
    let _nowTime = +new Date();
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments); //将this和参数传给原函数
      _lastTime = _nowTime;
    }
  };
};
/**获取手机信息 */
const getPhoneInfo = (callBack) => {
  wx.getSystemInfo({
    success(res) {
      callBack(res);
    },
    fail(err) {
      callBack(err);
    },
  });
};
/**num:要转换的数值,fixed:精确几位小数 */
const decimal = (num, fixed = 2) => {
  const pow = Math.pow(10, fixed);
  return Number(Math.round(num * pow) / pow);
};
/**
 * 禁止滑动
 */
const noScroll = () => {};
/**设置粘贴板内容 */
const setCopyData = (data, callBack) => {
  wx.setClipboardData({
    data: data,
    success(res) {
      if (callBack && typeof callBack === "function") callBack(res);
    },
  });
};
const promise = (callBack) => {
  return new Promise((resolve, reject) => {
    callBack(resolve, reject);
  });
};
/**是否全面屏 */
const isFullSucreen = (isComponents) => {
  const thisPage = $router.getPageInstance();
  const routerList = $router.getRouterList();
  const router = routerList.find((item) => item.url === `/${thisPage.route}`);
  let key = `${router.url.replace("/", "")}.html`;
  let val = false;
  if (__wxConfig && __wxConfig.page && __wxConfig.page[key]) {
    let {
      navigationStyle
    } = __wxConfig.page[key].window;
    wx.getSystemInfo({
      success(res) {
        if (res.platform != "android") {
          let {
            statusBarHeight,
            screenHeight,
            windowHeight
          } = res;
          if (navigationStyle && navigationStyle == "custom") {
            windowHeight = windowHeight - thisPage.data.navHeight || 0;
          }
          //兼容自定义标题
          val = router.isTab ?
            screenHeight - windowHeight - statusBarHeight - 32 > 72 :
            screenHeight - windowHeight > 72;
          if (isComponents) val = screenHeight - windowHeight > 72;
        }
      },
      fail(err) {
        return false;
      },
    });
  }

  return val;
};
/** */
const getSessionId = () => {
  return wx.getStorageSync("scrm_shopmall_sessionId");
};
const setSessionId = (sessionId) => {
  wx.setStorageSync("scrm_shopmall_sessionId", sessionId);
};
const removeSystemStorage = () => {
  wx.removeStorageSync("srcm_shopmall_user_info");
  wx.removeStorageSync("scrm_shopmall_sessionId");
  wx.removeStorageSync("guest_no");
  wx.removeStorageSync("equity_info");
  wx.removeStorageSync("packageList");
  wx.removeStorageSync("isVIP");
  wx.removeStorageSync("bizjiaUrl");
  wx.removeStorageSync("vip_card_info");
};
const setStorageSync = (key, data) => {
  wx.setStorageSync(key, JSON.stringify(data));
};
const getStorageSync = (key) => {
  let data = wx.getStorageSync(key) || null;
  return JSON.parse(data);
};
/** */
const getSceneId = (path) => {
  let [_route_, _options_] = path.split("?");
  let [target] = _route_.split("/");
  let name = _route_.split("/").pop();
  let scene = _options_ ? _options_.split("=")[1] : "";
  return {
    name,
    scene,
    target,
  };
};
/**
 * 获取url参数
 */
const filterUrlParam = (urlSearch) => {
  let ret = {};
  let regParam = /([^&=]+)=([\w\W]*?)(&|$|#)/g;
  if (urlSearch) {
    var strParam = urlSearch;
    var result;
    while ((result = regParam.exec(strParam)) != null) {
      ret[result[1]] = result[2];
    }
  }
  return ret;
};
/**设置价格 */
const setPrice = (price) => {
  let [num, decimal] = price.toString().split(".");
  if (!decimal) decimal = "00";
  return (
    (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, "$1,") + `.${decimal}`
  );
};
/**拨打电话 */
const phoneCall = (phoneNumber) => {
  wx.makePhoneCall({
    phoneNumber: `${phoneNumber}`,
  });
};
/**跳转至购物车 */
const goShoppingCart = () => {
  wx.$router.go("packageMall.shoppingCart", {
    title: '购物车'
  });
};
/**获取用户信息 */
const getUserInfo = () => {
  let user = wx.getStorageSync("srcm_shopmall_user_info") || null;
  return JSON.parse(user);
};
/**设置用户信息 */
const setUserInfo = (userInfo) => {
  wx.setStorageSync("srcm_shopmall_user_info", JSON.stringify(userInfo));
};
/**IOS时间兼容 */
const iosTimeFormat = (time) => {
  return time.replace(/\-/g, "/");
};
/**设置标题栏 */
const setNavigationBarTitleText = (title) => {
  setStorageSync("dj_shopmall_app_title", title);
};
/**获取app标题 */
const getNavigationBarTitleText = () => {
  return getStorageSync("dj_shopmall_app_title");
};
/**删除对象里的null值 */
const clearObjNull = (options) => {
  let obj = {};
  Object.keys(options).map((e) => {
    if (options[e] != null && options[e] != undefined) {
      if (typeof options[e] == "object") {
        Object.keys(options[e]).map((key) => {
          if (options[e][key] == null || options[e][key] == undefined)
            delete options[e][key];
        });
      }
      obj[e] = options[e];
    }
  });
  return obj;
};
/**分转元 */
const centsToyuan = (price) => {
  return decimal(price / 100, 2).toFixed(2);
};
/**查看大图 */
const previewImage = (params) => {
  wx.previewImage(params);
};
const decodeUrlLink = (options) => {
  let op = {};
  let query = Object.keys(options);
  if (query.length) {
    try {
      query.map((e) => {
        let params = decodeURIComponent(e).split("&");
        params.map((i, index) => {
          let [key, val] = i.split("=");
          if (val) op[key] = val;
          if (index == params.length - 1) {
            throw op;
          }
        });
      });
    } catch (res) {
      let that = wx.$router.getPageInstance();
      that.onLoad(res);
    }
  }
};
let _behaviorType = '',
  _taskId = '',
  _eventId = ''
/**SOP埋点 */
const customerbehavior = (behaviorType = 1) => {
  let {
    taskId,
    eventId
  } = wx.getLaunchOptionsSync().query;
  let {
    openId,
    phone
  } = getUserInfo();
  if (_behaviorType == behaviorType && (_taskId == taskId || _eventId == eventId)) return
  if (taskId) sopApi.customerbehavior({
    customerPhone: phone,
    behaviorType,
    taskId,
    openId,
  })
  if (eventId) sopApi.customerbehaviorByEventId({
    customerPhone: phone,
    behaviorType,
    eventId,
    openId,
  })
  _behaviorType = behaviorType
  _taskId = taskId
  _eventId = eventId
};
/**获取时间段总时长 */
const getScopeTime = (inputTime, curTime) => {
  let obj = {
    text: "-",
    day: 0,
    isDanger: false,
  };
  if (!inputTime || arguments.length === 0) return obj;
  let time = curTime / 1000 - inputTime / 1000;
  if (time < 60) {
    let s = parseInt(time);
    obj.text = `00:00:${s}`;
  } else if (time < 3600) {
    let m = parseInt(time / 60);
    let s = parseInt(time % 60);
    m = m < 10 ? `0${m}` : m;
    s = s < 10 ? `0${s}` : s;
    obj.text = `00:${m}:${s}`;
  } else if (time < 86400) {
    let h = parseInt(time / 3600);
    let min = time - h * 3600;
    let m = parseInt(min / 60);
    let s = parseInt(time % 60);
    m = m < 10 ? `0${m}` : m;
    s = s < 10 ? `0${s}` : s;
    obj.text = `${h}:${m}:${s}`;
  } else if (time > 86400) {
    let day = parseInt(time / 86400);
    let hour = time - day * 86400;
    let h = parseInt(hour / 3600);
    let min = hour - h * 3600;
    let m = parseInt(min / 60);
    let s = parseInt(time % 60);
    h = h < 10 ? `0${h}` : h;
    m = m < 10 ? `0${m}` : m;
    s = s < 10 ? `0${s}` : s;
    if (day > 7 || (day == 7 && h > 0)) obj.isDanger = false;
    obj.day = day;
    obj.text = `${day}天${h}:${m}:${s}`;
  }
  return obj.text;
};
/**获取图片版本号 */
const getImgVersion = () => {
  return commonApi.getImgVersion();
};
/**埋点上报 */
const reportData = (params, check, receive, isRecommended) => {
  let data = {
    add_way: "104",
  };
  let user = wx.getStorageSync("srcm_shopmall_user_info");
  if (user) {
    user = JSON.parse(user);
  }
  if (params.activity_id) {
    data.activity_id = params.activity_id;
  }
  if (params.merchantId) {
    data.merchant_id = params.merchantId;
  }
  if (params.phone || user.phone) {
    data.customer_phone = params.phone || user.phone;
  }
  if (check) {
    data.check_time = new Date().format("yyyy-MM-dd hh:mm:ss");
    data.check_status = 1;
  }
  if (receive) {
    data.receive_status = 1;
    data.receive_time = new Date().format("yyyy-MM-dd hh:mm:ss");
  }
  if (user.unionId) {
    data.union_id = user.unionId;
  }
  if (user.openId) {
    data.open_id = user.openId;
  }
  if (isRecommended) {
    data.item_type = params.item_type;
    data.action_type = params.action_type;
    data.business_type = 1;
    data.create_time = new Date().format("yyyy-MM-dd hh:mm:ss");
    data.staff_uuid = params.shareStaffUuid;
    data.item_id = params.item_id;
    if (params.order_id) {
      data.order_id = params.order_id;
    }
  }
  // let json = encodeURIComponent(JSON.stringify(data))
  let json = JSON.stringify(data);
  bigdatautilApi.reportCustomer({
    json
  });
};
const isMember = (isNeedToHttp, callBack) => {
  if (isNeedToHttp) {
    equityApi.checkOpenMember().then((res) => {
      let flag = false;
      if (res.code == 0 && res.data) {
        flag = true;
      }
      wx.setStorageSync("isVIP", flag);
      callBack && callBack(flag, res.data);
    });
    return;
  }
  return wx.getStorageSync("isVIP") || false;
};

/**
 * 日期格式化
 */
const formatTime = (time, cFormat) => {
  if (arguments.length === 0) {
    return "";
  }
  const format = cFormat || "{y}-{m}-{d}";
  let date;
  if (time === undefined || time === 0 || time === "") {
    return "";
  } else if (typeof time === "object") {
    date = time;
  } else {
    if (("" + time).length === 10) time = parseInt(time) * 1000;
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
};
const Util = {
  commentTime,
  setNavigationBarTitleText,
  getNavigationBarTitleText,
  removeSystemStorage,
  customerbehavior,
  setStorageSync,
  getStorageSync,
  goShoppingCart,
  filterUrlParam,
  getImgVersion,
  onReachBottom,
  isFullSucreen,
  iosTimeFormat,
  decodeUrlLink,
  replaceEmoji,
  previewImage,
  getPhoneInfo,
  getSessionId,
  getScopeTime,
  setSessionId,
  clearObjNull,
  getUserInfo,
  setUserInfo,
  centsToyuan,
  showLoading,
  hideLoading,
  getViewInfo,
  setCopyData,
  getSceneId,
  haveEmoji,

  showToast,
  phoneCall,
  noScroll,
  throttle,
  setPrice,
  decimal,
  promise,
  timeago,
  reportData,
  isMember,
  formatTime,
};
export default Util;