import { BASE_URL } from './CommonValues.js';
import { loginSystem } from '@/api/login.js';

export function GET(url, data) {
	return SIMPLE(url, data, 'GET');
}
export function GET_TOKEN(url, data, token) {
	return SIMPLE_TOKEN(url, data, token, 'GET');
}

export function POST(url, data) {
	return SIMPLE(url, data, 'POST');
}

export function POST_TOKEN(url, data) {
	return SIMPLE_TOKEN(url, data, token, 'POST');
}

export function DELETE(url, data) {
	return SIMPLE(url, data, 'DELETE');
}

export function PUT(url, data) {
	return SIMPLE(url, data, 'PUT');
}

let requestTime = 0;

export async function SIMPLE(url, data, method) {
	// 防止首次访问没有token
	if(requestTime == 0) {
		token = await loginSystem();
		if(token.data) {
			// 如果有code表示没有拿到token
			SIMPLE(url, data, method)
			return;
		}
		requestTime += 1;
	} else {
		var token = uni.getStorageSync("APP_TOKEN");
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}${url}`,
			method: method,  
			header: {
				"Content-Type": "application/json;charset=utf-8",
				"Authorization": token
			},
			dataType: 'json',
			data: data,
			success: res => {
				if(res.data.code == '200' || res.data.statusCode == '200') {
					resolve(res.data)
				} else {
					reject(res)
				}
			},
			fail: err => {
				reject(err)
			}
		})
	})
}

export function SIMPLE_TOKEN(url, data, token, method) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}${url}`,
			method: method,  
			header: {
				"Content-Type": "application/json;charset=utf-8",
				"Authorization": token
			},
			dataType: 'json',
			data: data,
			success: res => {
				if(res.data.code == '200' || res.data.statusCode == '200') {
					resolve(res.data)
				} else {
					reject(res)
				}
			},
			fail: err => {
				reject(err)
			}
		})
	})
}

export default {
	GET,
	POST,
	DELETE,
	PUT,
	GET_TOKEN
}