const Promise = require('../lib/bluebird')
const envInfo = require('../config/index').envInfo

class Http {
  constructor () {
    this.state = 'loaded'
    this.token = ''
    this.app = null
  }
  request ({
    url,
    data,
    header,
    method,
    dataType,
    responseType,
    channel,
    success,
    fail,
    complete
  }) {
    let path = ''
    if (channel) {
      path = channel + url
    } else {
      path = envInfo.ctx + url
    }
    if (/^http/gi.test(url)) {
      path = url
    }
    const that = this
    this.state = 'loading'
    return new Promise(function (resolve, reject) {
      wx.request({
        url: path,
        data,
        header,
        method,
        dataType,
        responseType,
        success: function (data, statusCode, header) {
          if (success) {
            resolve(data)
          } else {
            resolve(data)
          }
        },
        fail: function (data, statusCode, header) {
          if (fail) {
            reject(data)
          } else {
            reject(data)
          }
        },
        complete: function (data) {
          that.state = 'loaded'
          if (complete) {
            reject(data)
          } else {
            reject(data)
          }
          // complete ? complete.apply(this, arguments) : reject(data)
        }
      })
    })
      .then(this.checkStatus)
      .then(this.intercept)
      .then((data) => {
        if (success) {
          success(data)
        }
        return Promise.resolve(data)
      }, (data) => {
        if (fail) {
          fail(data)
        }
        return Promise.reject(data)
      })
      .catch(this.fail)
  }

  get (url, parmas) {
    return this.request({
      url,
      method: 'GET',
      header: {
        'buyer-token': this.getToken()
        // 'buyer-token': '3e15b819c551713ae210adc525da028b'
        // 'seller-token': 'f80d09122733517ea4a0c2628c4eb0e9'
      },
      data: parmas
    })
  }

  post (url, parmas, channel) {
    return this.request({
      url,
      method: 'POST',
      header: {
        'buyer-token': this.getToken()
        // 'buyer-token':'3e15b819c551713ae210adc525da028b'
        // 'seller-token': 'f80d09122733517ea4a0c2628c4eb0e9'
      },
      data: parmas,
      channel: channel
    })
  }

  checkStatus (resp) {
    let status = resp.statusCode
    if (status >= 200 && status < 300) {
      // return resp;
      return Promise.resolve(resp)
    } else {
      // var error = new Error(`status: ${resp.statusCode}`)
      // error.response = resp
      // return Promise.reject(resp.statusCode)
      return Promise.reject({
        state: resp.data.result,
        msg: resp.data.desc
      })
    }
  }

  intercept (res) {
    if (res.data && res.data.code === 401) {
      let baseUserInfo = wx.getStorageSync('_baseUserInfo')
      if (!baseUserInfo || baseUserInfo.isMember !== '1') {
        return Promise.reject({
          state: 401,
          msg: '登录过期'
        })
      } else {
        return Promise.reject({
          state: 402,
          msg: 'token失效'
        })
      }
    } else {
      return Promise.resolve(res)
    }
  }

  fail (error) {
    if (/timeout/.test(error.errMsg)) {
      wx.showModal({
        title: '网络不给力',
        content: '请求数据超时'
      })
    }
    if (error.msg && error.msg !='该用户尚未登录'){
      setTimeout(() => {
        wx.showToast({
          title: `${error.msg}`,
          icon: 'none',
          duration:2500
        })
      })
    }
    console.log(JSON.stringify(error))
    return Promise.reject(error)
  }

  getApp () {
    if (!this.app) {
      this.app = getApp()
    }
    return this.app
  }

  getToken () {
    // if (!this.token) {
    //   const token = wx.getStorageSync('token')
    //   this.token = token
    // }
    return wx.getStorageSync('token')
  }
}

export default Http
