util.js
9.14 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
import bigdatautilApi from '~/api/bigdatautil'
import api from '~/utils/request/request'
import {
Storage
} from '~/utils/cache/storage'
import sopApi from '~/api/sopApi'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
const $Storage = new Storage()
/**
* 日期格式化
* let time = new Date().format('yyyy-MM-dd hh:mm:ss') //log 2020-07-31 10:00:00
*/
Date.prototype.format = function (fmt) {
let o = {
'M+': this.getMonth() + 1, //月份
'd+': this.getDate(), //日
'h+': this.getHours(), //小时
'm+': this.getMinutes(), //分
's+': this.getSeconds(), //秒
//季度
'q+': Math.floor((this.getMonth() + 3) / 3),
S: this.getMilliseconds() //毫秒
}
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
for (let k in o) {
if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
}
return fmt
}
const isEmptyObj = (obj) => {
return JSON.stringify(obj) === "{}";
};
const setNavigationBarTitle = (title) => {
getSystemInfo({
success: (res) => {
// console.log('++++++++++++++', res);
// console.log('title length',title.length)
let width = res.safeArea.width / res.fontSizeSetting;
// console.log('width: ', width);
let space = '';
// for (let i = 0; i <= width+4; i++) {
// space = space + ' ';
// }
width = width - (title.length) / 2
for (let i = 0; i < width; i++) {
space = space + ' ';
}
if (res.system.includes('iOS') === false) {
wx.setNavigationBarTitle({
title: space + title
});
} else {
wx.setNavigationBarTitle({
title: title
});
}
}
});
}
/**节流 */
const 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) //将this和参数传给原函数
_lastTime = _nowTime
}
}
}
const debounce = (fn, delay = 500) => {
// timer 是在闭包中的
let timer = null
return function () {
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, arguments)
}, delay)
}
}
const promise = callBack => {
return new Promise((resolve, reject) => {
callBack(resolve, reject)
})
}
/** */
const getSessionId = () => {
return $Storage.get('scrm_shopmall_sessionId')
}
const setSessionId = sessionId => {
$Storage.set('scrm_shopmall_sessionId', sessionId)
}
// const setStorageSync = (key, data) => {
// wx.setStorageSync(key, JSON.stringify(data))
// }
// const getStorageSync = key => {
// let data = wx.getStorageSync(key) || null
// return JSON.parse(data)
// }
const getUserInfo = () => {
return $Storage.get('srcm_shopmall_user_info') || null
// return JSON.parse(user)
}
const setUserInfo = userInfo => {
$Storage.set('srcm_shopmall_user_info', userInfo)
}
/** 小程序扫码进来的sceneId */
const getSceneId = path => {
let [_route_, _options_] = path.split('?')
let [target] = _route_.split('/')
let name = _route_.split('/').pop()
let scene = _options_ ? _options_.split('=')[1] : ''
return {
name,
scene,
target
}
}
const clearObjNull = options => {
let obj = {}
Object.keys(options).map(e => {
if (options[e] != null && options[e] != undefined) {
if (typeof options[e] == 'object') {
Object.keys(options[e]).map(key => {
if (options[e][key] == null || options[e][key] == undefined) delete options[e][key]
})
}
obj[e] = options[e]
}
})
return obj
}
/**SOP埋点 */
let _behaviorType = '',
_taskId = '',
_eventId = ''
const customerbehavior = (behaviorType = 1) => {
if (wx.$authStatus) return
let {
taskId,
eventId
} = wx.getEnterOptionsSync().query
let {
openId,
phone
} = getUserInfo()
if (_behaviorType == behaviorType && (_taskId == taskId || _eventId == eventId)) return
let params = {
customerPhone: phone,
behaviorType,
openId,
}
if (taskId || eventId) {
if (taskId) {
params.taskId = taskId
_taskId = taskId
}
if (eventId) {
params.eventId = eventId
_eventId = eventId
}
sopApi.customerbehaviorByEventId(params)
}
_behaviorType = behaviorType
}
/**埋点上报 */
const reportData = (params, check, receive, isRecommended) => {
let data = {
add_way: '104'
}
const user = getUserInfo() || {}
if (params.activity_id) {
data.activity_id = params.activity_id
}
if (params.merchantId) {
data.merchant_id = params.merchantId
}
if (params.phone || user.phone) {
data.customer_phone = params.phone || user.phone
}
if (check) {
data.check_time = new Date().format('yyyy-MM-dd hh:mm:ss')
data.check_status = 1
}
if (receive) {
data.receive_status = 1
data.receive_time = new Date().format('yyyy-MM-dd hh:mm:ss')
}
if (user.unionId) {
data.union_id = user.unionId
}
if (user.openId) {
data.open_id = user.openId
}
if (isRecommended) {
data.item_type = params.item_type
data.action_type = params.action_type
data.business_type = 1
data.create_time = new Date().format('yyyy-MM-dd hh:mm:ss')
data.staff_uuid = params.shareStaffUuid
data.item_id = params.item_id
if (params.order_id) {
data.order_id = params.order_id
}
}
// let json = encodeURIComponent(JSON.stringify(data))
let json = JSON.stringify(data)
bigdatautilApi.reportCustomer({
json
})
}
const deepClone = (target) => {
const map = new WeakMap()
function isObject(target) {
return (typeof target === 'object' && target) || typeof target === 'function'
}
function clone(data) {
if (!isObject(data)) {
return data
}
if ([Date, RegExp].includes(data.constructor)) {
return new data.constructor(data)
}
if (typeof data === 'function') {
return new Function('return ' + data.toString())()
}
const exist = map.get(data)
if (exist) {
return exist
}
if (data instanceof Map) {
const result = new Map()
map.set(data, result)
data.forEach((val, key) => {
if (isObject(val)) {
result.set(key, clone(val))
} else {
result.set(key, val)
}
})
return result
}
if (data instanceof Set) {
const result = new Set()
map.set(data, result)
data.forEach(val => {
if (isObject(val)) {
result.add(clone(val))
} else {
result.add(val)
}
})
return result
}
const keys = Reflect.ownKeys(data)
const allDesc = Object.getOwnPropertyDescriptors(data)
const result = Object.create(Object.getPrototypeOf(data), allDesc)
map.set(data, result)
keys.forEach(key => {
const val = data[key]
if (isObject(val)) {
result[key] = clone(val)
} else {
result[key] = val
}
})
return result
}
return clone(target)
}
/**获取mock数据 */
let mockRequestCount = null,
mockTimer = {},
mockCache = null
const getMockData = async () => {
const MOCKDATA = $Storage.get('mock_data')
try {
if (MOCKDATA && Date.now() - MOCKDATA.createTime < 5 * 60e3) {
return Promise.resolve(MOCKDATA)
} else {
if (!mockRequestCount) {
mockCache = null
mockRequestCount = Date.now()
const data = await api.getMock()
data.createTime = Date.now()
mockCache = data
$Storage.set('mock_data', data)
return Promise.resolve(data)
} else {
const key = Date.now()
return new Promise((resolve) => {
mockTimer[key] = setInterval(() => {
if (mockCache) {
clearInterval(mockTimer[key])
mockRequestCount = null
resolve(mockCache)
}
}, 1e3)
})
}
}
} catch (error) {
if (mockTimer[key]) clearInterval(mockTimer[key])
mockRequestCount = null
return Promise.reject(error)
}
}
/**判断是不是续保商城商户*/
const judgeMerchantForXubao = () => {
const XUBAO_MERCHANTID = wx.$storage.get('srcm_shopmall_merchant_id')
let tabIndex = 0
if (XUBAO_MERCHANTID == 44209499 || XUBAO_MERCHANTID == 44211651 || XUBAO_MERCHANTID == 44211562) {
tabIndex = 1
}
return tabIndex
}
/**百度经纬度转腾讯经纬度
* lng
* lat
*/
const bMapTransQQMap = (lng, lat) => {
let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
let x = lng - 0.0065;
let y = lat - 0.006;
let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
let lngs = z * Math.cos(theta);
let lats = z * Math.sin(theta);
return {
lng: lngs,
lat: lats
};
}
const Util = {
customerbehavior,
getSessionId,
setSessionId,
clearObjNull,
getUserInfo,
setUserInfo,
getSceneId,
deepClone,
throttle,
promise,
reportData,
getMockData,
debounce,
isEmptyObj,
setNavigationBarTitle,
judgeMerchantForXubao,
bMapTransQQMap
}
export default Util