import axios from 'axios'
import { ElMessage } from 'element-plus'

const request = axios.create({
	baseURL: '/api',
	timeout: 20000,
})

request.interceptors.response.use(
	(response) => {
		if (response.config.responseType === 'blob') {
			return response.data
		}

		const payload = response.data

		if (typeof payload?.code !== 'undefined') {
			if (payload.code === 0) {
				return payload.data
			}

			ElMessage.error(payload.message || '请求失败')
			return Promise.reject(new Error(payload.message || '请求失败'))
		}

		return payload
	},
	(error) => {
		const message = error?.response?.data?.message || error.message || '网络异常'
		ElMessage.error(message)
		return Promise.reject(error)
	},
)

export default request