import store from '../store'
import tools from '@/tools/tools.js'
const accountInfo = wx.getAccountInfoSync();
const appid = accountInfo.miniProgram.appId
uni.setStorageSync('appid', appid)
let baseUrl = "https://irdhdt.com"

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) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				// console.log("https", res)
				// uni.hideLoading()
				if (res.data.code == 401) {
					uni.clearStorageSync()
					store.commit("changeLogout", false);
					uni.setStorageSync('token', null)
					uni.setStorageSync('sessionid', null)
					uni.setStorageSync('refreshtoken', null)
					uni.showToast({
						icon: "none",
						title: "登录后查看更多",
						duration: 2000
					});
					setTimeout(function() {
						uni.switchTab({
							url: "/pages/index/index"
						})
					}, 2000)
					return
				}
				// if (res[1].statusCode != 200) {
				// 	tools.msg(res[1].data.message)
				// 	return
				// }
				resolve(res.data)
			}
		).catch(
			(response) => {
				uni.hideLoading()
				reject(response)
			}
		)
	})
	return promise
};

function uploadFile(url, filePath) {
	let promise = new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseUrl + url,
			filePath: filePath.uploadpath,
			name: 'file',
			header: {
				'Authorization': "Bearer " + uni.getStorageSync('token'),
				'X-Authorization': "Bearer " + uni.getStorageSync('refreshtoken'),
			},
		}).then(res => {
			if (res.statusCode == 200) {
				var json = JSON.parse(res.data)
				if (json.code != 0) {
					tools.msg(json.message)
					return
				}
				resolve(json)
			}
		})
	});
	return promise
};
const get = (url, data) => {
	data.appid = appid
	data.sessionid = uni.getStorageSync('sessionid')
	return httpRequest(url, 'get', data)
}

const post = (url, data) => {
	data.appid = appid
	data.sessionid = uni.getStorageSync('sessionid')
	return httpRequest(url, 'post', data)
}
const upload = (url, filePath) => {
	return uploadFile(url, filePath)
}
export default {
	baseUrl,
	get,
	post,
	upload
}