/**
 * HTTP请求封装 - 基于 uni.request
 * 风格参考 gym-manage-cuit 的 request.ts
 */

// 后端API基础地址
// H5端: 使用 /gym-api 前缀走vite代理（避免与源码 api/ 目录冲突），代理重写为 /api
// App端: 直接请求后端域名
// #ifdef H5
const BASE_URL = '/gym-api'
// #endif
// #ifndef H5
const BASE_URL = 'http://localhost:8084'
// #endif

// token存储key
const TOKEN_KEY = 'coach_access_token'
const REFRESH_TOKEN_KEY = 'coach_refresh_token'
const USER_INFO_KEY = 'coach_user_info'

function getToken() {
	return uni.getStorageSync(TOKEN_KEY) || ''
}

function getRefreshToken() {
	return uni.getStorageSync(REFRESH_TOKEN_KEY) || ''
}

function setToken(token) {
	uni.setStorageSync(TOKEN_KEY, token)
}

function setRefreshToken(token) {
	uni.setStorageSync(REFRESH_TOKEN_KEY, token)
}

function clearAuth() {
	uni.removeStorageSync(TOKEN_KEY)
	uni.removeStorageSync(REFRESH_TOKEN_KEY)
	uni.removeStorageSync(USER_INFO_KEY)
}

/**
 * 发起请求
 */
function request(options) {
	return new Promise((resolve, reject) => {
		const token = getToken()
		const header = {
			'Content-Type': 'application/json',
			...(options.header || {})
		}

		if (token) {
			header['Authorization'] = `Bearer ${token}`
		}

		uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: header,
			timeout: options.timeout || 15000,
			success: (res) => {
				const statusCode = res.statusCode
				if (statusCode >= 200 && statusCode < 300) {
					resolve(res.data)
				} else if (statusCode === 401) {
					// token过期，清除登录状态
					const isLoginRequest = options.url?.includes('/auth/login')
					if (!isLoginRequest) {
						clearAuth()
						uni.reLaunch({ url: '/pages/login/login' })
					}
					reject(res)
				} else {
					reject(res)
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '网络请求失败',
					icon: 'none',
					duration: 2000
				})
				reject(err)
			}
		})
	})
}

// 导出便捷方法
request.get = function(url, params = {}) {
	let query = ''
	if (Object.keys(params).length > 0) {
		const parts = []
		for (const key in params) {
			if (params[key] !== undefined && params[key] !== null && params[key] !== '') {
				parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
			}
		}
		if (parts.length > 0) {
			query = '?' + parts.join('&')
		}
	}
	return request({ url: url + query, method: 'GET' })
}

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

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

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

export { request, getToken, setToken, setRefreshToken, clearAuth, TOKEN_KEY, USER_INFO_KEY }
export default request
