import store from '@/store'

//H5版本
// #ifdef H5
import Fly from 'flyio/dist/npm/fly'
// #endif

//微信小程序和APP版本
// #ifndef H5
import Fly from 'flyio/dist/npm/wx'
// #endif

const request = new Fly();
import config from "./config.js"
//请求拦截
request.interceptors.request.use((request) => {
	// uni.showLoading({
	// 	title: '努力加载中...'
	// });
	request.baseURL = config.baseUrl;  
	const userToken = uni.getStorageSync('userToken');
	if(userToken){
		request.headers["Authorization"] =  'Bearer ' + userToken;
		request.headers["Clientid"] = config.clientId;
	} 
	// 防止缓存
	if (request.method === 'POST' && request.headers['Content-Type'] !== 'multipart/form-data') {
		request.body = {
			...request.body,
			_t: Date.parse(new Date()) / 1000
		}
	} else if (request.method === 'GET') {
			request.params = {
			_t: Date.parse(new Date()) / 1000,
			...request.params
		}
	}
	return request
})

//响应拦截
request.interceptors.response.use(function(response) { //不要使用箭头函数，否则调用this.lock()时，this指向不对 
	let errmsg = '';
	const data = response.data;
	if (!data || typeof data !== 'object') {
		errmsg = '服务器响应格式错误';
		uni.showToast({
			title: errmsg,
			icon: 'none'
		})
	} else {
		const code = data.code;
		let msg = "";
		if(code != 200){
			console.log('data.msg: ', data.msg)
			uni.showToast({
				title: data.msg,
				duration: 3000,
				icon: 'none'
			})
			if(code == 401){
				try{
					store.commit('logout');
					uni.reLaunch({
						url: '/pages/auth/passwordLogin'
					})
				} catch(err) {
					console.log(err);
				}
				
			}
		}
		
	}
	
	uni.hideLoading();
	return data; // 只返回业务数据部分	
}, function(err) {
	
	// console.log("error-interceptor:" + JSON.stringify(err))
	let errmsg = err.message;
	switch (err.status) {
		case 0:
			errmsg = "网络连接错误";
			uni.showToast({
				title: errmsg,
				icon: 'none'
			})
			break;
		case 401:
			store.commit('logout');
			uni.reLaunch({
				url: '/pages/auth/login'
			})
			break;
		default:
			uni.showToast({
				title: errmsg,
				icon: 'none'
			})
	}
})
/**
 * 封装post方法
 * @param url
 * @param data
 * @returns {Promise}
 */
function post(url, params) {
    return new Promise((resolve, reject) => {
        request.post(url, params)
            .then(response => {
                resolve(response);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}


function get(url, params) {
    return new Promise((resolve, reject) => {
        request.get(url, params)
            .then(response => {
                resolve(response);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}

function DELETE(url, params) {
    return new Promise((resolve, reject) => {
        request.delete(url, params)
            .then(response => {
                resolve(response);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}

function put(url, params) {
    return new Promise((resolve, reject) => {
        request.put(url, params)
            .then(response => {
                resolve(response);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}
export {
	request,
	post,
	get,
	DELETE,
	put
} 