import axios from 'axios'
import Qs from 'qs'
import { MessageBox } from 'element-ui'
import { Cookie } from '../util/util'
import $store from '@/store'
import API from '@/api'

let host = ''
if (window.location.port == 8080||/test|webdev/.test(location.host)) {
  host = 'https://test-bptp.eosget.io'
} else {
  host = '//baccarat.eosget.io'
}

let ax = axios.create({
  baseURL: host,
  headers:{'Content-Type':'application/x-www-form-urlencoded'},
  transformRequest: [function (data) {
    data = Qs.stringify(data)
    return data
  }],
  transformResponse: [],
  withCredentials: true,
})

ax.interceptors.request.use(
  config => {
    //添加登陆态
    if(config.needLogin) {
      if($store.state.account == 'NO_LOGINING') {
        $store.dispatch('doScatterLogin').then((account) => {
          return handleConfig(config);
        })
      } else {
        return handleConfig(config);
      }
    } else {
      return config
    }
  },
  error => {
    return Promise.reject(error);
  }
)

//拦截器处理错误
ax.interceptors.response.use(
  response => {
    if (response.data.result === 1 || response.data.code == -90001) {   //返回200时请求成功
      return Promise.resolve(response)
    } else {
      if(response.data.code === -5) { //code为-5是登录态失效
        doLogin();
        return Promise.resolve(response)
      } else {
        // 请求出错提示错误
        MessageBox.confirm(response.data.msg, 'Error', {
          center: true,
          showCancelButton: false,
          showConfirmButton: false,
          callback () {}
        })
        return Promise.reject(response)
      }
    }
  },
  error => {
    return Promise.reject(error)
  }
)

function handleConfig (config) {
  let authData = {
    account: Cookie.getCookie('account') || $store.state.account.name,
    player: Cookie.getCookie('account') || $store.state.account.name,
    token: Cookie.getCookie('token') || ''
  }

  if(config.method == 'post') {
    config.data = Object.assign(config.data, authData);
  } else if(config.method == 'get') {
    config.params = Object.assign(config.params, authData);
  }
  return config
}

/**
 * 获取用户公钥
 * @param {string} name 用户名 
 */
async function getPubKey (name) {
  return new Promise((resolve, reject) => {
    let publicKey
    if(name) {
      $store.state.eos.getAccount(name).then(data => {
        const perms = JSON.parse(JSON.stringify(data.permissions))
        perms.forEach(v => {
          if (v.perm_name == "active") {
            publicKey = v.required_auth.keys[0].key
          }
        })
        resolve(publicKey)
      })
    } else {
      reject('account is not define')
    }
  })
}

/**
 * 生成随机数
 * @param {string} name 用户名 
 */
async function getRandom(name) {
  return new Promise((resolve, reject) => {
    API.user.getRandom({
      account: name
    }).then(data => {
      resolve(data.data.data)
    })
  })
}

async function doLogin() {
  let account = $store.state.account;
  let name = account.name;
  let [random, pubkey] = await Promise.all([getRandom(name), getPubKey(name)])
  return new Promise((resolve, reject) => {
    $store.state.scatter.getArbitrarySignature(pubkey, random, 'Need Login').then(sign => {
      let param = {
        account: account.name,
        sign,
        pubkey,
        data: random
      }
      API.user.login(param).then(({data}) => {
        if(data.result == 1) {
          let account = data.data.account
          let token = data.data.token
          Cookie.setCookie('account', account)
          Cookie.setCookie('token', token)
          resolve(data)
        } else {
          reject(data.msg)
        }
      })
    }).catch(err => {
      reject(err)
    })
  })  
}

export default ax