import { BASE_API, TOKEN_KEY, SUCCESS_CODE } from '@/common/config.js'
import { showToast } from '@/common/chat-data.js'

export function getToken() {
	try {
		return uni.getStorageSync(TOKEN_KEY) || ''
	} catch (e) {
		return ''
	}
}

export function setToken(token) {
	try {
		uni.setStorageSync(TOKEN_KEY, token)
	} catch (e) {}
}

export function clearToken() {
	try {
		uni.removeStorageSync(TOKEN_KEY)
	} catch (e) {}
}

function buildUrl(url) {
	if (/^https?:\/\//.test(url)) return url
	// 已是完整业务路径（如 /api/v1/public/drafts），勿再拼 mp 前缀
	if (typeof url === 'string' && url.indexOf('/api/') === 0) return url
	const base = (BASE_API || '').replace(/\/$/, '')
	if (!base) return ''
	const path = url.startsWith('/') ? url : `/${url}`
	return `${base}${path}`
}

function handleUnauthorized() {
	clearToken()
	const pages = getCurrentPages()
	const current = pages[pages.length - 1]
	const route = current && current.route
	if (route !== 'pages/auth/login' && route !== 'pages/index/index') {
		uni.reLaunch({ url: '/packageA/auth/login' })
	}
}

/** 将 uni.request fail 的 errMsg 转为中文提示 */
function getRequestFailMessage(err) {
	const errMsg = (err && err.errMsg) || ''

	if (!errMsg) return '网络连接失败，请稍后重试'
	if (errMsg.includes('url not in domain list')) {
		return '请求域名未配置，请在开发者工具中关闭域名校验'
	}
	if (errMsg.includes('timeout')) return '请求超时，请稍后重试'
	if (errMsg.includes('abort')) return '请求已取消'
	if (errMsg.includes('ssl') || errMsg.includes('certificate')) {
		return '网络证书校验失败，请检查接口地址'
	}
	if (errMsg.includes('fail')) return '网络连接失败，请检查网络或服务器地址'

	return '网络异常，请稍后重试'
}

/**
 * 统一请求封装，适配后端 R<T> 响应：{ code, msg, data }
 */
export function request(options = {}) {
	const {
		url,
		method = 'GET',
		data,
		header = {},
		auth = true,
		showError = true
	} = options

	if (!url) {
		return Promise.reject(new Error('request url is required'))
	}

	const fullUrl = buildUrl(url)
	if (!fullUrl) {
		if (showError) showToast('API 地址未配置')
		return Promise.reject(new Error('BASE_API is empty'))
	}

	return new Promise((resolve, reject) => {
		const headers = {
			'Content-Type': 'application/json',
			...header
		}

		if (auth) {
			const token = getToken()
			if (token) {
				headers.Authorization = `Bearer ${token}`
			}
		}

		uni.request({
			url: fullUrl,
			method,
			data,
			header: headers,
			success(res) {
				const { statusCode } = res
				const body = res.data

				if (statusCode < 200 || statusCode >= 300) {
					if (showError) showToast('网络请求失败')
					reject(res)
					return
				}

				if (body && typeof body.code === 'number') {
					if (body.code === SUCCESS_CODE) {
						resolve(body.data)
						return
					}

					if (body.code === 401) {
						handleUnauthorized()
					}

					if (showError) showToast(body.msg || '请求失败')
					reject(body)
					return
				}

				resolve(body)
			},
			fail(err) {
				console.error('[request fail]', fullUrl, err)
				if (showError) showToast(getRequestFailMessage(err))
				reject(err)
			}
		})
	})
}

export function get(url, data, options = {}) {
	return request({ url, method: 'GET', data, ...options })
}

export function post(url, data, options = {}) {
	return request({ url, method: 'POST', data, ...options })
}

export function put(url, data, options = {}) {
	return request({ url, method: 'PUT', data, ...options })
}

export function del(url, data, options = {}) {
	return request({ url, method: 'DELETE', data, ...options })
}

export default request
