import { fabric } from 'fabric-with-all'
import { createStaticCanvas } from './canvasFactory'
import { getObjectsBoundingBox, cloneObjects } from './canvasMethod'
/**  导出画布为图片
 * @param {fabric.Canvas} canvas - 画布对象
 * @param {boolean} isDisscar - 是否丢弃选中对象
 * @returns {Promise<string>} - 图片URL
 */
export async function exportCanvasToImage(canvas, isDisscar = true) {
	if (isDisscar) {
		canvas.discardActiveObject()
		canvas.renderAll()
	}
	const clonedObjects = await cloneObjects(canvas.getObjects())
	const staticCanvas = createStaticCanvas(document.createElement('canvas'))
	const width = canvas.clipPath.width
	const height = canvas.clipPath.height
	staticCanvas.setWidth(width)
	staticCanvas.setHeight(height)
	clonedObjects.forEach(obj => staticCanvas.add(obj))
	// 导出图片
	const dataURL = staticCanvas.toDataURL({
		type: 'image/png',
		quality: 1,
	})
	return dataURL
}
/**  导出指定对象 */
export async function exportObjectsToImage(objects = [], isDetails = false) {
	const clonedObjects = await cloneObjects(objects)
	const boundingBox = await getObjectsBoundingBox(clonedObjects)
	const staticCanvas = createStaticCanvas(document.createElement('canvas'))
	staticCanvas.setWidth(boundingBox.width)
	staticCanvas.setHeight(boundingBox.height)
	clonedObjects.forEach(obj => {
		obj.set({
			left: obj.left - boundingBox.left,
			top: obj.top - boundingBox.top,
		})
		if (obj.clipPath && obj.clipPath.absolutePositioned) {
			obj.clipPath.set({
				left: obj.clipPath.left - boundingBox.left,
				top: obj.clipPath.top - boundingBox.top,
			})
		}
		staticCanvas.add(obj)
	})
	// 导出图片
	const dataURL = staticCanvas.toDataURL({
		type: 'image/png',
		quality: 1,
	})
	return isDetails ? {
		url: dataURL,
		...boundingBox,
	} : dataURL
}

/**  导出指定对象为缩略图 */
export async function exportObjectToThumbnail(object, width = 100, height = 100) {
	const url = await exportObjectsToImage([object]);
	const staticCanvas = createStaticCanvas(document.createElement('canvas'))
	staticCanvas.setWidth(width)
	staticCanvas.setHeight(height)
	const image = await new Promise((resolve, reject) => {
		fabric.Image.fromURL(url, (img) => {
			const scale = Math.min(width / img.width, height / img.height)
			const left = (width - img.width * scale) / 2
			const top = (height - img.height * scale) / 2
			img.set({
				left,
				top,
				scaleX: scale,
				scaleY: scale,
			})
			resolve(img)
		})
	})
	staticCanvas.add(image)
	// 导出图片
	const dataURL = staticCanvas.toDataURL({
		type: 'image/png',
		quality: 1,
	})
	return dataURL
}