util.js 29 KB

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