util.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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 关闭所有页面跳转至非table上
  24. * tab=5 关闭当前页面跳转至table上
  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.switchTab({
  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. //关闭当前所有页面跳转至非table页面
  77. setTimeout(function() {
  78. uni.reLaunch({
  79. url: url,
  80. })
  81. }, endtime);
  82. break;
  83. case 5:
  84. //关闭当前页面跳转至非table页面
  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 function successFn 回调函数
  165. *
  166. *
  167. */
  168. PosterCanvas: function(arr2, store_name, price, successFn) {
  169. let that = this;
  170. uni.showLoading({
  171. title: '海报生成中',
  172. mask: true
  173. });
  174. const ctx = uni.createCanvasContext('myCanvas');
  175. ctx.clearRect(0, 0, 0, 0);
  176. /**
  177. * 只能获取合法域名下的图片信息,本地调试无法获取
  178. *
  179. */
  180. uni.getImageInfo({
  181. src: arr2[0],
  182. success: function(res) {
  183. console.log(res,'getImageInfo')
  184. const WIDTH = res.width;
  185. const HEIGHT = res.height;
  186. ctx.drawImage(arr2[0], 0, 0, WIDTH, HEIGHT);
  187. ctx.drawImage(arr2[1], 0, 0, WIDTH, WIDTH);
  188. ctx.save();
  189. let r = 90;
  190. let d = r * 2;
  191. let cx = 40;
  192. let cy = 990;
  193. ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
  194. // ctx.clip();
  195. ctx.drawImage(arr2[2], cx, cy,d,d);
  196. ctx.restore();
  197. const CONTENT_ROW_LENGTH = 40;
  198. let [contentLeng, contentArray, contentRows] = that.textByteLength(store_name, CONTENT_ROW_LENGTH);
  199. if (contentRows > 2) {
  200. contentRows = 2;
  201. let textArray = contentArray.slice(0, 2);
  202. textArray[textArray.length - 1] += '……';
  203. contentArray = textArray;
  204. }
  205. ctx.setTextAlign('center');
  206. ctx.setFontSize(32);
  207. let contentHh = 32 * 1.3;
  208. for (let m = 0; m < contentArray.length; m++) {
  209. ctx.fillText(contentArray[m], WIDTH / 2, 820 + contentHh * m);
  210. }
  211. ctx.setTextAlign('center')
  212. ctx.setFontSize(48);
  213. ctx.setFillStyle('red');
  214. ctx.fillText('¥' + price, WIDTH / 2, 880 + contentHh);
  215. ctx.draw(true, function() {
  216. uni.canvasToTempFilePath({
  217. canvasId: 'myCanvas',
  218. fileType: 'png',
  219. destWidth: WIDTH,
  220. destHeight: HEIGHT,
  221. success: function(res) {
  222. uni.hideLoading();
  223. successFn && successFn(res.tempFilePath);
  224. }
  225. })
  226. });
  227. },
  228. fail: function(err) {
  229. uni.hideLoading();
  230. that.Tips({
  231. title: '无法获取图片信息'
  232. });
  233. }
  234. })
  235. },
  236. /*
  237. * 单图上传
  238. * @param object opt
  239. * @param callable successCallback 成功执行方法 data
  240. * @param callable errorCallback 失败执行方法
  241. */
  242. uploadImageOne: function(opt, successCallback, errorCallback) {
  243. let that = this;
  244. if (typeof opt === 'string') {
  245. let url = opt;
  246. opt = {};
  247. opt.url = url;
  248. }
  249. let count = opt.count || 1,
  250. sizeType = opt.sizeType || ['compressed'],
  251. sourceType = opt.sourceType || ['album', 'camera'],
  252. is_load = opt.is_load || true,
  253. uploadUrl = opt.url || '',
  254. inputName = opt.name || 'pics';
  255. uni.chooseImage({
  256. count: count, //最多可以选择的图片总数
  257. sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有
  258. sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有
  259. success: function(res) {
  260. console.log()
  261. //启动上传等待中...
  262. uni.showLoading({
  263. title: '图片上传中',
  264. });
  265. uni.uploadFile({
  266. url: HTTP_REQUEST_URL + '/api/' + uploadUrl,
  267. filePath: res.tempFilePaths[0],
  268. name: 'file',
  269. formData: {
  270. 'filename': inputName
  271. },
  272. header: {
  273. // #ifdef MP
  274. "Content-Type": "multipart/form-data",
  275. // #endif
  276. "secret-key": "b1bd7a4b8da3e47ce58e73b9e5f656c4"
  277. },
  278. success: function(res) {
  279. uni.hideLoading();
  280. if (res.statusCode == 403) {
  281. that.Tips({
  282. title: res.data
  283. });
  284. } else {
  285. let data = res.data ? JSON.parse(res.data) : {};
  286. if (data.code == 200) {
  287. successCallback && successCallback(data)
  288. } else {
  289. errorCallback && errorCallback(data);
  290. that.Tips({
  291. title: data.msg
  292. });
  293. }
  294. }
  295. },
  296. fail: function(res) {
  297. uni.hideLoading();
  298. that.Tips({
  299. title: '上传图片失败'
  300. });
  301. }
  302. })
  303. // pathToBase64(res.tempFilePaths[0])
  304. // .then(imgBase64 => {
  305. // console.log(imgBase64);
  306. // })
  307. // .catch(error => {
  308. // console.error(error)
  309. // })
  310. }
  311. })
  312. },
  313. /**
  314. * 处理服务器扫码带进来的参数
  315. * @param string param 扫码携带参数
  316. * @param string k 整体分割符 默认为:&
  317. * @param string p 单个分隔符 默认为:=
  318. * @return object
  319. *
  320. */
  321. // #ifdef MP
  322. getUrlParams: function(param, k, p) {
  323. if (typeof param != 'string') return {};
  324. k = k ? k : '&'; //整体参数分隔符
  325. p = p ? p : '='; //单个参数分隔符
  326. var value = {};
  327. if (param.indexOf(k) !== -1) {
  328. param = param.split(k);
  329. for (var val in param) {
  330. if (param[val].indexOf(p) !== -1) {
  331. var item = param[val].split(p);
  332. value[item[0]] = item[1];
  333. }
  334. }
  335. } else if (param.indexOf(p) !== -1) {
  336. var item = param.split(p);
  337. value[item[0]] = item[1];
  338. } else {
  339. return param;
  340. }
  341. return value;
  342. },
  343. // #endif
  344. /*
  345. * 合并数组
  346. */
  347. SplitArray(list, sp) {
  348. if (typeof list != 'object') return [];
  349. if (sp === undefined) sp = [];
  350. for (var i = 0; i < list.length; i++) {
  351. sp.push(list[i]);
  352. }
  353. return sp;
  354. },
  355. trim(str) {
  356. return String.prototype.trim.call(str);
  357. },
  358. $h: {
  359. //除法函数,用来得到精确的除法结果
  360. //说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
  361. //调用:$h.Div(arg1,arg2)
  362. //返回值:arg1除以arg2的精确结果
  363. Div: function(arg1, arg2) {
  364. arg1 = parseFloat(arg1);
  365. arg2 = parseFloat(arg2);
  366. var t1 = 0,
  367. t2 = 0,
  368. r1, r2;
  369. try {
  370. t1 = arg1.toString().split(".")[1].length;
  371. } catch (e) {}
  372. try {
  373. t2 = arg2.toString().split(".")[1].length;
  374. } catch (e) {}
  375. r1 = Number(arg1.toString().replace(".", ""));
  376. r2 = Number(arg2.toString().replace(".", ""));
  377. return this.Mul(r1 / r2, Math.pow(10, t2 - t1));
  378. },
  379. //加法函数,用来得到精确的加法结果
  380. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
  381. //调用:$h.Add(arg1,arg2)
  382. //返回值:arg1加上arg2的精确结果
  383. Add: function(arg1, arg2) {
  384. arg2 = parseFloat(arg2);
  385. var r1, r2, m;
  386. try {
  387. r1 = arg1.toString().split(".")[1].length
  388. } catch (e) {
  389. r1 = 0
  390. }
  391. try {
  392. r2 = arg2.toString().split(".")[1].length
  393. } catch (e) {
  394. r2 = 0
  395. }
  396. m = Math.pow(100, Math.max(r1, r2));
  397. return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m;
  398. },
  399. //减法函数,用来得到精确的减法结果
  400. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
  401. //调用:$h.Sub(arg1,arg2)
  402. //返回值:arg1减去arg2的精确结果
  403. Sub: function(arg1, arg2) {
  404. arg1 = parseFloat(arg1);
  405. arg2 = parseFloat(arg2);
  406. var r1, r2, m, n;
  407. try {
  408. r1 = arg1.toString().split(".")[1].length
  409. } catch (e) {
  410. r1 = 0
  411. }
  412. try {
  413. r2 = arg2.toString().split(".")[1].length
  414. } catch (e) {
  415. r2 = 0
  416. }
  417. m = Math.pow(10, Math.max(r1, r2));
  418. //动态控制精度长度
  419. n = (r1 >= r2) ? r1 : r2;
  420. return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n);
  421. },
  422. //乘法函数,用来得到精确的乘法结果
  423. //说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
  424. //调用:$h.Mul(arg1,arg2)
  425. //返回值:arg1乘以arg2的精确结果
  426. Mul: function(arg1, arg2) {
  427. arg1 = parseFloat(arg1);
  428. arg2 = parseFloat(arg2);
  429. var m = 0,
  430. s1 = arg1.toString(),
  431. s2 = arg2.toString();
  432. try {
  433. m += s1.split(".")[1].length
  434. } catch (e) {}
  435. try {
  436. m += s2.split(".")[1].length
  437. } catch (e) {}
  438. return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
  439. },
  440. },
  441. // 获取地理位置;
  442. $L: {
  443. async getLocation() {
  444. // #ifdef APP-PLUS
  445. let status = await this.checkPermission();
  446. if (status !== 1) {
  447. return;
  448. }
  449. // #endif
  450. // #ifdef MP-WEIXIN || MP-TOUTIAO || MP-QQ
  451. let status = await this.getSetting();
  452. if (status === 2) {
  453. this.openSetting();
  454. return;
  455. }
  456. // #endif
  457. this.doGetLocation();
  458. },
  459. doGetLocation() {
  460. uni.getLocation({
  461. success: (res) => {
  462. uni.removeStorageSync('CACHE_LONGITUDE');
  463. uni.removeStorageSync('CACHE_LATITUDE');
  464. uni.setStorageSync('CACHE_LONGITUDE', res.longitude);
  465. uni.setStorageSync('CACHE_LATITUDE', res.latitude);
  466. },
  467. fail: (err) => {
  468. // #ifdef MP-BAIDU
  469. if (err.errCode === 202 || err.errCode === 10003) { // 202模拟器 10003真机 user deny
  470. this.openSetting();
  471. }
  472. // #endif
  473. // #ifndef MP-BAIDU
  474. if (err.errMsg.indexOf("auth deny") >= 0) {
  475. uni.showToast({
  476. title: "访问位置被拒绝"
  477. })
  478. } else {
  479. uni.showToast({
  480. title: err.errMsg
  481. })
  482. }
  483. // #endif
  484. }
  485. })
  486. },
  487. getSetting: function() {
  488. return new Promise((resolve, reject) => {
  489. uni.getSetting({
  490. success: (res) => {
  491. if (res.authSetting['scope.userLocation'] === undefined) {
  492. resolve(0);
  493. return;
  494. }
  495. if (res.authSetting['scope.userLocation']) {
  496. resolve(1);
  497. } else {
  498. resolve(2);
  499. }
  500. }
  501. });
  502. });
  503. },
  504. openSetting: function() {
  505. uni.openSetting({
  506. success: (res) => {
  507. if (res.authSetting && res.authSetting['scope.userLocation']) {
  508. this.doGetLocation();
  509. }
  510. },
  511. fail: (err) => {}
  512. })
  513. },
  514. async checkPermission() {
  515. let status = permision.isIOS ? await permision.requestIOS('location') :
  516. await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');
  517. if (status === null || status === 1) {
  518. status = 1;
  519. } else if (status === 2) {
  520. uni.showModal({
  521. content: "系统定位已关闭",
  522. confirmText: "确定",
  523. showCancel: false,
  524. success: function(res) {}
  525. })
  526. } else if (status.code) {
  527. uni.showModal({
  528. content: status.message
  529. })
  530. } else {
  531. uni.showModal({
  532. content: "需要定位权限",
  533. confirmText: "设置",
  534. success: function(res) {
  535. if (res.confirm) {
  536. permision.gotoAppSetting();
  537. }
  538. }
  539. })
  540. }
  541. return status;
  542. },
  543. }
  544. }