import tools from '@/tools/tools.js'
import store from '../store'
import config from '@/config.js'

let baseUrl = config.configPro.host
const httpRequest = (url, method = "get", data) => {
	let httpDefaultOpts = {
		url: baseUrl + url,
		data: data,
		method: method,
		header: {
			'Authorization': "Bearer " + uni.getStorageSync('token'),
			'X-Authorization': "Bearer " + uni.getStorageSync('refreshtoken'),
			'X-Requested-With': 'XMLHttpRequest',
			'content-type': 'application/json;charset=UTF-8',
		},
	}
	let promise = new Promise(function(resolve, reject) {
		if (httpDefaultOpts.url.indexOf("/api/device/detail") == -1) {
			uni.showLoading({
				title: '加载中...'
			})
		}
		uni.request(httpDefaultOpts).then(
			(res) => {
				uni.hideLoading()
				if (res[1].data.code == 401) {
					tools.msg(res[1].data.message)
					uni.clearStorageSync()
					uni.setStorageSync('token', "")
					uni.setStorageSync('iswxphone', true)
					store.commit("changeLogout", false);
					setTimeout(() => {
						uni.redirectTo({
							url: "/pageTwo/login/login"
						})
					}, 2000)
					return
				}
				if (res[1].statusCode != 200) {
					tools.msg(res[1].data.message)
					return
				}
				resolve(res[1].data)
			}
		).catch(
			(response) => {
				uni.hideLoading()
				reject(response)
			}
		)
	})
	return promise

};
const get = (url, data) => {
	data.appid = config.appid
	return httpRequest(url, 'get', data)
}

const post = (url, data) => {
	data.appid = config.appid
	return httpRequest(url, 'post', data)
}
export default {
	baseUrl,
	get,
	post
}