import { BASE_URL } from "@/lib/config"
import dlg from "@/lib/dlg"
import { getToken, getTenant } from "@/lib/auth/token"


function getHeader() {
	let header = {
		"Content-Type": "application/json"
	};
	//获取token
	let token = getToken()
	let tenant = getTenant()
	header["Authorization"] = "Bearer " + 'test1';
	if (token) {
		header["Authorization"] = "Bearer " + token;
		// header["token"] = token;
	}

	if (tenant) {
		header["tenant-id"] = tenant;
	}
	header["source-type"] = "app"
	// #ifdef APP
	let systemInfo = uni.getSystemInfoSync()
	let osName = systemInfo.osName
	let brand = systemInfo.brand
	let model = systemInfo.model
	let osVersion = systemInfo.osVersion
	let appVersion = systemInfo.appWgtVersion
	let channel = "uniapp"
	let userAgent = `app-${osName} ${brand} ${model}_${osVersion} APP_V${appVersion} CHANNEL_${channel}`
	header["user-agent"] = userAgent
	// #endif

	return header;
}


function getFileHeader() {
	let header = { "Authorization": "Bearer test1" };
	//获取token
	let token = getToken()
	if (token) {
		header["Authorization"] = "Bearer " + token;
	}
	return header;
}


const fetch = async (method : any, url : string, data : any, loading = false) => {

	return await new Promise((resolve, reject) => {
		//显示加载动画
		if (loading) {
			uni.showLoading();
		}
		if (url.indexOf("http") == -1) {
			url = BASE_URL + url;
		}
		// console.log('request url = ' + url);
		try {
			//发起请求
			uni.request({
				url,
				method,
				data,
				header: getHeader(),
				success: res => {
					let statusCode = res.statusCode;
					// console.log("res", res)
					if (statusCode == 200) {
						let { code, msg, data, message } = res.data
						// console.log(method + "[" + url + "]success", res);
						if (!isSuccess(code)) {
							if (msg) {
								reject(msg);
							}
							if (message) {
								dlg.error(message);
								reject(message);
							}
						}
						resolve(res.data['data']);
					} else {
						console.log(`\x1b[31m${res.data['status']} ${res.data['path']} ${res.data['error']}\x1b[0m`)
						reject(res.data)
					}
				},
				fail: err => {
					console.log("请求fail", err);
					reject(err);
					return null;
				},
				complete: () => {
					//结束加载动画
					if (loading) {
						uni.hideLoading();
					}
				}
			});

		} catch (e) {
			reject(e.message);
		}
	});

}

//文件上传
const uploadSync = (filePath) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: BASE_URL + '/admin-api/infra/file/upload',
			// file: image,
			header: getFileHeader(),
			filePath: filePath,
			name: 'file',
			success: (res) => {
				let result = JSON.parse(res.data);
				console.log("upload ", result);
				if (result.code < 0) {
					// console.log("请求出错" + url, result);
					dlg.error('上传出错' + result.message);
					reject(result)
					return null;
				}

				let data = result.data;
				console.log("upload data= ", data);
				resolve(data);
				return data;
			},
			fail: err => {
				dlg.error('上传出错' + err);
				reject(err)
				return null;
			},
		});
	});
}


//上传
const upload = async (file) => {
	console.log("file==>", JSON.stringify(file));
	return await uploadSync(file);
}


function isSuccess(code : number) {
	return code == 0 || code == 200 || code == 2001;
}

export const get = (url : string, params : any, loading = false) => {
	return fetch('GET', url, params, loading)
}

export const post = (url : string, params : any, loading = false) => {
	return fetch('POST', url, params, loading)
}

export const put = (url : string, params : any, loading = false) => {
	return fetch('PUT', url, params, loading)
}

export const del = (url : string, params : any, loading = false) => {
	return fetch('DELETE', url, params, loading)
}


export const checkErr = (fun : Function) => {
	try {
		return fun()
	} catch (e) {
		dlg.error(e.message)
		return null
	}
}

export default { get, post, put, del, checkErr, upload }