123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345 |
- import Taro from "@tarojs/taro";
- import { API_QUERY_USERINFO_BYID } from '@/constants/api';
- import { ROLE_CODE } from '@/constants/user'
- import { fetch } from '@/utils/request';
- import store from "@/store";
-
- /**
- * 是否为空
- * @param {*} o
- */
- export function isEmpty(o) {
- if (typeof o === "string") {
- if (!o || o === "null" || o === "undefined") {
- return true;
- }
- }
-
- if (o === null || o === undefined) {
- return true;
- }
-
- if (typeof o === "object") {
- return !Object.keys(o).length;
- }
-
- if (Array.isArray(o)) {
- return !o.length;
- }
-
-
-
- return false;
- }
-
- export function ifNull(o, def) {
- return isEmpty(o) ? def : o;
- }
-
- /**
- * 是否函数
- * @param {*} f
- */
- export function isFunction(f) {
- return typeof f === "function";
- }
-
- /**
- * 是否分享场景(含扫码)
- * @param {*} scene
- */
- export function sceneInShare(scene) {
- return (
- [1007, 1008, 1011, 1012, 1013, 1031, 1032, 1036, 1047, 1048, 1049].indexOf(
- scene
- ) > -1
- );
- }
-
- /**
- * 造空数组
- * @param {int}} n
- */
- export function times(n) {
- return n > 0 ? "*".repeat(n - 1).split("*") : [];
- }
-
- /**
- * 屏蔽手机中间 4 位
- * @param {*} phone
- */
- export function maskPhone(phone) {
- return phone.replace(/^(\d{3})(\d{4})/, "$1****");
- }
-
- /**
- * 将 b 中不为 null 或者 undefined 的值合并到 a 中
- * @param {*} a
- * @param {*} b
- */
- export function mergeNotNull(a, b) {
- const bKeys = Object.keys(b || {});
- if (!bKeys.length) {
- return a;
- }
-
- let res = { ...(a || {}) };
-
- bKeys.forEach(k => {
- const v = b[k];
- if (v === null || v === undefined) {
- return;
- }
-
- res[k] = v;
- });
-
- return res;
- }
-
- // eslint-disable-next-line no-undef
- const ossPath = OSS_PATH;
- // eslint-disable-next-line no-undef
- const ossFastPath = OSS_FAST_PATH;
-
- /**
- *
- * @param {*} img
- * @param {*} quality 仅支持 70,50,30,5
- */
- export function getThumbnail(img, quality) {
- if (!img) return img;
-
- if (img.indexOf(ossPath) === 0 || img.indexOf(ossFastPath) === 0) {
- return `${img.replace(
- ossPath,
- ossFastPath
- )}?x-oss-process=style/compress${quality || 30}`;
- }
-
- return img;
- }
-
- export function resizeImage(img, size) {
- if (!img) return img;
-
- if (img.indexOf(ossPath) === 0 || img.indexOf(ossFastPath) === 0) {
- return `${img.replace(
- ossPath,
- ossFastPath
- )}?x-oss-process=style/resize${size || 750}`;
- }
-
- return img;
- }
-
- /**
- * 压缩图片 80%, 最大宽度 750
- * @param {*} img
- */
- export function transferImage(img) {
- if (!img) return img;
-
- if (img.indexOf(ossPath) === 0 || img.indexOf(ossFastPath) === 0) {
- if (store.getState().system.systemInfo.platform !== "ios") {
- // ios 暂时不支持 webp
- return `${img.replace(
- ossPath,
- ossFastPath
- )}?x-oss-process=style/transwebp`;
- }
-
- return `${img.replace(
- ossPath,
- ossFastPath
- )}?x-oss-process=image/resize,m_lfit,w_750/quality,Q_80`;
- }
-
- return img;
- }
-
- /**
- * 简易版解析 url
- * @param {*} url
- */
- export function parseURL(url) {
- if (!url) return undefined;
-
- let strTmp;
- let query;
- let hash;
-
- const gotHash = url.split("#");
- strTmp = gotHash[0];
- if (gotHash.length > 1) {
- hash = gotHash[1];
- }
-
- const gotQuery = strTmp.split("?");
- strTmp = gotQuery[0];
- if (gotQuery.length > 1) {
- query = gotQuery[1];
- }
-
- // 小程序只支持 https 开头
- const [_, origin, path] = /(https?:\/\/[^/]+)(.*)/.exec(strTmp);
-
- return {
- origin,
- path,
- query,
- hash
- };
- }
-
- /**
- * 解析 queryString a=b&c=d ==> { a:b, c:d }
- * @param {*} queryString
- */
- export function parseQueryString(queryString) {
- if (!queryString || "?" === queryString) return undefined;
-
- const query =
- queryString.indexOf("?") === 0
- ? queryString.replace(/^\?/, "")
- : queryString;
-
- return query
- .split("&")
- .filter(x => x)
- .reduce((acc, it) => {
- const [k, v] = it.split("=");
- const val = Object.prototype.hasOwnProperty.call(acc, k)
- ? [...[].concat(acc[k]), v]
- : v;
-
- return {
- ...acc,
- [`${k}`]: ifNull(val, undefined)
- };
- }, {});
- }
-
- export function toQueryString(o) {
- const obj = o || {};
- return Object.keys(obj)
- .map(key => `${key}=${obj[key]}`)
- .join("&");
- }
-
- /**
- *
- * @param {*} url
- * @param {*} params
- */
- export function mergeQueryParams(from, to) {
- const originParams = parseQueryString(from) || {};
- const newParams = {
- ...originParams,
- ...(parseQueryString(to) || {})
- };
-
- return Object.keys(newParams)
- .map(key => `${key}=${newParams[key]}`)
- .join("&");
- }
-
- /**
- * 格式化剩余时间为 xx天xx小时xx分xx秒
- * @param {int} leftTime 时间毫秒数
- */
- export function formateLeftTime(leftTime, unit) {
- const nd = 1000 * 24 * 60 * 60;
- const nh = 1000 * 60 * 60;
- const nm = 1000 * 60;
- const ns = 1000;
-
- const day = Math.floor(leftTime / nd);
- const hour = Math.floor((leftTime % nd) / nh);
- const min = Math.floor(((leftTime % nd) % nh) / nm);
- const sec = Math.floor((((leftTime % nd) % nh) % nm) / ns);
-
- switch (unit) {
- case "min":
- return `${day}天${hour}小时${min}分`;
- default:
- return `${day}天${hour}小时${min}分${sec}秒`;
- }
- }
-
- /**
- * @description 获取当前页url
- */
- export const getCurrentPageUrl = () => {
- let pages = Taro.getCurrentPages();
- let currentPage = pages[pages.length - 1];
- let url = currentPage.route;
- return url;
- };
-
- export const pageToLogin = () => {
- let path = getCurrentPageUrl();
- if (!path.includes("login")) {
- Taro.navigateTo({
- url: "/pages/login/login"
- });
- }
- };
-
- export const isObject = function(value) {
- var type = typeof value;
- return value != null && type === "object";
- };
-
- //使用递归的方式实现数组、对象的深拷贝
- export const deepClone = function(obj) {
- if (!isObject(obj)) {
- throw new Error("obj 不是一个对象!");
- }
- let isArray = Array.isArray(obj);
- let cloneObj = isArray ? [] : {};
- for (let key in obj) {
- cloneObj[key] = isObject(obj[key]) ? deepClone(obj[key]) : obj[key];
- }
-
- return cloneObj;
- };
-
- export const getLocation = () => {
- return new Promise((resolve) => {
- Taro.getLocation().then(location => {
- Taro.setStorageSync('lat', location.latitude)
- Taro.setStorageSync('lon', location.longitude)
-
- resolve({ lon: location.longitude, lat: location.latitude })
- }).catch(err => {
- if (err.errMsg === 'getLocation:fail auth deny') {
- Taro.showModal({
- content: '请同意授权您的定位功能',
- showCancel: false,
- duration: 3000,
- })
- } else {
- Taro.showToast({
- title: `定位失败, 请手动选择城市: ${err.errMsg}`,
- icon: 'none',
- duration: 3000,
- })
- }
-
- console.error(err)
- resolve()
- })
- })
- }
-
- export function setRecommender(recommender) {
- fetch({ url: `${API_QUERY_USERINFO_BYID}/${recommender}` }).then((res) => {
- store.dispatch({ type: 'SYNC_RECOMMENDER', payload: res });
- if (res.personType === ROLE_CODE.CONSULTANT) {
- store.dispatch({ type: 'SYNC_CONSULTANT', payload: res });
- }
- }).catch((err) => {
- console.error(err);
- })
- }
|