import axios from 'axios'
import {ElMessage, ElMessageBox} from 'element-plus'
import Cookies from 'js-cookie'
import router from '@/router'
import store from '@/store'
import {startLoading, endLoading} from './loading'

const apiUrl = import.meta.env.VITE_BASE_URL

const service = axios.create({
    baseURL: apiUrl,
    withCredentials: true,
    timeout: 0,
})

/*axios请求拦截*/
service.interceptors.request.use(
    (config) => {
        if (typeof config.jdtTitle !== 'undefined') {
            store.commit('app/setJdt', {title: config.jdtTitle, isOpen: true, abnormalClosing: false})
        } else {
            startLoading()
        }
        if (store.getters['user/token']) {
            config.headers['token'] = store.state.user.token
        }
        return config
    },
    (error) => {
        endLoading()
        store.commit('app/closeJdt')
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    (response) => {
        endLoading()
        if (response.data.code === 200 || response.data.code === 0) {
            return response.data.data
        }
        if (response.data.code === 2002) {
            return response.data
        }
        if (response.data.code === 201) {
            ElMessage({
                type: 'success',
                title: '成功',
                duration: 2800,
                dangerouslyUseHTMLString: true,
                message: response.data.message,
                showClose: true,
                offset: 130,
            })
            return response.data.data
        }
        if (response.data.code > 1000 && response.data.code < 2000) {
            ElMessage({
                type: 'error',
                message: response.data.message,
                duration: 2000,
                showClose: true,
            })
        } else if (response.data.code > 2000 && response.data.code < 3000) {
            ElMessageBox.alert(response.data.message, '提示', {
                type: 'error',
                confirmButtonText: '确定',
                dangerouslyUseHTMLString: true,
            }).then(() => {
            })
        } else if (response.data.code > 3000 && response.data.code < 4000) {
            ElMessageBox.alert(response.data.message, '提示', {
                type: 'warning',
                confirmButtonText: '确定',
            }).then(() => {
                Cookies.remove('token')
                router.push('/login')
            })
        }
        if (response.data.data) {
            return Promise.reject(response.data)
        }
        return Promise.reject(response.data.message || '服务器内部错误')
    },
    (error) => {
        endLoading()
        store.commit('app/closeJdt')
        ElMessage({
            message: error,
            type: 'error',
            duration: 2500,
            showClose: true,
        })
        return Promise.reject(error)
    }
)

export default service
