import service from './newRequest.js'
import store from '../store';
import md5 from 'js-md5'
import {
	saveUrl,
	interceptor
} from '@/utils/loginUtils.js';
// 请求完成后拦截
service.interceptors.response(
	response => {
		try {
			let res = response.data || {};
			// 解析字符串为数字
			if (res.status !== 200) {
				if (res.status == 410000) {
					// 存储当前地址
					saveUrl()
					// 调用退出登录方法清空用户信息
					store.commit('logout');
					// 判断是否开启强制登录
					uni.showModal({
						title: "您未登录！是否马上登录？",
						success: (e) => {
							if (e.confirm) {
								// 保存当前页面地址
								// 跳转页面
								interceptor()
							}
						}
					})
				} else {
					if (res.msg.indexOf('人数过多') == -1) {
						if (res.msg != '系统出现异常' && res.msg != '0' && res.msg != 'ok' && res.msg != '找不到订单') {
							uni.showToast({
								title: res.msg,
								duration: 1500,
								mask: true,
								icon: 'none',
							})
						}
					}

				}
				// return 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');
		if (config.data) {
			if (config.data.fuck) {
				let uid = config.data.fuck + ''
				let timestamp = new Date().getTime();
				timestamp = parseInt(timestamp / 1000)
				let secret =
					'0a989ebc4a77b56a6e2bb7b19d995d185ce44090c13e2984b7ecc6d446d4b61ea9991b76a4c2f04b1b4d244841449454';
				let action = config.data.fuck_name
				let key = 'fuckrml'
				let str1 = uid + timestamp + secret + action + secret + key + timestamp + uid + secret
				console.log(str1, '1234567899874351');
				str1 = md5(str1) + secret
				str1 = md5(str1)
				if (!config.header) {
					config.header = {
						"Authori-zation": 'Bearer ' + token,
						"key": key,
						'time': timestamp,
						'sign': str1
					}
				} else {
					// 添加key请求头
					config.header["Authori-zation"] = 'Bearer ' + token;
					config.header["key"] = key;
					config.header['time'] = timestamp;
					config.header['sign'] = str1;
				}
			} else {
				if (!config.header) {
					config.header = {
						"Authori-zation": 'Bearer ' + token,
					}
				} else {
					// 添加key请求头
					config.header["Authori-zation"] = 'Bearer ' + token;
				}
			}
		} else {
			if (!config.header) {
				config.header = {
					"Authori-zation": 'Bearer ' + token,
				}
			} else {
				// 添加key请求头
				config.header["Authori-zation"] = 'Bearer ' + token;
			}
		}

		return config
	},
	error => {
		// 错误处理
		console.log(error)
		return Promise.reject(error)
	}
)
let upFilse = service.upFilse;
let upFilse1 = service.upFilse1;
export {
	upFilse,
	upFilse1
};
export default service.open;
