util.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. import {
  2. TOKENNAME
  3. } from './../config.js';
  4. const formatTime = date => {
  5. const year = date.getFullYear()
  6. const month = date.getMonth() + 1
  7. const day = date.getDate()
  8. const hour = date.getHours()
  9. const minute = date.getMinutes()
  10. const second = date.getSeconds()
  11. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  12. }
  13. const $h = {
  14. //除法函数,用来得到精确的除法结果
  15. //说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
  16. //调用:$h.Div(arg1,arg2)
  17. //返回值:arg1除以arg2的精确结果
  18. Div: function(arg1, arg2) {
  19. arg1 = parseFloat(arg1);
  20. arg2 = parseFloat(arg2);
  21. var t1 = 0,
  22. t2 = 0,
  23. r1, r2;
  24. try {
  25. t1 = arg1.toString().split(".")[1].length;
  26. } catch (e) {}
  27. try {
  28. t2 = arg2.toString().split(".")[1].length;
  29. } catch (e) {}
  30. r1 = Number(arg1.toString().replace(".", ""));
  31. r2 = Number(arg2.toString().replace(".", ""));
  32. return this.Mul(r1 / r2, Math.pow(10, t2 - t1));
  33. },
  34. //加法函数,用来得到精确的加法结果
  35. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
  36. //调用:$h.Add(arg1,arg2)
  37. //返回值:arg1加上arg2的精确结果
  38. Add: function(arg1, arg2) {
  39. arg2 = parseFloat(arg2);
  40. var r1, r2, m;
  41. try {
  42. r1 = arg1.toString().split(".")[1].length
  43. } catch (e) {
  44. r1 = 0
  45. }
  46. try {
  47. r2 = arg2.toString().split(".")[1].length
  48. } catch (e) {
  49. r2 = 0
  50. }
  51. m = Math.pow(100, Math.max(r1, r2));
  52. return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m;
  53. },
  54. //减法函数,用来得到精确的减法结果
  55. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
  56. //调用:$h.Sub(arg1,arg2)
  57. //返回值:arg1减去arg2的精确结果
  58. Sub: function(arg1, arg2) {
  59. arg1 = parseFloat(arg1);
  60. arg2 = parseFloat(arg2);
  61. var r1, r2, m, n;
  62. try {
  63. r1 = arg1.toString().split(".")[1].length
  64. } catch (e) {
  65. r1 = 0
  66. }
  67. try {
  68. r2 = arg2.toString().split(".")[1].length
  69. } catch (e) {
  70. r2 = 0
  71. }
  72. m = Math.pow(10, Math.max(r1, r2));
  73. //动态控制精度长度
  74. n = (r1 >= r2) ? r1 : r2;
  75. return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n);
  76. },
  77. //乘法函数,用来得到精确的乘法结果
  78. //说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
  79. //调用:$h.Mul(arg1,arg2)
  80. //返回值:arg1乘以arg2的精确结果
  81. Mul: function(arg1, arg2) {
  82. arg1 = parseFloat(arg1);
  83. arg2 = parseFloat(arg2);
  84. var m = 0,
  85. s1 = arg1.toString(),
  86. s2 = arg2.toString();
  87. try {
  88. m += s1.split(".")[1].length
  89. } catch (e) {}
  90. try {
  91. m += s2.split(".")[1].length
  92. } catch (e) {}
  93. return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
  94. },
  95. }
  96. const formatNumber = n => {
  97. n = n.toString()
  98. return n[1] ? n : '0' + n
  99. }
  100. /**
  101. * 处理服务器扫码带进来的参数
  102. * @param string param 扫码携带参数
  103. * @param string k 整体分割符 默认为:&
  104. * @param string p 单个分隔符 默认为:=
  105. * @return object
  106. *
  107. */
  108. const getUrlParams = (param, k, p) => {
  109. if (typeof param != 'string') return {};
  110. k = k ? k : '&'; //整体参数分隔符
  111. p = p ? p : '='; //单个参数分隔符
  112. var value = {};
  113. if (param.indexOf(k) !== -1) {
  114. param = param.split(k);
  115. for (var val in param) {
  116. if (param[val].indexOf(p) !== -1) {
  117. var item = param[val].split(p);
  118. value[item[0]] = item[1];
  119. }
  120. }
  121. } else if (param.indexOf(p) !== -1) {
  122. var item = param.split(p);
  123. value[item[0]] = item[1];
  124. } else {
  125. return param;
  126. }
  127. return value;
  128. }
  129. const wxgetUserInfo = function() {
  130. return new Promise((resolve, reject) => {
  131. wx.getUserInfo({
  132. lang: 'zh_CN',
  133. success(res) {
  134. resolve(res);
  135. },
  136. fail(res) {
  137. reject(res);
  138. }
  139. })
  140. });
  141. }
  142. /**
  143. * 新版小程序获取用户信息 2021 4.13微信小程序开始正式启用
  144. */
  145. const getUserProfile = function(code) {
  146. return new Promise((resolve, reject) => {
  147. wx.getUserProfile({
  148. lang: 'zh_CN',
  149. desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
  150. success(user) {
  151. resolve(res);
  152. },
  153. fail(res) {
  154. reject(res);
  155. }
  156. })
  157. })
  158. }
  159. const checkLogin = function(token, expiresTime, isLog) {
  160. if (getApp()) {
  161. token = getApp().globalData.token;
  162. expiresTime = getApp().globalData.expiresTime;
  163. isLog = getApp().globalData.isLog;
  164. }
  165. let res = token ? true : false;
  166. let res1 = isLog;
  167. let res2 = res && res1;
  168. if (res2) {
  169. let newTime = Math.round(new Date() / 1000);
  170. if (expiresTime < newTime) return false;
  171. }
  172. return res2;
  173. }
  174. const logout = function() {
  175. getApp().globalData.token = '';
  176. getApp().globalData.isLog = false;
  177. }
  178. const chekWxLogin = function() {
  179. return new Promise((resolve, reject) => {
  180. if (checkLogin())
  181. return resolve({
  182. userinfo: getApp().globalData.userInfo,
  183. isLogin: true
  184. });
  185. wx.getSetting({
  186. success(res) {
  187. if (!res.authSetting['scope.userInfo']) {
  188. return reject({
  189. authSetting: false
  190. });
  191. } else {
  192. wx.getStorage({
  193. key: 'cache_key',
  194. success(res) {
  195. wxgetUserInfo().then(userInfo => {
  196. userInfo.cache_key = res.data;
  197. return resolve({
  198. userInfo: userInfo,
  199. isLogin: false
  200. });
  201. }).catch(res => {
  202. return reject(res);
  203. });
  204. },
  205. fail() {
  206. getCodeLogin((code) => {
  207. wxgetUserInfo().then(userInfo => {
  208. userInfo.code = code.code;
  209. return resolve({
  210. userInfo: userInfo,
  211. isLogin: false
  212. });
  213. }).catch(res => {
  214. return reject(res);
  215. })
  216. });
  217. }
  218. })
  219. }
  220. },
  221. fail(res) {
  222. return reject(res);
  223. }
  224. })
  225. })
  226. }
  227. /**
  228. *
  229. * 授权过后自动登录
  230. */
  231. const autoLogin = function() {
  232. return new Promise((resolve, reject) => {
  233. wx.getStorage({
  234. key: 'cache_key',
  235. success(res) {
  236. wxgetUserInfo().then(userInfo => {
  237. userInfo.cache_key = res.data;
  238. return resolve(userInfo);
  239. }).catch(res => {
  240. return reject(res);
  241. })
  242. },
  243. fail() {
  244. getCodeLogin((code) => {
  245. wxgetUserInfo().then(userInfo => {
  246. userInfo.code = code;
  247. return resolve(userInfo);
  248. }).catch(res => {
  249. return reject(res);
  250. })
  251. });
  252. }
  253. });
  254. })
  255. }
  256. const getCodeLogin = function(successFn) {
  257. wx.login({
  258. success(res) {
  259. successFn(res);
  260. }
  261. })
  262. }
  263. /*
  264. * 合并数组
  265. */
  266. const SplitArray = function(list, sp) {
  267. if (typeof list != 'object') return [];
  268. if (sp === undefined) sp = [];
  269. for (var i = 0; i < list.length; i++) {
  270. sp.push(list[i]);
  271. }
  272. return sp;
  273. }
  274. /**
  275. * opt object | string
  276. * to_url object | string
  277. * 例:
  278. * this.Tips('/pages/test/test'); 跳转不提示
  279. * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
  280. * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
  281. * tab=1 一定时间后跳转至 table上
  282. * tab=2 一定时间后跳转至非 table上
  283. * tab=3 一定时间后返回上页面
  284. * tab=4 关闭所有页面跳转至非table上
  285. * tab=5 关闭当前页面跳转至table上
  286. */
  287. const Tips = function(opt, to_url) {
  288. if (typeof opt == 'string') {
  289. to_url = opt;
  290. opt = {};
  291. }
  292. var title = opt.title || '',
  293. icon = opt.icon || 'none',
  294. endtime = opt.endtime || 2000;
  295. if (title) wx.showToast({
  296. title: title,
  297. icon: icon,
  298. duration: endtime
  299. })
  300. if (to_url != undefined) {
  301. if (typeof to_url == 'object') {
  302. var tab = to_url.tab || 1,
  303. url = to_url.url || '';
  304. switch (tab) {
  305. case 1:
  306. //一定时间后跳转至 table
  307. setTimeout(function() {
  308. wx.switchTab({
  309. url: url
  310. })
  311. }, endtime);
  312. break;
  313. case 2:
  314. //跳转至非table页面
  315. setTimeout(function() {
  316. wx.navigateTo({
  317. url: url,
  318. })
  319. }, endtime);
  320. break;
  321. case 3:
  322. //返回上页面
  323. setTimeout(function() {
  324. wx.navigateBack({
  325. delta: parseInt(url),
  326. })
  327. }, endtime);
  328. break;
  329. case 4:
  330. //关闭当前所有页面跳转至非table页面
  331. setTimeout(function() {
  332. wx.reLaunch({
  333. url: url,
  334. })
  335. }, endtime);
  336. break;
  337. case 5:
  338. //关闭当前页面跳转至非table页面
  339. setTimeout(function() {
  340. wx.redirectTo({
  341. url: url,
  342. })
  343. }, endtime);
  344. break;
  345. }
  346. } else if (typeof to_url == 'function') {
  347. setTimeout(function() {
  348. to_url && to_url();
  349. }, endtime);
  350. } else {
  351. //没有提示时跳转不延迟
  352. setTimeout(function() {
  353. wx.navigateTo({
  354. url: to_url,
  355. })
  356. }, title ? endtime : 0);
  357. }
  358. }
  359. }
  360. /*
  361. * 单图上传
  362. * @param object opt
  363. * @param callable successCallback 成功执行方法 data
  364. * @param callable errorCallback 失败执行方法
  365. */
  366. const uploadImageOne = function(opt, successCallback, errorCallback) {
  367. if (typeof opt === 'string') {
  368. var url = opt;
  369. opt = {};
  370. opt.url = url;
  371. }
  372. var count = opt.count || 1,
  373. sizeType = opt.sizeType || ['compressed'],
  374. sourceType = opt.sourceType || ['album', 'camera'],
  375. is_load = opt.is_load || true,
  376. uploadUrl = opt.url || '',
  377. inputName = opt.name || 'pics';
  378. wx.chooseImage({
  379. count: count, //最多可以选择的图片总数
  380. sizeType: sizeType, // 可以指定是原图还是压缩图,默认二者都有
  381. sourceType: sourceType, // 可以指定来源是相册还是相机,默认二者都有
  382. success: function(res) {
  383. //启动上传等待中...
  384. wx.showLoading({
  385. title: '图片上传中',
  386. });
  387. wx.uploadFile({
  388. url: getApp().globalData.url + '/api/' + uploadUrl,
  389. filePath: res.tempFilePaths[0],
  390. name: inputName,
  391. formData: {
  392. 'filename': inputName
  393. },
  394. header: {
  395. "Content-Type": "multipart/form-data",
  396. [TOKENNAME]: 'Bearer ' + getApp().globalData.token
  397. },
  398. success: function(res) {
  399. wx.hideLoading();
  400. if (res.statusCode == 403) {
  401. Tips({
  402. title: res.data
  403. });
  404. } else {
  405. var data = res.data ? JSON.parse(res.data) : {};
  406. if (data.status == 200) {
  407. successCallback && successCallback(data)
  408. } else {
  409. errorCallback && errorCallback(data);
  410. Tips({
  411. title: data.msg
  412. });
  413. }
  414. }
  415. },
  416. fail: function(res) {
  417. wx.hideLoading();
  418. Tips({
  419. title: '上传图片失败'
  420. });
  421. }
  422. })
  423. }
  424. })
  425. }
  426. /**
  427. * 移除数组中的某个数组并组成新的数组返回
  428. * @param array array 需要移除的数组
  429. * @param int index 需要移除的数组的键值
  430. * @param string | int 值
  431. * @return array
  432. *
  433. */
  434. const ArrayRemove = (array, index, value) => {
  435. const valueArray = [];
  436. if (array instanceof Array) {
  437. for (let i = 0; i < array.length; i++) {
  438. if (typeof index == 'number' && array[index] != i) {
  439. valueArray.push(array[i]);
  440. } else if (typeof index == 'string' && array[i][index] != value) {
  441. valueArray.push(array[i]);
  442. }
  443. }
  444. }
  445. return valueArray;
  446. }
  447. /**
  448. * 生成海报获取文字
  449. * @param string text 为传入的文本
  450. * @param int num 为单行显示的字节长度
  451. * @return array
  452. */
  453. const textByteLength = (text, num) => {
  454. let strLength = 0;
  455. let rows = 1;
  456. let str = 0;
  457. let arr = [];
  458. for (let j = 0; j < text.length; j++) {
  459. if (text.charCodeAt(j) > 255) {
  460. strLength += 2;
  461. if (strLength > rows * num) {
  462. strLength++;
  463. arr.push(text.slice(str, j));
  464. str = j;
  465. rows++;
  466. }
  467. } else {
  468. strLength++;
  469. if (strLength > rows * num) {
  470. arr.push(text.slice(str, j));
  471. str = j;
  472. rows++;
  473. }
  474. }
  475. }
  476. arr.push(text.slice(str, text.length));
  477. return [strLength, arr, rows] // [处理文字的总字节长度,每行显示内容的数组,行数]
  478. }
  479. /**
  480. * 获取分享海报
  481. * @param array arr2 海报素材
  482. * @param string store_name 素材文字
  483. * @param string price 价格
  484. * @param function successFn 回调函数
  485. *
  486. *
  487. */
  488. const PosterCanvas = (arr2, store_name, price, successFn) => {
  489. wx.showLoading({
  490. title: '海报生成中',
  491. mask: true
  492. });
  493. const ctx = wx.createCanvasContext('myCanvas');
  494. ctx.clearRect(0, 0, 0, 0);
  495. /**
  496. * 只能获取合法域名下的图片信息,本地调试无法获取
  497. *
  498. */
  499. wx.getImageInfo({
  500. src: arr2[0],
  501. success: function(res) {
  502. const WIDTH = res.width;
  503. const HEIGHT = res.height;
  504. ctx.drawImage(arr2[0], 0, 0, WIDTH, HEIGHT);
  505. ctx.drawImage(arr2[1], 0, 0, WIDTH, WIDTH);
  506. ctx.save();
  507. let r = 90;
  508. let d = r * 2;
  509. let cx = 40;
  510. let cy = 990;
  511. ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
  512. ctx.clip();
  513. ctx.drawImage(arr2[2], cx, cy, d, d);
  514. ctx.restore();
  515. const CONTENT_ROW_LENGTH = 40;
  516. let [contentLeng, contentArray, contentRows] = textByteLength(store_name,
  517. CONTENT_ROW_LENGTH);
  518. if (contentRows > 2) {
  519. contentRows = 2;
  520. let textArray = contentArray.slice(0, 2);
  521. textArray[textArray.length - 1] += '……';
  522. contentArray = textArray;
  523. }
  524. ctx.setTextAlign('center');
  525. ctx.setFontSize(32);
  526. let contentHh = 32 * 1.3;
  527. for (let m = 0; m < contentArray.length; m++) {
  528. ctx.fillText(contentArray[m], WIDTH / 2, 820 + contentHh * m);
  529. }
  530. ctx.setTextAlign('center')
  531. ctx.setFontSize(48);
  532. ctx.setFillStyle('red');
  533. ctx.fillText('¥' + price, WIDTH / 2, 860 + contentHh);
  534. ctx.draw(true, function() {
  535. wx.canvasToTempFilePath({
  536. canvasId: 'myCanvas',
  537. fileType: 'png',
  538. destWidth: WIDTH,
  539. destHeight: HEIGHT,
  540. success: function(res) {
  541. wx.hideLoading();
  542. successFn && successFn(res.tempFilePath);
  543. }
  544. })
  545. });
  546. },
  547. fail: function() {
  548. wx.hideLoading();
  549. Tips({
  550. title: '无法获取图片信息'
  551. });
  552. }
  553. })
  554. }
  555. /**
  556. * 数字变动动画效果
  557. * @param float BaseNumber 原数字
  558. * @param float ChangeNumber 变动后的数字
  559. * @param object that 当前this
  560. * @param string name 变动字段名称
  561. * */
  562. const AnimationNumber = (BaseNumber, ChangeNumber, that, name) => {
  563. var difference = $h.Sub(ChangeNumber, BaseNumber) //与原数字的差
  564. var absDifferent = Math.abs(difference) //差取绝对值
  565. var changeTimes = absDifferent < 6 ? absDifferent : 6 //最多变化6次
  566. var changeUnit = absDifferent < 6 ? 1 : Math.floor(difference / 6);
  567. // 依次变化
  568. for (var i = 0; i < changeTimes; i += 1) {
  569. // 使用闭包传入i值,用来判断是不是最后一次变化
  570. (function(i) {
  571. setTimeout(() => {
  572. that.setData({
  573. [name]: $h.Add(BaseNumber, changeUnit)
  574. })
  575. // 差值除以变化次数时,并不都是整除的,所以最后一步要精确设置新数字
  576. if (i == changeTimes - 1) {
  577. that.setData({
  578. [name]: $h.Add(BaseNumber, difference)
  579. })
  580. }
  581. }, 100 * (i + 1))
  582. })(i)
  583. }
  584. }
  585. module.exports = {
  586. formatTime: formatTime,
  587. $h: $h,
  588. Tips: Tips,
  589. uploadImageOne: uploadImageOne,
  590. SplitArray: SplitArray,
  591. ArrayRemove: ArrayRemove,
  592. PosterCanvas: PosterCanvas,
  593. AnimationNumber: AnimationNumber,
  594. getUrlParams: getUrlParams,
  595. chekWxLogin: chekWxLogin,
  596. getCodeLogin: getCodeLogin,
  597. checkLogin: checkLogin,
  598. wxgetUserInfo: wxgetUserInfo,
  599. autoLogin: autoLogin,
  600. logout: logout,
  601. getUserProfile: getUserProfile
  602. }