import tools from '@/tools/tools.js'
import store from '../store'
import config from '@/config.js'
let baseUrl = "https://tc.pcxbc.com/"
const httpRequest = (url, method = "get", data) => {
	let httpDefaultOpts = {
		url: baseUrl + url,
		data: data,
		method: method,
		header: {
			'X-Requested-With': 'XMLHttpRequest',
			'content-type': 'application/json;charset=UTF-8',
		},
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				uni.hideLoading()
				if (res[1].data.code == 20001) {
					uni.clearStorageSync()
					uni.setStorageSync('token', null)
					setTimeout(function() {
						uni.reLaunch({
							url: "/pageTwo/login/login"
						})
					}, 2000)
					return
				}
				if (res[1].statusCode != 200) {
					tools.msg(res[1].data.msg)
					return
				}
				resolve(res[1].data)
			}
		).catch(
			(response) => {
				uni.hideLoading()
				reject(response)
			}
		)
	})
	return promise

};

function uploadFile(url, filePath) {
	config.log
	let promise = new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseUrl + url,
			filePath: filePath.uploadpath.tempFilePath,
			name: 'image',
			formData: {
				token: uni.getStorageSync('token') // 其他表单数据，如 token
			},
		}).then(res => {
			if (res[1].statusCode == 200) {
				var json = JSON.parse(res[1].data)
				if (json.code != 0) {
					tools.msg(json.message)
					return
				}
				resolve(json)
			}
		})
	});
	return promise
};
const get = (url, data) => {
	data.token = uni.getStorageSync('token') || ''
	return httpRequest(url, 'get', data)
}

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