util.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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. customerType
  17. } from '@/api/api.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. */
  118. addressInfo: function(str) {
  119. let reg = /.+?(省|市|自治区|自治州|行政区|盟|旗|县|区)/g // 省市区的正则
  120. const area = str.match(reg) // 分割省市区
  121. let citys = ['北京市', '天津市', '上海市', '重庆市']
  122. let address_component = {
  123. city: "",
  124. district: "",
  125. province: area[0]
  126. }
  127. if (citys.indexOf(area[0]) == -1) {
  128. address_component.city = area[1]
  129. address_component.district = area[2]
  130. } else {
  131. address_component.city = area[0]
  132. address_component.district = area[1]
  133. }
  134. return address_component
  135. },
  136. /**
  137. * 跳转路径封装函数
  138. * @param url 跳转路径
  139. * 选择跳转到其他小程序时,在h5也可以跳转路径
  140. */
  141. JumpPath: function(url){
  142. let arr = url.split('@APPID=');
  143. if(arr.length>1){
  144. //#ifdef MP
  145. uni.navigateToMiniProgram({
  146. appId:arr[arr.length-1],// 此为生活缴费appid
  147. path:arr[0],// 此为生活缴费首页路径
  148. envVersion:"release",
  149. success: res => {
  150. console.log("打开成功", res);
  151. },
  152. fail: err => {
  153. console.log('sgdhgf',err);
  154. }
  155. })
  156. //#endif
  157. //#ifndef MP
  158. this.Tips({
  159. title: 'h5与app端不支持跳转外部小程序'
  160. });
  161. //#endif
  162. }else{
  163. if(url == '/pages/short_video/appSwiper/index' || url == '/pages/short_video/nvueSwiper/index'){
  164. //#ifdef APP
  165. url = '/pages/short_video/appSwiper/index'
  166. //#endif
  167. //#ifndef APP
  168. url = '/pages/short_video/nvueSwiper/index'
  169. //#endif
  170. }
  171. if (url.indexOf("http") != -1) {
  172. uni.navigateTo({
  173. url: `/pages/annex/web_view/index?url=${url}`
  174. });
  175. } else {
  176. if (['/pages/goods_cate/goods_cate', '/pages/order_addcart/order_addcart', '/pages/user/index', '/pages/index/index','/pages/store_cate/store_cate']
  177. .indexOf(url.split('?')[0]) == -1) {
  178. uni.navigateTo({
  179. url: url
  180. })
  181. } else {
  182. uni.reLaunch({
  183. url: url
  184. })
  185. }
  186. }
  187. }
  188. },
  189. /**
  190. * 移除数组中的某个数组并组成新的数组返回
  191. * @param array array 需要移除的数组
  192. * @param int index 需要移除的数组的键值
  193. * @param string | int 值
  194. * @return array
  195. *
  196. */
  197. ArrayRemove: function(array, index, value) {
  198. const valueArray = [];
  199. if (array instanceof Array) {
  200. for (let i = 0; i < array.length; i++) {
  201. if (typeof index == 'number' && array[index] != i) {
  202. valueArray.push(array[i]);
  203. } else if (typeof index == 'string' && array[i][index] != value) {
  204. valueArray.push(array[i]);
  205. }
  206. }
  207. }
  208. return valueArray;
  209. },
  210. /**
  211. * 生成海报获取文字
  212. * @param string text 为传入的文本
  213. * @param int num 为单行显示的字节长度
  214. * @return array
  215. */
  216. textByteLength: function(text, num) {
  217. let strLength = 0;
  218. let rows = 1;
  219. let str = 0;
  220. let arr = [];
  221. for (let j = 0; j < text.length; j++) {
  222. if (text.charCodeAt(j) > 255) {
  223. strLength += 2;
  224. if (strLength > rows * num) {
  225. strLength++;
  226. arr.push(text.slice(str, j));
  227. str = j;
  228. rows++;
  229. }
  230. } else {
  231. strLength++;
  232. if (strLength > rows * num) {
  233. arr.push(text.slice(str, j));
  234. str = j;
  235. rows++;
  236. }
  237. }
  238. }
  239. arr.push(text.slice(str, text.length));
  240. return [strLength, arr, rows] // [处理文字的总字节长度,每行显示内容的数组,行数]
  241. },
  242. /**
  243. * 获取分享海报
  244. * @param array arr2 海报素材
  245. * @param string store_name 素材文字
  246. * @param string price 价格
  247. * @param string ot_price 原始价格
  248. * @param function successFn 回调函数
  249. *
  250. *
  251. */
  252. PosterCanvas: function(fontColor, themeColor, siteName, arr2, store_name, price, ot_price, posterTitle, successFn) {
  253. let that = this;
  254. uni.showLoading({
  255. title: '海报生成中',
  256. mask: true
  257. });
  258. const ctx = uni.createCanvasContext('myCanvas');
  259. ctx.clearRect(0, 0, 0, 0);
  260. /**
  261. * 只能获取合法域名下的图片信息,本地调试无法获取
  262. *
  263. */
  264. ctx.fillStyle = '#fff';
  265. ctx.fillRect(0, 0, 750, 1306);
  266. uni.getImageInfo({
  267. src: arr2[0],
  268. success: function(res) {
  269. const WIDTH = res.width;
  270. // const HEIGHT = res.height;
  271. // ctx.drawImage(arr2[0], 0, 0, WIDTH, 1050);
  272. ctx.save();
  273. ctx.setFillStyle(themeColor);
  274. ctx.fillRect(0, 0, WIDTH, 108);
  275. ctx.setFontSize(33)
  276. ctx.setFillStyle('#fff');
  277. ctx.setTextAlign('center');
  278. ctx.fillText(posterTitle, WIDTH/2, 65);
  279. ctx.save();
  280. ctx.drawImage(arr2[1], 32, 141, 685, 685);
  281. ctx.save();
  282. // ctx.setFillStyle(themeColor);
  283. // ctx.fillRect(32, 847, 85, 40);
  284. // ctx.setFontSize(30)
  285. // ctx.setFillStyle('#fff');
  286. // ctx.setTextAlign('left');
  287. // ctx.fillText('商城', 43, 878);
  288. // ctx.save();
  289. // ctx.setFontSize(36)
  290. // ctx.setFillStyle('#000');
  291. // ctx.fillText(siteName, 140, 880);
  292. // ctx.save();
  293. const CONTENT_ROW_LENGTH = 35;
  294. let [contentLeng, contentArray, contentRows] = that.textByteLength(store_name,
  295. CONTENT_ROW_LENGTH);
  296. if (contentRows > 2) {
  297. contentRows = 2;
  298. let textArray = contentArray.slice(0, 2);
  299. textArray[textArray.length - 1] += '...';
  300. contentArray = textArray;
  301. }
  302. ctx.setTextAlign('left');
  303. ctx.setFontSize(38);
  304. ctx.setFillStyle('#000');
  305. let contentHh = 38;
  306. for (let m = 0; m < contentArray.length; m++) {
  307. if (m) {
  308. ctx.fillText(contentArray[m], 30, 900 + contentHh * m + 18);
  309. } else {
  310. ctx.fillText(contentArray[m], 30, 900 + contentHh * m);
  311. }
  312. }
  313. ctx.save();
  314. ctx.setTextAlign('left')
  315. ctx.setFontSize(32);
  316. ctx.setFillStyle('#999');
  317. ctx.fillText('¥' + ot_price, 30, 1152 + contentHh);
  318. var underline = function(ctx, text, x, y, size, color, thickness, offset) {
  319. var width = ctx.measureText(text).width;
  320. switch (ctx.textAlign) {
  321. case "center":
  322. x -= (width / 2);
  323. break;
  324. case "right":
  325. x -= width;
  326. break;
  327. }
  328. y += size + offset;
  329. ctx.beginPath();
  330. ctx.strokeStyle = color;
  331. ctx.lineWidth = thickness;
  332. ctx.moveTo(x, y);
  333. ctx.lineTo(x + width, y);
  334. ctx.stroke();
  335. }
  336. underline(ctx, '¥' + ot_price, 30, 1146, 32, '#999', 2, 0);
  337. ctx.save();
  338. ctx.setTextAlign('left')
  339. ctx.setFontSize(54);
  340. ctx.setFillStyle(fontColor);
  341. ctx.fillText('¥' + price, 20, 1070 + contentHh);
  342. ctx.save();
  343. ctx.setFillStyle('#F5F5F5');
  344. ctx.fillRect(0, 1222, WIDTH, 84);
  345. ctx.setFontSize(28);
  346. ctx.setFillStyle('#999');
  347. // ctx.fillText('长按识别图中的二维码查看商品详情', 26, 1263);
  348. ctx.setTextAlign('center');
  349. ctx.fillText('长按识别图中的二维码查看商品详情', WIDTH/2, 1272);
  350. ctx.save();
  351. let r = 93;
  352. let d = r * 2;
  353. let cx = WIDTH - d - 30;
  354. // let cy = 1112;
  355. let cy = 1000;
  356. ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
  357. ctx.drawImage(arr2[2], cx, cy, d, d);
  358. ctx.restore();
  359. // ctx.setTextAlign('left')
  360. // ctx.setFontSize(28);
  361. // ctx.setFillStyle('#999');
  362. // ctx.fillText('长按或扫描查看', 490, 1030 + contentHh);
  363. ctx.draw(true, function() {
  364. uni.canvasToTempFilePath({
  365. canvasId: 'myCanvas',
  366. fileType: 'png',
  367. // destWidth: WIDTH,
  368. // destHeight: HEIGHT,
  369. success: function(res) {
  370. uni.hideLoading();
  371. successFn && successFn(res.tempFilePath);
  372. }
  373. })
  374. });
  375. },
  376. fail: function(err) {
  377. uni.hideLoading();
  378. that.Tips({
  379. title: '无法获取图片信息'
  380. });
  381. }
  382. })
  383. },
  384. /**
  385. * 获取砍价/拼团海报
  386. * @param array arr2 海报素材 背景图
  387. * @param string store_name 素材文字
  388. * @param string price 价格
  389. * @param string ot_price 原始价格
  390. * @param function successFn 回调函数
  391. *
  392. *
  393. */
  394. bargainPosterCanvas: function(arr2, title, label, msg, price, wd, hg, successFn) {
  395. let that = this;
  396. const ctx = uni.createCanvasContext('myCanvas');
  397. ctx.clearRect(0, 0, 0, 0);
  398. /**
  399. * 只能获取合法域名下的图片信息,本地调试无法获取
  400. *
  401. */
  402. ctx.fillStyle = '#fff';
  403. ctx.fillRect(0, 0, wd * 2, hg * 2);
  404. uni.getImageInfo({
  405. src: arr2[0],
  406. success: function(res) {
  407. const WIDTH = res.width;
  408. const HEIGHT = res.height;
  409. ctx.drawImage(arr2[0], 0, 0, wd, hg);
  410. // 保证在不同机型对应坐标准确
  411. let labelx = 0.6500 //标签x
  412. let labely = 0.166 //标签y
  413. let pricex = 0.1857 //价格x
  414. let pricey = 0.180 //价格x
  415. let codex = 0.385 //二维码
  416. let codey = 0.77
  417. let picturex = 0.1571 //商品图左上点
  418. let picturey = 0.2916
  419. let picturebx = 0.6857 //商品图右下点
  420. let pictureby = 0.3916
  421. let msgx = 0.1036 //msg
  422. let msgy = 0.2306
  423. let codew = 0.25
  424. ctx.drawImage(arr2[1], wd * picturex, hg * picturey, wd * picturebx, hg * pictureby);
  425. ctx.drawImage(arr2[2], wd * codex, hg * codey, wd * codew, wd * codew);
  426. ctx.save();
  427. //标题
  428. const CONTENT_ROW_LENGTH = 28;
  429. let [contentLeng, contentArray, contentRows] = that.textByteLength(title,
  430. CONTENT_ROW_LENGTH);
  431. if (contentRows > 2) {
  432. contentRows = 2;
  433. let textArray = contentArray.slice(0, 2);
  434. textArray[textArray.length - 1] += '…';
  435. contentArray = textArray;
  436. }
  437. ctx.setTextAlign('left');
  438. ctx.setFillStyle('#000');
  439. if (contentArray.length < 2) {
  440. ctx.setFontSize(20);
  441. } else {
  442. ctx.setFontSize(20);
  443. }
  444. let contentHh = 8;
  445. for (let m = 0; m < contentArray.length; m++) {
  446. if (m) {
  447. ctx.fillText(contentArray[m], wd * msgx, 35 + contentHh * m + 18, 1100);
  448. } else {
  449. ctx.fillText(contentArray[m], wd * msgx, 35, 1100);
  450. }
  451. }
  452. // 标签内容
  453. ctx.setTextAlign('left')
  454. ctx.setFontSize(16);
  455. ctx.setFillStyle('#FFF');
  456. ctx.fillText(label, wd * labelx, hg * labely);
  457. ctx.save();
  458. // 价格
  459. ctx.setFillStyle('red');
  460. ctx.setFontSize(26);
  461. ctx.fillText(price, wd * pricex, hg * pricey);
  462. ctx.save();
  463. // msg
  464. ctx.setFillStyle('#333');
  465. ctx.setFontSize(16);
  466. ctx.fillText(msg, wd * msgx, hg * msgy);
  467. ctx.save();
  468. ctx.draw(true, () => {
  469. uni.canvasToTempFilePath({
  470. canvasId: 'myCanvas',
  471. fileType: 'png',
  472. quality: 1,
  473. success: (res) => {
  474. successFn && successFn(res.tempFilePath);
  475. uni.hideLoading();
  476. }
  477. })
  478. });
  479. },
  480. fail: function(err) {
  481. uni.hideLoading();
  482. that.Tips({
  483. title: '无法获取图片信息'
  484. });
  485. }
  486. })
  487. },
  488. /**
  489. * 用户信息分享海报
  490. * @param array arr2 海报素材 1背景 0二维码
  491. * @param string nickname 昵称
  492. * @param string sitename 价格
  493. * @param function successFn 回调函数
  494. *
  495. *
  496. */
  497. userPosterCanvas: function(arr2, nickname, sitename, index, w, h, successFn) {
  498. let that = this;
  499. // uni.showLoading({
  500. // title: '海报生成中',
  501. // mask: true
  502. // });
  503. const ctx = uni.createCanvasContext('myCanvas' + index);
  504. ctx.clearRect(0, 0, 0, 0);
  505. /**
  506. * 只能获取合法域名下的图片信息,本地调试无法获取
  507. *
  508. */
  509. uni.getImageInfo({
  510. src: arr2[1],
  511. success: function(res) {
  512. const WIDTH = res.width;
  513. const HEIGHT = res.height;
  514. ctx.fillStyle = '#fff';
  515. ctx.fillRect(0, 0, w, h);
  516. ctx.drawImage(arr2[1], 0, 0, w, h);
  517. ctx.setTextAlign('left')
  518. ctx.setFontSize(12);
  519. ctx.setFillStyle('#333');
  520. // x:240 y:426
  521. let codex = 0.1906
  522. let codey = 0.7746
  523. let codeSize = 0.21666
  524. let namex = 0.4283
  525. let namey = 0.8215
  526. let markx = 0.4283
  527. let marky = 0.8685
  528. ctx.drawImage(arr2[0], w * codex, h * codey, w * codeSize, w * codeSize);
  529. if (w < 270) {
  530. ctx.setFontSize(8);
  531. } else {
  532. ctx.setFontSize(10);
  533. }
  534. ctx.fillText(nickname, w * namex, h * namey);
  535. if (w < 270) {
  536. ctx.setFontSize(8);
  537. } else {
  538. ctx.setFontSize(10);
  539. }
  540. const CONTENT_ROW_LENGTH = 30;
  541. const store_name = '邀请您加入'+sitename;
  542. let [contentLeng, contentArray, contentRows] = that.textByteLength(store_name,
  543. CONTENT_ROW_LENGTH);
  544. if (contentRows > 2) {
  545. contentRows = 2;
  546. let textArray = contentArray.slice(0, 2);
  547. textArray[textArray.length - 1] += '...';
  548. contentArray = textArray;
  549. }
  550. ctx.setTextAlign('left');
  551. // ctx.setFontSize(38);
  552. ctx.setFillStyle('#000');
  553. let contentHh = 38;
  554. for (let m = 0; m < contentArray.length; m++) {
  555. if (m) {
  556. ctx.fillText(contentArray[m], w * markx, h * marky+14);
  557. } else {
  558. ctx.fillText(contentArray[m], w * markx, h * marky);
  559. }
  560. }
  561. // ctx.fillText('邀请您加入' + sitename, w * markx, h * marky);
  562. ctx.save();
  563. ctx.draw(true, function() {
  564. uni.canvasToTempFilePath({
  565. canvasId: 'myCanvas' + index,
  566. fileType: 'png',
  567. quality: 1,
  568. success: function(res) {
  569. uni.hideLoading();
  570. successFn && successFn(res.tempFilePath);
  571. }
  572. })
  573. });
  574. },
  575. fail: function(err) {
  576. uni.hideLoading();
  577. that.Tips({
  578. title: ''
  579. });
  580. }
  581. })
  582. },
  583. // uniapp 判断 IOS和Android的GPS是否开启
  584. checkOpenGPSServiceByAndroidIOS() {
  585. let system = uni.getSystemInfoSync(); // 获取系统信息
  586. console.log('yyy', system);
  587. if (system.platform === 'android') { // 判断平台
  588. var context = plus.android.importClass("android.content.Context");
  589. var locationManager = plus.android.importClass("android.location.LocationManager");
  590. var main = plus.android.runtimeMainActivity();
  591. var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
  592. if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
  593. return false
  594. } else {
  595. return true
  596. }
  597. } else if (system.platform === 'ios' || 'devtools') {
  598. var cllocationManger = plus.ios.import("CLLocationManager");
  599. var enable = cllocationManger.locationServicesEnabled();
  600. var status = cllocationManger.authorizationStatus();
  601. plus.ios.deleteObject(cllocationManger);
  602. if (enable && status != 2) {
  603. return true
  604. console.log("手机系统的定位已经打开");
  605. } else {
  606. return false
  607. console.log("手机系统的定位没有打开");
  608. }
  609. }
  610. },
  611. /*
  612. * 单图上传
  613. * @param object opt
  614. * @param callable successCallback 成功执行方法 data
  615. * @param callable errorCallback 失败执行方法
  616. */
  617. uploadImageOne: function(opt, successCallback, errorCallback) {
  618. let that = this;
  619. if (typeof opt === 'string') {
  620. let url = opt;
  621. opt = {};
  622. opt.url = url;
  623. }
  624. let count = opt.count || 1,
  625. sizeType = opt.sizeType || ['compressed'],
  626. sourceType = opt.sourceType || ['album', 'camera'],
  627. is_load = opt.is_load || true,
  628. uploadUrl = opt.url || '',
  629. inputName = opt.name || 'pics',
  630. fileType = opt.fileType || 'image';
  631. uni.chooseImage({
  632. count: count, //最多可以选择的图片总数
  633. sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有
  634. sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有
  635. success: function(res) {
  636. //启动上传等待中...
  637. uni.showLoading({
  638. title: '图片上传中',
  639. });
  640. uni.uploadFile({
  641. url: HTTP_REQUEST_URL + '/api/' + uploadUrl,
  642. filePath: res.tempFilePaths[0],
  643. fileType: fileType,
  644. name: inputName,
  645. formData: {
  646. 'filename': inputName
  647. },
  648. header: {
  649. // #ifdef MP
  650. "Content-Type": "multipart/form-data",
  651. // #endif
  652. [TOKENNAME]: 'Bearer ' + store.state.app.token
  653. },
  654. success: function(res) {
  655. uni.hideLoading();
  656. if (res.statusCode == 403) {
  657. that.Tips({
  658. title: res.data
  659. });
  660. } else if (res.statusCode == 413) {
  661. that.Tips({
  662. title: '上传图片失败,请重新上传小尺寸图片'
  663. });
  664. } else {
  665. let data = res.data ? JSON.parse(res.data) : {};
  666. if (data.status == 200) {
  667. successCallback && successCallback(data)
  668. } else {
  669. errorCallback && errorCallback(data);
  670. that.Tips({
  671. title: data.msg
  672. });
  673. }
  674. }
  675. },
  676. fail: function(res) {
  677. uni.hideLoading();
  678. that.Tips({
  679. title: '上传图片失败'
  680. });
  681. }
  682. })
  683. }
  684. })
  685. },
  686. /*
  687. * 单图上传压缩版
  688. * @param object opt
  689. * @param callable successCallback 成功执行方法 data
  690. * @param callable errorCallback 失败执行方法
  691. */
  692. uploadImageChange: function(opt, successCallback, errorCallback, sizeCallback) {
  693. let that = this;
  694. if (typeof opt === 'string') {
  695. let url = opt;
  696. opt = {};
  697. opt.url = url;
  698. }
  699. let count = opt.count || 1,
  700. sizeType = opt.sizeType || ['compressed'],
  701. sourceType = opt.sourceType || ['album', 'camera'],
  702. is_load = opt.is_load || true,
  703. uploadUrl = opt.url || '',
  704. inputName = opt.name || 'pics',
  705. fileType = opt.fileType || 'image';
  706. uni.chooseImage({
  707. count: count, //最多可以选择的图片总数
  708. sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有
  709. sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有
  710. success: function(res) {
  711. //启动上传等待中...
  712. let imgSrc
  713. let objImg = res.tempFilePaths;
  714. objImg.forEach(item => {
  715. uni.getImageInfo({
  716. src: item,
  717. success(ress) {
  718. uni.showLoading({
  719. title: '图片上传中',
  720. });
  721. if (res.tempFiles[0].size <= 2097152) {
  722. uploadImg(ress.path)
  723. return
  724. }
  725. // uploadImg(canvasPath.tempFilePath)
  726. let canvasWidth, canvasHeight, xs, maxWidth = 750
  727. xs = ress.width / ress.height // 宽高比例
  728. if (ress.width > maxWidth) {
  729. canvasWidth = maxWidth // 这里是最大限制宽度
  730. canvasHeight = maxWidth / xs
  731. } else {
  732. canvasWidth = ress.width
  733. canvasHeight = ress.height
  734. }
  735. sizeCallback && sizeCallback({
  736. w: canvasWidth,
  737. h: canvasHeight
  738. })
  739. let canvas = uni.createCanvasContext('canvas');
  740. canvas.width = canvasWidth
  741. canvas.height = canvasHeight
  742. canvas.clearRect(0, 0, canvasWidth, canvasHeight);
  743. canvas.drawImage(ress.path, 0, 0, canvasWidth, canvasHeight)
  744. canvas.save();
  745. // 这里的画布drawImage是一种异步属性 可能存在未绘制全就执行了draw的问题 so添加延迟
  746. setTimeout(e => {
  747. canvas.draw(true, () => {
  748. uni.canvasToTempFilePath({
  749. canvasId: 'canvas',
  750. fileType: 'JPEG',
  751. destWidth: canvasWidth,
  752. destHeight: canvasHeight,
  753. quality: 0.7,
  754. success: function(
  755. canvasPath) {
  756. uploadImg(
  757. canvasPath
  758. .tempFilePath
  759. )
  760. }
  761. })
  762. });
  763. }, 200)
  764. }
  765. })
  766. })
  767. }
  768. })
  769. function uploadImg(filePath) {
  770. uni.uploadFile({
  771. url: HTTP_REQUEST_URL + '/api/' + uploadUrl,
  772. filePath,
  773. fileType: fileType,
  774. name: inputName,
  775. formData: {
  776. 'filename': inputName
  777. },
  778. header: {
  779. // #ifdef MP
  780. "Content-Type": "multipart/form-data",
  781. // #endif
  782. [TOKENNAME]: 'Bearer ' + store.state.app.token
  783. },
  784. success: function(res) {
  785. uni.hideLoading();
  786. if (res.statusCode == 403) {
  787. that.Tips({
  788. title: res.data
  789. });
  790. } else {
  791. let data = res.data ? JSON.parse(res.data) : {};
  792. if (data.status == 200) {
  793. successCallback && successCallback(data)
  794. } else {
  795. errorCallback && errorCallback(data);
  796. that.Tips({
  797. title: data.msg
  798. });
  799. }
  800. }
  801. },
  802. fail: function(res) {
  803. uni.hideLoading();
  804. that.Tips({
  805. title: '上传图片失败'
  806. });
  807. }
  808. })
  809. }
  810. },
  811. /**
  812. * 处理客服不同的跳转;
  813. *
  814. */
  815. getCustomer(userInfo, url, storeInfo, show) {
  816. let self = this;
  817. customerType().then(res => {
  818. let data = res.data;
  819. if (data.customer_type == 1) {
  820. uni.makePhoneCall({
  821. phoneNumber: data.customer_phone
  822. });
  823. } else if (data.customer_type == 2) {
  824. let href = data.customer_url;
  825. let hrefO = href + '?uid=' + userInfo.uid + '&nickName=' + userInfo.nickname + '&phone=' +
  826. userInfo.phone + '&sex=' + userInfo.sex + '&avatar=' + userInfo.avatar +
  827. '&openid=' + userInfo.openid;
  828. let hrefT = href + '&uid=' + userInfo.uid + '&nickName=' + userInfo.nickname + '&phone=' +
  829. userInfo.phone + '&sex=' + userInfo.sex + '&avatar=' + userInfo.avatar +
  830. '&openid=' + userInfo.openid;
  831. let urls = encodeURIComponent(href.indexOf('?') === -1 ? hrefO : hrefT);
  832. if (data.customer_url.indexOf('work.weixin.qq.com') > 0) {
  833. // #ifdef MP
  834. wx.openCustomerServiceChat({
  835. extInfo: {
  836. url: data.customer_url
  837. },
  838. corpId: data.wechat_work_corpid,
  839. showMessageCard: show?true:false,
  840. sendMessageTitle: show?storeInfo.store_name:'',
  841. sendMessagePath: show?storeInfo.path:'',
  842. sendMessageImg: show?storeInfo.image:'',
  843. success(res) {},
  844. fail(err) {
  845. self.Tips({
  846. title: err.errMsg
  847. });
  848. }
  849. })
  850. // #endif
  851. // #ifdef H5
  852. return window.location.href = data.customer_url
  853. // #endif
  854. // #ifdef APP-PLUS
  855. plus.runtime.openURL(data.customer_url)
  856. // #endif
  857. } else {
  858. uni.navigateTo({
  859. url: `/pages/annex/web_view/index?url=${urls}`
  860. });
  861. }
  862. } else {
  863. uni.navigateTo({
  864. url: url || '/pages/extension/customer_list/chat'
  865. })
  866. }
  867. }).catch(err => {
  868. self.Tips({
  869. title: err
  870. });
  871. })
  872. },
  873. /**
  874. * 小程序头像获取上传
  875. * @param uploadUrl 上传接口地址
  876. * @param filePath 上传文件路径
  877. * @param successCallback success回调
  878. * @param errorCallback err回调
  879. */
  880. uploadImgs(uploadUrl, filePath, successCallback, errorCallback) {
  881. let that = this;
  882. uni.uploadFile({
  883. url: HTTP_REQUEST_URL + '/api/' + uploadUrl,
  884. filePath: filePath,
  885. fileType: 'image',
  886. name: 'pics',
  887. formData: {
  888. 'filename': 'pics'
  889. },
  890. header: {
  891. // #ifdef MP
  892. "Content-Type": "multipart/form-data",
  893. // #endif
  894. [TOKENNAME]: 'Bearer ' + store.state.app.token
  895. },
  896. success: (res) => {
  897. uni.hideLoading();
  898. if (res.statusCode == 403) {
  899. that.Tips({
  900. title: res.data
  901. });
  902. } else if (res.statusCode == 413) {
  903. that.Tips({
  904. title: '上传图片失败,请重新上传小尺寸图片'
  905. });
  906. } else {
  907. let data = res.data ? JSON.parse(res.data) : {};
  908. if (data.status == 200) {
  909. successCallback && successCallback(data)
  910. } else {
  911. errorCallback && errorCallback(data);
  912. that.Tips({
  913. title: data.msg
  914. });
  915. }
  916. }
  917. },
  918. fail: (err) => {
  919. uni.hideLoading();
  920. that.Tips({
  921. title: '上传图片失败'
  922. });
  923. }
  924. })
  925. },
  926. /**
  927. * 小程序比较版本信息
  928. * @param v1 当前版本
  929. * @param v2 进行比较的版本
  930. * @return boolen
  931. *
  932. */
  933. compareVersion(v1, v2) {
  934. v1 = v1.split('.')
  935. v2 = v2.split('.')
  936. const len = Math.max(v1.length, v2.length)
  937. while (v1.length < len) {
  938. v1.push('0')
  939. }
  940. while (v2.length < len) {
  941. v2.push('0')
  942. }
  943. for (let i = 0; i < len; i++) {
  944. const num1 = parseInt(v1[i])
  945. const num2 = parseInt(v2[i])
  946. if (num1 > num2) {
  947. return 1
  948. } else if (num1 < num2) {
  949. return -1
  950. }
  951. }
  952. return 0
  953. },
  954. /**
  955. * 处理服务器扫码带进来的参数
  956. * @param string param 扫码携带参数
  957. * @param string k 整体分割符 默认为:&
  958. * @param string p 单个分隔符 默认为:=
  959. * @return object
  960. *
  961. */
  962. // #ifdef MP
  963. getUrlParams: function(param, k, p) {
  964. if (typeof param != 'string') return {};
  965. k = k ? k : '&'; //整体参数分隔符
  966. p = p ? p : '='; //单个参数分隔符
  967. var value = {};
  968. if (param.indexOf(k) !== -1) {
  969. param = param.split(k);
  970. for (var val in param) {
  971. if (param[val].indexOf(p) !== -1) {
  972. var item = param[val].split(p);
  973. value[item[0]] = item[1];
  974. }
  975. }
  976. } else if (param.indexOf(p) !== -1) {
  977. var item = param.split(p);
  978. value[item[0]] = item[1];
  979. } else {
  980. return param;
  981. }
  982. return value;
  983. },
  984. // #endif
  985. /*
  986. * 合并数组
  987. */
  988. SplitArray(list, sp) {
  989. if (typeof list != 'object') return [];
  990. if (sp === undefined) sp = [];
  991. for (var i = 0; i < list.length; i++) {
  992. sp.push(list[i]);
  993. }
  994. return sp;
  995. },
  996. trim(backUrlCRshlcICwGdGY) {
  997. return String.prototype.trim.call(backUrlCRshlcICwGdGY);
  998. },
  999. $h: {
  1000. //除法函数,用来得到精确的除法结果
  1001. //说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
  1002. //调用:$h.Div(arg1,arg2)
  1003. //返回值:arg1除以arg2的精确结果
  1004. Div: function(arg1, arg2) {
  1005. arg1 = parseFloat(arg1);
  1006. arg2 = parseFloat(arg2);
  1007. var t1 = 0,
  1008. t2 = 0,
  1009. r1, r2;
  1010. try {
  1011. t1 = arg1.toString().split(".")[1].length;
  1012. } catch (e) {}
  1013. try {
  1014. t2 = arg2.toString().split(".")[1].length;
  1015. } catch (e) {}
  1016. r1 = Number(arg1.toString().replace(".", ""));
  1017. r2 = Number(arg2.toString().replace(".", ""));
  1018. return this.Mul(r1 / r2, Math.pow(10, t2 - t1));
  1019. },
  1020. //加法函数,用来得到精确的加法结果
  1021. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
  1022. //调用:$h.Add(arg1,arg2)
  1023. //返回值:arg1加上arg2的精确结果
  1024. Add: function(arg1, arg2) {
  1025. arg2 = parseFloat(arg2);
  1026. var r1, r2, m;
  1027. try {
  1028. r1 = arg1.toString().split(".")[1].length
  1029. } catch (e) {
  1030. r1 = 0
  1031. }
  1032. try {
  1033. r2 = arg2.toString().split(".")[1].length
  1034. } catch (e) {
  1035. r2 = 0
  1036. }
  1037. m = Math.pow(100, Math.max(r1, r2));
  1038. return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m;
  1039. },
  1040. //减法函数,用来得到精确的减法结果
  1041. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
  1042. //调用:$h.Sub(arg1,arg2)
  1043. //返回值:arg1减去arg2的精确结果
  1044. Sub: function(arg1, arg2) {
  1045. arg1 = parseFloat(arg1);
  1046. arg2 = parseFloat(arg2);
  1047. var r1, r2, m, n;
  1048. try {
  1049. r1 = arg1.toString().split(".")[1].length
  1050. } catch (e) {
  1051. r1 = 0
  1052. }
  1053. try {
  1054. r2 = arg2.toString().split(".")[1].length
  1055. } catch (e) {
  1056. r2 = 0
  1057. }
  1058. m = Math.pow(10, Math.max(r1, r2));
  1059. //动态控制精度长度
  1060. n = (r1 >= r2) ? r1 : r2;
  1061. return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n);
  1062. },
  1063. //乘法函数,用来得到精确的乘法结果
  1064. //说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
  1065. //调用:$h.Mul(arg1,arg2)
  1066. //返回值:arg1乘以arg2的精确结果
  1067. Mul: function(arg1, arg2) {
  1068. arg1 = parseFloat(arg1);
  1069. arg2 = parseFloat(arg2);
  1070. var m = 0,
  1071. s1 = arg1.toString(),
  1072. s2 = arg2.toString();
  1073. try {
  1074. m += s1.split(".")[1].length
  1075. } catch (e) {}
  1076. try {
  1077. m += s2.split(".")[1].length
  1078. } catch (e) {}
  1079. return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
  1080. },
  1081. },
  1082. // 获取地理位置;
  1083. $L: {
  1084. async getLocation() {
  1085. // #ifdef APP-PLUS
  1086. let status = await this.checkPermission();
  1087. if (status !== 1) {
  1088. return;
  1089. }
  1090. // #endif
  1091. // #ifdef MP-WEIXIN || MP-TOUTIAO || MP-QQ
  1092. let status = await this.getSetting();
  1093. if (status === 2) {
  1094. this.openSetting();
  1095. return;
  1096. }
  1097. // #endif
  1098. this.doGetLocation();
  1099. },
  1100. doGetLocation() {
  1101. uni.getLocation({
  1102. success: (res) => {
  1103. uni.removeStorageSync('CACHE_LONGITUDE');
  1104. uni.removeStorageSync('CACHE_LATITUDE');
  1105. uni.setStorageSync('CACHE_LONGITUDE', res.longitude);
  1106. uni.setStorageSync('CACHE_LATITUDE', res.latitude);
  1107. },
  1108. fail: (err) => {
  1109. // #ifdef MP-BAIDU
  1110. if (err.errCode === 202 || err.errCode === 10003) { // 202模拟器 10003真机 user deny
  1111. this.openSetting();
  1112. }
  1113. // #endif
  1114. // #ifndef MP-BAIDU
  1115. if (err.errMsg.indexOf("auth deny") >= 0) {
  1116. uni.showToast({
  1117. title: "访问位置被拒绝"
  1118. })
  1119. } else {
  1120. uni.showToast({
  1121. title: err.errMsg
  1122. })
  1123. }
  1124. // #endif
  1125. }
  1126. })
  1127. },
  1128. getSetting: function() {
  1129. return new Promise((resolve, reject) => {
  1130. uni.getSetting({
  1131. success: (res) => {
  1132. if (res.authSetting['scope.userLocation'] === undefined) {
  1133. resolve(0);
  1134. return;
  1135. }
  1136. if (res.authSetting['scope.userLocation']) {
  1137. resolve(1);
  1138. } else {
  1139. resolve(2);
  1140. }
  1141. }
  1142. });
  1143. });
  1144. },
  1145. openSetting: function() {
  1146. uni.openSetting({
  1147. success: (res) => {
  1148. if (res.authSetting && res.authSetting['scope.userLocation']) {
  1149. this.doGetLocation();
  1150. }
  1151. },
  1152. fail: (err) => {}
  1153. })
  1154. },
  1155. async checkPermission() {
  1156. let status = permision.isIOS ? await permision.requestIOS('location') :
  1157. await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');
  1158. if (status === null || status === 1) {
  1159. status = 1;
  1160. } else if (status === 2) {
  1161. uni.showModal({
  1162. content: "系统定位已关闭",
  1163. confirmText: "确定",
  1164. showCancel: false,
  1165. success: function(res) {}
  1166. })
  1167. } else if (status.code) {
  1168. uni.showModal({
  1169. content: status.message
  1170. })
  1171. } else {
  1172. uni.showModal({
  1173. content: "需要定位权限",
  1174. confirmText: "设置",
  1175. success: function(res) {
  1176. if (res.confirm) {
  1177. permision.gotoAppSetting();
  1178. }
  1179. }
  1180. })
  1181. }
  1182. return status;
  1183. },
  1184. }
  1185. }