tools.js 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. import Taro from "@tarojs/taro";
  2. import { API_QUERY_USERINFO_BYID } from '@/constants/api';
  3. import { ROLE_CODE } from '@/constants/user'
  4. import { fetch } from '@/utils/request';
  5. import store from "@/store";
  6. /**
  7. * 是否为空
  8. * @param {*} o
  9. */
  10. export function isEmpty(o) {
  11. if (typeof o === "string") {
  12. if (!o || o === "null" || o === "undefined") {
  13. return true;
  14. }
  15. }
  16. if (o === null || o === undefined) {
  17. return true;
  18. }
  19. if (typeof o === "object") {
  20. return !Object.keys(o).length;
  21. }
  22. if (Array.isArray(o)) {
  23. return !o.length;
  24. }
  25. return false;
  26. }
  27. export function ifNull(o, def) {
  28. return isEmpty(o) ? def : o;
  29. }
  30. /**
  31. * 是否函数
  32. * @param {*} f
  33. */
  34. export function isFunction(f) {
  35. return typeof f === "function";
  36. }
  37. /**
  38. * 是否分享场景(含扫码)
  39. * @param {*} scene
  40. */
  41. export function sceneInShare(scene) {
  42. return (
  43. [1007, 1008, 1011, 1012, 1013, 1031, 1032, 1036, 1047, 1048, 1049].indexOf(
  44. scene
  45. ) > -1
  46. );
  47. }
  48. /**
  49. * 造空数组
  50. * @param {int}} n
  51. */
  52. export function times(n) {
  53. return n > 0 ? "*".repeat(n - 1).split("*") : [];
  54. }
  55. /**
  56. * 屏蔽手机中间 4 位
  57. * @param {*} phone
  58. */
  59. export function maskPhone(phone) {
  60. return phone.replace(/^(\d{3})(\d{4})/, "$1****");
  61. }
  62. /**
  63. * 将 b 中不为 null 或者 undefined 的值合并到 a 中
  64. * @param {*} a
  65. * @param {*} b
  66. */
  67. export function mergeNotNull(a, b) {
  68. const bKeys = Object.keys(b || {});
  69. if (!bKeys.length) {
  70. return a;
  71. }
  72. let res = { ...(a || {}) };
  73. bKeys.forEach(k => {
  74. const v = b[k];
  75. if (v === null || v === undefined) {
  76. return;
  77. }
  78. res[k] = v;
  79. });
  80. return res;
  81. }
  82. // eslint-disable-next-line no-undef
  83. const ossPath = OSS_PATH;
  84. // eslint-disable-next-line no-undef
  85. const ossFastPath = OSS_FAST_PATH;
  86. /**
  87. *
  88. * @param {*} img
  89. * @param {*} quality 仅支持 70,50,30,5
  90. */
  91. export function getThumbnail(img, quality) {
  92. if (!img) return img;
  93. if (img.indexOf(ossPath) === 0 || img.indexOf(ossFastPath) === 0) {
  94. return `${img.replace(
  95. ossPath,
  96. ossFastPath
  97. )}?x-oss-process=style/compress${quality || 30}`;
  98. }
  99. return img;
  100. }
  101. export function resizeImage(img, size) {
  102. if (!img) return img;
  103. if (img.indexOf(ossPath) === 0 || img.indexOf(ossFastPath) === 0) {
  104. return `${img.replace(
  105. ossPath,
  106. ossFastPath
  107. )}?x-oss-process=style/resize${size || 750}`;
  108. }
  109. return img;
  110. }
  111. /**
  112. * 压缩图片 80%, 最大宽度 750
  113. * @param {*} img
  114. */
  115. export function transferImage(img) {
  116. if (!img) return img;
  117. if (img.indexOf(ossPath) === 0 || img.indexOf(ossFastPath) === 0) {
  118. if (store.getState().system.systemInfo.platform !== "ios") {
  119. // ios 暂时不支持 webp
  120. return `${img.replace(
  121. ossPath,
  122. ossFastPath
  123. )}?x-oss-process=style/transwebp`;
  124. }
  125. return `${img.replace(
  126. ossPath,
  127. ossFastPath
  128. )}?x-oss-process=image/resize,m_lfit,w_750/quality,Q_80`;
  129. }
  130. return img;
  131. }
  132. /**
  133. * 简易版解析 url
  134. * @param {*} url
  135. */
  136. export function parseURL(url) {
  137. if (!url) return undefined;
  138. let strTmp;
  139. let query;
  140. let hash;
  141. const gotHash = url.split("#");
  142. strTmp = gotHash[0];
  143. if (gotHash.length > 1) {
  144. hash = gotHash[1];
  145. }
  146. const gotQuery = strTmp.split("?");
  147. strTmp = gotQuery[0];
  148. if (gotQuery.length > 1) {
  149. query = gotQuery[1];
  150. }
  151. // 小程序只支持 https 开头
  152. const [_, origin, path] = /(https?:\/\/[^/]+)(.*)/.exec(strTmp);
  153. return {
  154. origin,
  155. path,
  156. query,
  157. hash
  158. };
  159. }
  160. /**
  161. * 解析 queryString a=b&c=d ==> { a:b, c:d }
  162. * @param {*} queryString
  163. */
  164. export function parseQueryString(queryString) {
  165. if (!queryString || "?" === queryString) return undefined;
  166. const query =
  167. queryString.indexOf("?") === 0
  168. ? queryString.replace(/^\?/, "")
  169. : queryString;
  170. return query
  171. .split("&")
  172. .filter(x => x)
  173. .reduce((acc, it) => {
  174. const [k, v] = it.split("=");
  175. const val = Object.prototype.hasOwnProperty.call(acc, k)
  176. ? [...[].concat(acc[k]), v]
  177. : v;
  178. return {
  179. ...acc,
  180. [`${k}`]: ifNull(val, undefined)
  181. };
  182. }, {});
  183. }
  184. export function toQueryString(o) {
  185. const obj = o || {};
  186. return Object.keys(obj)
  187. .map(key => `${key}=${obj[key]}`)
  188. .join("&");
  189. }
  190. /**
  191. *
  192. * @param {*} url
  193. * @param {*} params
  194. */
  195. export function mergeQueryParams(from, to) {
  196. const originParams = parseQueryString(from) || {};
  197. const newParams = {
  198. ...originParams,
  199. ...(parseQueryString(to) || {})
  200. };
  201. return Object.keys(newParams)
  202. .map(key => `${key}=${newParams[key]}`)
  203. .join("&");
  204. }
  205. /**
  206. * 格式化剩余时间为 xx天xx小时xx分xx秒
  207. * @param {int} leftTime 时间毫秒数
  208. */
  209. export function formateLeftTime(leftTime, unit) {
  210. const nd = 1000 * 24 * 60 * 60;
  211. const nh = 1000 * 60 * 60;
  212. const nm = 1000 * 60;
  213. const ns = 1000;
  214. const day = Math.floor(leftTime / nd);
  215. const hour = Math.floor((leftTime % nd) / nh);
  216. const min = Math.floor(((leftTime % nd) % nh) / nm);
  217. const sec = Math.floor((((leftTime % nd) % nh) % nm) / ns);
  218. switch (unit) {
  219. case "min":
  220. return `${day}天${hour}小时${min}分`;
  221. default:
  222. return `${day}天${hour}小时${min}分${sec}秒`;
  223. }
  224. }
  225. /**
  226. * @description 获取当前页url
  227. */
  228. export const getCurrentPageUrl = () => {
  229. let pages = Taro.getCurrentPages();
  230. let currentPage = pages[pages.length - 1];
  231. let url = currentPage.route;
  232. return url;
  233. };
  234. export const pageToLogin = () => {
  235. let path = getCurrentPageUrl();
  236. if (!path.includes("login")) {
  237. Taro.navigateTo({
  238. url: "/pages/login/login"
  239. });
  240. }
  241. };
  242. export const isObject = function(value) {
  243. var type = typeof value;
  244. return value != null && type === "object";
  245. };
  246. //使用递归的方式实现数组、对象的深拷贝
  247. export const deepClone = function(obj) {
  248. if (!isObject(obj)) {
  249. throw new Error("obj 不是一个对象!");
  250. }
  251. let isArray = Array.isArray(obj);
  252. let cloneObj = isArray ? [] : {};
  253. for (let key in obj) {
  254. cloneObj[key] = isObject(obj[key]) ? deepClone(obj[key]) : obj[key];
  255. }
  256. return cloneObj;
  257. };
  258. export const getLocation = () => {
  259. return new Promise((resolve) => {
  260. Taro.getLocation().then(location => {
  261. Taro.setStorageSync('lat', location.latitude)
  262. Taro.setStorageSync('lon', location.longitude)
  263. resolve({ lon: location.longitude, lat: location.latitude })
  264. }).catch(err => {
  265. if (err.errMsg === 'getLocation:fail auth deny') {
  266. Taro.showModal({
  267. content: '请同意授权您的定位功能',
  268. showCancel: false,
  269. duration: 3000,
  270. })
  271. } else {
  272. Taro.showToast({
  273. title: `定位失败, 请手动选择城市: ${err.errMsg}`,
  274. icon: 'none',
  275. duration: 3000,
  276. })
  277. }
  278. console.error(err)
  279. resolve()
  280. })
  281. })
  282. }
  283. export function setRecommender(recommender) {
  284. fetch({ url: `${API_QUERY_USERINFO_BYID}/${recommender}` }).then((res) => {
  285. store.dispatch({ type: 'SYNC_RECOMMENDER', payload: res });
  286. if (res.personType === ROLE_CODE.CONSULTANT) {
  287. store.dispatch({ type: 'SYNC_CONSULTANT', payload: res });
  288. }
  289. }).catch((err) => {
  290. console.error(err);
  291. })
  292. }