You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

956 lines
25 KiB

3 months ago
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
  5. // +----------------------------------------------------------------------
  6. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  7. // +----------------------------------------------------------------------
  8. // | Author: CRMEB Team <admin@crmeb.com>
  9. // +----------------------------------------------------------------------
  10. import animationType from '@/utils/animationType.js'
  11. import {
  12. TOKENNAME,
  13. HTTP_REQUEST_URL
  14. } from '../config/app.js';
  15. import store from '../store';
  16. import {
  17. pathToBase64
  18. } from '@/plugin/image-tools/index.js';
  19. import util from 'utils/util'
  20. // #ifdef APP-PLUS
  21. import permision from "./permission.js"
  22. // #endif
  23. export default {
  24. /**
  25. * 链接地址跳转
  26. * @param {Object} url 链接地址
  27. */
  28. navigateTo(url) {
  29. if (url.indexOf("http") !== -1) {
  30. // #ifdef H5
  31. location.href = url
  32. // #endif
  33. // #ifdef APP-PLUS || MP
  34. uni.navigateTo({
  35. url: '/pages/users/web_page/index?webUel=' + encodeURIComponent(url)
  36. })
  37. // #endif
  38. } else {
  39. if (['/pages/goods_cate/goods_cate', '/pages/order_addcart/order_addcart', '/pages/user/index',
  40. '/pages/discover_index/index', '/pages/index/index'
  41. ].indexOf(url) == -1) {
  42. uni.navigateTo({
  43. animationType: animationType.type,
  44. animationDuration: animationType.duration,
  45. url: url
  46. })
  47. } else {
  48. uni.switchTab({
  49. animationType: animationType.type,
  50. animationDuration: animationType.duration,
  51. url: url
  52. })
  53. }
  54. }
  55. },
  56. /**
  57. * 对象转数组
  58. * @param data 对象
  59. * @returns {*[]}
  60. */
  61. objToArr(data) {
  62. let obj = Object.keys(data).sort();
  63. let m = obj.map(key => data[key]);
  64. return m;
  65. },
  66. /**
  67. * opt object | string
  68. * to_url object | string
  69. * :
  70. * this.Tips('/pages/test/test'); 跳转不提示
  71. * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
  72. * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
  73. * tab=1 一定时间后跳转至 table上
  74. * tab=2 一定时间后跳转至非 table上
  75. * tab=3 一定时间后返回上页面
  76. * tab=4 关闭所有页面跳转至非table上
  77. * tab=5 关闭当前页面跳转至table上
  78. */
  79. Tips: function(opt, to_url) {
  80. if (typeof opt == 'string') {
  81. to_url = opt;
  82. opt = {};
  83. }
  84. let title = opt.title || '',
  85. icon = opt.icon || 'none',
  86. endtime = opt.endtime || 2000,
  87. success = opt.success;
  88. if (title) uni.showToast({
  89. title: title,
  90. icon: icon,
  91. duration: endtime,
  92. success
  93. })
  94. if (to_url != undefined) {
  95. if (typeof to_url == 'object') {
  96. let tab = to_url.tab || 1,
  97. url = to_url.url || '';
  98. switch (tab) {
  99. case 1:
  100. //一定时间后跳转至 table
  101. setTimeout(function() {
  102. uni.switchTab({
  103. url: url
  104. })
  105. }, endtime);
  106. break;
  107. case 2:
  108. //跳转至非table页面
  109. setTimeout(function() {
  110. uni.navigateTo({
  111. url: url,
  112. })
  113. }, endtime);
  114. break;
  115. case 3:
  116. //返回上页面
  117. setTimeout(function() {
  118. // #ifndef H5
  119. uni.navigateBack({
  120. delta: parseInt(url),
  121. })
  122. // #endif
  123. // #ifdef H5
  124. history.back();
  125. // #endif
  126. }, endtime);
  127. break;
  128. case 4:
  129. //关闭当前所有页面跳转至非table页面
  130. setTimeout(function() {
  131. uni.reLaunch({
  132. url: url,
  133. })
  134. }, endtime);
  135. break;
  136. case 5:
  137. //关闭当前页面跳转至非table页面
  138. setTimeout(function() {
  139. uni.redirectTo({
  140. url: url,
  141. })
  142. }, endtime);
  143. break;
  144. }
  145. } else if (typeof to_url == 'function') {
  146. setTimeout(function() {
  147. to_url && to_url();
  148. }, endtime);
  149. } else {
  150. //没有提示时跳转不延迟
  151. setTimeout(function() {
  152. uni.navigateTo({
  153. url: to_url,
  154. })
  155. }, title ? endtime : 0);
  156. }
  157. }
  158. },
  159. /**
  160. * 移除数组中的某个数组并组成新的数组返回
  161. * @param array array 需要移除的数组
  162. * @param int index 需要移除的数组的键值
  163. * @param string | int
  164. * @return array
  165. *
  166. */
  167. ArrayRemove: function(array, index, value) {
  168. const valueArray = [];
  169. if (array instanceof Array) {
  170. for (let i = 0; i < array.length; i++) {
  171. if (typeof index == 'number' && array[index] != i) {
  172. valueArray.push(array[i]);
  173. } else if (typeof index == 'string' && array[i][index] != value) {
  174. valueArray.push(array[i]);
  175. }
  176. }
  177. }
  178. return valueArray;
  179. },
  180. /**
  181. * 生成海报获取文字
  182. * @param string text 为传入的文本
  183. * @param int num 为单行显示的字节长度
  184. * @return array
  185. */
  186. textByteLength: function(text, num) {
  187. let strLength = 0;
  188. let rows = 1;
  189. let str = 0;
  190. let arr = [];
  191. for (let j = 0; j < text.length; j++) {
  192. if (text.charCodeAt(j) > 255) {
  193. strLength += 2;
  194. if (strLength > rows * num) {
  195. strLength++;
  196. arr.push(text.slice(str, j));
  197. str = j;
  198. rows++;
  199. }
  200. } else {
  201. strLength++;
  202. if (strLength > rows * num) {
  203. arr.push(text.slice(str, j));
  204. str = j;
  205. rows++;
  206. }
  207. }
  208. }
  209. arr.push(text.slice(str, text.length));
  210. return [strLength, arr, rows] // [处理文字的总字节长度,每行显示内容的数组,行数]
  211. },
  212. /**
  213. * 获取分享海报
  214. * @param array arr2 海报素材
  215. * @param string store_name 素材文字
  216. * @param string price 价格
  217. * @param string ot_price 原始价格
  218. * @param function successFn 回调函数
  219. *
  220. *
  221. */
  222. PosterCanvas: function(arr2, store_name, price, ot_price, successFn) {
  223. let that = this;
  224. const ctx = uni.createCanvasContext('firstCanvas');
  225. ctx.clearRect(0, 0, 0, 0);
  226. /**
  227. * 只能获取合法域名下的图片信息,本地调试无法获取
  228. *
  229. */
  230. ctx.fillStyle = '#fff';
  231. ctx.fillRect(0, 0, 750, 1150);
  232. uni.getImageInfo({
  233. src: arr2[0],
  234. success: function(res) {
  235. const WIDTH = res.width;
  236. const HEIGHT = res.height;
  237. // ctx.drawImage(arr2[0], 0, 0, WIDTH, 1050);
  238. ctx.drawImage(arr2[1], 0, 0, WIDTH, WIDTH);
  239. ctx.save();
  240. let r = 110;
  241. let d = r * 2;
  242. let cx = 480;
  243. let cy = 790;
  244. ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
  245. // ctx.clip();
  246. ctx.drawImage(arr2[2], cx, cy, d, d);
  247. ctx.restore();
  248. const CONTENT_ROW_LENGTH = 20;
  249. let [contentLeng, contentArray, contentRows] = that.textByteLength(store_name,
  250. CONTENT_ROW_LENGTH);
  251. if (contentRows > 2) {
  252. contentRows = 2;
  253. let textArray = contentArray.slice(0, 2);
  254. textArray[textArray.length - 1] += '……';
  255. contentArray = textArray;
  256. }
  257. ctx.setTextAlign('left');
  258. ctx.setFontSize(36);
  259. ctx.setFillStyle('#000');
  260. // let contentHh = 36 * 1.5;
  261. let contentHh = 36;
  262. for (let m = 0; m < contentArray.length; m++) {
  263. // ctx.fillText(contentArray[m], 50, 1000 + contentHh * m,750);
  264. if (m) {
  265. ctx.fillText(contentArray[m], 50, 1000 + contentHh * m + 18, 1100);
  266. } else {
  267. ctx.fillText(contentArray[m], 50, 1000 + contentHh * m, 1100);
  268. }
  269. }
  270. ctx.setTextAlign('left')
  271. ctx.setFontSize(72);
  272. ctx.setFillStyle('#DA4F2A');
  273. ctx.fillText('¥' + price, 40, 820 + contentHh);
  274. ctx.setTextAlign('left')
  275. ctx.setFontSize(36);
  276. ctx.setFillStyle('#999');
  277. ctx.fillText('¥' + ot_price, 50, 876 + contentHh);
  278. var underline = function(ctx, text, x, y, size, color, thickness, offset) {
  279. var width = ctx.measureText(text).width;
  280. switch (ctx.textAlign) {
  281. case "center":
  282. x -= (width / 2);
  283. break;
  284. case "right":
  285. x -= width;
  286. break;
  287. }
  288. y += size + offset;
  289. ctx.beginPath();
  290. ctx.strokeStyle = color;
  291. ctx.lineWidth = thickness;
  292. ctx.moveTo(x, y);
  293. ctx.lineTo(x + width, y);
  294. ctx.stroke();
  295. }
  296. underline(ctx, '¥' + ot_price, 55, 865, 36, '#999', 2, 0)
  297. ctx.setTextAlign('left')
  298. ctx.setFontSize(28);
  299. ctx.setFillStyle('#999');
  300. ctx.fillText('长按或扫描查看', 490, 1030 + contentHh);
  301. ctx.draw(true, function() {
  302. uni.canvasToTempFilePath({
  303. canvasId: 'firstCanvas',
  304. fileType: 'png',
  305. destWidth: WIDTH,
  306. destHeight: HEIGHT,
  307. success: function(res) {
  308. // uni.hideLoading();
  309. successFn && successFn(res.tempFilePath);
  310. }
  311. })
  312. });
  313. },
  314. fail: function(err) {
  315. console.log('失败', err)
  316. uni.hideLoading();
  317. that.Tips({
  318. title: '无法获取图片信息'
  319. });
  320. }
  321. })
  322. },
  323. /**
  324. * 绘制文字自动换行
  325. * @param array arr2 海报素材
  326. * @param Number x , y 绘制的坐标
  327. * @param Number maxWigth 绘制文字的宽度
  328. * @param Number lineHeight 行高
  329. * @param Number maxRowNum 最大行数
  330. */
  331. canvasWraptitleText(canvas, text, x, y, maxWidth, lineHeight, maxRowNum) {
  332. if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
  333. return;
  334. }
  335. // canvas.font = '20px Bold PingFang SC'; //绘制文字的字号和大小
  336. // 字符分隔为数组
  337. var arrText = text.split('');
  338. var line = '';
  339. var rowNum = 1
  340. for (var n = 0; n < arrText.length; n++) {
  341. var testLine = line + arrText[n];
  342. var metrics = canvas.measureText(testLine);
  343. var testWidth = metrics.width;
  344. if (testWidth > maxWidth && n > 0) {
  345. if (rowNum >= maxRowNum) {
  346. var arrLine = testLine.split('')
  347. arrLine.splice(-9)
  348. var newTestLine = arrLine.join("")
  349. newTestLine += "..."
  350. canvas.fillText(newTestLine, x, y);
  351. //如果需要在省略号后面添加其他的东西,就在这个位置写(列如添加扫码查看详情字样)
  352. //canvas.fillStyle = '#2259CA';
  353. //canvas.fillText('扫码查看详情',x + maxWidth-90, y);
  354. return
  355. }
  356. canvas.fillText(line, x, y);
  357. line = arrText[n];
  358. y += lineHeight;
  359. rowNum += 1
  360. } else {
  361. line = testLine;
  362. }
  363. }
  364. canvas.fillText(line, x, y);
  365. },
  366. /**
  367. * 获取活动分享海报
  368. * @param array arr2 海报素材
  369. * @param string storeName 素材文字
  370. * @param string price 价格
  371. * @param string people 人数
  372. * @param string count 剩余人数
  373. * @param function successFn 回调函数
  374. */
  375. activityCanvas: function(arrImages, storeName, price, people, count, num, successFn) {
  376. let that = this;
  377. let rain = 2;
  378. const context = uni.createCanvasContext('activityCanvas');
  379. context.clearRect(0, 0, 0, 0);
  380. /**
  381. * 只能获取合法域名下的图片信息,本地调试无法获取
  382. *
  383. */
  384. context.fillStyle = '#fff';
  385. context.fillRect(0, 0, 594, 850);
  386. uni.getImageInfo({
  387. src: arrImages[0],
  388. success: function(res) {
  389. context.drawImage(arrImages[0], 0, 0, 594, 850);
  390. context.setFontSize(14 * rain);
  391. context.setFillStyle('#333333');
  392. that.canvasWraptitleText(context, storeName, 110 * rain, 110 * rain, 230 * rain, 30 *
  393. rain, 1)
  394. context.drawImage(arrImages[2], 68 * rain, 194 * rain, 160 * rain, 160 * rain);
  395. context.save();
  396. context.setFontSize(14 * rain);
  397. context.setFillStyle('#fc4141');
  398. context.fillText('¥', 157 * rain, 145 * rain);
  399. context.setFontSize(24 * rain);
  400. context.setFillStyle('#fc4141');
  401. context.fillText(price, 170 * rain, 145 * rain);
  402. context.setFontSize(10 * rain);
  403. context.setFillStyle('#fff');
  404. context.fillText(people, 118 * rain, 143 * rain);
  405. context.setFontSize(12 * rain);
  406. context.setFillStyle('#666666');
  407. context.setTextAlign('center');
  408. context.fillText(count, (167 - num) * rain, 166 * rain);
  409. that.handleBorderRect(context, 27 * rain, 94 * rain, 75 * rain, 75 * rain, 6 * rain);
  410. context.clip();
  411. context.drawImage(arrImages[1], 27 * rain, 94 * rain, 75 * rain, 75 * rain);
  412. context.draw(true, function() {
  413. uni.canvasToTempFilePath({
  414. canvasId: 'activityCanvas',
  415. fileType: 'png',
  416. destWidth: 594,
  417. destHeight: 850,
  418. success: function(res) {
  419. // uni.hideLoading();
  420. successFn && successFn(res.tempFilePath);
  421. }
  422. })
  423. });
  424. },
  425. fail: function(err) {
  426. console.log('失败', err)
  427. uni.hideLoading();
  428. that.Tips({
  429. title: '无法获取图片信息'
  430. });
  431. }
  432. })
  433. },
  434. /**
  435. * 图片圆角设置
  436. * @param string x x轴位置
  437. * @param string y y轴位置
  438. * @param string w 图片宽
  439. * @param string y 图片高
  440. * @param string r 圆角值
  441. */
  442. handleBorderRect(ctx, x, y, w, h, r) {
  443. ctx.beginPath();
  444. // 左上角
  445. ctx.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI);
  446. ctx.moveTo(x + r, y);
  447. ctx.lineTo(x + w - r, y);
  448. ctx.lineTo(x + w, y + r);
  449. // 右上角
  450. ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI);
  451. ctx.lineTo(x + w, y + h - r);
  452. ctx.lineTo(x + w - r, y + h);
  453. // 右下角
  454. ctx.arc(x + w - r, y + h - r, r, 0, 0.5 * Math.PI);
  455. ctx.lineTo(x + r, y + h);
  456. ctx.lineTo(x, y + h - r);
  457. // 左下角
  458. ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, Math.PI);
  459. ctx.lineTo(x, y + r);
  460. ctx.lineTo(x + r, y);
  461. ctx.fill();
  462. ctx.closePath();
  463. },
  464. /**
  465. * 小程序头像获取上传
  466. * @param uploadUrl 上传接口地址
  467. * @param filePath 上传文件路径
  468. * @param successCallback success回调
  469. * @param errorCallback err回调
  470. */
  471. uploadImgs(filePath, opt, successCallback, errorCallback) {
  472. let that = this;
  473. if (typeof opt === 'string') {
  474. let url = opt;
  475. opt = {};
  476. opt.url = url;
  477. }
  478. let count = opt.count || 1,
  479. sizeType = opt.sizeType || ['compressed'],
  480. sourceType = opt.sourceType || ['album', 'camera'],
  481. is_load = opt.is_load || true,
  482. uploadUrl = opt.url || '',
  483. inputName = opt.name || 'pics',
  484. pid = opt.pid,
  485. model = opt.model;
  486. let urlPath = HTTP_REQUEST_URL + '/api/front/upload/image' + "?model=" + model +
  487. "&pid=" + pid
  488. uni.uploadFile({
  489. url: urlPath,
  490. filePath: filePath,
  491. name: inputName,
  492. formData: {
  493. 'filename': inputName
  494. },
  495. header: {
  496. // #ifdef MP
  497. "Content-Type": "multipart/form-data",
  498. // #endif
  499. [TOKENNAME]: store.state.app.token
  500. },
  501. success: function(res) {
  502. uni.hideLoading();
  503. if (res.statusCode == 403) {
  504. that.Tips({
  505. title: res.data
  506. });
  507. } else {
  508. let data = res.data ? JSON.parse(res.data) : {};
  509. if (data.code == 200) {
  510. successCallback && successCallback(data)
  511. } else {
  512. errorCallback && errorCallback(data);
  513. that.Tips({
  514. title: data.message
  515. });
  516. }
  517. }
  518. },
  519. fail: function(res) {
  520. console.log('res', res)
  521. uni.hideLoading();
  522. that.Tips({
  523. title: '上传图片失败'
  524. });
  525. }
  526. })
  527. },
  528. /*
  529. * 单图上传
  530. * @param object opt
  531. * @param callable successCallback 成功执行方法 data
  532. * @param callable errorCallback 失败执行方法
  533. */
  534. uploadImageOne: function(opt, successCallback, errorCallback) {
  535. let that = this;
  536. if (typeof opt === 'string') {
  537. let url = opt;
  538. opt = {};
  539. opt.url = url;
  540. }
  541. let count = opt.count || 1,
  542. sizeType = opt.sizeType || ['compressed'],
  543. sourceType = opt.sourceType || ['album', 'camera'],
  544. is_load = opt.is_load || true,
  545. uploadUrl = opt.url || '',
  546. inputName = opt.name || 'pics',
  547. pid = opt.pid,
  548. model = opt.model;
  549. uni.chooseImage({
  550. count: count, //最多可以选择的图片总数
  551. sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有
  552. sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有
  553. success: function(res) {
  554. //启动上传等待中...
  555. uni.showLoading({
  556. title: '图片上传中',
  557. });
  558. let urlPath = HTTP_REQUEST_URL + '/api/front/upload/image' + "?model=" + model +
  559. "&pid=" + pid
  560. let localPath = res.tempFilePaths[0];
  561. uni.uploadFile({
  562. url: urlPath,
  563. filePath: localPath,
  564. name: inputName,
  565. header: {
  566. // #ifdef MP
  567. "Content-Type": "multipart/form-data",
  568. // #endif
  569. [TOKENNAME]: store.state.app.token
  570. },
  571. success: function(res) {
  572. uni.hideLoading();
  573. if (res.statusCode == 403) {
  574. that.Tips({
  575. title: res.data
  576. });
  577. } else {
  578. let data = res.data ? JSON.parse(res.data) : {};
  579. if (data.code == 200) {
  580. data.data.localPath = localPath;
  581. successCallback && successCallback(data)
  582. } else {
  583. errorCallback && errorCallback(data);
  584. that.Tips({
  585. title: data.message
  586. });
  587. }
  588. }
  589. },
  590. fail: function(res) {
  591. uni.hideLoading();
  592. that.Tips({
  593. title: '上传图片失败'
  594. });
  595. }
  596. })
  597. },
  598. fail: function(err) {
  599. that.Tips({
  600. title: err.errMsg
  601. });
  602. console.log('选择图片失败:', err);
  603. }
  604. })
  605. },
  606. /**
  607. * 处理服务器扫码带进来的参数
  608. * @param string param 扫码携带参数
  609. * @param string k 整体分割符 默认为&
  610. * @param string p 单个分隔符 默认为=
  611. * @return object
  612. *
  613. */
  614. // #ifdef MP
  615. getUrlParams: function(param, k, p) {
  616. if (typeof param != 'string') return {};
  617. k = k ? k : '&'; //整体参数分隔符
  618. p = p ? p : '='; //单个参数分隔符
  619. var value = {};
  620. if (param.indexOf(k) !== -1) {
  621. param = param.split(k);
  622. for (var val in param) {
  623. if (param[val].indexOf(p) !== -1) {
  624. var item = param[val].split(p);
  625. value[item[0]] = item[1];
  626. }
  627. }
  628. } else if (param.indexOf(p) !== -1) {
  629. var item = param.split(p);
  630. value[item[0]] = item[1];
  631. } else {
  632. return param;
  633. }
  634. return value;
  635. },
  636. /**
  637. * @param {Object} value
  638. */
  639. formatMpQrCodeData(value) {
  640. let values = value.split(',');
  641. let result = {};
  642. if (values.length === 2) {
  643. let v1 = values[0].split(":");
  644. if (v1[0] === 'pid') {
  645. result.spread = v1[1];
  646. } else {
  647. result.id = v1[1];
  648. }
  649. let v2 = values[1].split(":");
  650. if (v2[0] === 'pid') {
  651. result.spread = v2[1];
  652. } else {
  653. result.id = v2[1];
  654. }
  655. } else {
  656. result.spread = values[0].split(":")[1];
  657. }
  658. return result;
  659. },
  660. // #endif
  661. /*
  662. * 合并数组
  663. */
  664. SplitArray(list, sp) {
  665. if (typeof list != 'object') return [];
  666. if (sp === undefined) sp = [];
  667. for (var i = 0; i < list.length; i++) {
  668. sp.push(list[i]);
  669. }
  670. return sp;
  671. },
  672. trim(str) {
  673. return String.prototype.trim.call(str);
  674. },
  675. $h: {
  676. //除法函数,用来得到精确的除法结果
  677. //说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
  678. //调用:$h.Div(arg1,arg2)
  679. //返回值:arg1除以arg2的精确结果
  680. Div: function(arg1, arg2) {
  681. arg1 = parseFloat(arg1);
  682. arg2 = parseFloat(arg2);
  683. var t1 = 0,
  684. t2 = 0,
  685. r1, r2;
  686. try {
  687. t1 = arg1.toString().split(".")[1].length;
  688. } catch (e) {}
  689. try {
  690. t2 = arg2.toString().split(".")[1].length;
  691. } catch (e) {}
  692. r1 = Number(arg1.toString().replace(".", ""));
  693. r2 = Number(arg2.toString().replace(".", ""));
  694. return this.Mul(r1 / r2, Math.pow(10, t2 - t1));
  695. },
  696. //加法函数,用来得到精确的加法结果
  697. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
  698. //调用:$h.Add(arg1,arg2)
  699. //返回值:arg1加上arg2的精确结果
  700. Add: function(arg1, arg2) {
  701. arg2 = parseFloat(arg2);
  702. var r1, r2, m;
  703. try {
  704. r1 = arg1.toString().split(".")[1].length
  705. } catch (e) {
  706. r1 = 0
  707. }
  708. try {
  709. r2 = arg2.toString().split(".")[1].length
  710. } catch (e) {
  711. r2 = 0
  712. }
  713. m = Math.pow(100, Math.max(r1, r2));
  714. return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m;
  715. },
  716. //减法函数,用来得到精确的减法结果
  717. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
  718. //调用:$h.Sub(arg1,arg2)
  719. //返回值:arg1减去arg2的精确结果
  720. Sub: function(arg1, arg2) {
  721. arg1 = parseFloat(arg1);
  722. arg2 = parseFloat(arg2);
  723. var r1, r2, m, n;
  724. try {
  725. r1 = arg1.toString().split(".")[1].length
  726. } catch (e) {
  727. r1 = 0
  728. }
  729. try {
  730. r2 = arg2.toString().split(".")[1].length
  731. } catch (e) {
  732. r2 = 0
  733. }
  734. m = Math.pow(10, Math.max(r1, r2));
  735. //动态控制精度长度
  736. n = (r1 >= r2) ? r1 : r2;
  737. return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n);
  738. },
  739. //乘法函数,用来得到精确的乘法结果
  740. //说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
  741. //调用:$h.Mul(arg1,arg2)
  742. //返回值:arg1乘以arg2的精确结果
  743. Mul: function(arg1, arg2) {
  744. arg1 = parseFloat(arg1);
  745. arg2 = parseFloat(arg2);
  746. var m = 0,
  747. s1 = arg1.toString(),
  748. s2 = arg2.toString();
  749. try {
  750. m += s1.split(".")[1].length
  751. } catch (e) {}
  752. try {
  753. m += s2.split(".")[1].length
  754. } catch (e) {}
  755. return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
  756. },
  757. },
  758. // 获取地理位置;
  759. $L: {
  760. getLocation() {
  761. return new Promise(async (resolve, reject) => {
  762. // #ifdef APP-PLUS
  763. let status = await this.checkPermission();
  764. if (status !== 1) {
  765. uni.removeStorageSync('user_latitude');
  766. uni.removeStorageSync('user_longitude');
  767. resolve(status);
  768. return;
  769. }
  770. // #endif
  771. // #ifdef MP
  772. let status = await this.getSetting();
  773. if (status === 2) {
  774. uni.removeStorageSync('user_latitude');
  775. uni.removeStorageSync('user_longitude');
  776. this.Tips({
  777. title: '获取当前定位遇到困难,如需定位请开启权限'
  778. });
  779. //this.openSetting();
  780. resolve(status);
  781. return;
  782. }
  783. // #endif
  784. let Location = await this.doGetLocation();
  785. resolve(Location);
  786. });
  787. },
  788. doGetLocation() {
  789. return new Promise((resolve, reject) => {
  790. uni.getLocation({
  791. type: 'wgs84',
  792. // altitude: true,
  793. // geocode: true,
  794. success: (res) => {
  795. uni.setStorageSync('user_latitude', res.latitude);
  796. uni.setStorageSync('user_longitude', res.longitude);
  797. resolve(res);
  798. },
  799. complete: (res) => {
  800. uni.setStorageSync('user_latitude', res.latitude);
  801. uni.setStorageSync('user_longitude', res.longitude);
  802. resolve(res);
  803. },
  804. fail: (err) => {
  805. uni.removeStorageSync('user_latitude');
  806. uni.removeStorageSync('user_longitude');
  807. reject(err);
  808. // #ifdef MP-BAIDU
  809. if (err.errCode === 202 || err.errCode ===
  810. 10003) { // 202模拟器 10003真机 user deny
  811. this.openSetting();
  812. }
  813. // #endif
  814. // #ifndef MP-BAIDU
  815. if (err.errMsg.indexOf("auth deny") >= 0) {
  816. uni.showToast({
  817. title: '访问位置被拒绝',
  818. icon: 'none',
  819. duration: 2000
  820. });
  821. } else {
  822. uni.showToast({
  823. title: err.errMsg,
  824. icon: 'none',
  825. duration: 2000
  826. });
  827. }
  828. // #endif
  829. }
  830. })
  831. });
  832. },
  833. getSetting: function() {
  834. return new Promise((resolve, reject) => {
  835. uni.getSetting({
  836. success: (res) => {
  837. if (res.authSetting['scope.userLocation'] === undefined) {
  838. resolve(0);
  839. return;
  840. }
  841. if (res.authSetting['scope.userLocation']) {
  842. resolve(1);
  843. } else {
  844. resolve(2);
  845. }
  846. }
  847. });
  848. });
  849. },
  850. /**
  851. * 开启权限提示
  852. */
  853. openSetting: function() {
  854. uni.openSetting({
  855. success: (res) => {
  856. if (res.authSetting && res.authSetting['scope.userLocation']) {
  857. this.doGetLocation();
  858. }
  859. },
  860. fail: (err) => {}
  861. })
  862. },
  863. async checkPermission() {
  864. let status = permision.isIOS ? await permision.requestIOS('location') :
  865. await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');
  866. let pages = getCurrentPages();
  867. let prePage = pages[pages.length - 1].route;
  868. if (status === null || status === 1) {
  869. status = 1;
  870. } else if (status === 2) {
  871. if (prePage === 'pages/users/user_address/index')
  872. uni.showModal({
  873. content: "系统定位已关闭",
  874. confirmText: "确定",
  875. showCancel: false,
  876. success: function(res) {}
  877. })
  878. } else if (status.code) {
  879. if (prePage === 'pages/users/user_address/index')
  880. uni.showModal({
  881. content: status.message
  882. })
  883. } else {
  884. if (prePage === 'pages/users/user_address/index')
  885. uni.showModal({
  886. content: "需要定位权限",
  887. confirmText: "设置",
  888. success: function(res) {
  889. if (res.confirm) {
  890. permision.gotoAppSetting();
  891. }
  892. }
  893. })
  894. }
  895. return status;
  896. },
  897. },
  898. toStringValue: function(obj) {
  899. if (obj instanceof Array) {
  900. var arr = [];
  901. for (var i = 0; i < obj.length; i++) {
  902. arr[i] = toStringValue(obj[i]);
  903. }
  904. return arr;
  905. } else if (typeof obj == 'object') {
  906. for (var p in obj) {
  907. obj[p] = toStringValue(obj[p]);
  908. }
  909. } else if (typeof obj == 'number') {
  910. obj = obj + '';
  911. }
  912. return obj;
  913. },
  914. /*
  915. * 替换域名
  916. */
  917. setDomain: function(url) {
  918. url = url ? url.toString() : '';
  919. if (url.indexOf("https://") > -1) return url;
  920. else return url.replace('http://', 'https://');
  921. },
  922. /**
  923. * 姓名除了姓显示其他
  924. */
  925. formatName: function(str) {
  926. return str.substr(0, 1) + new Array(str.length).join('*');
  927. }
  928. }