import router from '@/router'
import axios, { AxiosInstance, AxiosError, AxiosResponse, AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import { recordValueTrim } from './tools'

const service: AxiosInstance = axios.create({
  timeout: 40000,
  baseURL: 'https://apinew.hldcloud.cn'
})
// 请求拦截
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = localStorage.getItem('yz-Token')
    if (token) {
      config!.headers!.Authorization = ('Bearer ' + token) as string
    }
    // 处理get请求参数值字符串左右空格
    if (config.params) {
      config.params = recordValueTrim(config.params)
    }
    // 处理post请求参数值字符串左右空格
    if (config.data) {
      if (config.data.constructor === Object) {
        const data = recordValueTrim(config.data)
        config.data = data
      }
    }
    if (config?.headers?.['Content-Type'] == 'application/x-www-form-urlencoded') {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  (error: AxiosError) => {
    // console.log(error)
    return Promise.reject()
  }
)

service.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status === 200) {
      if (response.data.success) {
        return response.data.result
      } else {
        // 用户未登录
        if (response.data.error.code === 401) {
          localStorage.removeItem('HDToken')
          return router.push('/login')
        }
        ElMessage.error(response.data.error.message)
        throw new Error(response.data.error.message)
      }
    } else {
      Promise.reject()
    }
  },
  (error: AxiosError) => {
    // console.log(error)
    ElMessage.error(error?.message)
    return Promise.reject()
  }
)

export default service
