import service from './newRequest.js'
import store from '../store';

import {
	saveUrl,
	interceptor
} from '@/utils/loginUtils.js';
import {
	unfreeze
} from '@/api/index.js';
// 请求完成后拦截
service.interceptors.response(
	response => {
		try {
			const that = getApp();
			let res = response;
			// 解析字符串为数字
			if (res.statusCode !== 200) {
				switch (res.statusCode) {
					case 401:
						// 调用退出登录方法清空用户信息
						store.commit('user/logout');
						// 判断是否开启强制登录
						// 保存当前页面地址
						saveUrl()
						// 跳转页面
						interceptor()
						break;
					case 402:
						that.$util.Tips({
							title: that.$t('base.请先绑定'),
							icon: 'error',
						}, '/pages/index/bind')
						break;
					case 408:
						uni.showModal({
							title: that.$t('base.温馨提示'),
							content: that.$t('base.请先解冻'),
							cancelText: that.$t('base.关闭'),
							confirmText: that.$t('base.确定'),
							success: res => {
								if (res.confirm) {
									const UNFREEZE = 'UNFREEZE' + (new Date()).getTime();
									ethereum.request({
										"method": "personal_sign",
										"params": [
											UNFREEZE,
											store.state.user.userInfo.address
										]
									}).then((res) => {
										unfreeze({
											sign: res,
											msg: UNFREEZE,
										}).then((res) => {
											uni.showToast({
												title: that.$t('base.解冻成功'),
												mask: false,
											})
											console.log(res, 'res');
										}).catch((res) => {

										})
									});
								}
							},
						});
						break;
					case 500:
						uni.showToast({
							title: "服务器500错误",
							duration: 1500,
							mask: false,
							icon: 'none',
						})
						// uni.showModal({
						// 	content: JSON.stringify(res),
						// 	success: res => {
						// 	},
						// });
						break;
					default:
						if (res.data.msg != '系统出现异常') {
							uni.showToast({
								title: res.data.msg,
								duration: 1500,
								mask: false,
								icon: 'none',
							})
						}
						break;
				}
				return Promise.reject(res.data)
			} else {
				if (res.data.code == 1) {
					return res.data
				} else {
					return Promise.reject(res.data)
				}
			}
		} catch (e) {
			console.log(e);
		}
	},
	error => {
		if (error) {
			console.log(error, 'error');
		}
		uni.showToast({
			title: "加载错误请重试",
			duration: 1500,
			mask: false,
			icon: 'none',
		})
		return Promise.reject(error)
	}
)

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