/**
 * 封装请求方法
 */

import { tansParams, showToast } from "@/utils/common";
import type { RequestConfig } from "@/types/request";
const TOKEN_KEY = "USER_TOKEN";
const USER_KEY = "USER_KEY";
let timeout = 10000;
let baseUrl = import.meta.env.VITE_APP_URL;
// #ifdef MP-WEIXIN
baseUrl = import.meta.env.VITE_APP_URL;
// #endif

// #ifdef H5
baseUrl = import.meta.env.VITE_APP_DEV;
// #endif

export const requestCommon = {
	isAndroid: function (): boolean {
		const res = uni.getSystemInfoSync();
		return res.platform.toLocaleLowerCase() === "android";
	},
	isPhoneX: function (): boolean {
		const res = uni.getSystemInfoSync();
		let iphonex = false;
		const models = [
			"iphonex",
			"iphonexr",
			"iphonexsmax",
			"iphone11",
			"iphone11pro",
			"iphone11promax",
		];
		const model = res.model.replace(/\s/g, "").toLowerCase();
		if (models.includes(model)) {
			iphonex = true;
		}
		return iphonex;
	},
	// 获取 token
	getToken() {
		return uni.getStorageSync(TOKEN_KEY);
	},
	// 设置 token
	setToken(token: string) {
		uni.setStorageSync(TOKEN_KEY, token);
	},
	//设置用户信息
	setUserData(data: object) {
		uni.setStorageSync(USER_KEY, data);
	},
	removeAll() {
		uni.removeStorageSync(USER_KEY);
		uni.removeStorageSync(TOKEN_KEY);
	},
	//获取用户信息
	getUserData() {
		return uni.getStorageSync(USER_KEY);
	},
};

export const request = (
	config: RequestConfig,
	isLoading = true
): Promise<any> => {
	isLoading && uni.showLoading();
	// 是否需要设置 token
	config.header = config.header || {};
	config.header["Authorization"] = requestCommon.getToken();
	// get 请求映射 params 参数
	if (config.params) {
		let url = config.url + "?" + tansParams(config.params);
		url = url.slice(0, -1);
		config.url = url;
	}
	return new Promise((resolve, reject) => {
		uni
			.request({
				method: config.method || "GET",
				timeout: config.timeout || timeout,
				url: config.baseUrl || baseUrl + config.url,
				data: config.data,
				header: config.header,
				dataType: "json",
			})
			.then((response) => {
				console.log("000", response);

				const responseData: any = response.data;
				const code = responseData.code || 1110000000;
				const msg = responseData.detail;
				if (code == 401) {
					reject("会话已过期，请重新登陆");
					isLoading && uni.hideLoading();
					uni.showModal({
						title: "提示",
						content: "会话已过期，请重新登陆",
						success: function (res) {
							if (res.confirm) {
								uni.redirectTo({
									url: "/pages/login/index",
								});
							} else if (res.cancel) {
								console.log("用户点击取消");
							}
						},
					});
					return false;
				} else if (code == 500) {
					showToast(msg);
					reject(msg);
				} else if (code == 1112020000) {
					showToast(msg);
					reject(response.data);
				} else if (code == 1112020013) {
					showToast("用户不存在请申请!")
					setTimeout(() => {
						uni.redirectTo({ url: "/pages/apply/index" });
					}, 1000);
					reject(msg);
				} else if (code != 1110000000) {
					showToast(msg);
					reject(msg);
				}
				isLoading && uni.hideLoading();
				resolve(response.data);
			})
			.catch((error) => {
				console.log("22222", error);

				let errMsg = error.detail || "请求失败";
				if (errMsg === "request:fail timeout") {
					errMsg = "前方网络拥挤请重试";
				}
				isLoading && uni.hideLoading();
				showToast(errMsg);
				reject(error);
			});
	});
};

/**
 * 上传文件
 * @param string url 请求地址
 * @param string src 文件路径
 */
export const uploadFile = (
	url: string,
	src: string,
	isLoading = true
): Promise<any> => {
	isLoading && uni.showLoading();
	return new Promise((resolve, reject) => {
		const uploadTask = uni.uploadFile({
			url: baseUrl + url,
			filePath: src,
			name: "file",
			header: {
				Authorization: requestCommon.getToken(),
			},
			formData: {},
			success: function (res) {
				resolve(res);
				// uni.hideLoading();
				// let d;
				// try {
				// 	d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}");
				// } catch (error) {
				// 	d = { code: 500, message: "解析返回数据失败" };
				// }
				// if (d.code % 100 === 0) {
				// 	// 返回图片地址
				// 	let fileObj = d.data;
				// 	resolve(res);
				// } else {
				// 	showToast(d.message || "上传失败");
				// }
			},
			fail: function (res) {
				showToast(res.errMsg || "上传失败");
				reject(res);
			},
		});
	});
};
