import {
	toast,
	loading
} from "@/utils/common"

let url;
// #ifdef H5
url = '/api'
// #endif
// #ifdef MP-WEIXIN 
url = 'http://www.opsoul.com'
// #endif

export const uri = url;

const axios = {
	header() {
		return {
			// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
			// 'Cookie': uni.getStorageSync('token') ? `${uni.getStorageSync('token')}` : ''
		}
	},
	success(res) {
		if (res.data.code != "100000" && res.data.msg) {
			toast(res.data.msg);
			err(res.data.code);
			return res.data;
		} else {
			return res.data;
		}
	},
	fail() {

	},
	complete() {
		uni.hideLoading();
		uni.stopPullDownRefresh();
	},

	upload(url, data, showLoading = true) {
		if (showLoading) loading();
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: uri + '/common/upload',
				name: 'file',
				file: data,
				header: axios.header(),
				success: res => {
					resolve(axios.success(res));
				},
				fail: axios.fail,
				complete: axios.complete
			});
		})
	},

	post(url, data, showLoading = true, contentType = 'application/json;charset=utf-8') {
		if (showLoading) loading();
		console.log(data);
		return new Promise((resolve, reject) => {
			uni.request({
				url: uri + url,
				method: 'post',
				data: data,
				header: {
					// ...axios.header(),
					'Content-Type': contentType
				},
				success: res => {
					resolve(axios.success(res));
				},
				fail: axios.fail,
				complete: axios.complete
			});
		})
	},
	put(url, data, showLoading = true) {
		console.log(url);
		if (showLoading) loading();
		return new Promise((resolve, reject) => {
			uni.request({
				url: uri + url,
				method: 'put',
				data: data,
				header: axios.header(),
				success: res => {
					resolve(axios.success(res));
				},
				fail: axios.fail,
				complete: axios.complete
			});
		})
	},

	delete(url, data, showLoading = true) {
		console.log(url);
		if (showLoading) loading();
		return new Promise((resolve, reject) => {
			uni.request({
				url: uri + url,
				method: 'delete',
				data: data,
				header: axios.header(),
				success: res => {
					resolve(axios.success(res));
				},
				fail: axios.fail,
				complete: axios.complete
			});
		})
	},

	get(url, data) {
		return new Promise((resolve, reject) => {
			uni.request({
				url: uri + url,
				method: 'get',
				data: data,
				header: axios.header(),
				success: res => {
					resolve(axios.success(res));
				},
				fail: (e) => {

				},
				complete: () => {
					uni.stopPullDownRefresh();
				}
			})
		});
	}

};

function err(code) {
	if (code == 401) {
		uni.reLaunch({
			url: '/pages/login/login'
		})
	}
}

export default axios;