util.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
  5. // +----------------------------------------------------------------------
  6. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  7. // +----------------------------------------------------------------------
  8. // | Author: CRMEB Team <admin@crmeb.com>
  9. // +----------------------------------------------------------------------
  10. import {
  11. TOKENNAME,
  12. HTTP_REQUEST_URL
  13. } from '../config/app.js';
  14. import store from '../store';
  15. import {
  16. pathToBase64
  17. } from '@/plugin/image-tools/index.js';
  18. // #ifdef APP-PLUS
  19. import permision from "./permission.js"
  20. // #endif
  21. export default {
  22. /**
  23. * opt object | string
  24. * to_url object | string
  25. * 例:
  26. * this.Tips('/pages/test/test'); 跳转不提示
  27. * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
  28. * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
  29. * tab=1 一定时间后跳转至 table上
  30. * tab=2 一定时间后跳转至非 table上
  31. * tab=3 一定时间后返回上页面
  32. * tab=4 关闭所有页面,打开到应用内的某个页面
  33. * tab=5 关闭当前页面,跳转到应用内的某个页面
  34. */
  35. Tips: function(opt, to_url) {
  36. if (typeof opt == 'string') {
  37. to_url = opt;
  38. opt = {};
  39. }
  40. let title = opt.title || '',
  41. icon = opt.icon || 'none',
  42. endtime = opt.endtime || 2000,
  43. success = opt.success;
  44. if (title) uni.showToast({
  45. title: title,
  46. icon: icon,
  47. duration: endtime,
  48. success
  49. })
  50. if (to_url != undefined) {
  51. if (typeof to_url == 'object') {
  52. let tab = to_url.tab || 1,
  53. url = to_url.url || '';
  54. switch (tab) {
  55. case 1:
  56. //一定时间后跳转至 table
  57. setTimeout(function() {
  58. uni.navigateTo({
  59. url: url
  60. })
  61. }, endtime);
  62. break;
  63. case 2:
  64. //跳转至非table页面
  65. setTimeout(function() {
  66. uni.navigateTo({
  67. url: url,
  68. })
  69. }, endtime);
  70. break;
  71. case 3:
  72. //返回上页面
  73. setTimeout(function() {
  74. // #ifndef H5
  75. uni.navigateBack({
  76. delta: parseInt(url),
  77. })
  78. // #endif
  79. // #ifdef H5
  80. history.back();
  81. // #endif
  82. }, endtime);
  83. break;
  84. case 4:
  85. //关闭所有页面,打开到应用内的某个页面
  86. setTimeout(function() {
  87. uni.reLaunch({
  88. url: url,
  89. })
  90. }, endtime);
  91. break;
  92. case 5:
  93. //关闭当前页面,跳转到应用内的某个页面
  94. setTimeout(function() {
  95. uni.redirectTo({
  96. url: url,
  97. })
  98. }, endtime);
  99. break;
  100. }
  101. } else if (typeof to_url == 'function') {
  102. setTimeout(function() {
  103. to_url && to_url();
  104. }, endtime);
  105. } else {
  106. //没有提示时跳转不延迟
  107. setTimeout(function() {
  108. uni.navigateTo({
  109. url: to_url,
  110. })
  111. }, title ? endtime : 0);
  112. }
  113. }
  114. },
  115. /**
  116. * 移除数组中的某个数组并组成新的数组返回
  117. * @param array array 需要移除的数组
  118. * @param int index 需要移除的数组的键值
  119. * @param string | int 值
  120. * @return array
  121. *
  122. */
  123. ArrayRemove: function(array, index, value) {
  124. const valueArray = [];
  125. if (array instanceof Array) {
  126. for (let i = 0; i < array.length; i++) {
  127. if (typeof index == 'number' && array[index] != i) {
  128. valueArray.push(array[i]);
  129. } else if (typeof index == 'string' && array[i][index] != value) {
  130. valueArray.push(array[i]);
  131. }
  132. }
  133. }
  134. return valueArray;
  135. },
  136. /**
  137. * 生成海报获取文字
  138. * @param string text 为传入的文本
  139. * @param int num 为单行显示的字节长度
  140. * @return array
  141. */
  142. textByteLength: function(text, num) {
  143. let strLength = 0;
  144. let rows = 1;
  145. let str = 0;
  146. let arr = [];
  147. for (let j = 0; j < text.length; j++) {
  148. if (text.charCodeAt(j) > 255) {
  149. strLength += 2;
  150. if (strLength > rows * num) {
  151. strLength++;
  152. arr.push(text.slice(str, j));
  153. str = j;
  154. rows++;
  155. }
  156. } else {
  157. strLength++;
  158. if (strLength > rows * num) {
  159. arr.push(text.slice(str, j));
  160. str = j;
  161. rows++;
  162. }
  163. }
  164. }
  165. arr.push(text.slice(str, text.length));
  166. return [strLength, arr, rows] // [处理文字的总字节长度,每行显示内容的数组,行数]
  167. },
  168. /**
  169. * 获取分享海报
  170. * @param array arr2 海报素材
  171. * @param string store_name 素材文字
  172. * @param string price 价格
  173. * @param string ot_price 原始价格
  174. * @param function successFn 回调函数
  175. *
  176. *
  177. */
  178. PosterCanvas: function(arr2, store_name, price,ot_price, successFn) {
  179. let that = this;
  180. uni.showLoading({
  181. title: '海报生成中',
  182. mask: true
  183. });
  184. const ctx = uni.createCanvasContext('myCanvas');
  185. ctx.clearRect(0, 0, 0, 0);
  186. /**
  187. * 只能获取合法域名下的图片信息,本地调试无法获取
  188. *
  189. */
  190. ctx.fillStyle = '#fff';
  191. ctx.fillRect(0, 0, 750, 1150);
  192. uni.getImageInfo({
  193. src: arr2[0],
  194. success: function(res) {
  195. const WIDTH = res.width;
  196. const HEIGHT = res.height;
  197. // ctx.drawImage(arr2[0], 0, 0, WIDTH, 1050);
  198. ctx.drawImage(arr2[1], 0, 0, WIDTH, WIDTH);
  199. ctx.save();
  200. let r = 110;
  201. let d = r * 2;
  202. let cx = 480;
  203. let cy = 790;
  204. ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
  205. // ctx.clip();
  206. ctx.drawImage(arr2[2], cx, cy,d,d);
  207. ctx.restore();
  208. const CONTENT_ROW_LENGTH = 18;
  209. let [contentLeng, contentArray, contentRows] = that.textByteLength(store_name, CONTENT_ROW_LENGTH);
  210. if (contentRows > 2) {
  211. contentRows = 2;
  212. let textArray = contentArray.slice(0, 2);
  213. textArray[textArray.length - 1] += '……';
  214. contentArray = textArray;
  215. }
  216. ctx.setTextAlign('left');
  217. ctx.setFontSize(36);
  218. ctx.setFillStyle('#000');
  219. // let contentHh = 36 * 1.5;
  220. let contentHh = 36;
  221. for (let m = 0; m < contentArray.length; m++) {
  222. // ctx.fillText(contentArray[m], 50, 1000 + contentHh * m,750);
  223. if (m) {
  224. ctx.fillText(contentArray[m], 50, 1000 + contentHh * m + 18,1100);
  225. } else {
  226. ctx.fillText(contentArray[m], 50, 1000 + contentHh * m,1100);
  227. }
  228. }
  229. ctx.setTextAlign('left')
  230. ctx.setFontSize(72);
  231. ctx.setFillStyle('#DA4F2A');
  232. ctx.fillText('¥' + price, 40, 820 + contentHh);
  233. ctx.setTextAlign('left')
  234. ctx.setFontSize(36);
  235. ctx.setFillStyle('#999');
  236. ctx.fillText('¥' + ot_price, 50, 876 + contentHh);
  237. var underline = function(ctx, text, x, y, size, color, thickness ,offset){
  238. var width = ctx.measureText(text).width;
  239. switch(ctx.textAlign){
  240. case "center":
  241. x -= (width/2); break;
  242. case "right":
  243. x -= width; break;
  244. }
  245. y += size+offset;
  246. ctx.beginPath();
  247. ctx.strokeStyle = color;
  248. ctx.lineWidth = thickness;
  249. ctx.moveTo(x,y);
  250. ctx.lineTo(x+width,y);
  251. ctx.stroke();
  252. }
  253. underline(ctx,'¥'+ot_price, 55,865,36,'#999',2,0)
  254. ctx.setTextAlign('left')
  255. ctx.setFontSize(28);
  256. ctx.setFillStyle('#999');
  257. ctx.fillText('长按或扫描查看', 490, 1030 + contentHh);
  258. ctx.draw(true, function() {
  259. uni.canvasToTempFilePath({
  260. canvasId: 'myCanvas',
  261. fileType: 'png',
  262. destWidth: WIDTH,
  263. destHeight: HEIGHT,
  264. success: function(res) {
  265. uni.hideLoading();
  266. successFn && successFn(res.tempFilePath);
  267. }
  268. })
  269. });
  270. },
  271. fail: function(err) {
  272. uni.hideLoading();
  273. that.Tips({
  274. title: '无法获取图片信息'
  275. });
  276. }
  277. })
  278. },
  279. /*
  280. * 单图上传
  281. * @param object opt
  282. * @param callable successCallback 成功执行方法 data
  283. * @param callable errorCallback 失败执行方法
  284. */
  285. uploadImageOne: function(opt, successCallback, errorCallback) {
  286. let that = this;
  287. if (typeof opt === 'string') {
  288. let url = opt;
  289. opt = {};
  290. opt.url = url;
  291. }
  292. let count = opt.count || 1,
  293. sizeType = opt.sizeType || ['compressed'],
  294. sourceType = opt.sourceType || ['album', 'camera'],
  295. is_load = opt.is_load || true,
  296. uploadUrl = opt.url || '',
  297. inputName = opt.name || 'pics',
  298. fileType = opt.fileType || 'image';
  299. uni.chooseImage({
  300. count: count, //最多可以选择的图片总数
  301. sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有
  302. sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有
  303. success: function(res) {
  304. //启动上传等待中...
  305. uni.showLoading({
  306. title: '图片上传中',
  307. });
  308. uni.uploadFile({
  309. url: HTTP_REQUEST_URL + '/api/' + uploadUrl,
  310. filePath: res.tempFilePaths[0],
  311. fileType: fileType,
  312. name: inputName,
  313. formData: {
  314. 'filename': inputName
  315. },
  316. header: {
  317. // #ifdef MP
  318. "Content-Type": "multipart/form-data",
  319. // #endif
  320. [TOKENNAME]: 'Bearer ' + store.state.app.token
  321. },
  322. success: function(res) {
  323. uni.hideLoading();
  324. if (res.statusCode == 403) {
  325. that.Tips({
  326. title: res.data
  327. });
  328. } else {
  329. let data = res.data ? JSON.parse(res.data) : {};
  330. if (data.status == 200) {
  331. successCallback && successCallback(data)
  332. } else {
  333. errorCallback && errorCallback(data);
  334. that.Tips({
  335. title: data.msg
  336. });
  337. }
  338. }
  339. },
  340. fail: function(res) {
  341. uni.hideLoading();
  342. that.Tips({
  343. title: '上传图片失败'
  344. });
  345. }
  346. })
  347. // pathToBase64(res.tempFilePaths[0])
  348. // .then(imgBase64 => {
  349. // console.log(imgBase64);
  350. // })
  351. // .catch(error => {
  352. // console.error(error)
  353. // })
  354. }
  355. })
  356. },
  357. /**
  358. * 处理服务器扫码带进来的参数
  359. * @param string param 扫码携带参数
  360. * @param string k 整体分割符 默认为:&
  361. * @param string p 单个分隔符 默认为:=
  362. * @return object
  363. *
  364. */
  365. // #ifdef MP
  366. getUrlParams: function(param, k, p) {
  367. if (typeof param != 'string') return {};
  368. k = k ? k : '&'; //整体参数分隔符
  369. p = p ? p : '='; //单个参数分隔符
  370. var value = {};
  371. if (param.indexOf(k) !== -1) {
  372. param = param.split(k);
  373. for (var val in param) {
  374. if (param[val].indexOf(p) !== -1) {
  375. var item = param[val].split(p);
  376. value[item[0]] = item[1];
  377. }
  378. }
  379. } else if (param.indexOf(p) !== -1) {
  380. var item = param.split(p);
  381. value[item[0]] = item[1];
  382. } else {
  383. return param;
  384. }
  385. return value;
  386. },
  387. // #endif
  388. /*
  389. * 合并数组
  390. */
  391. SplitArray(list, sp) {
  392. if (typeof list != 'object') return [];
  393. if (sp === undefined) sp = [];
  394. for (var i = 0; i < list.length; i++) {
  395. sp.push(list[i]);
  396. }
  397. return sp;
  398. },
  399. trim(str) {
  400. return String.prototype.trim.call(str);
  401. },
  402. $h: {
  403. //除法函数,用来得到精确的除法结果
  404. //说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
  405. //调用:$h.Div(arg1,arg2)
  406. //返回值:arg1除以arg2的精确结果
  407. Div: function(arg1, arg2) {
  408. arg1 = parseFloat(arg1);
  409. arg2 = parseFloat(arg2);
  410. var t1 = 0,
  411. t2 = 0,
  412. r1, r2;
  413. try {
  414. t1 = arg1.toString().split(".")[1].length;
  415. } catch (e) {}
  416. try {
  417. t2 = arg2.toString().split(".")[1].length;
  418. } catch (e) {}
  419. r1 = Number(arg1.toString().replace(".", ""));
  420. r2 = Number(arg2.toString().replace(".", ""));
  421. return this.Mul(r1 / r2, Math.pow(10, t2 - t1));
  422. },
  423. //加法函数,用来得到精确的加法结果
  424. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
  425. //调用:$h.Add(arg1,arg2)
  426. //返回值:arg1加上arg2的精确结果
  427. Add: function(arg1, arg2) {
  428. arg2 = parseFloat(arg2);
  429. var r1, r2, m;
  430. try {
  431. r1 = arg1.toString().split(".")[1].length
  432. } catch (e) {
  433. r1 = 0
  434. }
  435. try {
  436. r2 = arg2.toString().split(".")[1].length
  437. } catch (e) {
  438. r2 = 0
  439. }
  440. m = Math.pow(100, Math.max(r1, r2));
  441. return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m;
  442. },
  443. //减法函数,用来得到精确的减法结果
  444. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
  445. //调用:$h.Sub(arg1,arg2)
  446. //返回值:arg1减去arg2的精确结果
  447. Sub: function(arg1, arg2) {
  448. arg1 = parseFloat(arg1);
  449. arg2 = parseFloat(arg2);
  450. var r1, r2, m, n;
  451. try {
  452. r1 = arg1.toString().split(".")[1].length
  453. } catch (e) {
  454. r1 = 0
  455. }
  456. try {
  457. r2 = arg2.toString().split(".")[1].length
  458. } catch (e) {
  459. r2 = 0
  460. }
  461. m = Math.pow(10, Math.max(r1, r2));
  462. //动态控制精度长度
  463. n = (r1 >= r2) ? r1 : r2;
  464. return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n);
  465. },
  466. //乘法函数,用来得到精确的乘法结果
  467. //说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
  468. //调用:$h.Mul(arg1,arg2)
  469. //返回值:arg1乘以arg2的精确结果
  470. Mul: function(arg1, arg2) {
  471. arg1 = parseFloat(arg1);
  472. arg2 = parseFloat(arg2);
  473. var m = 0,
  474. s1 = arg1.toString(),
  475. s2 = arg2.toString();
  476. try {
  477. m += s1.split(".")[1].length
  478. } catch (e) {}
  479. try {
  480. m += s2.split(".")[1].length
  481. } catch (e) {}
  482. return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
  483. },
  484. },
  485. // 获取地理位置;
  486. $L: {
  487. async getLocation() {
  488. // #ifdef APP-PLUS
  489. let status = await this.checkPermission();
  490. if (status !== 1) {
  491. return;
  492. }
  493. // #endif
  494. // #ifdef MP-WEIXIN || MP-TOUTIAO || MP-QQ
  495. let status = await this.getSetting();
  496. if (status === 2) {
  497. this.openSetting();
  498. return;
  499. }
  500. // #endif
  501. this.doGetLocation();
  502. },
  503. doGetLocation() {
  504. uni.getLocation({
  505. success: (res) => {
  506. uni.removeStorageSync('CACHE_LONGITUDE');
  507. uni.removeStorageSync('CACHE_LATITUDE');
  508. uni.setStorageSync('CACHE_LONGITUDE', res.longitude);
  509. uni.setStorageSync('CACHE_LATITUDE', res.latitude);
  510. },
  511. fail: (err) => {
  512. // #ifdef MP-BAIDU
  513. if (err.errCode === 202 || err.errCode === 10003) { // 202模拟器 10003真机 user deny
  514. this.openSetting();
  515. }
  516. // #endif
  517. // #ifndef MP-BAIDU
  518. if (err.errMsg.indexOf("auth deny") >= 0) {
  519. uni.showToast({
  520. title: "访问位置被拒绝"
  521. })
  522. } else {
  523. uni.showToast({
  524. title: err.errMsg
  525. })
  526. }
  527. // #endif
  528. }
  529. })
  530. },
  531. getSetting: function() {
  532. return new Promise((resolve, reject) => {
  533. uni.getSetting({
  534. success: (res) => {
  535. if (res.authSetting['scope.userLocation'] === undefined) {
  536. resolve(0);
  537. return;
  538. }
  539. if (res.authSetting['scope.userLocation']) {
  540. resolve(1);
  541. } else {
  542. resolve(2);
  543. }
  544. }
  545. });
  546. });
  547. },
  548. openSetting: function() {
  549. uni.openSetting({
  550. success: (res) => {
  551. if (res.authSetting && res.authSetting['scope.userLocation']) {
  552. this.doGetLocation();
  553. }
  554. },
  555. fail: (err) => {}
  556. })
  557. },
  558. async checkPermission() {
  559. let status = permision.isIOS ? await permision.requestIOS('location') :
  560. await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');
  561. if (status === null || status === 1) {
  562. status = 1;
  563. } else if (status === 2) {
  564. uni.showModal({
  565. content: "系统定位已关闭",
  566. confirmText: "确定",
  567. showCancel: false,
  568. success: function(res) {}
  569. })
  570. } else if (status.code) {
  571. uni.showModal({
  572. content: status.message
  573. })
  574. } else {
  575. uni.showModal({
  576. content: "需要定位权限",
  577. confirmText: "设置",
  578. success: function(res) {
  579. if (res.confirm) {
  580. permision.gotoAppSetting();
  581. }
  582. }
  583. })
  584. }
  585. return status;
  586. },
  587. }
  588. }