import HttpRequest from '@/libs/axios'
import config from '@/config'
import { getToken, getUid } from '@/libs/util'
import store from '@/store'
import router from '@/router'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro
// const axios = new HttpRequest(baseUrl)
let axiosMap = {}
for (let key in baseUrl) {
  axiosMap[key] = new HttpRequest(baseUrl[key])
}

class IFetch {
  constructor (apiConfig, verify, alertServerErrMsg, clearAdminInfo) {
    if (!apiConfig) {
      throw new Error('apiConfig is required, please refer to the api_config_demo.js file')
    }

    if (!verify) {
      throw new Error('verify is required, please refer to the verify_demo.js file')
    }

    if (!alertServerErrMsg) {
      console.info('better alert better experience~')
      alertServerErrMsg = window.alert
    }

    this.apiConfig = apiConfig
    this.verify = verify
    this.alertServerErrMsg = alertServerErrMsg

    if (clearAdminInfo) {
      this.clearAdminInfo = clearAdminInfo
    }

    return this.doFetch.bind(this)
  }

  checkStatus (response) {
    if (response.status >= 200 && response.status < 300) {
      return response
    } else if (response.status === 401 && window.location.pathname !== '/') {
      let error = new Error('clearAdminInfo')
      throw error
    } else {
      let error = new Error(response.statusText)
      error.response = response
      throw error
    }
  }

  doFetch (config = {}) {
    if (config.apiName && this.apiConfig[config.apiName]) {
      config = { ...this.apiConfig[config.apiName], ...config }
    }

    const {
      type = 'mall',
      success,
      error,
      failed,
      complete,
      method = 'POST',
      notNeedVerify,
      dealReqData,

      dealUrl
    } = config

    let { url, postdata = {} } = config

    if (dealReqData) {
      postdata = dealReqData(postdata)
    }
    if (dealUrl) {
      url = dealUrl(url, postdata)
    }

    let headers = {
      'Content-Type': 'application/json',
      adminId: store.state.admin.uid,
      token: store.state.admin.token
    }

    let requestConfig = {
      method,
      headers,
      url
    }
    if (['POST', 'PUT', 'DELETE'].indexOf(method.toUpperCase()) >= 0) {
      requestConfig.data = postdata
    } else {
      requestConfig.params = postdata
    }

    // let r = axios.request(requestConfig).then(this.checkStatus)
    let r = axiosMap[type].request(requestConfig).then(this.checkStatus)
      .then(res => {
        complete && complete()
        if (notNeedVerify) {
          success && success(res.data)
          return null
        } else {
          let alertServerErrMsg = this.alertServerErrMsg
          let clearAdminInfo = this.clearAdminInfo
          return this.verify({ res, success, error, alertServerErrMsg, clearAdminInfo, url })
        }
      })
      .catch(e => {
        complete && complete()
        if (failed) {
          failed(e)
        } else {
          if (e.message === 'clearAdminInfo') {
            if (router.currentRoute.name !== 'login') {
              router.push({ name: 'login' })
            }
            // this.clearAdminInfo()
          } else {
            // this.alertServerErrMsg(e.message)
            this.alertServerErrMsg('系统异常，请您稍后重试~')
          }
        }
      })
    return r
  }
}

export default IFetch
