request.js 5.64 KB
import {
	gscDomain,
  secretKey,
  domain,
  path,
  sign
} from './http.js'
// console.log(secretKey, 'secretKey')
import util from '~/utils/util.js'
import {
  envIndex
} from '~/config'
import qs from '~/utils/lib/qs'
/**接口 */
class Request {
  get(method, data, noSignAttr, requestPath, domainName, failTips) {
    return this.request('GET', method, data, noSignAttr, requestPath, domainName, failTips)
  }
  post(method, data, noSignAttr, requestPath, domainName, failTips) {
    return this.request('POST', method, data, noSignAttr, requestPath, domainName, failTips)
  }
	
  request(RequestMethods, method, data, noSignAttr = [], requestPath, domainName = 'dj', failTips = true) {
    let _this = this
    return new Promise((resolve, reject) => {
      wx.showNavigationBarLoading()
      wx.getNetworkType({
        success(res) {
          if (res.networkType == "none") {
            wx.hideLoading();
            wx.showToast({
              title: '网络异常',
              icon: "none",
            })
            return;
          }
          if (!data) data = {}
          let header =
            RequestMethods === 'POST' ? {
              'content-type': 'application/x-www-form-urlencoded'
            } : {};
          let url = `${domain[domainName]}${requestPath || path}`;
          // console.log(requestPath)
          if (method) {
            data = _this.getData(data, method, noSignAttr, domainName == 'merchants')
            url = `${domain[domainName]}${requestPath || path}?method=${method}`;
          } else {
            header = {
              'content-type': 'application/json'
            }
          }
          // console.log('reqData',data?.sessionId);
          // delete
          // if (data?.sessionId) {
          //   delete data?.sessionId
          // }
          wx.request({
            url,
            data,
            method: RequestMethods,
            header,
            dataType: 'json',
            responseType: 'text',
            success(response) {
              /**业务代码 */
              let {
                data: {
                  code,
                  message,
                  subErrors
                },
                data
              } = response

              if (code == 20 || code == 21) {
                let thisPage = wx.$router.getPageInstance()
                // console.log(thisPage);
                wx.hideLoading()
                if (thisPage.route != 'pages/wxLogin/wxLogin') {
                  getApp().login(true, '', url)
                }
              } else if (code == -1) {
                wx.showToast({
                  title: message || '网络请求失败',
                  icon: 'none'
                })
                resolve(data)
              } else {
                // util.debounce( getApp().test(true),500)
                // getApp().test()
                // console.log(data,'data');
                resolve(data)
              }
            },
            fail(error) {
              wx.hideLoading()
              console.error(`接口异常:${domain[domainName]}${requestPath || path}?method=${method}`, error)
              if (failTips) {
                wx.showToast({
                  title: '系统异常',
                  icon: 'error'
                })
              }
              reject(error)
            },
            complete() {
              wx.stopPullDownRefresh()
              wx.hideNavigationBarLoading()
            }
          })
        }
      })
    })
  }
  getData(data, method, noSignAttr, merchant) {
    let sessionId = util.getSessionId()
    if (sessionId) data['sessionId'] = sessionId
    // console.log(data,'request');
    data['v'] = '1.0.0'
    data['method'] = method
    data['format'] = 'json'
    data['locale'] = 'zh_CN'
    data['source'] = 'dj-wechat'

    // 兼容线上dj和scrm appkey和secret不一样的情况
    let apiName = data.method.split('.api')[0]
    // 为空报错
    if (!apiName) {
      throw new Error('apiName is null')
    }
    if (apiName.split('.').length > 1) apiName = apiName.split('.')[0]
    if (merchant) apiName = 'merchants'
    const appKey = secretKey[apiName].appKey
    const secret = secretKey[apiName].secret

    data['appKey'] = appKey
    let obj = sign(data, secret, noSignAttr)

    //data['sign'] = obj.sign;
    return obj
  }
  getMock(configModule = 'dj-car-boutique-work-wechat-miniapp') {
    const env = {
        '1': 'develop',
        '2': 'test',
        '3': 'production',
        '4': 'beta'
      } [envIndex],
      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)
        }
      })
    })
  }
	gscPost(url, data = {}, returnAll = false) {
    return this.gscRequest(url, data, 'POST', returnAll)
  }
	gscRequest(url, data = {}, method = 'GET', returnAll) {
    return new Promise((resolve, reject) => {
      wx.showNavigationBarLoading()
      wx.request({
        url: `${gscDomain}/gsc-agent-manage-biz/${url}`,
        data,
        method,
        success(response) {
          let {
            data
          } = response
          if (returnAll) {
            resolve(data)
            return
          }
          resolve(data.data)
        },
        fail(error) {
          wx.hideLoading()
          reject(error)
        },
        complete() {
          wx.stopPullDownRefresh()
          wx.hideNavigationBarLoading()
        }
      })
    })
  }
}
export default new Request()