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) {
    let baseUserInfo = wx.getStorageSync('_baseUserInfo')
    
    if(baseUserInfo){
      return this.request({
        url,
        method: 'GET',
        header: {
          'buyer-token': this.getToken(),
          'tentacle-content': this.getTentacle(),
          // 'tentacle-content': '{"id":"621346354647797760","tentacleType":3,"tentacleId":"611969009872691200","contentType":1}'
        },
        data: parmas
      })
    } else {
      return this.request({
        url,
        method: 'GET',
        header: {
          // 'tunnel-token': 'aa8a1bfb7f6c5031d172d94b6574293ef954a6f2d4e16657da008e0cc15588feD', // 测试
          'tunnel-token' : 'd6db651f8b9c7db4176465accfc1c913843fd9ad328cd5f4fe201d918072c9e8', // 生产
          'tunnel-token' : 'brand1001', // 开发
          'tentacle-content': this.getTentacle(),
          // 'tentacle-content': '{"id":"621346354647797760","tentacleType":3,"tentacleId":"611969009872691200","contentType":1}'

        },
        data: parmas
      })
    }
    
  }

  post (url, parmas, channel) {
    let baseUserInfo = wx.getStorageSync('_baseUserInfo')
    let guideUserInfo = wx.getStorageSync('guidBaseInfo');
    // console.log('--------------header-----------------', this.getTentacle())
    // console.log('--------------token-----------------', this.getToken())

    if (baseUserInfo || guideUserInfo){
      return this.request({
        url,
        method: 'POST',
        header: {
          'buyer-token': this.getToken(),
          'tentacle-content': this.getTentacle()
          // 'tentacle-content': '{"id":"621346354647797760","tentacleType":3,"tentacleId":"611969009872691200","contentType":1}'
        },
        data: parmas,
        channel: channel
      })
    } else {
      return this.request({
        url,
        method: 'POST',
        header: {
          // 'tunnel-token': 'aa8a1bfb7f6c5031d172d94b6574293ef954a6f2d4e16657da008e0cc15588feD', // 测试
          'tunnel-token' : 'd6db651f8b9c7db4176465accfc1c913843fd9ad328cd5f4fe201d918072c9e8', // 生产
          'tunnel-token' : 'brand1001', // 开发
          'tentacle-content': this.getTentacle()
          // 'tentacle-content': '{"id":"621346354647797760","tentacleType":3,"tentacleId":"611969009872691200","contentType":1}'
        },
        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')
  }

  getTentacle(){
    let time = Date.parse(new Date())
    let TIME_EXPIRATION = wx.getStorageSync('TIME_EXPIRATION')
    let storage = wx.getStorageSync('TENTACLE_CONTENT') , tentacle = '';

    if (storage){
      tentacle = storage.obj;
    }
    if (tentacle && TIME_EXPIRATION > time){
      wx.setStorageSync('TIME_EXPIRATION', time + 30*60*1000);
      return JSON.stringify(tentacle);
    }else{
      // wx.removeStorageSync('TENTACLE_CONTENT')
      // wx.removeStorageSync('TIME_EXPIRATION')
    }

    return JSON.stringify(null);
  }
}

export default Http
