<template>
	<fullscreen-dialog
		v-model="dialogVisible"
		@close="() => depthCanvasRef.onWorkbench()"
		hide-destroy
	>
		<div class="canvas-box">
			<depth-canvas
				ref="depthCanvasRef"
				:config="config"
				@close="onClose"
				@workbench="onWorkbench"
			/>
		</div>
	</fullscreen-dialog>
</template>

<script setup lang="ts">
	import { base64Tofile } from '../tools/tools'
	import { uploadImage } from '@/api/upload'
	import { getDepthCanvas, saveDepthCanvas } from '@/api/depth-canvas'
	import FullscreenDialog from '../components/fullscreen-dialog.vue'
	import depthCanvas from './depth-canvas.vue'
	import { ref, watch } from 'vue'
	import { useRoute } from 'vue-router'
	const route = useRoute()
	watch(
		() => route.path,
		() => dialogVisible.value && (dialogVisible.value = false)
	)
	const dialogVisible = ref(false)
	const config = ref({
		canvasId: '',
		sketchId: '',
		url: '',
		canvasData: '' as any,
		onWorkbench(options) {},
		onClose() {}
	})
	const depthCanvasRef = ref(null)

	const open = async (options) => {
		config.value = options
		if (config.value.canvasId) {
			const res = await getDepthCanvas(config.value.canvasId)
			const canvas = res.deepCanvasDetail
			const images = res.images
			if (canvas && images) {
				config.value.canvasData = { canvas: JSON.stringify(canvas), images }
			} else {
				config.value.canvasData = null
			}
		}

		dialogVisible.value = true
	}
	// 工作区
	const onWorkbench = async (options: { canvas: string; images: Object; url: string }) => {
		// 保存画布数据
		const data = {
			deepCanvasDetail: JSON.parse(options.canvas),
			images: options.images,
			sketchId: config.value.sketchId,
			id: config.value.canvasId || null
		}
		const sData = await saveDepthCanvas(data)

		const canvasId = sData.id
		// base64 转 file 上传转换为 url
		const file = base64Tofile(options.url, 'canvas.png')
		const formData = new FormData()
		formData.append('file', file)
		const url = await uploadImage(formData, true)
		config.value.onWorkbench?.({ url, canvasId })

		dialogVisible.value = false
	}
	// 关闭
	const onClose = () => {
		dialogVisible.value = false
		config.value.onClose?.()
	}

	defineExpose({
		open,
		close: () => {
			dialogVisible.value = false
		}
	})
</script>
<style lang="less" scoped>
	.canvas-box {
		padding-top: 10rem;
		width: 100%;
		height: 100%;
	}
</style>
