import store from "../store/index.js";
import { baseUrl } from "./api.js";

import {
	doLogin
} from '@/common/api/login.js'
const HOST = location && location.origin 
export default () => {
	
	// 初始化请求配置
	uni.$u.http.setConfig((config) => {
		// #ifdef APP-PLUS
		config.baseURL = baseUrl;  // 测试地址
		// #endif
		
		// #ifdef H5
		config.baseURL = location.origin; /* 根域名 */
		// #endif
		return config
	});
	
	// 请求拦截
	uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
		config.data = config.data || {};
		config.baseURL = 'http://103.39.230.169:8085';  // 不使用请求代理  上线记得注释掉 ***********************************************************
		
		let apiToken = store.getters['api/getApiToken']
		
		let serverTime = (parseInt(Date.now() /1000) - store.getters['api/getServerTime'])
		
		config.header.ApiToken = apiToken
		config.header.timestamp = serverTime
		config.header.validate = store.getters['api/getValidate'] || ''
		config.header.safeverify = store.getters['api/getSafeCode'] || ''
		
		let ob = (config.method == 'GET'?config.params:config.data)
		
		// config.header.token = utils.makeSign(ob,serverTime)
		store.commit('api/setToken', config.header.token);
		uni.showLoading({
			mask: true,
			title:"加载中..."
		})
		return config
	}, config => { // 可使用async await 做异步操作
		return Promise.reject(config)
	})

	// 响应拦截
	uni.$u.http.interceptors.response.use((response) => {
		// 判断高防接口第一次被拉拦截
		if (response.data.data == undefined) {
			uni.showToast({
				mask: true,
				title: '太火爆了，请点击右上角刷新重试',
				icon: 'none'
			})
		}
		
		uni.hideLoading({});
		
		if (response.config.responseType == "arrayBuffer") {
			let base64 = "data:image/png;base64," + uni.arrayBufferToBase64(response.data)
			return base64
		}
		
		/* 对响应成功做点什么 可使用async await 做异步操作*/
		const data = response.data
		const custom = response.config?.custom
		if (data.code !== 200) {
			// 机器验证
			if (data.code === 8888) {
				 // 0 页内跳转 1 页外跳转
				if (data.type == 0) {
					uni.navigateTo({  
						url: `/pages/user/robot`
					});
				} else {
					// #ifdef APP-PLUS
					uni.navigateTo({
						url: `/pages/user/pay_webview/pay_webview?title=跳转页&urlLink=${encodeURIComponent(data.path)}`
					})
					// #endif
					
					// #ifdef H5
					window.location.href = data.path;
					// #endif
				};
			};
			
			if (data.code === 401) {
				let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
				let curRoute = routes[routes.length - 1].route //获取当前页面路由
				// 在微信小程序或是app中，通过curPage.options
				// 如果是H5，则需要curPage.$route.query（H5中的curPage.options为undefined)
				let curParam = routes[routes.length - 1].options || routes[routes.length - 1].$route.query; //获取路由参数
				// 拼接参数
				let param = ''
				let yqCode = ''
				for (let key in curParam) {
					param += '&' + key + '=' + curParam[key]
					if (key == 'yq_code') {
						yqCode = curParam[key]
					}
				}
				let _thisUrl = ''
				if (curRoute.indexOf('?') == -1) {
					_thisUrl = curRoute + (param ? ('?' + param) : '')
				} else {
					_thisUrl = curRoute + (param ? ('&' + param) : '')
				}
				
				uni.showToast({
					mask: true,
					title:data.msg,
					icon:'none'
				})
				setTimeout(e => {
					utils.goPath('/pages/login/login');
				},1000)
			} else if (data.code === 400) {
				uni.showToast({
					mask: true,
					title: data.msg,
					icon: 'none'
				})
			} else if (data.code === 0) {
				uni.showToast({
					mask: true,
					title: data.msg,
					icon: 'none'
				})
			}
			
			if (custom.toast !== false) {
				uni.$u.toast(data.msg)
			}
			
			console.log(response.config.url)
			return Promise.reject(data)
		}
		
		return data.data === undefined ? {} : data.data;
	}, (response) => {
		uni.showToast({
			mask: true,
			title: '服务器响应失败' + response.statusCode,
			icon: 'none'
		})
		return Promise.reject(response)
	})
}
