import service from './newRequest.js'
import store from '../store';
import {
	saveUrl,
	interceptor
} from '@/utils/loginUtils.js';
// 请求完成后拦截
service.interceptors.response(
	response => {
		try {
			const that = getApp();
			let res = response.data;
			// 解析字符串为数字
			if(res.code == 1 || res.code == 0){
				return res
			}else{
				if(res.code == 401){
					// 调用退出登录方法清空用户信息
					store.commit('user/logout');
					// 判断是否开启强制登录
					uni.showModal({
						title: that.$t('common.温馨提示'),
						content: that.$t('common.您未登录'),
						cancelText: that.$t('common.取消'),
						confirmText: that.$t('common.确定'),
						success: (e) => {
							// 判断是否点击确认按钮
							if (e.confirm) {
								// 保存当前页面地址
								saveUrl()
								// 跳转页面
								interceptor()
							}
						}
					})
				}
			}
		} catch (e) {
			console.log(e);
		}
	},
	error => {
		const that = getApp();
		uni.showToast({
			title: that.$t('common.加载错误请重试'),
			duration: 1500,
			mask: false,
			icon: 'none',
		})
		return Promise.reject(error)
	}
)

// 请求前拦截器
service.interceptors.request(
	config => {
		let token = uni.getStorageSync('tokens') || '';
		let lang = ''
		if(store.state.lang == 'en'){
			lang = 'en-us'
		}else{
			lang = 'zh-cn'
		}
		if (!config.header) {
			config.header = {
				"token":token,
				"lang":lang
			}
		} else {
			// 添加key请求头
			config.header["token"] =  token;
			config.header["lang"] =  lang
		}
		return config
	},
	error => {
		// 错误处理
		console.log(error)
		return Promise.reject(error)
	}
)
let upFilse = service.upFilse;
export {
	upFilse
};
export default service.open;
