import {
	useUserStore,useLangStore
} from '@/store/index.js';
import {
	navTo
} from '@/utils/navigate.js'
import {
	apihost
} from '@/api/index.js'

export default class Request {
	http(param) {
		let url = param.url;
		let method = param.method;
		let header = param.header || {
			'content-type': "application/json"
		};

		const userStore = useUserStore()
		const langStore = useLangStore()
		let token = userStore.token
		if (token != undefined || token != "") {
			header = Object.assign(header, {
				Authorization: token
			})
		}

		let data = Object.assign(param.data);
		data = Object.assign(data, {
			"language": langStore.lang
		})
		let requestUrl = apihost + url;


		// console.log('------------http----------')
		// console.log(`url:${url}`)
		// console.log(`method:${method}`)
		// console.log(`header:${JSON.stringify(header)}`)
		// console.log(`data:${JSON.stringify(data)}`)
		// console.log('------------http----------')
		return new Promise((resolve, reject) => {
			uni.request({
				url: requestUrl,
				data: data,
				method: method,
				header: header,
				success: (res) => {
					console.log()
					if (res.data.code === 0) {
						console.log('请求成功！');
						// console.log(`resp:${JSON.stringify(res.data)}`)
						resolve({
							success: true,
							data: res.data.data
						});
						return true
					} else {
						if (res.data.code === 61) {
							console.log('token过期');
							navTo('/pages/login/login')
							return false
						}
						console.log('其他错误', res);
						resolve({
							success: false,
							error: '其他错误',
							code: res.data.code,
							data: res.data,
						});
						return false;
					}

				},
				fail: (err) => {
					console.log('请求失败');
					return false;
				},
			})
		})
	}
}

let request = new Request().http

export function get(url, data, header) {
	return request({
		url: url,
		method: 'GET',
		data: data,
		header: header
	})
}

export function post(url, data, header) {
	return request({
		url: url,
		method: 'POST',
		data: data,
		header: header,
	})
}