util.js 20 KB

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