import JSZip from 'jszip'
export const createId = (before: string = 'node') => {
	const time = Date.now().toString(36)
	const random = Math.random().toString(36).substring(2, 20)
	return `${before}_${time}${random}`
}

/** 下载图片 */
export const downloadImage = (url: string, name: string) => {
	fetch(url)
		.then((res) => res.blob())
		.then((blob) => {
			const a = document.createElement('a')
			a.href = URL.createObjectURL(blob)
			a.target = '_blank'
			a.download = name || 'image.png'
			a.click()
		})
}

/** 批量下载图片 */
export const downImgListToZip = async (imagesParams,callback) => {
	const zip = new JSZip()
	const promises = []
	// 遍历下载每个图片
	let progress = 0
	imagesParams.forEach((img, index) => {
		const promise = new Promise((resolve, reject) => {
			const xhr = new XMLHttpRequest()
			xhr.open('GET', img.url, true)
			xhr.responseType = "blob";
			xhr.onload = () => {
				if (xhr.status === 200) {
					const fileName = img.name
					zip.file(fileName, xhr.response)
					progress++
					callback(progress)
					resolve('')
				} else {
					reject(new Error(`下载失败: ${img.url}`))
				}
			}
			xhr.onerror = () => reject(new Error(`网络错误: ${img.url}`))
			xhr.send()
		})
		promises.push(promise)
	})

	// 等待所有图片下载完成
	Promise.all(promises)
		.then(() => zip.generateAsync({ type: 'blob' }))
		.then((content) => {
			// 下载zip
			console.log(content)
			const link = document.createElement('a')
			link.href = URL.createObjectURL(content)
			link.download = 'DesignFiles'
			link.click()
			// URL.revokeObjectURL(link.href)
		})
		.catch((error) => console.error('下载失败:', error))
}

/** base64转二进制 */
export const base64Tofile = (base64: string,name: string) => {
	const arr = base64.split(',')
	const mime = arr[0].match(/:(.*?);/)[1]
	const bstr = atob(arr[1])
	// 2. 转换为 Uint8Array
	let n = bstr.length
	const u8arr = new Uint8Array(n)
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n)
	}
	// 3. 创建 Blob
	const blob = new Blob([u8arr], { type: mime })
	// 4. 创建 File 对象（可选）
	const file = new File([blob], name, { type: mime })
	return file
}
/** 二进制转base64 */
/**
 * File 对象转 Base64
 * @param {File} file - 文件对象
 * @returns {Promise<string>} Base64 字符串
 */
export const fileToBase64 = (file: File) => {
	return new Promise((resolve, reject) => {
	  const reader = new FileReader()
	  reader.onload = () => {
		resolve(reader.result) // Base64 字符串
	  }
	  reader.onerror = (error) => {
		reject(error)
	  }
	  reader.readAsDataURL(file)
	})
}
//获取当前时间2026-03-20 11:38:29
export const getCurrentTime = () => {
	const now = new Date()
	const currentTime = 
	now.getFullYear() + '-' +
	String(now.getMonth() + 1).padStart(2, '0') + '-' +
	String(now.getDate()).padStart(2, '0') + ' ' +
	String(now.getHours()).padStart(2, '0') + ':' +
	String(now.getMinutes()).padStart(2, '0') + ':' +
	String(now.getSeconds()).padStart(2, '0')
	return currentTime
}