<template>
	<div class="homeBox">
		<div class="mark_loading" v-show="isShowMark || dataLoad">
			<a-spin size="large" />
		</div>
		<div class="show">
			<!-- <div v-show="openType === 'history'" class="function">
				<design :key="componentKey" ref="design"></design>
			</div> -->
			<router-view v-show="
				(openType && openType != 'history' && !routeQuery.id) || 
				$route.path != '/home'" 
				@setTask="setTask"
				v-slot="{ Component, route }"
			>
				<keep-alive :include="cachedRoutes">
					<component 
						:is="Component" 
						:key="route.name"
					/>
				</keep-alive>
			</router-view>
			<!-- <div v-else-if="routeQuery.id" class="function">
				<design :key="componentKey" ref="design"></design>
			</div> -->
			<div v-if="!$route.params.id && !routeQuery.id" class="function">
				<newPorject ref="newPorject" @newProject=newProject></newPorject>
			</div>
			<!-- <iframe src="https://kaput-relative-4bb.notion.site/ebd/22a8f755cedd809e98a2c8c6366ee701" width="100%" height="100%" frameborder="0" allowfullscreen /> -->

			
		</div>
	</div>
	<!-- <chat ref="chatDom" @chatChange="chatChange" v-show="openType == 'history'"></chat> -->
</template>
<script lang="ts">
import { defineComponent,computed,inject,watch,nextTick,provide,toRefs, reactive, onMounted} from 'vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Https } from "@/tool/https";
import { useStore } from "vuex";
import { useI18n } from 'vue-i18n'
import { useRouter,useRoute } from 'vue-router'
import newPorject from "./newProject/index.vue"
import router from '@/router';
import {getMinioUrl, getUniversalZoomLevel} from '@/tool/util'
import chat from "./chat/index.vue"
export default defineComponent({
	components:{
		newPorject,chat
	},
	emits:['setTask','setNewProject'],
	setup(props,{emit}) {
		const store = useStore();
		const route = useRoute()
		const data = reactive({
			openType:'', 
			componentKey:null,
			isShowMark:true,
			routeQuery:{} as any,
			selectObject:computed(()=>store.state.Workspace.probjects) as any,//选择的项目
			chatData:null as any,
			dataLoad:true as any,
			cachedRoutes:computed(()=>store.state.Workspace.cachedRoutes),//
		})
		onMounted(()=>{
			data.isShowMark = false
		})
		let settingGetHistory:any = inject('settingGetHistory')
		const setIsShowMark = (boolean:boolean)=>{
			data.isShowMark = boolean
		}
		provide('setIsShowMark',setIsShowMark)
		const dataDom = reactive({
			design:null as any,
			newPorject:null as any,
			chatDom:null as any,
		})
		//切换风格更新模特   更新设置交互变更
		// watch(() => data.selectObject.styleId,(newVal,oldVal)=>{
		// 	if(newVal == oldVal || !oldVal)return
		// 	if((data.selectObject?.id == route.query?.history) && route.query?.history){
		// 		getHistory(route.query.history)
		// 	}
		// })
		watch(
			() => route,
			(newRoute) => {
				const routeName = newRoute.name as string
				const shouldCache = newRoute.meta?.cache === true
				if (shouldCache && routeName && !data.cachedRoutes.includes(routeName)) {
					if(routeName == 'tools' && !route.query?.id)return
					data.cachedRoutes.push(routeName)// 保证缓存只有一个项目
				} else if ((!route.query?.id && shouldCache) || (!shouldCache && routeName && data.cachedRoutes.includes(routeName))) {
				// } else if (!shouldCache && routeName && data.cachedRoutes.includes(routeName)) {
					for (let i = data.cachedRoutes.length - 1; i >= 0; i--) {
						if (data.cachedRoutes[i] !== routeName) {
							data.cachedRoutes.splice(i, 1);
						}
					}
				}
			},
			{ immediate: true, deep: true }
		)
		watch(() => route.query,
			(query:any, oldQuery:any) => {
				data.routeQuery = query
				if(query.history)data.componentKey = query.history
				let key = Object.keys(query)?.[0]
				if(route.params?.id)key = 'history'
				if(key){
					data.openType = key
				}else{
					data.openType = ''
					data.dataLoad = false
					return
				}

				// 检查是否需要重新初始化
				const currentPath = route.fullPath
				const storedPath = store.state.Workspace.projectPath
				const isSameProject = currentPath === storedPath
				
				if((data.openType == 'history' && route.params?.id) || (data.openType == 'tools' && query.id)){
					store.commit('setProjectPath',route.fullPath)
				}
				
				// 如果是同一个项目且openType为history，跳过重新初始化
				// if(oldQuery?.id && !query?.id)return createData()
				const tempUrl = new URL(storedPath, window.location.origin);
				const params2 = {
					tools: tempUrl.searchParams.get('tools'),
					id: tempUrl.searchParams.get('id')
				};
				if(isSameProject || (!route.params?.id && !query.id) || params2.id){
					data.dataLoad = false
					// dataDom.design?.init()
					return
				}
				nextTick(()=>{
					if(route.params?.id || query?.id){
						//切换新项目需要清除首次design提示
						sessionStorage.removeItem('firstDesign');

						if(data.openType == 'tools')data.isShowMark = true
						data.dataLoad = true
						if(query?.source != 'batch'){
							createData()
						}else{
							let arr = ['moodBoard','printBoard','sketchBoard','colorBoard']
							arr.forEach((item:any)=>{
								store.commit("clearAllBoardData",item);
							})
							store.commit("createProbject");
							store.commit("clearAllData");
						}
						getHistory(query.id || route.params?.id)
					}else{
						data.dataLoad = false
						createData()
					}
				})
				
			},
			{ immediate: true } // 立即触发一次以处理初始参数
		);
		const createData = ()=>{
			store.commit("createProbject");
			store.commit("clearAllData");
			store.commit("clearAllCollection");
			store.commit("setAllBoardDataChoose",{});
			store.commit("clearShowSketchboard",{});
			store.commit("clearAllCloudList");
			let arr = ['moodBoard','printBoard','sketchBoard','colorBoard']
			arr.forEach((item:any)=>{
				store.commit("clearAllBoardData",item);
			})
		}
		const getHistory = (id:any)=>{
			let value = {
				id,
			}
			if(!id)return data.isShowMark = false
			Https.axiosPost(Https.httpUrls.selectHistoryProject,value).then((rv: any) => {
				setProjectData(rv)
			}).catch((res)=>{
				data.isShowMark = false
			})
		}
		const setTask = (item:any)=>{
			emit('setTask',item)
		}
		const setProjectData = (rv:any)=>{
			let storeData = {
				name:rv.name,
				id:rv.id,
				type:rv.process == 'SERIES_DESIGN'?'seriesDesign':'singleProductDesign',
				httpType:rv.process,//项目类型
				ageGroup:rv.workspaceVO?.ageGroup,
				style:rv.workspaceVO?.style,
				styleId:rv.workspaceVO?.styleId,
				styleName:rv.workspaceVO?.styleName,
				sex:rv.workspaceVO?.sex,
				userBrandDnaImg:rv.workspaceVO?.userBrandDnaImg,
				userBrandDnaName:rv.workspaceVO?.userBrandDnaName,
				brandPercentage:rv.workspaceVO?.brandPercentage,
				userBrandDna:rv.workspaceVO?.userBrandDna,
				systemDesignerPercentage:rv.workspaceVO?.systemDesignerPercentage,
				position:{
					label:rv.workspaceVO?.positionEnum?.value,
					value:rv.workspaceVO?.positionEnum?.name
				},
				workspaceId:rv.workspaceVO?.id,
				positionList:[],
				publishData:{
					id:rv.portfolioDTO?.id?rv.portfolioDTO?.id:'',
					portfolioDes:rv.portfolioDTO?.portfolioDes?rv.portfolioDTO?.portfolioDes:'',
					portfolioName:rv.portfolioDTO?.portfolioName?rv.portfolioDTO?.portfolioName:'',
					tagsDTO:rv.portfolioDTO?.tagsDTO?rv.portfolioDTO?.tagsDTO:[],
				},
				// model:[]
			}
			let position = []
			if(storeData.sex == "Female"){
				position = store.state.UserHabit.FemalePosition
			}else{
				position = store.state.UserHabit.MalePosition
			}
			data.selectObject.positionList = position
			storeData.positionList = position
			store.commit('setProbject',storeData)
			// setChatData()
			if(route.name == 'tools'){
				getCollection('tools',null)	
			}else{
				getCollection('design',null)	
			}
		}
		const setChatData = ()=>{
			if(!data.chatData)return
			nextTick(()=>{
				dataDom.chatDom.enableThinking = data.chatData.enableThinking
				dataDom.chatDom.filList = data.chatData.filList
				dataDom.chatDom.chatContent = data.chatData.chatContent
				dataDom.chatDom.isFinish = true
				dataDom.chatDom.isChattingRecords = true
				dataDom.chatDom.sendChat()
				data.chatData = null
			})
			
		}
		// const setitemData = (arr:any)=>{
		// 	return new Promise((resolve,reject)=>{
		// 	    nextTick(()=>{
		// 			arr.forEach((rv:any)=>{
		// 				if(arr.indexOf(rv) > -1 || !dataDom[rv])return
		// 				dataDom[rv].openSetData()
		// 			})
		// 			resolve('')
		// 		})
		// 	})
		// }
		const getCollection = (type:string,module:any)=>{
			return new Promise((resolve, reject) => {
				let moduleList = [] as any
				if(type == 'design'){
					moduleList = ["moodBoard", "printBoard", "colorBoard", "sketchBoard",'design','mannequin','toProduct','relight','poseTransfer']
				}else{
					moduleList = ["printBoard", "colorBoard", "sketchBoard",'design','toProduct','relight','poseTransfer','mannequin',"patternMaking3D",'deReconstruction','uploadElement']
				}
				if(module)moduleList = [module]
				let value:any = {
					"id":data.selectObject.id,
					"moduleList":moduleList,
				}
				data.isShowMark = true
				Https.axiosPost(Https.httpUrls.getModuleContent,value).then(async (rv)=>{
					store.commit('clearAllCollection')
					if(rv.uploadElement){//toproduct、relight、poseTransfer
						let uploadElementData = {
							str:'add',
							list:rv.uploadElement,
							isGetModule:true,
						}
						store.commit('setUploadElement',uploadElementData)

					}
					historyChooseData(rv)//设置历史数据
					if(rv.mannequin.length>0){
						let arr = [] as any
						rv.mannequin.forEach((item:any)=>{
							arr.push({
								url:item.url,
								id:item.mannequinRelationId,
								type:item.mannequinRelationType,
								collectionElementId:item.collectionId,
								level3Type:item.level3Type
							})
						})
						store.commit('setProbject',{model:arr})
					}
					let allBoardData = ['sketchBoard','moodBoard','printBoard','colorBoard']
					// let allBoardData = ['sketchBoard','moodBoard','printBoard','colorBoard','toProduct','relight','poseTransfer','mannequin']
					let canvasData = ['deReconstruction']
					// let canvasData = ['canvas','deReconstruction']
					for (let index = 0; index < canvasData.length; index++) {
						const item = canvasData[index];
						await getCanvasData(item)
					}
					
					// await setitemData(allBoardData)
					//还有一个canvas
					if(rv.boundingBox)store.commit('setShowSketchboard',rv.boundingBox)
					
					allBoardData.forEach((item)=>{
						let value = {
							type:item,
							objectName:data.selectObject.type,
						}
						let arr  = ['sketchBoard','moodBoard','printBoard','colorBoard']
						if(arr.indexOf(item) != -1){
							// store.dispatch('setAllBoardData',value)
						}else{
							store.dispatch('setModularData',value)
						}
					})
					data.isShowMark = false
					data.dataLoad = false
					if(type == 'design' && dataDom.design){
						nextTick(()=>{
						dataDom.design.openSetData()
						})
					}
					resolve('')
				}).catch(()=>{
					data.isShowMark = false
					data.dataLoad = false
					resolve('')
				})
			})
			
		}
		const getCanvasData = (str:any)=>{
			return new Promise((resolve, reject) => {
				let value = {
					module:str,
					projectId:data.selectObject.id,
				}
				Https.axiosPost(Https.httpUrls.exportSearch, value)
				.then((rv) => {
					store.commit("setCanvasData", {type:str,file:rv});
					resolve('')
				})
				.catch((rv) => {
					resolve(null)
				});
			})
		}
		const historyChooseData = async (dataValue:any)=>{
			let ifMoodTemplateUrl = true
			if(dataValue?.moodBoard?.moodTemplateUrl){
				await new Promise<void>((resolve, reject) => {
					let img = new Image()
					img.src = dataValue.moodBoard?.moodTemplateUrl
					img.onload = ()=>{
						resolve()
					}
					img.onerror = ()=>{
						ifMoodTemplateUrl = false
						resolve()
					}
				})
			}
			let collectionData = {
				disposeMoodboard: (dataValue.moodBoard?.moodTemplateId && ifMoodTemplateUrl)?[{
					id:dataValue.moodBoard?.moodTemplateId,
					imgUrl:dataValue.moodBoard?.moodTemplateUrl,
					resData:{
						name:dataValue.moodBoard?.moodTemplateName,
					}
				}]:[],
				moodboardPosition:dataValue.moodBoard?.moodboardPosition?JSON.parse(dataValue.moodBoard?.moodboardPosition):{},
				moodboardFiles: dealViewChooseData(
					dataValue.moodBoard?.moodBoards,"Moodboard"
				),
				printboardFiles: dealViewChooseData(
					dataValue.printBoard,"Printboard"
				),
				generatePrintFiles: [],
				colorBoards: dealViewChooseColor(
					dataValue.colorBoard 
				),
				sketchboardFiles: dealViewChooseData(
					dataValue.sketchBoard,"Sketchboard"
				),
			};
			if(dataValue.moodBoard?.moodTemplateId)store.commit("setMoodTemplateId", dataValue.moodBoard.moodTemplateId);
			store.commit("setAllBoardDataChoose", collectionData);
			if(dataValue.sketchBoards)store.commit("setShowSketchboard", dataValue.sketchBoards);
			let likeDesignCollectionList:any = []
			if(dataValue.design?.userLikeDetails){
				dataValue.design?.userLikeDetails.map(
				(v: any) => {
					let dataValue = {
						...v, 
						groupDetailId: v.id,
						designItemUrl: v.designOutfitUrl,
						designItemId: v.designItemId,
					};
					return dataValue;
				}
			); 
			}
			if(dataValue.design?.userLikeDetails)store.commit("setLikeDesignCollectionList",dataValue.design?.userLikeDetails);
			store.commit("setUserGroupId", dataValue.design?.userGroupId);
			if(dataValue.toProduct){
				let value = {
					list:dataValue.toProduct.list.filter((rv)=>rv.status != 'Invalid' && rv.status != 'Fail'),
					likedList:dataValue.toProduct.likedList,
					str:'add',
					index:-1,
				}
				store.commit("setToProductImage", value);
			}
			if(dataValue.relight){
				let value = {
					list:dataValue.relight.list.filter((rv)=>rv.status != 'Invalid' && rv.status != 'Fail'),
					likedList:dataValue.relight.likedList,
					str:'add',
					index:-1,
				}
				store.commit("setRelightList", value);
			}
			if(dataValue.poseTransfer){
				let value = {
					list:dataValue.poseTransfer.list.filter((rv)=>rv.status != 'Invalid' && rv.status != 'Fail'),
					likedList:dataValue.poseTransfer.likedList,
					str:'add',
					index:-1,
				}
				store.commit("setPoseTransfer", value);
			}
			if(dataValue.patternMaking3D){
				let patternMaking3DData = {
					collectionElementId:dataValue.patternMaking3D.collectionElementId,
					threeDSimpleId:dataValue.patternMaking3D.threeDSimpleId,
					url:dataValue.patternMaking3D.printMinioUrl,
					printMinioUrl:getMinioUrl(dataValue.patternMaking3D.printMinioUrl),
					x:dataValue.patternMaking3D.x,
					y:dataValue.patternMaking3D.y,
				};
				store.commit('setPatternMaking3D',patternMaking3DData)
			}
			if(dataValue.deReconstruction){
				let deReconstruction = {
					str:'add',
					list:[
						{
							isLike:dataValue.deReconstruction.liked,
							category:dataValue.deReconstruction.category,
							url:dataValue.deReconstruction.collageSketchUrl,
							categoryValue:dataValue.deReconstruction.categoryValue,
						}
					]
				};
				let uploadImages = {
					str:'add',
					list:dataValue.deReconstruction?.uploadImages
				};
				store.commit('setDeReconstructionUploadImages',uploadImages)
			}
		}
		//统一处理选择组的渲染数据
		const dealViewChooseData = (dataValue: any,str:string)=> {
			if (!dataValue) {
				return [];
			}
			let filesList = dataValue.map((v: any) => {
				let newData: any = {
					imgUrl: v.url?v.url:v.designOutfitUrl,
					id: v.id,
					status: "done",
					resData: v,
					type_:{
						type1:'material',
						type2:v.level1Type
					}
				};
				if (v.level1Type === "Sketchboard") {
					newData.pin = v.isPin;
					newData.categoryValue = v.level2Type;
					newData.level2Type = v.level2Type;
				}
				if (v.level1Type === "Printboard") {
					newData.pin = v.isPin;
					newData.level2Type = v.level2Type;
					newData.categoryValue = v.level2Type;
				}
				return newData;
			});
			return filesList;
		}
		//统一处理选择组的渲染数据
		const dealViewChooseColor = (dataValue: any)=>{
			if(!dataValue)return [];
			let colorList = dataValue.map((v: any) => {
				let rgbValue = v.rgbValue.split(" ");
				let newData: any = {
					id: v.id,
					name: v.name,
					tcx: v.tcx || "",
					rgbValue: {
						r: rgbValue[0],
						g: rgbValue[1],
						b: rgbValue[2],
						a: 1,
					},
				};
				if(v.gradient){
					newData.gradient = v.gradient;
				}else{
					delete newData.gradient;
				}
				return newData;
			});
			return colorList;
		}
		let queue = [] as any
		let start = false
		const chatChange = (value:any)=>{

			if(value.type == 'design_control_signal' && dataDom.design){
				queue.push(
					{
						type:'design',
						fun:dataDom.design.designNewCollection,
					}
				)
				// dataDom.design.designNewCollection()
			}else{
				queue.push(
					{
						type:'promise',
						fun:getCollection,
						module:value.module,
						str:'design'
					}
				)
				// getCollection('design',value.module)
			}
			if(!start){
				startQueue()
			}
		}
		const startQueue = async ()=>{
			start = true
			if(queue[0].type){
				if(queue[0].type == 'promise'){
					await queue[0].fun(queue[0].str,queue[0].module)
				}else{
					await queue[0].fun()
				}
				queue.splice(0,1)
			}
			if(queue.length>0){
				startQueue()
			}else{
				start = false

			}
		}
		const newProject = (value:any)=>{
			emit('setNewProject')
			let chatModel = false
			if(value.newMode == 'chat'){
				chatModel = true
			}else{
				chatModel = false
			}
			router.push(`/home/history/${value?.id}`)
			// router.push(`home?history=${value.id}&chatMode=${chatModel}`)
			settingGetHistory()
			data.chatData = value
			
		}
		return{
			...toRefs(dataDom),
			...toRefs(data),
			setTask,
			chatChange,
			newProject,
		}
	},
	provide() {
		return {
		}
	},
})
</script>
<style lang="less" scoped>
	.homeBox{
		width: 100%;
		height: 100%;
		position: relative;
		> .show{
			width: 100%;
			height: 100%;
			> .function{
				width: 100%;
				height: 100%;
			}
		}
	}
</style>