const superagent = require('superagent')

class request {
   constructor({ proxy, userKey, message, timeout = 3000, interceptor } = {}) {
      this.proxy = proxy || '/_api'
      this.userKey = userKey || 'user'
      this.message = message
      this.timeout = timeout
      this.interceptor = interceptor // => (res, err) =>{ }
   }

   #getToken () {
      const sessionUser = sessionStorage.getItem(this.userKey)
      if (sessionUser) {
         const user = JSON.parse(sessionUser)
         return user?.token
      } else {
         return ''
      }
   }

   #request (url, method, options = {}) {
      const { query = {}, body = {}, params = {}, header = {}, timeout, tipSuccess, tipFail, tip } = options
      return new Promise((resolve, reject) => {

         let url_ = url
         if (Object.keys(params).length) {
            /* 拼接路由参数 */
            const regex = new RegExp(Object.keys(params).join('|'), 'g')
            url_ = url.replace(regex, matched => {
               return params[matched];
            })
         }

         superagent[method](url_?.startsWith('http') ? url_ : this.proxy + url_)
            .query(query)
            .send(body)
            .set({
               token: this.#getToken(),
               ...header,
            })
            .timeout(timeout || this.timeout)
            .then(res => {
               if (this.message && (tip ?? true !== false)) {
                  if (tipSuccess) {
                     this.message.success(tipSuccess)
                  } else if (tip) {
                     this.message.success(tip + "成功")
                  }
               }
               resolve(this?.interceptor(res, null) ?? res)
            })
            .catch(err => {
               if (this.message && tip !== false) {
                  const { message } = err?.response?.body ?? {}
                  if (message) {
                     this.message.error(message)
                  } else if (tipFail) {
                     this.message.error(tipFail)
                  } else if (tip) {
                     this.message.error(tip + "失败")
                  }
               }
               // this.#errBack(err.status)
               reject(this?.interceptor(null, err) ?? err)
            })
      })
   }

   get (url, options = {}) {
      return this.#request(url, 'get', options)
   }
   post (url, options) {
      return this.#request(url, 'post', options)
   }
   put (url, options) {
      return this.#request(url, 'put', options)
   }
   delete (url, options) {
      return this.#request(url, 'delete', options)
   }
}

module.exports = request
