request.js 5.34 KB
import {
  secretKey,
  djSecretKey,
  pathEnum,
  domain,
  djDomain,
  merchantDomain,
  index,
  sign
} from './http.js'
import util from '~/utils/util.js'
import {
  login
} from '~/utils/appFn/index'
const HOST = {
    scrm: domain,
    dj: djDomain,
    merchant:merchantDomain
}
let requestTimes = 0
/**接口 */
class Request {
  get(params, returnAll = false, isShowLoading = false, hostType = 'scrm') {
    return this.request('GET', params, returnAll, isShowLoading, hostType)
  }
  post(params, returnAll = false, isShowLoading = false, hostType = 'scrm') {
    return this.request('POST', params, returnAll, isShowLoading, hostType)
  }
  async request(RequestMethods, params, returnAll, isShowLoading, hostType = 'scrm') {
    wx.showNavigationBarLoading()
    let projectName = params.projectName
    if (!projectName) projectName = this.getRopProject(params.method)
    const path = pathEnum[projectName]
    params = await this.getData(params, hostType)
    return new Promise((resolve, reject) => {
      let header =
        RequestMethods === 'POST' ? {
          'content-type': 'application/x-www-form-urlencoded'
        } : {}
      const merchantId = wx.$storage.get('srcm_shopmall_merchant_id')
      if (merchantId) header.merchantId = merchantId
      if (isShowLoading) {
        requestTimes++
        wx.showLoading({
          title: '加载中'
        })
      }
      wx.request({
        url: `${HOST[hostType]}${path}router?method=${params.method}`,
        data: params,
        method: RequestMethods,
        header,
        dataType: 'json',
        responseType: 'text',
        success(response) {
          /**业务代码 */
          let {
            data: {
              code,
              message
            },
            data
          } = response
          if (returnAll) {
            resolve(data)
            return
          }
          if (code == 20 || code == 21) {
            wx.hideLoading()
            if (wx.$loginFlag) return
            if (!wx.$authStatus) {
              wx.$loginFlag = true
              login().then(() => {
                const thisPage = wx.$router.getPageInstance()
                if (thisPage.init && thisPage.data.userInfo) thisPage.init()
                if (thisPage.loginCallBack && thisPage.data.userInfo) thisPage.loginCallBack(thisPage.data.userInfo)
                if (thisPage.onRoute) thisPage.onRoute()
                thisPage.onLoad()
                thisPage.onShow()
                wx.$loginFlag = false
              }).catch(() => wx.$loginFlag = false)
            }
          } else {
            if (code == '0') {
              resolve(data.data)
            } else {
              console.log(data)
              wx.showToast({
                title: typeof message == 'string' ? message : JSON.stringify(message) || '系统异常',
                icon: 'none'
              })
              reject()
            }
          }
        },
        fail(error) {
          wx.hideLoading()
          console.error(`接口异常:`, error)
          wx.showToast({
            title: typeof error == 'string' ? error : JSON.stringify(error) || '系统异常',
            icon: 'error'
          })
          reject(error)
        },
        complete() {
          if (isShowLoading) {
            requestTimes--;
            if (requestTimes == 0) {
              wx.hideLoading()
            }
          }
          wx.stopPullDownRefresh()
          wx.hideNavigationBarLoading()
        }
      })
    })
  }
  reportTrack(params) {
    return this.request('POST', params, true)
  }
  async getData(params, hostType = 'scrm') {
    let projectName = params.projectName
    if (!projectName) projectName = this.getRopProject(params.method)
    else delete params.projectName
    let appKey = '48e5e13229b82c1b4e6e8c96151f0637'
    let secret = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
    if (secretKey[projectName]) {
      appKey = secretKey[projectName].appKey
      secret = secretKey[projectName].secret
    }
    if (hostType == 'dj') {
      appKey = djSecretKey.appKey
      secret = djSecretKey.secret
    }
    let {
      sessionId
    } = wx.$storage.get()
    if (!sessionId) sessionId = wx.$storage.get('scrm_shopmall_sessionId')
    let noSignAttr = []
    if (!params.sessionId && sessionId) params.sessionId = sessionId
    if (params.delSessionId) {
      delete params.sessionId
      delete params.delSessionId
    }
    if (params.noSignAttr) {
      noSignAttr = params.noSignAttr
      delete params.noSignAttr
    }
    params.v = '1.0.0'
    params.format = 'json'
    params.locale = 'zh_CN'
    params.source = 'dj-wechat'
    params.appKey = appKey
    return sign(params, secret, noSignAttr)
  }
  getRopProject(method) {
    const projectName = method.split('.')[2]
    return projectName
  }
  getMock() {
    const configModule = 'scrm-shopmall',
      env = {
        '1': 'develop',
        '2': 'test',
        '3': 'production',
        '4': 'beta'
      } [index],
      configUrl = `https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=${configModule}&env=${env}`
    return new Promise(resolve => {
      wx.request({
        url: configUrl,
        data: {},
        method: 'GET',
        header: {},
        dataType: 'json',
        responseType: 'text',
        success(response) {
          resolve(response.data)
        }
      })
    })
  }
}
export default new Request()