import Request from 'luch-request'
import sysConfig from '@/config'
import store from '@/store'

const request = new Request()

// 错误码常量
const ERROR_CODES = {
	TOKEN_EXPIRED: 2000,
	TOKEN_INVALID: 2001
}

// HTTP状态码处理映射
const HTTP_ERROR_MESSAGES = {
	400: '请求参数错误',
	401: '未授权，请重新登录',
	403: '拒绝访问',
	404: '请求地址不存在',
	500: '服务器内部错误',
	502: '网络连接失败',
	503: '服务不可用',
	504: '网关超时'
}

request.setConfig((config) => {
	config.baseURL = sysConfig.baseURL
	config.header = {
		'content-type': 'application/json',
	}
	config.timeout = 30000
	config.sslVerify = false
	return config
})

request.interceptors.request.use((config) => {
	// 从本地存储获取 token
	const token = store.state.user.token || ''
	config.header.Authorization = `Bearer ${token}`

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

request.interceptors.response.use((response) => {
	const { code, message } = response.data || {}

	// 处理 token 过期或无效
	if (code === ERROR_CODES.TOKEN_EXPIRED || code === ERROR_CODES.TOKEN_INVALID) {
		uni.showToast({
			icon: 'none',
			title: message || '登录已过期，请重新登录',
			duration: 1500
		})
		setTimeout(() => {
			store.dispatch('userLogout')
		}, 100)
		return Promise.reject(response.data)
	}

	return response.data
}, (error) => {
	const { statusCode, errMsg } = error || {}
	const errorMessage = HTTP_ERROR_MESSAGES[statusCode] || errMsg || '请求失败，请稍后重试'

	if (statusCode === 401) {
		store.dispatch('userLogout')
	}

	return Promise.reject(error)
})

export default request
