import App from '@/App.vue'
import store from '@/store/index.js'; //在js文件引入store模块
import Vue from 'vue'
import Vuex from 'vuex'
import {
	getSign
} from './appsecret.js';

function guid2() {
	function S4() {
		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
	}
	return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
let tiem;

function http(options) {
	return new Promise((resolve, reject) => {
		let settingFile = Vue.prototype.$siteinfo;
		let author = Vue.prototype.$author;
		let token = uni.getStorageSync('token') || '';
		let data = options.data || {};
		let time = parseInt(new Date().getTime() / 1000)
		data.version = settingFile.version;
		data.token = token;
		// #ifdef H5
		data.unid = Vue.prototype.$uuid;
		// #endif
		// #ifndef H5
		data.unid = settingFile.uniacid;
		// #endif
		var sdata={
			unid:data.unid,
			version:data.version
		};
		data.sign = getSign(sdata, time)
		data.time = time;
		let baseUrl = settingFile.siteroot;
		// #ifdef H5
		baseUrl = Vue.prototype.$siteinfo.h5_siteroot;
		// #endif
		let purl = baseUrl + options.url;
		if (author.we7_v2 == 1) {
			purl = baseUrl + '/addons/yq_breedingmall/index.php' + options.url;
		}
		// console.log('purl', purl)
		// console.log('data', JSON.stringify(data))
		var setting = {
			url: purl,
			data: data,
			method: options.method.toUpperCase() || 'GET',
			timeout: 60000,
			header: {
				'content-type': 'application/x-www-form-urlencoded', // from data
			},
			success(res) {
				if (res.data.status == 401) {
					console.log('进入了')
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 1000
					})
					store.commit('logout')
					uni.clearStorage()
					if (tiem) clearTimeout(tiem)
					tiem = setTimeout(() => {
						console.log('进入判断')
						uni.switchTab({
							url: '/pages/user/user'
						})
					}, 1000)

				}
				resolve(res.data);
				uni.hideLoading();
			},
			fail(err) {
				console.log('res', JSON.stringify(err))
				uni.showToast({
					icon: 'error',
					title: '网络超时!'
				})
				reject(err);
			},
		}
		if (options.files) {
			setting.files = Object.assign(setting.files, options.files);
		}
		if (options.header) {
			setting.header = Object.assign(setting.header, options.header);
		}
		uni.request(setting);
	}).catch(error => {
		console.log('error', JSON.stringify(error))
		reject(error)
	});
}
export default http;
