// import axios from 'axios';
import { dateStrFormat } from './formatTime';
import request from '@/utils/request';
import { Session } from '@/utils/storage';
const BASE_URL_FILE = `/uploads`;

export const addWindowResizeHandler = function (handler: any) {
	let oldHandler: any = window.onresize;
	if (typeof window.onresize != 'function') {
		window.onresize = handler;
	} else {
		window.onresize = function () {
			oldHandler();
			handler();
		};
	}
};
export const getNodeUUid = function () {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
		var r = (Math.random() * 16) | 0,
			v = c == 'x' ? r : (r & 0x3) | 0x8;
		return v.toString(16);
	});
};

export const isJSON = (str: string) => {
	let result = false;
	try {
		JSON.parse(str);
		result = true;
	} catch (e) {
		result = false;
	}
	return result;
};

// 上传文件
export function uploadFile(file: any, imgName: any, data = { isPublic: 1, isCatalogue: 0, parentId: 0 }) {
	return new Promise((resolve, reject) => {
		// 创建一个FormData对象
		var formData = new FormData();
		// 将文件添加到formData中
		formData.append('file', file);
		// 发起PUT请求
		request
			.put(`${BASE_URL_FILE}?isPublic=${data.isPublic}&isCatalogue=${data.isCatalogue}&parentId=${data.parentId}`, formData, {
				headers: {
					'Content-Type': 'multipart/form-data',
				},
				onUploadProgress: function (progressEvent: any) {
					var percentComplete = (progressEvent.loaded / progressEvent.total) * 100;
					console.log('上传进度：' + percentComplete + '%');
				},
			})
			.then(function (response) {
				console.log('文件上传成功！', response);
				const idRegex = /id: ([\w-]+)/;
				const match = response.match(idRegex);
				const id = match && match[1];
				resolve(id);
			})
			.catch(function (error) {
				console.log('文件上传失败！');
				reject(error);
			});
	});
}

// 2024-01-31T00:00:00+08:00  格式转日期 不含具体时间点
export const formatWithDate = (date: any) => {
	return dateStrFormat(date).substring(0, 10);
};

/***** 下划线命名转驼峰 ****/
export const underlineToCamelCase = (underlineName: string) => {
	var words = underlineName.split('_');
	var camelCaseName = words[0];
	for (var i = 1; i < words.length; i++) {
		var capitalizedWord = words[i].charAt(0).toUpperCase() + words[i].slice(1);
		camelCaseName += capitalizedWord;
	}
	return camelCaseName;
};

/*** 获取文件链接 */
export const getFileUrl = (fileId: string) => {
	return new Promise((resolve, reject) => {
		request({
			url: `${BASE_URL_FILE}?fileId=${fileId}`,
			method: 'get',
		}).then((res) => {
			if (res.fileType && res.fileType.includes('image')) {
				resolve(res.filePath + '?token=' + Session.get('token'));
			}
		});
	});
};

/*** 删除上传的文件 */
export const delFile = (fileId: string) => {
	return new Promise((resolve, reject) => {
		request({
			url: `${BASE_URL_FILE}?fileId=${fileId}`,
			method: 'DELETE',
		}).then((res) => {
			resolve(res);
		});
	});
};

/* 跳转身份认证 */
export function goAuth() {
	Session.clear(); // 清除缓存/token等
	const url = window.location.href;
	window.location.href = `/app/panel/#/login`;
}

/* 获取URL中的参数 */
export function getUrlParams(url) {
	// 定义一个空对象，用于存储参数
	const params = {};
	// 获取URL中的查询字符串
	const queryString = url.match(/\?.*/) ? url.match(/\?.*/)[0] : '';

	// 如果查询字符串存在
	if (queryString) {
		// 定义一个正则表达式，用于匹配参数
		const regex = /[?&]?([^=]+)=([^&]*)/g;
		let match;
		while ((match = regex.exec(queryString)) !== null) {
			params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
		}
	}
	return params as any;
}
