import { useUserStore } from '@/stores/user'
import config from './config'
import utils from './utils'
import { convertUrlParams } from '@/utils/share'

const request = (method, url, data, opt) => {
	const userStore = useUserStore()
	opt.showLoading && uni.showLoading({
		title: opt.loadingTitle,
		mask: method === 'POST' ? true : false
	})
	return uni.request({
		method,
		url: utils.isHttp(url) ? url : config.apiBaseUrl + url,
		header: {
			Authorization: userStore.token || '',
			...opt.header
		},
		data
	}).then(res => {
		const { statusCode, data } = res
		const { code, errCode, msg, message, success } = data || {}
		if (statusCode === 401 && [100002, 100003].includes(code)) {
			uni.showToast({
				title: '登录已过期，即将重新登录...',
				icon: 'none'
			})
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1]
			const route = ('/' + currentPage.route) || '/pages/index/index'
			const options = Object.keys(currentPage.options).length ? currentPage.options : {}
			const params = convertUrlParams({ ...options, sharePath: route })
			setTimeout(() => {
				uni.redirectTo({
					url: `/pages/index/welcome${params}`
				})
			}, 1500);
			return data
		} else {
			if (code !== 200 && success !== true) {
				uni.showToast({
					title: message || msg || '请求失败',
					icon: 'none'
				})
			}
			return data
		}
	}).catch(err => {
		uni.showToast({
			title: err.msg || '请求失败',
			icon: 'none'
		})
	}).finally(() => {
		opt.showLoading && uni.hideLoading({ noConflict: true })
	})

}

const http = {}
const methods = ['GET', 'POST', 'PUT', 'DELETE']

methods.forEach(method => {
	http[method.toLowerCase()] = (url, data, options) => {
		const loadingTitle = method === 'GET' ? '加载中...' : '提交中...'
		const opt = Object.assign({
			loadingTitle
		},
			config.httpDefaultOption,
			options
		)

		if (opt.isAuth) {
			const userStore = useUserStore()
			if (!userStore.token) {
				// uni.navigateTo({
				// 	url: '/pages/login/login'
				// })
				// return Promise.reject({
				// 	msg: '无token'
				// })
			}
		}

		// 提交数据中值为undefined的改成空字符串
		if (typeof data === 'object') {
			for (let key in data) {
				if (data[key] === 'undefined') {
					data[key] = ''
				}
			}
		}

		return request(method, url, data, opt)
	}
})

export default http
