<template>
	<div class="agent-wrapper flex space-between">
		<div class="openVersionTree">
			<div class="btn" :class="{ 'is-disabled': isAgentGenerating }" @click="handleOpenVersionTree">
				Version Tree
			</div>
		</div>
		<div class="content-wrapper">
			<KeepAlive :max="10">
				<Agent
					:key="proJectId"
					ref="agentRef"
					:title="agentTitle"
					@update:sketchList="updateSketchList"
					@setTitle="handleSetTitle"
				/>
			</KeepAlive>
			<div class="preview-wrapper">
				<Preview
					ref="previewRef"
					:type="previewType"
					:sketchList="sketchList"
					@deleteSketch="handleDeleteSketch"
				/>
			</div>
		</div>
		<VersionTreeIndex
			ref="VersionTreeIndexRef"
			v-model:versionTreeData="versionTreeData"
			@restore="handleRestore"
			@selectNode="handleSelectNode"
		/>
	</div>
</template>

<script setup lang="ts">
	import { ref, watch, onMounted, computed, onUnmounted } from 'vue'
	import Agent from './components/Agent.vue'
	import Preview from './components/Preview.vue'
	import VersionTreeIndex from './components/versionTree/index.vue'
	import { useProjectStore } from '@/stores'
	import { getProjectInfo } from '@/api/agent'
	import { clearNodeChat, getNodeAncestors } from '@/api/versitonTree'
	import { useRoute, useRouter } from 'vue-router'
	import MyEvent from '@/utils/myEvent'
	import { useI18n } from 'vue-i18n'

	const route = useRoute()
	const router = useRouter()
	const { t } = useI18n()
	const projectStore = useProjectStore()

	const previewRef = ref(null)
	const proJectId = computed(() => route.params.id)
	const agentTitle = ref('Conversation')
	const previewType = ref<'sketch' | 'report'>('sketch')
	const VersionTreeIndexRef = ref()
	const agentRef = ref()
	const sketchList = ref([])
	const isAgentGenerating = computed(() => Boolean(agentRef.value?.isGenerating))
	const updateSketchList = (newVal) => {
		sketchList.value = newVal
		// VersionTreeIndexRef.value.getVersionTree()
	}

	const handleDeleteSketch = (id) => {
		sketchList.value = sketchList.value
			.map((sketchItem) => {
				if (Object.prototype.hasOwnProperty.call(sketchItem, id)) {
					delete sketchItem[id]
				}
				return sketchItem
			})
			.filter((sketchItem) => Object.keys(sketchItem).length > 0)
	}

	const handleSetTitle = (title: string) => {
		agentTitle.value = title
	}

	const versionTreeData = ref({
		drawer: false
	})

	const handleOpenVersionTree = () => {
		if (isAgentGenerating.value) return
		versionTreeData.value.drawer = true
	}

	const handleRestore = () => {
		// agentRef.value?.inputRef?.addReportTag('Restore')
		clearNodeChat({ projectId: projectStore.state.id, id: projectStore.state.nodeId }).then(
			(res) => {
				agentRef.value.setChatInfo({ conversation: res, project: {} })
			}
		)
	}
	const handleSelectNode = () => {
		getNodeAncestors({ projectId: projectStore.state.id, id: projectStore.state.nodeId }).then(
			(res) => {
				agentRef.value.setChatInfo({ conversation: res, project: {} })
			}
		)
	}

const handleGetProjectInfoAndHistory = () => {
		sketchList.value = []
		getProjectInfo({ id: route.params.id }).then((res) => {
			if (!res) {
				router.push({ name: 'mainInput' })
				ElMessage.warning(t('Home.notFound'))
				return
			}
			handleOpenSketch()
			if (res) agentRef.value.setChatInfo(res)
			let data = res?.project || res
			if (data?.latestNodeId) data.nodeId = data.latestNodeId
			if (data) {
				agentTitle.value = data.name
			}
			projectStore.setProject({
				...data
			})
		})
	}

	const handleOpenReport = (data) => {
		previewRef.value.setSessionId(data.sessionId)
		previewRef.value.setReport(data.reportName, data.report)
		previewType.value = 'report'
	}

	const handleOpenUrls = (data) => {
		previewRef.value.setUrls(data)
		previewType.value = 'url'
	}

	const handleOpenSketch = (id) => {
		previewType.value = 'sketch'
	}

	watch(
		() => proJectId.value,
		(newVal, oldVal) => {
			projectStore.clearProject()
			if (newVal) {
				handleGetProjectInfoAndHistory()
				MyEvent.emit('projectChange')
				// MyEvent.emit('resetAgent')
			}
		}
	)

	const handleRenameConversation = (item) => {
		if (String(item.id) === String(proJectId.value)) {
			handleSetTitle(item.name)
		}
	}

	onMounted(() => {
		MyEvent.add('openReport', handleOpenReport)
		MyEvent.add('openUrls', handleOpenUrls)
		MyEvent.add('openSketch', handleOpenSketch)
		MyEvent.add('renameConversation', handleRenameConversation)
		MyEvent.add('closeFlowCanvas', handleGetProjectInfoAndHistory)
		projectStore.clearProject()
		if (proJectId.value) {
			handleGetProjectInfoAndHistory()
		}
	})
	onUnmounted(() => {
		MyEvent.remove('openReport', handleOpenReport)
		MyEvent.remove('openUrls', handleOpenUrls)
		MyEvent.remove('openSketch', handleOpenSketch)
		MyEvent.remove('renameConversation', handleRenameConversation)
		MyEvent.remove('closeFlowCanvas', handleGetProjectInfoAndHistory)
	})
</script>

<style lang="less" scoped>
	.agent-wrapper {
		width: 100%;
		height: 100%;
		border-top: 0.1rem solid #c9c9c9;
		padding: 0rem 2.3rem 6rem 2.8rem;
		flex-direction: column;
		.openVersionTree {
			padding: 2rem 0rem;
			width: 100%;
			display: flex;
			justify-content: flex-end;
			height: min-content;
			> .btn {
				padding: 0 1.45rem;
				line-height: 4rem;
				font-weight: 500;
				font-size: 1.4rem;
				border-radius: 3rem;
				position: relative;
				background: white;
				cursor: pointer;
				&::before {
					content: '';
					position: absolute;
					inset: -1px;
					background: linear-gradient(
						119.03deg,
						rgba(233, 121, 60, 0.8) 1.61%,
						rgba(255, 207, 144, 0.8) 101.01%
					);
					border-radius: 2.5rem;
					z-index: -1;
				}
				&.is-disabled {
					cursor: not-allowed;
					opacity: 0.6;
				}
			}
		}

		.content-wrapper {
			display: flex;
			flex: 1;
			justify-content: space-between;
			overflow: hidden;
		}

		.c-svg {
			width: initial;
		}

		.preview-wrapper {
			// width: 56%;
			flex: 1;
		}
	}
</style>
