import config from "../config/config.js";
import store from "../../store/index.js"
import msg from './message.js'
import statusCode from './statusCode.js'
import utils from './util.js'
import storage from './storage.js'
export default{
	config:{
		header: {
			TargetCode: 3
		},
		data: {},
		url: config.baseUrl,
		method: "POST",
		timeout: 10000
	},
	async request(options = {}){
		let token = await storage.getStorageSync('token') || ''
		options.data.token = token
		!options.data.isUnShowLoading && msg.showLoading(); // isUnShowLoading为true时不显示加载
		return new Promise((resolve,reject)=>{
			options.header = options.header || this.config.header
			options.timeout = options.timeout || this.config.timeout
			options.method = options.method || this.config.method
			options.data = options.data || this.config.data
			options.url = options.url
			options.success = (response) => {
				!options.data.isUnShowLoading && msg.hideLoading()
				if (response.statusCode === 404) {
					console.log(options.url);
					return msg.showToast('未知的请求!')
				}
				let res = response.data
				// 状态码处理
				// if(res.code == statusCode.OCCUPY_CODE) {
				// 	msg.showToast('账号信息已过期,请重新登录!')
				// 	storage.removeStorageSync('token')
				// 	return utils.openReLaunch('/pages/login/login')
				// }else if(res.code == statusCode.UNKNOW_CODE) {
				// 	if(res.msg == 'The token field is required.') {
				// 		if(options.url.indexOf('api/Account/UpdatePhoneOnline') === -1) {
				// 			msg.showToast('登录信息有误,请重新登录!')
				// 		}
				// 		storage.removeStorageSync('token')
				// 		return utils.openReLaunch('/pages/login/login')
				// 	}else {
				// 		console.log(options.url);
				// 		console.log(res)
				// 		return msg.showToast(`字段错误!\n${res.msg}`)
				// 	}
				// }else if(res.code !== 0) {
				// 	msg.showToast(`${res.msg}`)
				// 	return resolve(res);
				// }
				return resolve(res);
			}
			options.fail = (err) => {
				console.log('请求失败')
				console.log(err)
				// console.log(options)
				msg.showToast('请求失败,请检查网络是否正常!')
				msg.hideLoading()
				return reject(err)
			}
			uni.request(options)
		});
	},
	post2(url,data,options={}){
		// 于测试切换ip
		options.url = config.baseUrl + url;
		// console.log(options.url, 'url');
		// options.url = config.baseUrl + url;
		options.data = data;
		options.method = 'POST';
		return this.request(options)
	},
	post(url,data,options={}){
		// 于测试切换ip
		options.url = config.baseUrl + url;
		// console.log(options.url, 'url');
		// options.url = config.baseUrl + url;
		options.data = data;
		options.method = 'POST';
		return this.request(options)
	},
	get(url,data,options={}){
		options.url = config.baseUrl + url;
		options.method = 'GET';
		return this.request(options)
		
	}
}