/**
 * Copyright (c) 2013-Now http://aidex.vip All rights reserved.
 */
// 此处第二个参数vm，就是我们在页面使用的this，你可以通过vm获取vuex等操作
const install = (Vue, vm) => {
	// 通用请求头设定
	const ajaxHeader = 'x-ajax';
	const sessionIdHeader = 'Authorization';
	const rememberMeHeader = 'x-remember';
	
	// 请求参数默认配置
	Vue.prototype.$u.http.setConfig({
		baseUrl: vm.$store.state.apiurl,
		originalData: true, 
		// 默认头部，http2约定header名称统一小写 aidex
		header: {
      'Platform': 2,
			'content-type': 'application/x-www-form-urlencoded',
			'x-requested-with': 'XMLHttpRequest'
		}
	});
	
	// 请求拦截，配置Token等参数
	Vue.prototype.$u.http.interceptor.request = (req) => {
		const reqUrl = req && req.url ? String(req.url) : '';
		const isAbsolute = /^https?:\/\//i.test(reqUrl);
		const fullUrl = isAbsolute ? reqUrl : (vm.$store.state.apiurl + reqUrl);
		// 用 JSON 字符串输出，避免 HBuilderX 控制台对象被截断、点击 URL 跳浏览器
		console.log('request => ' + JSON.stringify({
			url: fullUrl,
			method: req.method,
			data: req.data,
			header: req.header
		}, null, 2));
		if (!req.header){
			req.header = [];
		}
		req.header["source"] = "app";
		
		// 默认指定返回 JSON 数据
		if (!req.header[ajaxHeader]){
			req.header[ajaxHeader] = 'json';
		}
		
		// 设定传递 Token 认证参数 aidex
		if (!req.header[sessionIdHeader] && vm.vuex_token){
			req.header[sessionIdHeader] = vm.vuex_token;
		}
		
		// 为节省流量，记住我数据不是每次都发送的，当会话失效后，尝试重试登录 aidex
		if (!req.header[rememberMeHeader] && vm.vuex_remember && req.remember){
			req.header[rememberMeHeader] = vm.vuex_remember;
			req.remember = false;
		}
		return req;
	}
	
	// 响应拦截，判断状态码是否通过
	Vue.prototype.$u.http.interceptor.response = async (res, req) => {
	    console.log('response', res);
	    console.log('response statusCode', res?.statusCode);
	    console.log('response data', res?.data);
	    console.log('response errMsg', res?.errMsg);
		
		// 处理401未授权状态码
		if (res.statusCode === 401) {
			vm.$u.toast('登录已过期，请重新登录');
			// 清除token和用户信息
			uni.removeStorageSync('token');
			vm.$u.vuex('vuex_token', '');
			vm.$u.vuex('vuex_user', {});
			// 跳转到登录页面
			uni.reLaunch({
				url: '/pages/sys/login/index'
			});
			return false;
		}
		// 非业务 JSON（如 404 page not found）
		if (res.statusCode && res.statusCode !== 200) {
			const msg = (res.data && res.data.msg) || `请求失败(${res.statusCode})`;
			vm.$u.toast(msg);
			return Promise.reject(new Error(msg));
		}
		console.log('res',res)
		if (!(res.data)){
			vm.$u.toast('未连接到服务器')
			return Promise.reject(new Error('未连接到服务器'));
		}
		if (typeof res.data !== 'object') {
			const msg = '接口返回异常';
			vm.$u.toast(msg);
			return Promise.reject(new Error(msg));
		}
		
		if(res.data.code !== 0) {
			vm.$u.toast(res.data.msg)
			return Promise.reject(new Error(res.data.msg))
		}
		let data = res.data.data;
		console.log('data',data)
		if (typeof data === 'object' && !(data instanceof Array)){
			if (data.token){
				console.log('token',data.token)
				vm.$u.vuex('vuex_token', data.token);
				if (data.user){
					vm.$u.vuex('vuex_user', data.user);
				}
				vm.$u.vuex('vuex_isAgent', data.isAgent);
			}
			if (data.result === 'login'){
				vm.$u.vuex('vuex_user', {});
				if (req.tryagain == undefined || req.tryagain){
					req.tryagain = false; req.remember = true;
					await vm.$u.http.request(req).then(res => {
						data = res;
					});
				}
				if (data.result === 'login'){
					if (!req.data.loginCheck){
						vm.$u.toast(data.msg);
					}
					req.tryagain = true;
				}
			}
		}
		
		if (res.header && res.header[rememberMeHeader]){
			let remember = res.header[rememberMeHeader];
			if (remember && remember != 'deleteMe'){
				vm.$u.vuex('vuex_remember', remember);
			}else{
				vm.$u.vuex('vuex_remember', '');
			}
		}
		
		return data;
	}
	
	// 封装 get text 请求
	vm.$u.getText = (url, data = {}, header = {}) => {
		return vm.$u.http.request({
			dataType: 'text',
			method: 'GET',
			url,
			header,
			data
		})
	}
	
	// 封装 post json 请求
	vm.$u.postJson = (url, data = {}, header = {}) => {
		console.log('header', header, url, vm.$store.state.apiurl)
		header['content-type'] = 'application/json';
		return vm.$u.http.request({
			url,
			method: 'POST',
			header,
			data
		})
	}
	// 封装 post json 请求
	vm.$u.putJson = (url, data = {}, header = {}) => {
		console.log('header', header, url, vm.$u)
		header['content-type'] = 'application/json';
		return vm.$u.http.request({
			url,
			method: 'PUT',
			header,
			data
		})
	}
	
	// 封装不使用 baseUrl 的请求（用于完整URL）
	vm.$u.putJsonFullUrl = (url, data = {}, header = {}) => {
		header['content-type'] = 'application/json';
		return new Promise((resolve, reject) => {
			uni.request({
				url,
				method: 'PUT',
				header: {
					...header,
					'Platform': 2,
					'x-requested-with': 'XMLHttpRequest',
					'Authorization': vm.vuex_token || ''
				},
				data,
				success: (res) => {
					console.log('res',res)
					if (res.data && res.data.code === 0) {
						resolve(res.data.data);
					} else {
						reject(res.data);
					}
				},
				fail: (err) => {
					reject(err);
				}
			});
		});
	}
}

export default {
	install
}
