import qs from 'qs'
const ToolClass = {
  DemoImg () {
    return 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1597250549302&di=7483208ccacdeb49188263423a9c8316&imgtype=0&src=http%3A%2F%2Ft9.baidu.com%2Fit%2Fu%3D3363001160%2C1163944807%26fm%3D79%26app%3D86%26f%3DJPEG%3Fw%3D1280%26h%3D830'
  },
  ReplaceURLParams (url, params) {
    const args = { ...(params || {}), org: 'MQ' }
    return Object.keys(args).reduce((acc, k) => { // 此方法对每个元素进行处理
      const re = new RegExp(`:${k}(?!w)`, 'i')
      return acc.replace(re, args[k])
    }, url)
  },
  WxRequest (config) { // 网络请求
    let _that = this
    let urlData = qs.stringify(config.urlData)
    let queryData = qs.stringify(config.queryData)
    if (config.url.indexOf(':') > -1) {
      if (typeof config.urlData === 'object') {
        config.url = this.ReplaceURLParams(config.url, config.urlData)
      } else {
        config.url = config.url.slice(0, config.url.indexOf(':')) + urlData
      }
    }
    if (queryData) {
      config.url += '?' + queryData
    }
    let Header = {}
    if (wx.getStorageSync('token') !== '') { // 本地获取token
      Header['X-Authorization-JWT'] = wx.getStorageSync('token')
    }
    wx.request({
      url: `https://dev.fangdeal.cn/liyuanhui/wx${config.url}`,
      method: config.method,
      ...(config.data || {}),
      header: { ...Header },
      success: (res) => {
        if (res.header['X-Authorization-JWT'] !== undefined) { // 更新本地存储token
          wx.setStorageSync('token', res.header['X-Authorization-JWT'])
        }
        if (res.data.code - 0 === 1001) { // token失效
          wx.login({ // 微信获取code
            success (subRes) {
              wx.request({ // 登录获取token
                url: `https://dev.fangdeal.cn/liyuanhui/wx/login?code=${subRes.code}`,
                method: `post`,
                success: (cRes) => {
                  if (cRes.header['X-Authorization-JWT'] !== undefined) { // 更新本地存储token
                    wx.setStorageSync('token', cRes.header['X-Authorization-JWT'])
                    _that.WxRequest(config) // 获得token之后重新请求接口
                  }
                }
              })
            }
          })
        }
        if (config.success !== undefined && res.data.code - 0 === 1000) {
          config.success(res)
        }
        if (config.error !== undefined && res.data.code - 0 !== 1000) {
          config.error(res)
        }
      },
      fail: (res) => {
        if (res.header['X-Authorization-JWT'] !== undefined) { // 更新本地存储token
          wx.setStorageSync('token', res.header['X-Authorization-JWT'])
        }
        if (res.data.code - 0 === 1001) { // token失效
          wx.navigateTo({ url: '../../pages/SignIn/index' })
        }
        if (config.error !== undefined) {
          config.error(res)
        }
      }
    })
  }
}

export default ToolClass
