import { BASE_URL, TIMEOUT, DEFAULT_HEADERS } from './config'

const request = (options = {}) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('token') || ''
		const method = (options.method || 'GET').toUpperCase()
		const useParams = method === 'GET' || method === 'DELETE'
		const requestData = useParams ? (options.params || options.data || {}) : (options.data || {})
		
		uni.request({
			url: BASE_URL + options.url,
			method: method,
			data: requestData,
			header: {
				...DEFAULT_HEADERS,
				'Content-Type': 'application/json',
				'Authorization': token ? `Bearer ${token}` : '',
				...options.header
			},
			timeout: TIMEOUT,
		success: (res) => {
			if (res.statusCode !== 200) {
				return reject(res.data?.msg || res.data?.message || '网络请求异常')
			}
			const { code, msg, data, total, rows } = res.data
			if (code === 200) {
				resolve(rows !== undefined ? { total, rows } : data)
			} else if (code === 401) {
				uni.removeStorageSync('token')
				uni.reLaunch({ url: '/pages/login/index' })
				reject(msg || '未登录，请重新登录')
			} else {
				reject(msg || '操作失败')
			}
		},
		fail: (err) => {
			reject(err?.errMsg || err?.message || '网络异常，请稍后重试')
		}
		})
	})
}

export { request }
