import axios from 'axios'
import { ElMessage } from 'element-plus'
import { ROOTPATH } from './httpUrl'

const apiClient = axios.create({
	baseURL: ROOTPATH,
	timeout: 10000
})

// 请求拦截器
apiClient.interceptors.request.use(
	config => {
		if (config.type === 'json') {
			config.headers['Content-Type'] = 'application/json'
		} else {
			config.headers['Content-Type'] = 'multipart/form-data'
		}

		// token
		const token = localStorage.getItem('token')
		if (token) {
			config.headers['token'] = token
		}

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

// 响应拦截器
apiClient.interceptors.response.use(
	response => {
		const res = response.data

		// ✅ 判断业务状态码
		if (res.code !== 0) {
			// 弹出提示信息
			ElMessage({
				message: res.msg || '请求失败',
				type: 'warning',
				duration: 2000
			})
		}

		// 无论成功失败都返回，方便前端继续逻辑判断
		return res
	},
	error => {
		// 网络错误、超时、服务器错误时
		ElMessage({
			message: error.message || '网络错误，请稍后再试',
			type: 'error',
			duration: 2000
		})

		return Promise.reject(error)
	}
)

export default apiClient
