import { BASE_URL } from '@/config'
import { storage, SESSION_KEY } from '@/utils/storage'

export const request = {
	async request(options) {
		const sessionKey = storage.get(SESSION_KEY)

		return new Promise((resolve, reject) => {
			uni.request({
				url: BASE_URL + options.url,
				method: options.method || 'GET',
				data: options.data,
				header: {
					'Content-Type': 'application/json',
					'Authorization': sessionKey ? `Bearer ${sessionKey}` : ''
				},
				success: async (res) => {
					if (res.statusCode === 401) {
						const { login } = await import('./auth')
						try {
							await login()
							resolve(this.request(options))
						} catch (e) {
							reject(e)
						}
						return
					}

					if (res.statusCode !== 200) {
						uni.showToast({
							title: res.data?.message || '请求失败',
							icon: 'none'
						})
						reject(new Error(res.data?.message || '请求失败'))
						return
					}

					resolve(res.data)
				},
				fail: (err) => {
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					})
					reject(err)
				}
			})
		})
	},

	get(url, params) {
		return this.request({ url, method: 'GET', data: params })
	},

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

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

	delete(url) {
		return this.request({ url, method: 'DELETE' })
	}
}
