export const request = async (type, data = {}, config = {}) => {
  const needUsername = config.needUsername || false
  const loadMask = config.loadingMask === false ? false : true
  if (loadMask) {
    wx.showLoading()
  }
  let transData = {
    ...data
  }
  if (needUsername) {
    const userInfo = getApp().globalData.userInfo || {}
    if (!userInfo || !userInfo.username) {
      return wx.navigateTo({
        url: '/pages/login/index',
      })
    }
    transData.username = userInfo.username
  }
  const [name, type1] = type.split("/")
  return new Promise((resolve, reject) => {
    wx.cloud.callFunction({
      name,
      data: {
        type: type1,
        data: transData,
      },
      success: (res) => {
        wx.hideLoading()
        if (res.result.success) {
          resolve(res.result)
        } else {
          reject(res)
          wx.showToast({
            title: res.result.msg || "错误",
            icon: "none"
          })
        }
      },
      error: (res) => {
        wx.hideLoading()
        wx.showToast({
          title: res.message || "错误",
          icon: "none",
        })
        reject(res)
      },
    })
  })

}