util.js 17 KB

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