import {
	toast,
	clearStorageSync,
	getStorageSync,
	useRouter
} from './utils'
import store from '@/store/index.js'
import RequestManager from '@/util/requestManager.js'

let BASE_URL = store.state.apiUrl;
// // #ifdef H5
// BASE_URL = process.env.NODE_ENV === 'production' ? BASE_URL : '/api';
// // #endif
const manager = new RequestManager()

const baseRequest = async (url, method, data = {}, loading = true) => {

	const u = getStorageSync('u');
	// let requestId = manager.generateId(method, url, data)
	// if (!requestId) {
	// 	console.log('重复请求')
	// }
	// if (!requestId) return false;
	var openid = uni.getStorageSync('openid');
	if (openid) {
		data.openid = openid;
	}
	return new Promise((reslove, reject) => {
		loading && uni.showLoading({
			title: '加载中...'
		})
		uni.request({
			url: BASE_URL + url,
			method: method || 'GET',
			header: {
				'token': u.token || '',
				'content-type': 'application/json'
			},
			timeout: 10000,
			data: data || {},
			complete: () => {
				uni.hideLoading()
				//manager.deleteById(requestId)
			},
			success: (successData) => {
				const res = successData.data;
				if (successData.statusCode == 200) {
					reslove(res)
				} else {
					toast('网络连接失败，请稍后重试')
					reject(res)
				}
			},
			fail: (msg) => {
				toast('网络连接失败，请稍后重试')
				reject(msg)
			}
		})
	})
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, loading) => baseRequest(api, method, data, loading)
})

export default request