
import Taro from '@tarojs/taro'

const logger = Taro.getRealtimeLogManager()

const object2QueryString = (params) => {
  if (!params) return ;

  const keys = Object.keys(params)
  const arr = keys.map((key) => {
    const val = params[key]
    return `${key}=${encodeURIComponent(val)}`
  })

  return arr.join('&')
}

export default (url, options) => {
  const { params, skipError, header, ...leftOptions } = options || {}
  const queryStr = object2QueryString(params)

  const urlWithParams = queryStr ? `${url}?${queryStr}` : url;
  const nwUrl = `${HOST}/api/wx${urlWithParams}`

  const authToken = Taro.getStorageSync('token')
  const tokenHeader = authToken ? { 'X-Authorization-JWT': authToken } : {}
  const nwHeader = {
    ...(header || {}),
    ...tokenHeader,
  }

  return new Promise((resolve, reject) => {
    Taro.request({
      ...leftOptions,
      url: nwUrl,
      header: nwHeader,
      success: (res) => {
        const { code, message, data, token } = res.data

        if (token || data?.token) {
          Taro.setStorage({ key: 'token', data: token || data?.token })
        }

        if (code === 1000) {
          resolve(data)
        } else {
          console.error(res)

          logger.error(nwUrl)
          logger.error(options)
          logger.error(res)

          if (!skipError) {
            Taro.showToast({
              title: message,
              icon: 'none',
            })
          }

          reject(message.indexOf('java') > -1 ? '系统内部错误' : message)
        }
      },
    
      fail: (err) => {
        console.error(err)

        logger.error('网络错误')
        logger.error(nwUrl)
        logger.error(options)
        logger.error(err)

        const message = err.message || err.errMsg || err

        if (!skipError) {
          Taro.showToast({
            title: message,
            icon: 'none',
          })
        }

        reject(message)
      }
    })
  })


}
