jazz
2023-12-08 bf4dca5344dee1a84b75d9993f4dfc59de3f3ee9
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
/**
 * http事件委托
 *
 * udData 说明
 * udData.noloading 不需要请求
 * udData.fullData 使用 reponse 返回的对象进行 success 回调 (jun_http.js)
 * udData.nodomain 仅限于web端使用,不适用 baseUrl 前置(即当前网址根路径) (jun_http.js)
 * udData.nokey 不需要mpToken参数
 */
 
import Login from './jun_login'
// import { MessageBox, Message, Loading } from 'element-ui'
import fn from './fn'
import xioFn from '../utils/xio_fn.js'
import resStatusCode from './jun_httpStatus'
// 过滤 html
function filterHtml(str) {
  if (typeof str !== 'string') {
    return str
  }
  return str.replace(/\n|\t|\s/g, '').replace(/<script\s?.+><\/script>/g, '').replace(/<[^>]+>/g, '')
}
// 对象转url参数
function urlEncode(param, key, encode) {
  if (param == null) return ''
  var paramStr = ''
  var t = typeof (param)
  if (t === 'string' || t === 'number' || t === 'boolean') {
    paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param)
  } else {
    for (var i in param) {
      var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
      paramStr += urlEncode(param[i], k, encode)
    }
  }screenLeft
  return paramStr
}
 
/**
 * 使用 element-ui loading service
 */
// let loadingInstance // 定义loading变量
// // 开始loading
// function startLoading(){
//     loadingInstance = Loading.service({
//         lock: true,
//         text: '加载中...',
//         background: 'rgba(255,255,255,0.7)',
//         fullscreen: true,
//     })
// }
// // 结束loading
// function endLoading(){
//     loadingInstance && loadingInstance.close()
// }
 
// 开始loading
function startLoading(__request_option) {
  // console.log(request_option.udData)
  // request_option.udData && typeof request_option.udData.loading === 'function' && request_option.udData.loading()
  typeof window.appLoading === 'function' && window.appLoading()
}
 
// 结束loading
function endLoading(_request_option) {
  // request_option.udData && typeof request_option.udData.hideLoading === 'function' && request_option.udData.hideLoading()
  typeof window.appHideLoading === 'function' && window.appHideLoading()
}
 
// 请求前处理参数 - get
function getChangeRequestOption(get_option) {
  get_option = xioFn.httpOptionMd5Handle(get_option)
  if (!get_option.udData || !get_option.udData.nokey) {
    if (!get_option.params) {
      get_option.params = {}
    }
    // 补充参数
    // 需要 we_session
    var we_session = fn.getLocalStorage('we_session')
    if (we_session && we_session.we_session) {
      get_option.params.key = we_session.we_session
      get_option.params.mpToken = we_session.we_session
    }
  }
  return get_option
}
// 请求前处理参数 - post
function postChangeRequestOption(post_option) {
  // console.log('============================>', post_option)
  // adminToken
  // var adminToken = fn.getSessionStorage('adminToken')
  // var urlEncodes = {}
  // if (adminToken && (!post_option.udData || !post_option.udData.nokey)) {
  //   urlEncodes = { adminToken: adminToken, mpToken: adminToken }
  // }
  // // // 将请求参数放到链接后面
  // var paramsUrl = urlEncode(urlEncodes)
  // if (!/\?/.test(post_option.url)) {
  //   paramsUrl = paramsUrl.replace('&', '?')
  // }
  // post_option.url = post_option.url + paramsUrl
  
  // 请求头md5处理
  post_option = xioFn.httpOptionMd5Handle(post_option)
  if (!post_option.udData || !post_option.udData.nokey) {
    if (!post_option.data) {
      post_option.data = {}
    }
    // 补充参数
    // 需要 we_session
    var we_session = fn.getLocalStorage('we_session')
    if (we_session && we_session.we_session) {
      post_option.data.key = we_session.we_session
      post_option.data.mpToken = we_session.we_session
    }
  }
  return post_option
}
 
var httpEventCode = {
  code200() {
    // console.log(data, 200)
  },
  code404(_url) {
    // element-ui
    // Message.error('无法访问接口,状态404:' + url)
  },
  code500(_data, __url) {
    // element-ui
    // Message.error('请求失败,状态500:' + url)
  }
}
 
var g_login_counter = 0 // 登录请求次数
const g_LOGIN_MAX = 10 // 最大请求次数
 
var g_flag_loading = false // 是否已经loading
var g_flag_login_requested = false // 是否正在请求登录
var g_login_result = null // 登录返回数据
var g_flag_config_requested = false // 其余配置请求
var g_config_result = null // 配置请求返回
// 请求前
function beforeRequest(res) {
  // 开启loading
  if (!g_flag_loading && (!res.request_option.udData || !res.request_option.udData.noLoading)) {
    res.http_option.debug && console.log('jun_httpEvent beforeRequest loading')
    // wx.showLoading({
    //     title: '加载中',
    //     mask: true
    // })
    // loading
    startLoading(res.request_option)
    g_flag_loading = true
  }
 
  // 重置登录请求标记
  var we_session = fn.getLocalStorage('we_session')
  if (we_session && we_session.we_session) {
    g_flag_login_requested = false
  }
}
 
// 请求后
function afterRequest(_res) {
  // console.log('请求后')
}
 
// 处理返回数据
// @return {Object} 处理过的数据
function successChangeData(res) {
  return res
}
 
// 批量请求完成
function afterMultiRequests(request_option) {
  // console.log("多个请求结束之后")
  // 关闭loading
  if (g_flag_loading) {
    // wx.hideLoading()
    endLoading(request_option)
    g_flag_loading = false
  }
}
 
function updateKey(res, key) {
  // 更新 key 值
  if (res.request_option.method === 'GET' && (!res.request_option.udData || !res.request_option.udData.nokey)) {
    res.request_option.url = res.request_option.url.replace(/mpToken=[^&]*/g, `mpToken=${key}`)
  }
  if (res.request_option.method === 'POST' && (!res.request_option.udData || !res.request_option.udData.nokey)) {
    res.request_option.data.mpToken = key
  }
  return res
}
 
// 模拟数据处理流程
function mockFlow(res) {
  return new Promise(async(resolve, _reject) => {
    // 打印请求信息
    res.http_option.debug && console.log('模拟请求', res.request_option)
 
    var mockData = res.request_option.mockData || { code: 100, data: {}, message: 'success' }
 
    // 打印返回信息
    res.http_option.debug && console.log('模拟返回', { data: mockData })
    res.http_option.debug && console.log('开始模拟等待800ms')
    var timer = setTimeout(() => {
      clearTimeout(timer)
      // 关闭loading
      if (g_flag_loading) {
        // wx.hideLoading()
        endLoading(res.request_option)
        g_flag_loading = false
      }
      res.http_option.debug && console.log('结束模拟等待800ms')
      if (res.request_option.udData && res.request_option.fullData) {
        resolve({ data: mockData })
      } else {
        resolve(mockData)
      }
    }, 800)
  })
}
 
// 请求前处理流程
function beforeFlow(res) {
  return new Promise(async(resolve) => {
    // 预留请求前处理
    // 设置为true,下次处理跳过 beforeFlow,避免死循环
    res.request_option.skip_before_flow = true
    // 再次请求
    resolve(res.Request(res.request_option))
  })
}
 
// 预留其余处理
function configRequest() {
  return new Promise((resolve, reject) => {
    resolve({})
  })
}
 
// 登录处理
function appLogin(option = {}) {
  return new Promise((resolve, reject) => {
    // Login.checkLogin({
    //     force: !!option.forceLogin,
    //     callback: (key)=>{
    //         resolve(key)
    //     }
    // })
    Login.toLongUrl()
  })
}
 
// 请求后处理
function afterFlow(res) {
  return new Promise((resolve, reject) => {
    var data = res.res.data
    // console.log('0000000000000000000', res)
    // 登录超时
    if (
      (data && data.res && data.res.status == 2) ||
            (data && data.code == 603)
    ) {
      res.http_option.debug && console.log('登录超时,需要重新登录', res.res)
      // 登录超时,需要重新登录
      // 清空we_session
      // getApp().globalData.we_session = null
      // fn.removeLocalStorage('we_session')
      // resolve(retryLogin(res))
      // todo
      // // 清空登录凭证和用户数据
      // sessionStorage.clear()
      // // 未登录,跳转登录页面
      // this.$router.replace({ path: '/login' })
      return
    }
 
    // status不为0
    if (
      (data && data.res && data.res.status != 0) ||
            (data && data.code != 100)
    ) {
      if (data.res) {
        console.error('status不为0:' + (res.res.errMsg || ''), res.res)
        // 弹出提示
        // wx.showModal({
        //     title: '请求提示',
        //     content: data.res.errMsg || `请求有误,status=${data.res.status}`,
        //     confirmText: '确定',
        //     confirmColor: '#576B95',
        //     showCancel: false
        // })
 
        // element-ui
        // Message.error(data.res.errMsg || `请求有误,status=${data.res.status}`)
 
        // 根据status处理
        if (typeof resStatusCode['status' + data.res.status] === 'function') {
          resStatusCode['status' + data.res.status](data)
        }
      }
 
      if (typeof data.code !== 'undefined') {
        console.error('code不为100:' + data.code, data.msg, res.res)
      }
 
      reject(res.res)
      return
    }
 
    // status为空
    if (data && !data.res && typeof data.code === 'undefined') {
      console.error('status为空', res.res)
      let tips = ''
      if (res.res.statusCode == '500') {
        tips = '当前网络状态不佳,请稍后再试:statusCode=500;'
      } else if (res.res.statusCode == '200') {
        if (typeof res.data === 'string') {
          tips = filterHtml(res.data)
        }
        if (typeof res.data === 'object') {
          tips = filterHtml(JSON.stringify(res.data))
        }
        tips = '网络状况不佳,点击确定重试:statusCode=200;' + tips
      } else {
        tips = `连接服务器失败,点击确定重试:statusCode=${res.res.statusCode};`
      }
      // 请求提示
 
      // 小程序
      // wx.showModal({
      //     title: '请求提示',
      //     content: tips,
      //     confirmText: '确定',
      //     confirmColor: '#576B95',
      //     showCancel: false,
      //     success (res) {
      //         if (res.confirm) {
      //             // 点击确认后重新请求
      //             resolve(res.Request(res.request_option))
      //         }
      //     }
      // })
 
      // element-ui
      // MessageBox.alert(tips, '网络提示', {
      //     confirmButtonText: '确定',
      //     type: 'error'
      // }).then(()=>{
      //     resolve(res.Request(res.request_option))
      // }).catch(()=>{
      //     // 点击取消
      // })
      return
    }
 
    // 打印返回信息
    res.http_option.debug && console.log('返回', res.res)
    if (res.request_option.udData) {
      // 返回全部数据
      if (res.request_option.udData.fullData === true) {
        resolve(res.res)
      }
    }
    g_login_counter && (g_login_counter = 0)
    resolve(data)
  })
}
 
// 重新登录
async function retryLogin(res) {
  // 次数+1
  g_login_counter++
  return new Promise(async(resolve, _reject) => {
    // 等待登录
    var login_result = await appLogin({ forceLogin: true })
    // 登录失败
    if (!login_result && g_login_counter < g_LOGIN_MAX) {
      // 2秒后重试
      var timer = setTimeout(() => {
        clearTimeout(timer)
        resolve(retryLogin(res))
      }, 2000)
    }
    // 登录成功
    if (login_result) {
      // 更新key值
      res = updateKey(res, login_result)
      // 再次请求
      resolve(res.Request(res.request_option))
    }
  })
}
 
export default {
  httpEventCode,
 
  getChangeRequestOption,
  postChangeRequestOption,
  successChangeData,
 
  beforeRequest,
  afterRequest,
  afterMultiRequests,
 
  mockFlow,
  beforeFlow,
  afterFlow
}