util.js 16 KB

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