import axios from 'axios'
import { Message } from 'element-ui'
import { getAppBaseUrl } from './host'
import store from '../../store'
import i18n from '../../i18n'

setTimeout(() => {
  console.log('---store', store.state.wallet.interfaceSignature)
}, 2000)

const service = axios.create({
  baseURL: getAppBaseUrl(),
  timeout: 30000,
  headers: {'Content-Type': 'application/json; charset=utf-8'}
})

service.interceptors.request.use(
  config => {
    if(!store.getters.walletConnected && !config.notNecessary){
      console.log('-----没有连接钱包');
      return;
    }
    
    const {wallet, network, } = store.state;
    
    let tokenObj = {
      chainId: network.chainId, 
      address: wallet.currentWalletAddress, 
      expireTime: wallet.expireTime,
      signature: wallet.interfaceSignature
    }
    
    // let tokenObj = {
      //   chainId: '1', 
      //   address: '0xf167a1c5c5fab6bddca66118216817af3fa86827', 
      //   expireTime: 1701590202,
      //   signature: '0x937bd5ea7c65b0d4081ddcbf6bbbfd67611ef9a8cf4c0d8e876a65d0e40ec63d7e871fbda25c74510ec99f935ada831e54b4e227b0f0067efee4f65713a3b6121b'
      // }
      
      config.headers
      // 设置请求的语言
      config.headers['locale'] = 'zh_CN'
      config.headers['token'] = JSON.stringify(tokenObj)
      if(!store.getters.walletConnected && config.notNecessary){
        delete config.headers['token']
      }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  res => {
    let data = res.data || {}
    if (data.code === 200 || (!data.code && data) || data.code === 20000) {  // 临时
      return data
    } else {
      if (data.code === 510) {
        Message({
          message: i18n.t('message3'),
          type: 'error',
          duration: 2 * 1000
        })
      } else if (data.code === 902) {
        commit('SET_CURRENT_WALLET_ADDRESS', '');
        commit('SET_INTERFACE_SIGNATURE', '');
      } else {
        Message({
          message: data.msg,
          type: 'error',
          duration: 2 * 1000
        })
      }
      return Promise.reject(data)
    }
  },
  error => {
    let msg = ''
    let data = error.data || {}
    console.dir('----error', error)
    if (error == 'Error: timeout of 5000ms exceeded') {
      msg = i18n.t('message4')
    } else {
      msg = data.msg
    }
    if(msg){
      Message({
        message: msg,
        type: 'error',
        duration: 2 * 1000
      })
    }
   
    return Promise.reject(error)
  }
)

export default service
