346149741
2024-06-22 ade1aa658df84e8b52f5d1dfa9d2971da5cdad55
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
import {
    config
} from "@/common/config.js"
/**
 * 跳转到指定页面
 * url=跳转的url
 * skip = 条转方式,1保留当前页面,跳转到应用内的某个页面(默认)
 * 2关闭所有页面,打开到应用内的某个页面
 */
function go(dataset) {
    var url = dataset.url;
 
    if ("/" + getPageInfo("route") == url) {
        return;
    }
 
    var skip = dataset.skip;
    if (skip == undefined) {
        skip = 1
    }
    if (skip == 1) {
        wx.navigateTo({
            url: url,
        })
    }
    if (skip == 2) {
        wx.reLaunch({
            url: url,
        })
    }
    if (skip == 3) {
        wx.redirectTo({
            url: url,
        })
    }
}
/**
 * 页面后退
 * {page:页面路径} 返回到指定路径
 * {page:1} 返回到上一层
 */
function retreat(e) {
    if (e.page == undefined) {
        e.page = 1
    }
    if (!isNaN(e.page)) {
        uni.navigateBack({
            delta: e.page
        })
        return;
    } else {
        console.log(111)
        if (e.page.indexOf('index') > 1 || e.page.indexOf('sort') > 1 || e.page.indexOf('shop') > 1 || e.page.indexOf(
                'cart') > 1 || e.page.indexOf('person') > 1) {
            uni.switchTab({
                url: "/" + e.page
            })
        } else {
            // 添加参数
            if (!!e.argu) {
                var options = JSON.parse(e.argu);
                let argu = "?"
                for (var key in options) {
                    argu += key + '=' + options[key] + '&'
                }
 
                uni.redirectTo({
                    url: "/" + e.page + argu
                })
            } else {
                uni.redirectTo({
                    url: "/" + e.page
                })
            }
 
        }
        return;
    }
}
 
/**
 * 获取当前页面信息
 * -- route:页面路径
 */
 
function getPageInfo(key) {
    var pages = getCurrentPages(); //获取加载的页面信息(结果是个数组)
 
    return pages[pages.length - 1][key];
}
 
function checkPhone(phone) {
    /**
     * 电话号码正则
     * @param {String} phone - 电话号码
     * @return {Boolean} 是否通过
     */
    if (!(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(phone))) {
        return false;
    }
    return true;
}
 
function checkIdCard(idCard) {
    /**
     * 身份证正则
     * @param {String} idCard - 身份证号码
     * @return {Boolean} 是否通过
     */
    if (!(/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(idCard))) {
        return false;
    }
    return true;
}
 
function isPerfectInfo(app) {
    /**
     * 判断是否完善个人信息
     * @return {Boolean} 
     */
    if (app.globalData.isPerfectInfo) {
        return true;
    } else {
        wx.showModal({
            title: '提示',
            content: '您尚未完善个人信息,请点击确定按钮完善个人信息',
            success(res) {
                if (res.confirm) {
                    // 跳转完善个人信息页
                    go({
                        url: '/pages/perfectInfo/perfectInfo',
                        skip: 1
                    })
                } else if (res.cancel) {}
            }
        })
        return false;
    }
}
 
function accMul(arg1, arg2) {
    /**
     * 乘法
     */
    let m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length
    } catch (e) {}
    try {
        m += s2.split(".")[1].length
    } catch (e) {}
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}
 
function isTimeOut(date) {
    /**
     * 判断传入的日期是否大于当前日期
     */
    var nowDate = new Date().getTime();
    var checkDate = new Date(date).getTime();
    if (nowDate < checkDate) {
        return false;
    }
    return true;
}
/**
 * 后台返回日期截取
 */
function splitDate(date) {
    var arr = date.split(' ')[0];
    var str = arr.split('-')[0] + '.' + arr.split('-')[1] + '.' + arr.split('-')[2];
    return str;
}
 
 
/**
 * 日期格式化
 * @param {Object} date
 * @param {Object} fmt
 */
function dateFormat(date, fmt) {
    if (!date) {
        return
    }
    if (!fmt) {
        fmt = 'yyyy-MM-dd hh:mm'
    }
    if (!(date instanceof Date)) {
        date = new Date(date.replace(/-/g, '/'))
    }
 
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
 
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
 
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length));
        }
    }
    return fmt;
}
 
function isBlank(str) {
    if (str === undefined || str === 'undefined' || str === null || str === 'null' || str === '' || str === '{}' ||
        str === {} || str === '[]' || str === [] || str === 'null' || str
        .length == 0) {
        return true
    } else {
        return false
    }
}
 
function GetQueryString(path, name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var idx = path.indexOf("?");
    if (idx === -1) {
        return null
    }
    var r = path.substring(idx + 1).match(reg); //获取url中"?"符后的字符串并正则匹配
    var context = "";
    if (r != null)
        context = decodeURIComponent(r[2]);
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
}
/**
 * param 将要转为URL参数字符串的对象
 * key URL参数字符串的前缀
 * encode true/false 是否进行URL编码,默认为true
 * idx ,循环第几次,用&拼接
 * return URL参数字符串
 */
function urlEncode(param, idx, key, encode) {
    if (param == null) return '';
    var paramStr = '';
    var t = typeof(param);
    if (t == 'string' || t == 'number' || t == 'boolean') {
        var one_is = idx < 3 ? '?' : '&';
        paramStr += one_is + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
    } else {
        for (var i in param) {
            var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
            idx++
            paramStr += urlEncode(param[i], idx, k, encode);
        }
    }
    return paramStr;
};
/**
 * 加密手机号
 */
function encodePhone(phone) {
    var str = phone.substring(0, 3) + "****" + phone.substring(7);
    return str;
}
 
function json2str(json) {
    return encodeURIComponent(JSON.stringify(json))
}
/**
 * 获取距离
 */
function getDistance(dis) {
    var s = 0;
    dis = dis - 0;
    if (dis < 100) s = '<100m';
    if (dis < 1000 && dis > 100) s = dis.toFixed(1) + 'm';
    if (dis > 1000) s = (dis / 1000).toFixed(2) + 'km';
    if (dis > 100000) s = '>100km';
    return s;
}
/**
 * 百分比整数位置
 */
function getPercentage(salesPercentage) {
    if (salesPercentage == null) {
        salesPercentage = '0.0';
    }
    return salesPercentage.substring(0, salesPercentage.indexOf("."));
}
 
function checkNav(url) {
    // var checkList = ['/h5Redirect/h5Redirect', '/vip/vip']
    var checkList = ['/vip/vip']
    return checkList.some(function(item) {
        return url.indexOf(item) != -1
    })
}
 
/**
 * 获取星星数
 */
function getStar(score) {
    if (score > 80) {
        return 5;
    } else if (score > 60) {
        return 4;
    } else if (score > 40) {
        return 3;
    } else if (score > 20) {
        return 2;
    } else {
        return 1;
    }
}
 
function getArrayImgPath(jsonArray, url) {
    if (!jsonArray) {
        return "";
    }
    var json = JSON.parse(jsonArray)[0];
    var baseUrl = url || config.ftpUrl
    // var result = 'https://scstq.183.sc.cn/f-static' + json.path;//邮政
    var result = baseUrl + json.path; //金明源
    return result;
}
 
function getImgPath(jsonstr, url) {
    //if (jsonstr != null && jsonstr != 'null') {
    // }
    // var result = 'https://scstq.183.sc.cn/f-static' + jsonstr.path;//邮政
    var baseUrl = url || config.ftpUrl
    var result = baseUrl + jsonstr.path;
    return result;
}
 
function fenToYuan(amount) {
    if (!amount) {
        return "0";
    }
    amount = amount.toString();
    if (amount.length == 1) {
        return parseFloat("0.0" + amount);
    } else if (amount.length == 2) {
        return parseFloat("0." + amount);
    } else {
        return parseFloat(amount.substring(0, amount.length - 2) + "." + amount.substring(amount.length - 2));
    }
}
 
function requestPayment(data, sucessUrl, failUrl) {
    // 微信支付
    // #ifdef MP-WEIXIN
    uni.requestPayment({
        appId: data.appId,
        timeStamp: data.timeStamp,
        nonceStr: data.nonceStr,
        package: data.package,
        signType: data.signType,
        paySign: data.paySign,
        success: function(res) {
            if (res.errMsg.charCodeAt('ok') > -1) {
                uni.redirectTo({
                    url: sucessUrl
                });
            } else {
                uni.redirectTo({
                    url: failUrl
                });
            }
        },
        fail: function(res) {
            uni.redirectTo({
                url: failUrl
            });
        }
    });
    // #endif
    // #ifdef H5
    WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
            "appId": data.appId, //公众号ID,由商户传入
            "timeStamp": data.timeStamp, //时间戳,自1970年以来的秒数
            "nonceStr": data.nonceStr, //随机串
            "package": data.package,
            "signType": data.signType, //微信签名方式:
            "paySign": data.paySign //微信签名
        },
        (res) => {
            if (res.err_msg == "get_brand_wcpay_request:ok") {
                // 使用以上方式判断前端返回,微信团队郑重提示:
                uni.redirectTo({
                    url: sucessUrl
                });
            } else {
                uni.redirectTo({
                    url: failUrl
                });
            }
        });
    // #endif
}
 
/* 跳转确认支付页 */
function toConfirmPay(url, type = 'redirectTo') {
    // #ifdef MP-WEIXIN
    uni[type]({
        url
    })
    // #endif
    // #ifdef H5
 
    let redirect_uri = encodeURIComponent(config.webURL + url)
    window.location.href = config.authCallBackUrl + redirect_uri
    // #endif
}
 
function toH5Auth() {
    // #ifdef H5
    let redirect_uri = encodeURIComponent(`${config.webURL}/pages/login/login`)
    const pages = getCurrentPages()
    let prevRoute = pages[pages.length - 1]
    uni.setStorageSync('prevPage', JSON.stringify({
        page: prevRoute.$page.fullPath.replace('/', ''),
    }))
    if (isWxOrAli() == 2) {
        window.location.href =
            `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.wx_appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
    } else if (isWxOrAli() == 5) {
        window.location.href =
            `https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=${config.ali_appid}&scope=auth_base&redirect_uri=${redirect_uri}&state=STATE`
    } else {
        uni.showModal({
            title: '提示',
            content: '请在微信内打开网页',
            success: () => {
 
            }
        })
    }
    // #endif
}
// 判断微信、支付宝  2微信 5支付宝 3其他
function isWxOrAli() {
    var ua = window.navigator.userAgent.toLowerCase();
    //判断是不是微信
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return 2;
    }
    //判断是不是支付宝
    if (ua.match(/AlipayClient/i) == 'alipayclient') {
        return 5;
    }
    return 3;
}
/**
 * @description 计算角度
 * @param arg1 角度
 * @param 数量
 */
function accDiv(arg1, arg2) {
    let t = 0
    arg1 = arg1 ? arg1.toString() : '0'
    arg2 = arg2 ? arg2.toString() : '0'
    if (arg2.includes('.')) {
        t = arg2.split('.')[1].length
    }
    if (arg1.includes('.')) {
        t -= arg1.split('.')[1].length
    }
    const r1 = Number(arg1.replace('.', ''))
    const r2 = Number(arg2.replace('.', ''))
    return this.accMul((r1 / r2), Math.pow(10, t))
}
 
function getApplyPayWay(applyPayWayStr) {
    let payWay = {
        '1': '微信',
        '2': '支付宝',
        '3': '快捷支付'
    }
    if (!applyPayWayStr) {
        return '不限'
    }
    let arr = applyPayWayStr.split(',')
    if (arr.length === 3) {
        return '不限'
    }
    return arr.map(i => payWay[i]).join('、')
}
//转化成小程序模板语言 这一步非常重要 不然无法正确调用
module.exports = {
    go: go,
    getPageInfo: getPageInfo,
    splitDate: splitDate,
    retreat: retreat,
    json2str,
    encodePhone,
    checkIdCard,
    checkPhone,
    isPerfectInfo,
    accMul,
    isTimeOut,
    dateFormat,
    isBlank,
    GetQueryString,
    urlEncode,
    getDistance,
    getPercentage,
    checkNav,
    getStar,
    getArrayImgPath,
    getImgPath,
    fenToYuan,
    toH5Auth,
    isWxOrAli,
    toConfirmPay,
    requestPayment,
    getApplyPayWay,
    accDiv,
};