import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const noticeError = (msg) => {
  // Message.error(msg)
  ElMessage({
    message: msg,
    type: 'error',
  })
}
const guid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}
const instance = axios.create({
  baseURL: '/',
  timeout: 100000,
  responseType: 'json',
})

// HTTP request拦截
instance.interceptors.request.use(
  (config) => {
    const method = config.url
    const params = config.data
    config.url = '/jsonrpc'
    config.data = {
      id: guid(),
      jsonrpc: '2.0',
      method,
      params,
      session: useUserStore().token,
      timestampin: Date.now().toString(),
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// HTTP response拦截
instance.interceptors.response.use(
  (response) => {
    if (response.data.error.code === 200) {
      return Promise.resolve(response.data.result)
    } else if (response.data.error.code === 401) {
      noticeError(response.data.error.message)
      useUserStore().logout()
      return Promise.reject(response.data.error.message)
    } else {
      noticeError(response.data.error.message)
      return Promise.reject(response.data.error.message)
    }
  },
  (error) => {
    noticeError(error.message)
    return Promise.reject(error)
  },
)

export default instance
