util.js 15KB

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