import service from './newRequest.js'
import store from '../store';
import md5 from './md5.js'
import sha1 from './sha1.js'
import {
	saveUrl,
	interceptor
} from '@/utils/loginUtils.js';
// 请求完成后拦截
service.interceptors.response(
	response => {
		try {
			console.log(response,'response+++++++++++++++')
			let res = response.data;
			console.log(res.code,'res.code++++++++++++++++++')
			// 解析字符串为数字
			if (res.code != 1) {
				if (res.code == 401) {
					console.log('登录过期')
					// 存储当前地址
					saveUrl()
					// 调用退出登录方法清空用户信息
					store.commit('user/logout');
					// 判断是否开启强制登录
					// 跳转页面
					uni.showModal({
						title: "您未登录！是否马上登录？",
						success: (e) => {
							if (e.confirm) {
								// 保存当前页面地址
								interceptor()
							}
						}
					})
				} else {
					if (res.msg != '系统出现异常') {
						uni.showToast({
							title: res.msg,
							duration: 1500,
							mask: false,
							icon: 'none',
						})
					}
				}
				console.log(res,'扑街');
				return Promise.reject(new Error(res.msg || 'Error'))
			} else {
				return res
			}
		} catch (e) {
			console.log(e);
		}
	},
	error => {
		uni.showToast({
			title: "加载错误请重试",
			duration: 1500,
			mask: false,
			icon: 'none',
		})
		return Promise.reject(error)
	}
)

// 请求前拦截器
service.interceptors.request(
	config => {
		let token = uni.getStorageSync('token') || '';
		let sign_time = new Date().getTime();
		let sys_appid = 'xgred20211207'
		let sys_appsecret = '70211202dergxxgred20211207'
		let sys_token = md5(md5(sys_appid + sys_appsecret) + sign_time + sha1(sys_appsecret + sign_time))

		if (!config.header) {
			config.header = {
				"sys-appid": sys_appid,
				"sign-time": sign_time,
				"sys-token": sys_token,
				"token": token
			}
		} else {

			config.header['sys-appid'] = sys_appid
			config.header['sign-time'] = sign_time
			config.header['sys-token'] = sys_token
			config.header['token'] = token
		}
		return config
	},
	error => {
		// 错误处理
		console.log(error)
		return Promise.reject(error)
	}
)
let upFilse = service.upFilse;
export {
	upFilse
};
export default service.open;
