util.js 19 KB

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