<template>
	<!-- 结果图片 -->
	 <div class="result-image-container" :class="{'show-border': data.imageProcessTasks.length > 1}">
		<div class="result-image" 
			v-for="(item, i) in data.imageProcessTasks" 
			:key="item.taskId" 
			:class="{'active': node.id == stateManager.activeNodeID.value && item.taskId == data.selectTaskId}"
			@mousedown="setSelectTaskId(item.taskId)"
		>
			<div class="header" v-if="item.status == 'RETURNED'" v-show="showHeader && node.id == stateManager.activeNodeID.value && item.taskId == data.selectTaskId" @mousedown.stop>
				<span class="icon">
					<svg-icon name="chat-compose" size="20" size-unit="px" />
				</span>
				<span class="icon" @click="onPreview(item)">
					<svg-icon name="expand-lg" size="20" size-unit="px" />
				</span>
				<span class="icon" @click="onDownload(item)">
					<svg-icon name="download" size="20" size-unit="px" />
				</span>
				<button class="edit" @click="onEdit(item)" v-if="node.data.superiorNodeType !== NODE_DATATYPE.TO_3D_MODEL || node.data.tier == 0">
					<span class="icon"><svg-icon name="edit" size="13" /></span>
					<span class="text">{{ $t('FlowCanvas.edit') }}</span>
				</button>
			</div>
			<img
				class="image"
				v-if="item.status == 'RETURNED'"
				:src="item?.url"
				:style="{ transform: `scale(${item?.scale?.x || 1}, ${item?.scale?.y || 1})` }"
			/>
			<div class="status" v-else>
				<div class="content">
					<HighlightAdmin>
						<img src="@/assets/images/generateLoading.png" alt="">
						<div class="mask"></div>
					</HighlightAdmin>
				</div>
			</div>
			<div class="more" v-if="item.status == 'RETURNED'" @mousedown="clickimageProcessTaskItem(item.taskId)">
				<svg-icon name="more" size="24" size-unit="px" color="#C9C9C9" />
			</div>
			<div class="menu" v-show="showMenu && item.taskId === data.selectTaskId && node.id == stateManager.activeNodeID.value" @mousedown.stop>
				<div
					v-for="(v, i) in menus"
					:key="i"
					:class="[v.isDivide ? 'divide' : 'item', { disabled: v.disabled }]"
					@click="onMenuItem(v)"
				>
					<template v-if="!v.isDivide">
						<span class="label">{{ v.label }}</span>
						<span class="tip">{{ v.tip }}</span>
					</template>
				</div>
			</div>
		</div>
		<div class="add" @mousedown.stop v-if="isAdd" @click="onAdd">
			<svg-icon name="add" size="14" size-unit="px" />
		</div>
	 </div>
</template>

<script setup lang="ts">
	import myEvent from '@/utils/myEvent'
	import { downloadImage } from '../../../tools/tools'
	import { reactive, ref, onBeforeUnmount, useAttrs, inject, watch, computed, onMounted } from 'vue'
	import HighlightAdmin from '@/components/highlightAdmin.vue'
	import { NODE_DATATIER, NODE_DATATYPE } from '../../tools/index.d'
	import { useI18n } from 'vue-i18n'
	import { updateVersionSketchUrlApi } from '@/api/flow-canvas'
	const { t } = useI18n()
	const openImagePreview = inject('openImagePreview') as (url: string) => void
	const openThreeModelPreview = inject('openThreeModelPreview') as (obj: any) => void
	const props = defineProps({
		node: {
			type: Object,
			default: () => ({})
		},
		config: {
			type: Object,
			default: () => ({})
		},
		data: {
			type: Object,
			default: () => ({})
		}
	})
	const emit = defineEmits([
		'delete-node',
		'copy-node',
		'bring-to-font',
		'send-to-back',
		'update-data'
	])
	// const attrs = useAttrs()
	const showHeader = ref(true)
	// const showHeader = ref(!!props.node?.data?.isHeader)
	const showMenu = ref(false)
	const generateManager = inject('generateManager') as any
	const stateManager = inject('stateManager') as any
	const eventManager = inject('eventManager') as any
	const clickimageProcessTaskItem = (taskId: string) => {
		if(data.selectTaskId == taskId){
			showMenu.value = !showMenu.value
		}else{
			showMenu.value = true
		}
		data.selectTaskId = taskId
	} 
	const data = reactive({
		selectTaskId: props.data?.selectTaskId || '',
		imageProcessTasks: props.data?.imageProcessTasks,
		superiorNodeType: props?.node?.data?.superiorNodeType,
		isActive: props.data?.isActive || false,
	})
	const setSelectTaskId = (taskId: string) => {
		data.selectTaskId = taskId
	}
	watch(
		() => props.data.status,
		(newVal) => {
			data.imageProcessTasks.forEach((item) => {
				if(item.status !== 'RETURNED'){
					generateManager.addTaskId(item,props.node.id)
				}
			})
			
		},
		{ immediate: true }
	)
	const menus = ref([
		{ label: t('FlowCanvas.copy'), tip: 'Ctrl+C', on: () => emit('copy-node') },
		{
			label: t('FlowCanvas.delete'),
			tip: 'Del',
			on: () => {
				emit('delete-node', props.node.id)
			},
			disabled: !!props.config?.disableDelete
		},
		{ isDivide: true },
		{
			label: t('FlowCanvas.flipHorizontal'),
			tip: '',
			on: () => {
				data.imageProcessTasks.forEach((item) => {
					if(item.taskId == data.selectTaskId){
						if(!item.scale){
							item.scale = { x: 1, y: 1 }
						}
						item.scale.x = -item.scale.x
					}
				})
				stateManager.recordState()
				stateManager.exportFlow(stateManager.saveCanvasTimeInterval)
			}
		},
		{
			label: t('FlowCanvas.flipVertical'),
			tip: '',
			on: () => {
				data.imageProcessTasks.forEach((item) => {
					if(item.taskId == data.selectTaskId){
						if(!item.scale){
							item.scale = { x: 1, y: 1 }
						}
						item.scale.y = -item.scale.y
					}
				})
				stateManager.recordState()
				stateManager.exportFlow(stateManager.saveCanvasTimeInterval)
			}
		}
	])
	const onPreview = (item: any) => {
		if(data.superiorNodeType == NODE_DATATYPE.TO_3D_MODEL && tier.value != 0){
			openThreeModelPreview({
				glbPath:item?.glbPath,
				glbInfoObj:item?.glbInfoObj,
				nodeId:props.node?.id,
				nodeType:props.node.data?.superiorNodeType,
				superiorGenerateImg:props.node.data?.superiorGenerateImg,
			})
		}else{
			openImagePreview(item.url)
		}
	}
	const onDownload = (item: any) => {
		if(data.superiorNodeType == NODE_DATATYPE.TO_3D_MODEL){
			if(item?.glbPath)downloadImage(item.glbPath, 'model.glb')
		}else{
			downloadImage(item.url, 'image.png')
		}
	}
	const onMenuItem = (v) => {
		if (v.disabled) return
		v.on && v.on()
		hideMenu()
	}
	const hideMenu = () => {
		showMenu.value = false
	}

	const depthCanvasClose = ()=>{
		eventManager.registerEvents()
	}
	const depthCanvasWorkbench = (options)=>{
		data.imageProcessTasks.forEach((item) => {
			if(item.taskId == options.taskId){
				item.url = options.url
				item.canvasId = options.canvasId || null
			}
		})
		stateManager.recordState()
		stateManager.exportFlow()
	}

	const onEdit = (item: any) => {
		const data = { 
			url:item.url,
			canvasId: item?.canvasId || null,
			sketchId: stateManager.sketchId.value,
			onWorkbench:(options)=>{
				let workbenchData = {
					...item,
					...options,
				}
				depthCanvasWorkbench(workbenchData)
				depthCanvasClose()
				//更新VersionNode的sketchIDAndUrl中指定key的URL值
				updateVersionSketchUrlApi({
					sketchId: stateManager.sketchId.value,
					newUrl: options.url,
				}).then(()=>{
					//更新VersionNode的versionImgUpdataList中指定key的URL值
					let initialNode = stateManager.getInitialNode()
					initialNode.data.versionImgUpdataList.push(options.url)
				})
			},
			onClose:depthCanvasClose 
		}
		eventManager.removeEvents()
		myEvent.emit('openDepthCanvas', data)
	}

	const isSubord = computed(() => props.node.id == stateManager.activeNodeID.value)
	const tier = computed(() => Number(props.node?.data?.tier || 0))
	//只有3d模型才有三级菜单,目前三级菜单内容少直接禁用按钮
	// const isAdd3d = computed(() => (tier.value === 2 && props.node?.data?.superiorNodeType === NODE_DATATYPE.TO_3D_MODEL) || (props.node?.data?.superiorNodeType !== NODE_DATATYPE.TO_3D_MODEL && tier.value !== 2))
	const isReturned = computed(() => {
		return (
			props.node.data.type == NODE_DATATYPE.RESULT_IMAGE &&
			props.node.data.data.imageProcessTasks[0].status == 'RETURNED'
		)
	})
	const isAdd = computed(
		() =>
			NODE_DATATYPE.RESULT_IMAGE === props.node.data.type &&
			!(tier.value === NODE_DATATIER.TO_3VIEW) &&
			isReturned.value && 
			// isAdd3d.value && 
			isSubord.value
	)
	const onAdd = () => {
		const tier_ = tier.value + 1
		const subordNodes = stateManager.getSubordNodes(props.node.id)
		stateManager.nodeManager.createCardsSelect({
			data: { 
				tier: tier_, 
				superiorID: props.node.id, 
				createIndexPosition: subordNodes.length + 1,
				isActive: subordNodes.length == 0
			}
		})
	}
	document.addEventListener('mousedown', hideMenu)
	onBeforeUnmount(() => {
		document.removeEventListener('mousedown', hideMenu)
	})
	onMounted(()=>{
		emit('update-data', data)
	})
	defineExpose({ data })
</script>

<style lang="less" scoped>
	.result-image-container{
		&.show-border{
			border: 1px solid #d9d9d9;
			border-radius: 9.4px;
			padding: 16px;	
			display: grid;
			grid-template-columns: repeat(2, 1fr); /* 一行3列 */
			gap: 8px;
		}
	}
	.add {
		position: absolute;
		width: 32px;
		height: 32px;
		border: 2px solid #fff;
		top: var(--top);
		right: -16px;
		transform: translateY(-50%);
		background-color: #ed8936;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #fff;
		font-size: 25px;
		box-shadow: 0 8px 20px 0 #71809633;
		cursor: pointer;
		z-index: 20;
	}
	.result-image {
		width: 244px;
		border-radius: 16px;
		border: 1px solid #d9d9d9;
		box-shadow: 0 15px 21px 0 rgba(0, 0, 0, 0.05);
		padding: 25px 6px;
		user-select: none;
		background-color: #fff;
		&.active {
			box-shadow: 0 15px 21px 0 rgba(0, 0, 0, 0.05), 0 0 0 2px #d9d9d9;
		}
		> .header {
			position: absolute;
			top: -20px;
			left: 50%;
			transform: translate(-50%, -100%);
			width: auto;
			height: 50px;
			border-radius: 10px;
			border: 2px solid #ebebeb;
			box-shadow: 0px 15px 21px 0px #0000000d;
			display: flex;
			align-items: center;
			justify-content: center;
			user-select: none;
			padding: 0 19px;
			gap: 12px;
			background-color: #fff;
			> .icon {
				cursor: pointer;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 32px;
				height: 32px;
				--svg-icon-color: #000;
				border-radius: 3px;
				&:hover {
					background-color: #ebebeb;
				}
			}
			> .edit {
				width: 80px;
				height: 30px;
				border-radius: 4px;
				border: none;
				background-color: #ed8936;
				color: #fff;
				font-size: 12px;
				display: flex;
				align-items: center;
				justify-content: center;
				gap: 8px;
				cursor: pointer;
				&:active {
					opacity: 0.8;
				}
			}
		}

		> .image {
			width: 100%;
			height: auto;
			max-height: 200px;
			object-fit: contain;
		}
		> .status{
			width: 100%;
			// height: 140px;
			height: 100%;
			min-height: 140px;
			display: flex;
			align-items: center;
			justify-content: center;
			> .content{
				width: 86px;
				height: 60px;
				position: relative;
				.mask{
					background-color: rgba(255, 255, 255, 0.2);
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
				}
				img{
					width: 100%;
					height: 100%;
				}
			}
		}
		position: relative;

		> .more {
			position: absolute;
			top: 5px;
			right: 9px;
			width: 24px;
			height: 24px;
			cursor: pointer;
		}
		> .menu {
			position: absolute;
			width: 244px;
			height: auto;
			top: 0;
			right: -10px;
			transform: translate(100%, 0);
			border-radius: 16px;
			padding: 16px 14px;
			box-shadow: 0px 15px 21px 0px rgba(0, 0, 0, 0.05);
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			gap: 12px;
			background-color: #fff;
			z-index: 50;
			> .item {
				width: 100%;
				height: 27px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 8px;
				border-radius: 8px;
				cursor: pointer;
				font-size: 14px;
				&.disabled {
					cursor: not-allowed;
					> .tip,
					> .label {
						color: rgba(0, 0, 0, 0.2);
					}
				}
				&:not(.disabled):hover {
					background: #f3f3f3;
				}
				> .label {
					color: #000;
				}
				> .tip {
					color: rgba(0, 0, 0, 0.3);
				}
			}
			> .divide {
				width: 100%;
				height: 0;
				border-bottom: 1px solid #e5e5e5;
			}
		}
	}
</style>
