import axios from 'axios'
import router from '../../router'
import { useMessage } from 'naive-ui'
import { storage } from '@/utils/storage'
//@ts-ignore
import qs from 'qs'
import { useUserStore } from '@/store/modules/user'
import cleanDeep from 'clean-deep'

// 配置新建一个 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL as any,
  timeout: 200000,
  headers: { 'Content-Type': 'application/json' }
})

// 添加请求拦截器
service.interceptors.request.use(
  (config: any) => {
    // token
    const userStore = useUserStore()
    const tocken = userStore.getToken
    if (tocken && !config.noToken) {
      ;(<any>config.headers)['Authorization'] = tocken
    }
    // 是否进行数据过滤
    const noCleanDeep = config.noCleanDeep || false
    if (config.requestType === 'form') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      config.data = qs.stringify(noCleanDeep ? config.data : cleanDeep(config.data))
    } else if (config.requestType === 'multipart') {
      config.headers['Content-Type'] = 'multipart/form-data'
    } else {
      config.data = noCleanDeep ? config.data : cleanDeep(config.data)
    }
    config.params = noCleanDeep ? qs.stringify(config.params) : cleanDeep(config.params)
    return config
  },
  (error) => {
    // 对请求错误做些什么
    console.log(error)
    return Promise.reject(error)
  }
)

// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    const res = response.data
    if (res.code) {
      // `token` 过期或者账号已在别处登录
      if (res.code === 401 || res.code === 4001 || res.code == 403 || res.code == 5000) {
        console.log(res, 'res')
        storage.clear() // 清除浏览器全部临时缓存
        location.reload()
        return
      }
      if (res.code == 404) {
        router.push({ path: '/404' })
      }
      if (
        (((res.code < 200 && res.code != 100) || (res.code >= 300 && res.code != 100)) &&
          res.code != 0 &&
          res.code == 5200) ||
        res.code == 5400 ||
        (res.code >= 5000 && res.code < 6000) ||
        res.code == -1
      ) {
        let str = res.message || `请求失败code码为${res.code}`
        ;(window as any)['$message'].error(str)
        return Promise.reject(str)
      } else {
        return res
      }
    } else {
      return Promise.reject()
    }
  },
  (error) => {
    // 对响应错误做点什么
    if (error.message.indexOf('timeout') != -1) {
      ;(window as any)['$message'].error('网络超时')
    } else if (error.message == 'Network Error') {
      ;(window as any)['$message'].error('网络连接错误')
    } else {
      if (error) {
        ;(window as any)['$message'].error('请求错误')
      } else {
        ;(window as any)['$message'].error('接口路径找不到')
      }
    }
    return Promise.reject(error)
  }
)

// 导出 axios 实例
export default service
