import _env from "../env";
import {
	getOrigin
} from "./app";
import utils from "./utils";

const env = {
	..._env,
}

/**
 * 请求基类
 * @param {Object} options  请求参数 { url: String 路径, [data: Object 请求携带的数据], [method: String 请求方式] }
 */
export function request(options) {

	options.header = {
		Authorization: `Bearer ${uni.getStorageSync("token")}`,
	}

	options.noclient ? (options.url = env.host + options.url) : (options.url = env.host + "" + options.url);

	return new Promise((resolve, reject) => {
		uni.request({
			url: options.url,
			timeout: env.NETWORK_TIME_OUT,
			// data: { ...options.data, store_id: env.store_id, mini_id: env.mini_id, origin: getOrigin() },
			data: { ...options.data, ...env, origin: getOrigin() },
			header: options.header,
			method: options.method,
			success: (res) => {
				uni.hideLoading();
				let { statusCode } = res;
				switch (statusCode) {
					case 200:
						resolve(res.data);
						break;

					case 401:
						// 401 过期
						setTimeout(() => {
							utils.loginOut();
						}, 300)
						break;

					default:
						console.log("请求失败(" + statusCode + ")")
						reject(res)
						uni.$u.toast(res?.data?.message || "出错了");
						break;
				}
			},

			fail: (res) => {
				console.log(res, 'reslogin')
				// #ifdef MP-ALIPAY
				if (res.statusCode == 401) {
					setTimeout(() => {
						utils.loginOut();
					}, 300)
				}
				// #endif
				reject(res.data.data);
			},
		});
	});
}

export function uploadFile({
	filePath,
	name,
	formData
}) {

	return new Promise((resolve, reject) => {

		// #ifdef MP-ALIPAY
		let fileType = ""
		let contentType = '';
		if (filePath.endsWith('.image')) {
			contentType = 'image/png';
			fileType = 'image';
		} else if (filePath.endsWith('.video')) {
			contentType = 'video/mp4';
			fileType = 'video';
		}
		// #endif

		uni.uploadFile({
			url: env.host + '/client/common/upload',
			name: "file",
			filePath: filePath,

			fileName: "file",
			// #ifdef MP-ALIPAY
			fileType: fileType,
			// #endif

			headers: {
				// #ifdef MP-ALIPAY
				"Content-Type": "application/x-www-form-urlencoded"
				// #endif
			},
			formData: {
				...formData,
				store_id: env.store_id,
				origin: getOrigin()
			},
			timeout: 10000,
			success: (res) => {
				switch (res.statusCode) {
					case 200:
						resolve(JSON.parse(res.data))
						break;

					case 401:
						// 401 过期
						utils.loginOut();
						break;

					default:
						uni.$u.toast(console.log("请求失败(" + statusCode + ")"));
						break;
				}
			},
			fail: (err) => {
				my.alert({
					title: '上传失败',
					content: JSON.stringify(err)
				});
			},
		});
	})
}

const uploadImage = async ({ filePath, formData, name } = {}) => {

	return new Promise(async (resolve, reject) => {

		try {
			const token = uni.getStorageSync("token");
			const header = {
				Authorization: `Bearer ${token}`
			};

			const formData = {
				parent_id: 0,
				type: "image",
			};

			uni.uploadFile({
				url: 'https://saasdemo.byin.vip/admin/system/uploadImage',
				filePath: filePath,
				name: name || 'file', // 表单中文件字段的名称
				formData: formData,
				header: header,
				success: (uploadFileRes) => {
					const result = JSON.parse(uploadFileRes.data);
					resolve(result)
				}
			});

		} catch (error) {
			reject(error)
		}

	})



};

export { uploadImage };
