public.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. // 日期格式化原型扩展(单独维护)
  2. Date.prototype.Format = function (fmt) {
  3. const o = {
  4. "M+": this.getMonth() + 1, // 月份
  5. "D+": this.getDate(), // 日
  6. "h+": this.getHours(), // 小时
  7. "m+": this.getMinutes(), // 分
  8. "s+": this.getSeconds(), // 秒
  9. "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
  10. "S": this.getMilliseconds() // 毫秒
  11. };
  12. if (/(Y+)/.test(fmt)) {
  13. fmt = fmt.replace(
  14. RegExp.$1,
  15. (this.getFullYear() + "").substr(4 - RegExp.$1.length)
  16. );
  17. }
  18. for (const k in o) {
  19. if (new RegExp(`(${k})`).test(fmt)) {
  20. fmt = fmt.replace(
  21. RegExp.$1,
  22. RegExp.$1.length === 1
  23. ? o[k]
  24. : (`00${o[k]}`).substr((o[k] + "").length)
  25. );
  26. }
  27. }
  28. return fmt;
  29. };
  30. // 路由相关工具方法
  31. const routerUtil = {
  32. navTo(url) {
  33. if (!url) return;
  34. uni.navigateTo({ url });
  35. },
  36. switchTo(url) {
  37. uni.switchTab({ url });
  38. },
  39. reLaunchTo(url) {
  40. uni.reLaunch({ url });
  41. },
  42. meRouter(option) {
  43. const type = parseInt(option.jump || 0);
  44. switch (type) {
  45. case 1:
  46. this.navTo(`/pages/activity/lifeDetail?id=${option.jump_address}`);
  47. break;
  48. case 2:
  49. this.navTo(`/pages/activity/newsDetail?id=${option.jump_address}`);
  50. break;
  51. default:
  52. break;
  53. }
  54. }
  55. };
  56. // 图片相关工具方法
  57. const imageUtil = {
  58. showPic(arr, index) {
  59. uni.previewImage({
  60. indicator: "none",
  61. current: index,
  62. urls: arr
  63. });
  64. },
  65. save(imgs) {
  66. uni.downloadFile({
  67. url: imgs,
  68. success: res => {
  69. if (res.statusCode === 200) {
  70. uni.saveImageToPhotosAlbum({
  71. filePath: res.tempFilePath,
  72. success: () => this.$u.toast('保存下载成功'),
  73. fail: () => this.$u.toast('保存失败,请稍后重试')
  74. });
  75. } else {
  76. this.tools.toast('下载失败');
  77. }
  78. }
  79. });
  80. }
  81. };
  82. // 数据格式化工具方法
  83. const formatUtil = {
  84. formatTime(time, pattern) {
  85. // uview: uni.$u.date('1585926095536', 'yyyy-mm')
  86. // 过滤器: '1585926095536' | date('yyyy-mm')
  87. const times = time * 1000;
  88. let d = new Date(times).Format("YYYY-MM-DD hh:mm:ss");
  89. if (pattern) {
  90. d = new Date(times).Format(pattern);
  91. }
  92. return d.toLocaleString();
  93. },
  94. // 格式化距离
  95. formatDistance(value) {
  96. if (value == null) return '-';
  97. const numValue = parseFloat(value);
  98. if (isNaN(numValue)) return '无效距离';
  99. if (numValue < 0.001) return '<1m';
  100. if (numValue < 1) return `${Math.round(numValue * 1000)}m`;
  101. return numValue % 1 === 0
  102. ? `${numValue}km`
  103. : `${numValue.toFixed(2)}km`;
  104. },
  105. // 格式化销售数
  106. formatSales(sales) {
  107. if (typeof sales !== 'number' || !isFinite(sales)) return '0';
  108. // 处理负数
  109. sales = Math.max(0, Math.floor(sales));
  110. if (sales < 100) return `${sales}`;
  111. if (sales < 1000) return `${Math.floor(sales / 100) * 100}+`;
  112. if (sales < 10000) return `${Math.floor(sales / 1000)}k+`;
  113. return '1w+';
  114. },
  115. // 格式化评价星数
  116. formatRating(val) {
  117. if (val >= 4.5) return "超赞";
  118. if (val >= 4.0) return "满意";
  119. if (val >= 3.0) return "一般";
  120. if (val >= 2.0) return "不满意";
  121. return "非常差";
  122. },
  123. // 格式化数额差值
  124. formatSubtract(num1, num2) {
  125. const len1 = (num1.toString().split('.')[1] || '').length;
  126. const len2 = (num2.toString().split('.')[1] || '').length;
  127. const base = Math.pow(10, Math.max(len1, len2));
  128. return (Math.round(num1 * base) - Math.round(num2 * base)) / base;
  129. },
  130. };
  131. // 节流工具方法
  132. const throttleUtil = {
  133. // 基础节流
  134. throttle(func, wait = 500, immediate = false) {
  135. let timeout = null;
  136. return function (...args) {
  137. if (timeout !== null) clearTimeout(timeout);
  138. if (immediate) {
  139. const callNow = !timeout;
  140. timeout = setTimeout(() => {
  141. timeout = null;
  142. }, wait);
  143. if (callNow) func && func.apply(this, args);
  144. } else {
  145. timeout = setTimeout(() => {
  146. func && func.apply(this, args);
  147. }, wait);
  148. }
  149. };
  150. },
  151. // 高级节流(带配置项)
  152. throttles(func, delay, options = {}) {
  153. let lastTime = 0;
  154. let timer = null;
  155. const { leading = true, trailing = true } = options;
  156. return function (...args) {
  157. const now = Date.now();
  158. if (!lastTime && !leading) lastTime = now;
  159. const remaining = delay - (now - lastTime);
  160. if (remaining <= 0) {
  161. if (timer) {
  162. clearTimeout(timer);
  163. timer = null;
  164. }
  165. lastTime = now;
  166. func.apply(this, args);
  167. } else if (!timer && trailing) {
  168. timer = setTimeout(() => {
  169. lastTime = !leading ? 0 : Date.now();
  170. timer = null;
  171. func.apply(this, args);
  172. }, remaining);
  173. }
  174. };
  175. }
  176. };
  177. // 其他工具方法
  178. const otherUtil = {
  179. makePhoneCall(phone) {
  180. if (phone) {
  181. console.log(typeof phone, phone)
  182. uni.makePhoneCall({ phoneNumber: phone });
  183. }
  184. },
  185. // 以token判断是否登录
  186. checkLogin(options = {}) {
  187. const {
  188. type,
  189. modalText = '请登录账号后再操作',
  190. } = options;
  191. const token = uni.getStorageSync('token') || '';
  192. const expireTime = uni.getStorageSync("expireTime");
  193. const now = Date.now();
  194. const isLogin = !!token && expireTime > now;
  195. // 后退参数
  196. let str = uni.$u.queryParams({ isBack: 1 });
  197. // 跳转路由
  198. let path = `/packageF/pages/login/login${str}`;
  199. // #ifdef MP-WEIXIN
  200. path = `/packageF/pages/login/wxLogin${str}`;
  201. // #endif
  202. // 未登录时,根据 type 执行对应操作
  203. if (!isLogin) {
  204. switch (type) {
  205. case 'reLaunch':
  206. uni.reLaunch({
  207. url: path,
  208. success: () => {
  209. console.log('未登录,已跳转至登录页');
  210. }
  211. });
  212. break;
  213. case 'navigate':
  214. // 跳转登录页(带返回跳转,可返回原页面)
  215. uni.navigateTo({
  216. url: path,
  217. success: () => {
  218. console.log('未登录,已跳转至登录页');
  219. }
  220. });
  221. break;
  222. case 'modal':
  223. // 弹窗提示,确认后跳转登录页
  224. uni.showModal({
  225. title: '温馨提示',
  226. content: modalText,
  227. confirmText: '前往登录',
  228. confirmColor: '#0879FF',
  229. success: (res) => {
  230. if (res.confirm) {
  231. uni.navigateTo({ url: path });
  232. }
  233. }
  234. });
  235. break;
  236. // 默认:仅返回登录状态,不执行额外操作
  237. default:
  238. console.log('未登录,仅返回登录状态');
  239. break;
  240. }
  241. }
  242. return isLogin;
  243. },
  244. // 获取多级对象的长链
  245. getProp(obj, path, defaultValue = '') {
  246. const keys = path.split('.');
  247. let result = obj;
  248. for (const key of keys) {
  249. if (result && typeof result === 'object' && key in result) {
  250. result = result[key];
  251. } else {
  252. return defaultValue;
  253. }
  254. }
  255. return result;
  256. },
  257. // 获取多图拼接的值
  258. getSplitImg(e, index = 0) {
  259. // 先处理原始数据:若e为空,返回空数组
  260. if (!e || typeof e !== 'string') {
  261. return [];
  262. }
  263. // 分割图片字符串为数组
  264. const imgArr = e.split(',');
  265. // 判断index是否为null/undefined(用户传空时),返回完整数组
  266. if (index === null || index === undefined) {
  267. return imgArr;
  268. }
  269. // 处理索引:确保是整数,且在有效范围内(0 <= index < 数组长度)
  270. const validIndex = Math.floor(Number(index)); // 转为整数(避免传入字符串/小数)
  271. if (isNaN(validIndex) || validIndex < 0 || validIndex >= imgArr.length) {
  272. return ''; // 索引无效时,返回空字符串(避免显示错误图片)
  273. }
  274. // 返回指定索引的图片URL
  275. return imgArr[validIndex];
  276. },
  277. //判断是安装了支付宝
  278. isAlipayConfig() {
  279. const params = {
  280. pname: 'com.eg.android.AlipayGphone',
  281. action: 'alipay://'
  282. };
  283. // 判断是否安装支付宝
  284. if (!plus.runtime.isApplicationExist(params)) {
  285. uni.$u.toast('未检测到支付宝,请安装后重试');
  286. return false
  287. }else{
  288. return true
  289. }
  290. },
  291. //判断是安装了微信
  292. isWechatConfig() {
  293. const params = {
  294. pname: 'com.tencent.mm',
  295. action: 'weixin://'
  296. };
  297. // 判断是否安装支付宝
  298. if (!plus.runtime.isApplicationExist(params)) {
  299. uni.$u.toast('未检测到微信,请安装后重试');
  300. return false
  301. }else{
  302. return true
  303. }
  304. },
  305. /*
  306. 会员部分使用
  307. */
  308. // 转json
  309. getConfigJson(item) {
  310. // 先判断是否有值,避免null/undefined
  311. if (!item || !item.configJson) {
  312. return null;
  313. }
  314. // 防止JSON格式错误导致报错
  315. try {
  316. return JSON.parse(item.configJson);
  317. } catch (e) {
  318. console.error('解析configJson失败:', e);
  319. return null;
  320. }
  321. },
  322. // 获取 configJson 类型
  323. getConfigType(item) {
  324. const cfg = this.getConfigJson(item);
  325. if (!cfg) return null;
  326. return cfg;
  327. },
  328. // 安全取值,空时返回 ''
  329. getConfigVal(item, key) {
  330. const cfg = this.getConfigJson(item);
  331. if (!cfg || cfg[key] == null || cfg[key] === '') return '';
  332. return cfg[key];
  333. },
  334. };
  335. // 组合导出
  336. export default {
  337. ...routerUtil,
  338. ...imageUtil,
  339. ...formatUtil,
  340. ...throttleUtil,
  341. ...otherUtil,
  342. };