util.js
13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
var uri = require('uri.js')
const Buffer = require('./upload/buffer.js');
const CryptoJS = require('./upload/hmac-sha1.js');
const base64 = require('./upload/enc-base64.js');
import qiniuUploader from "./upload/qiniuUploader";
function formatTime(date, type, connect) {
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
var second = date.getSeconds()
if (type == 1) {
if (connect) {
return [year, month, day].map(formatNumber).join(connect)
} else {
return [year, month, day].map(formatNumber).join('/')
}
} else if (type == 2) {
return [month, day].map(formatNumber).join('/')
} else {
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
}
function imageZoomHeightUtil(originalWidth,originalHeight,imageWidth){
let imageSize = {};
if(imageWidth){
imageSize.imageWidth = imageWidth;
imageSize.imageHeight = (imageWidth * originalHeight) / originalWidth;
}else{//如果没有传imageWidth,使用屏幕的宽
wx.getSystemInfo({
success: function (res) {
imageWidth = res.windowWidth;
imageSize.imageWidth = imageWidth;
imageSize.imageHeight = (imageWidth * originalHeight) / originalWidth;
}
});
}
return imageSize;
}
function formatNumber(n) {
n = n.toString()
return n[1] ? n : '0' + n
}
//时间戳转为时间
function unixtoTime(ns, format = '') {
var result;
var time = new Date(ns * 1000);
//result=format || 'YYYY年MM月DD日 HH时II分SS秒 WW';
result = format || 'YYYY年MM月DD日 HH时II分SS秒';
//console.log(format);
result = result.toUpperCase();
result = result.replace('YYYY', time.getFullYear());
var m = time.getMonth() + 1;
result = result.replace('MM', m > 9 ? m : "0" + m);
var d = time.getDate();
result = result.replace('DD', d > 9 ? d : '0' + d);
var hh = time.getHours();
result = result.replace('HH', hh > 9 ? hh : '0' + hh);
var ii = time.getMinutes();
result = result.replace('II', ii > 9 ? ii : '0' + ii);
var ss = time.getSeconds();
result = result.replace('SS', ss > 9 ? ss : '0' + ss);
var week;
switch (time.getDay()) {
case 0:
week = "日";
break
case 1:
week = "一";
break
case 2:
week = "二";
break
case 3:
week = "三";
break
case 4:
week = "四";
break
case 5:
week = "五";
break
case 6:
week = "六";
break
}
result = result.replace('WW', week);
if (format.indexOf('DAY') > 0) {
// 获取当天 0 点的时间戳
var timeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000;
var day1 = timeStamp + 86400//今天结束
var day2 = day1 + 86400//明天结束
//console.log('ns<day.getTime()',timeStamp,ns,day1,day2)
if (ns >= timeStamp && ns < day1) {
result = result.replace('DAY', '今天');
} else {
if (ns >= day1 && ns < day2) {
result = result.replace('DAY', '明天');
} else {
result = result.replace('DAY', '');
}
}
}
if (format.indexOf('`') > -1) {
result = result.replace(/`(.*)\/(.*)`/ig, function ($0, $1, $2) {
return $1 || $2;
});
}
return result;
}
//时间转为时间戳
function timetouUnix(dasr, connect) {
if (connect) {
var newstr = dasr.replace(/-/g, connect);
} else {
var newstr = dasr.replace(/-/g, '/');
}
var date = new Date(newstr);
var time_str = date.getTime().toString();
return time_str.substr(0, 10);
}
/**
* 将小程序的API封装成支持Promise的API
* @params fn {Function} 小程序原始API,如wx.login
*/
const wxPromisify = fn => {
return function (obj = {}) {
return new Promise((resolve, reject) => {
obj.success = function (res) {
resolve(res)
}
obj.fail = function (res) {
reject(res)
}
fn(obj)
})
}
}
// 判断数据是否为空,不为空则JSON.parse转化json数据
function parseDataValue(val) {
var arr = Object.keys(JSON.parse(val));
if(arr.length!= '0'){
let data=JSON.parse(val)
return data
}
}
// 判断是json 进行parse转化
function determine(str) {
if (typeof str == 'string') {
try {
var obj = JSON.parse(str);
return obj;
} catch (e) {
return str;
}
}else{
return str
}
}
// 比较大小函数key字段
function objCompare (obj1, obj2,key){
var val1 = obj1[key];
var val2 = obj2[key];
if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}
// 判断是数组还是对象 返回 object 或者 array
function getType(variable) {
return ({}).toString.call(variable).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
// 上传图片
function uploadFile(imgArr, token,type){
let path = imgArr.split('//')[1]
let promisevariable = new Promise(function (resolve, reject) {
qiniuUploader.upload(
imgArr, //上传的图片
(res) => { //回调 success
console.log(res, '七牛云返回')
resolve(res.imageURL)
}, (error) => { //回调 fail
reject('error');
},
{ // 参数设置 地区代码 token domain 和直传的链接 注意七牛四个不同地域的链接不一样,我使用的是华南地区
uptokenURL: token,
uploadURL: 'http://nosqn.colorcun.com',
region: 'ECN', //服务器区域号
domain: 'http://nosqn.colorcun.com',//七牛云域名
key: `pinglun/${type}/${path}`, // 上传到七牛云图片就是这路径
uptoken: token,
uptokeFunc:'',
})
})
return promisevariable;
}
function base64ToUrlSafe(v) {
return v.replace(/\//g, '_').replace(/\+/g, '-');
};
// 删除
function deletelUpload(filename,token,cb) {
var secretkey = 'oZMMVN6phk49lG0J1xwmi1Ju0ETT15EnAEWcU9Cs'; //你的sk
var accessKey = 'uva-aaonM8dukeR6phc9yuPBrOXk9brrNW_PxLD7';
var bucket = 'colorcun-attr' //你的空间名
var cdn = 'http://nosqn.colorcun.com' //CDN 测试域名
var str = bucket + ':' + filename.split( cdn + '/')[1];
var encoded = Buffer.from(str).toString('base64'); //字符串64编码
var encodedEntryURI = base64ToUrlSafe(encoded); //安全编码就是替换掉一些符号看
var signingStr = '/delete/' + encodedEntryURI + '\n'
var sign = CryptoJS.HmacSHA1(signingStr, secretkey); //HmacSHA1签名
var cod = base64.stringify(sign); //HmacSHA1的64编码
var encodedSign = base64ToUrlSafe(cod);
// 拼接accessToken
var accessToken = accessKey + ":" + encodedSign
wx.request({
url: "https://rs.qiniuapi.com/delete/" + encodedEntryURI,
method: "POST",
header: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": 'QBox '+accessToken
},
success: function (res) {
wx.showToast({
title: '删除成功!',
icon: 'none',
duration: 500
})
return typeof cb == "function" && cb(res.data) //更具返回数据判断
},
fail: function (fail) {
console.log('删除失败',fail);
wx.showToast({
title: '删除失败',
icon: 'none',
duration: 500
})
return typeof cb == "function" && cb(false)
}
})
};
// 节流函数
function throttle(fn, gapTime) {
if (gapTime == null || gapTime == undefined) {
gapTime = 1500
}
let _lastTime = null
return function () {
let _nowTime = + new Date()
if (_nowTime - _lastTime > gapTime || !_lastTime) {
fn.apply(this, arguments)
_lastTime = _nowTime
}
}
}
let roles = {
cancel: ['管理员', '前台'],//取消预订
edit: ['管理员', '前台'],//变更预订
sending: ['管理员', '前台'],//发送短信
arrival: ['管理员', '店长', '前台', '迎宾'],//到店
leave: ['管理员', '店长', '前台', '迎宾'],//离店
addBanquet: ['管理员', '店长', '客户经理', '收银员', '服务员', '前台'],//创建宴会
addBook: ['管理员', '店长', '客户经理', '收银员', '服务员', '前台'],//新建预订
depositNuclearMeal: ['管理员', '店长', '客户经理', '收银员', '服务员', '前台'],//核餐和订金
}
module.exports = {
formatTime: formatTime,
unixtoTime: unixtoTime,
timetouUnix: timetouUnix,
parseDataValue,
determine,
objCompare,
getType,
imageZoomHeightUtil,
uploadFile,
deletelUpload,
throttle,
roles,
cgi: function (act) {
return uri.HOST__LINE + act //正式
//return uri.HOST__TEST+act //测试
},
wxApiIsUse: function (api) {
if (wx.canIUse(api)) {
return true;
} else {
this.alert('当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。');
}
},
openXcx: function (data) {
if (this.wxApiIsUse('navigateToMiniProgram')) {
wx.navigateToMiniProgram({
appId: data.appId,
path: data.path,
extraData: {
foo: 'bar'
},
envVersion: 'trial',
//envVersion: '',
success(res) {
// 打开成功
}
})
}
},
loading: function (flag) {
if (flag == 'clear' || flag == "clean") {
wx.hideNavigationBarLoading();
return;
}
wx.showNavigationBarLoading();
},
alert: function (msg, success, cancel, title) {
wx.showModal({
title: title ? title : "提示信息",
content: msg,
showCancel: typeof cancel == 'undefined' ? false : true,
success: function (res) {
if (res.confirm) {
if (success) success();
} else {
if (cancel) cancel();
}
}
});
},
toast: function (title, icon = 'success',duration) {
wx.showToast({
title: title,
icon: icon,
duration,
})
},
showLoading: function (title) {
wx.showLoading({
title: '加载中',
})
},
cache: function (key, value) {
if (value) {
wx.setStorageSync(key, value);
}
return wx.getStorageSync(key);
},
remove: function (key) {
if (key) {
wx.removeStorage({key: key})
}
},
image: function (id, width = "") {
var url = this.cgi(uri.CGI__DOWNLOAD + '/id/' + id);
if (width) {
url += '/width/' + width;
}
return url;
},
avatar: function (id, t = 'pu') {
return this.cgi(uri.CGI__AVATAR + '/' + t + '/' + id);
},
trim: function (str) {
return str.replace(/^([ ]+)/, "").replace(/([ ]+)$/, "");
},
clear: function (str) {//去除html标签
return this.trim(str.replace(/<[^>]+>/ig, ""));
},
val: function (e, key = '') {
if (key != '') return e.detail.value[key] || '';
return e.detail.value;
},
attr: function (e, key = '') {
if (!key) {
return e.currentTarget.dataset
}
return e.currentTarget.dataset[key];
},
extend: function (destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
},
compare: function (property) {
return function (a, b) {
var value1 = a[property];
var value2 = b[property];
return value1 - value2;
}
},
getJsonLength: function (jsonData) {
var jsonLength = 0;
for (var item in jsonData) {
jsonLength++;
}
return jsonLength;
},
testPhone: function (phone) {
if (!/^1[3-9][0-9]{9}$/.test(phone)) {
this.alert("请输入正确的电话号码");
return false;
}
},
setBarTitle: function (title) {
wx.setNavigationBarTitle({
title: title
})
},
//
isEOne: function (arr, value) {
for (var i = 0, vlen = arr.length; i < vlen; i++) {
if (arr[i] == value) {
return i;
}
}
return -1;
},
linkTo: function (url, sellerid, code) {
var path = 'pages/menu/' + url;
if (code != '') {
path += '?sellerid=' + sellerid + '&code=' + code
}
if (sellerid != '') {
path += '?sellerid=' + sellerid
}
console.log(path)
wx.navigateToMiniProgram({
appId: 'wx52646daaa3f42a4f',
path: path,
envVersion: 'release',
success: function (res) {
console.log(path)
}
})
},
setting: function () {
if (wx.canIUse('openSetting') == true) {
wx.openSetting({
success: function (res) {
console.log(res.authSetting)
return res.authSetting
}
})
}
},
//获取设备信息
getsystem: function () {
try {
var res = wx.getSystemInfoSync()
return res;
} catch (e) {
return false
}
},
http_build_query(obj, url = '') {
let ps = []
for (let i in obj) {
if (typeof obj[i] == 'undefined' || obj[i] == null || obj[i] === false) continue;
ps.push(i + '=' + obj[i].toString())
}
ps = ps.join('&');
if (!url) {
return ps;
}
if(ps){
url += (url.indexOf('?') > -1 ? '&' : '?') + ps;
}
return url;
},
/**
* @param edata is object: ename,edata
*/
elog(edata,ename='EVENT_NAME') {
let key='EVENT_LOG_CACHE'
let ps=getCurrentPages();
console.log(ps)
let page=ps[ps.length-1]
edata=edata?edata:{}
edata.curPage={
path:page.route,
options:page.options,
}
let eobj={
ename:ename,
edata:edata,
page:this.http_build_query(page.options,page.route),
time:parseInt(new Date()/1000),
}
wx.getStorage({
key:key,
success:res=>{
let data=res.data||[]
data.push(eobj)
wx.setStorage({
key:key,
data:data,
})
},
fail:res=>{
let data=[eobj]
wx.setStorage({
key:key,
data:data,
})
},
})
},
wxPromisify:wxPromisify,
}