import axios from 'axios'
import md5 from 'js-md5'
import qs from 'qs'
import { Modal, notification } from 'antd'

function getToken() {
  return window.localStorage.getItem('kiwi.token') ? window.localStorage.getItem('kiwi.token') : ''
}

function showLoginModal() {
  Modal.warning({
    title: '登录状态已过期，请重新登录',
    onOk() {
      localStorage.removeItem('kiwi.gpt.token')
      location.href = '/login'
    }
  })
}

// 排序
function alphabeticalSort(a, b) {
  return a.localeCompare(b)
}

const httpRequest = axios.create({
  // timeout: 60000,
  withCredentials: true
})

// 请求拦截器
httpRequest.interceptors.request.use(
  config => {
    const token = getToken()
    // 应用设置
    const appId = 'TzEU5jPk2tu80266'
    const appSecret = '0a006048a4480481b18fef1405120b83'
    const timestamp = Math.floor(Date.now() / 1000)

    const signData = {
      ...config.data,
      appId,
      appSecret,
      timestamp,
      token,
      url: config.url
    }

    const signStr = qs.stringify(signData, { sort: alphabeticalSort })

    const salt = '&4F6g4Y6b5L4R9'
    const sign = md5(md5(signStr + salt))

    const defaultHeaders = {
      Authorization: token,
      AppId: appId,
      AppSecret: appSecret,
      Timestamp: timestamp,
      Sign: sign
    }
    config.headers = { ...config.headers, ...defaultHeaders }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
httpRequest.interceptors.response.use(
  response => {
    const { data } = response
    if (data.code === 401 || data.code === 403) {
      if (location.pathname !== '/login') {
        showLoginModal()
      }
      return Promise.reject(data)
    }
    if (data.code !== 200) {
      notification.error({ message: data.message || '请求错误' })
      return Promise.reject(data)
    }
    return data
  },
  error => {
    if (error.response) {
      const { status, data = {} } = error.response
      if (status === 401 || status === 403) {
        showLoginModal()
      } else {
        notification.error({ message: data.message || '请求错误' })
        console.error(`${status}: ${data.message}`)
      }
    } else {
      console.log(error)
    }
    return Promise.reject(error.response || error)
  }
)

export default httpRequest
