<template>
    <div ref="designDetailModal" class="designDetailModal" v-if="designDetailShow">
		<!-- designDetailShow -->
		<!-- :class="[driver__.driver?'hideEvents':'']" -->
        <a-modal class="Guide_1_18 generalModel fullScreen" 
            v-model:visible="designDetailShow" 
            :footer="null" 
			:get-container="() => $refs.designDetailModal"
            width="100%"
			height="100%"
            :maskClosable="false"
			:mask="false"
            :centered="true"
			:keyboard="false"
			:destroyOnClose="true"
			:closable="false"
        >
			<div class="content">
				<div class="nav" :class="{isEditPattern:isEditPattern.value}">
					<div class="back_home">
						<div class="gallery_btn" @click="closeModal()">
							<i class="fi fi-rs-house-chimney"></i>
						</div>
					</div>
					<div class="nav_list">
						<div class="nav_item" :class="{active:currentDetailType == 'sketch'}" @click="setCurrentDetail('sketch')">
							<img src="@/assets/images/icon/details_sketch.png" alt="">
							<div class="detailText">{{$t('DesignPrintOperation.Apparel')}}</div>
						</div>
						<div class="nav_item" :class="{active:currentDetailType == 'print'}" @click="setCurrentDetail('print')">
							<img src="@/assets/images/icon/details_print.png" alt="">
							<div class="detailText">{{$t('DesignPrintOperation.Print')}}</div>
						</div>
						<div class="nav_item" :class="{active:currentDetailType == 'color'}" @click="setCurrentDetail('color')">
							<img src="@/assets/images/icon/details_color.png" alt="">
							<div class="detailText">{{$t('DesignPrintOperation.Color')}}</div>
						</div>
						<div class="nav_item" :class="{active:currentDetailType == 'element'}" @click="setCurrentDetail('element')">
							<img src="@/assets/images/icon/details_elements.png" alt="">
							<div class="detailText">{{$t('DesignPrintOperation.Elements')}}</div>
						</div>
						<!-- <div class="nav_item" :class="{active:currentDetailType == 'accessory'}" @click="setCurrentDetail('accessory')">
							<img src="@/assets/images/icon/details_elements.png" alt="">
							<div class="detailText">{{$t('DesignPrintOperation.Accessory')}}</div>
						</div> -->
						<div class="nav_item" v-if="selectObject.type == 'seriesDesign'" :class="{active:currentDetailType == 'models'}" @click="setCurrentDetail('models')">
							<img src="@/assets/images/icon/details_model.svg" alt="">
							<div class="detailText">{{$t('DesignPrintOperation.Model')}}</div>
						</div>
					</div>
				</div>
				<div class="item detailLeft" :class="{isEditPattern:isEditPattern.value}">
					<detailLeft v-if="currentDetailType" ref="detailLeft" :detailLeftColorKey="detailLeftColorKey"></detailLeft>
					<!-- <detailLeft v-if="selectDetail && selectDetail.id && currentDetailType"></detailLeft> -->
					 <div class="btn" style="margin: 0;" v-show="currentDetailType == 'color'">
						<div class="gallery_btn" @click="previwe">{{$t('DesignPrintOperation.Preview')}}</div>
					</div>
				</div>

				<div class="item model" >
					<model 
						ref="model" 
						:key="positionKey"
						@detailEdit="detailEdit" 
						@addSketch="()=>isEditPattern.value = ''"
						@revocation="revocation"
						@oppositeRevocation="oppositeRevocation"
						@sketchSysToLibrary="sketchSysToLibrary"
					></model>
					<div class="btn">
						<div class="gallery_btn" style="margin-right: 0;" @click="submit">{{$t('DesignPrintOperation.Submit')}}</div>
						<div v-show="isEditPattern.value" style="margin-left: 2rem;" class="gallery_btn" @click="previwe">{{$t('DesignPrintOperation.Preview')}}</div>
					</div>
				</div>
				<div class="item detailRight" :class="{canvas:isEditPattern.value}">
					<div class="submit">
					</div>
					<div class="contentRight" v-if="currentDetailType === 'sketch' && !selectDetail?.newDetail?.[currentDetailType] && !selectDetail.sketchString && !isEditPattern.value">
						<img 
							style="width: 100%; height: 100%;object-fit: contain;"
							:src="
							'/image/toolsGuide/' +
							(locale == 'ENGLISH' ? 'detailEN' : 'detailCN') +
							'.png'
						" alt="">
					</div>
					<div class="contentRight" v-else-if="currentDetailType && !isEditPattern.value">
						<detailRight ref="detailRight" :sketchSize="sketchSize"></detailRight>
						<div class="btn" 
							v-show="
								currentDetailType !== 'color' &&
								(currentDetailType === 'element' ||
								currentDetailType === 'accessory' ||
								currentDetailType === 'print' ||
								(currentDetailType === 'sketch' && selectDetail?.newDetail?.[currentDetailType])|| 
								(currentDetailType === 'sketch' && selectDetail?.sketchString)|| 
								(currentDetailType === 'models' && designDetail?.newModel))
								"
						>
							<div class="gallery_btn" @click="previwe">{{$t('DesignPrintOperation.Preview')}}</div>
						</div>
					</div>
					<div class="contentRight canvas" v-if="selectDetail && selectDetail.id && currentDetailType" :class="{'active': isEditPattern.value}">
						<canvasBox ref="canvasBox" v-model:loadingShow="loadingShow" :key="canvasKey" :sketchSize="sketchSize" @setSloganData="setSloganData" :isEditPattern="isEditPattern.value" :updateOtherLayers="updateOtherLayers"></canvasBox>
					</div>
					<!-- 画布 -->
					<!-- <div class="content" v-else-if="selectDetail && selectDetail.id">
					</div> -->
				</div>
			</div>
        </a-modal>
         <div class="mark_loading" v-show="loadingShow">
            <a-spin size="large" />
        </div>
    </div>
    
</template>
<script lang="ts">
import { defineComponent,computed,onBeforeUnmount,provide,nextTick,createVNode,toRefs, reactive, onMounted, watch} from 'vue'
import detailLeft from './detailLeft/index.vue'
import model from './model/index.vue'
import detailRight from './detailRight/index.vue'
import canvasBox from './canvas/index.vue'

// import setDesignItem from '@/component/Detail/setDesignItem2.vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Https } from "@/tool/https";
import { Modal,message } from 'ant-design-vue';
import {getUploadUrl,segmentImage,setGradual,rgbToHsv,rgbaToHex} from '@/tool/util'
import { useStore } from "vuex";
import { openGuide,driverObj__ } from "@/tool/guide";
import { KeyValueDB } from "@/tool/indexedDB";
import { useI18n } from 'vue-i18n'
import { convertToEC4StyleForCustomSerise } from 'echarts/types/src/util/styleCompat.js'
export default defineComponent({
    components:{
		detailLeft,model,detailRight,canvasBox
    },
	emits:['destroy'],
    setup(props,{emit}) {
        const store = useStore();
		const {locale} = useI18n()
		const detailDom = reactive({
			model:null,
			canvasBox,
			detailRight,
			detailLeft:null as any,
		})
		const userDetail = computed(()=>{
			return store.state.UserHabit.userDetail
		})
		const detailData = reactive({
			selectObject:computed(()=>store.state.Workspace.probjects) as any,//选择的项目
			designDetail:computed(()=>store.state.DesignDetail.designDetail),
			currentDetailType:computed(()=>store.state.DesignDetail.currentDetailType),
			frontBack:computed(()=>store.state.DesignDetail.frontBack),
			selectDetail:computed(()=>store.state.DesignDetail.selectDetail),
			designDetailShow:false,
			loadingShow:false,
			oppositeRevocationShow:-1,
			imgDomIndex:-1,
			revocationShow:-1,
			isEditPattern:{
				value:'' as any,
			},// 是否编辑图案
			canvasKey:computed(()=>store.state.DesignDetail.canvasKey),
			singleOveral:{
				value:'overall'
			},
			getCanvasIfEdit:{
				fun:null,
			},
			positionKey:0,
			detailLeftColorKey:0,
			sketchSize:{
				width:0,
				height:0,
			}
		})
		const getSketchSize:any = async ()=>{
			let img = new Image();
			img.src = detailData.selectDetail.path;	
			await new Promise((resolve, reject) => {
				img.onload = () => {
					detailData.sketchSize.width = img.width
					detailData.sketchSize.height = img.height
					resolve([img.width, img.height]);
				}
				img.onerror = reject;
			});
		}
		watch(()=>detailData.selectDetail,async (newValue,oldValue)=>{
			detailData.imgDomIndex = detailData.frontBack.front.findIndex((item:any)=>item.id == newValue.id)
			if(newValue?.path)await getSketchSize()
			if(newValue?.id && (newValue?.id != oldValue?.id)){
				store.commit('DesignDetail/changeCanvasKey')
			}
			// privewDetail(oldValue)
		},{immediate: true})
		provide('getCanvasIfEdit',detailData.getCanvasIfEdit)
		provide('singleOveral',detailData.singleOveral)
		provide('isEditPattern',detailData.isEditPattern)
		const closeModal = async ()=>{
			await KeyValueDB.remove('oppositeRevocation')
			await KeyValueDB.remove('revocation')
			detailData.designDetailShow = false
			emit('destroy')
		}
		
		const showDesignDetailModal = (data:any,str:any)=>{
			return new Promise<void>((resolve, reject) => {
				store.commit('DesignDetail/clearDetailData')
				// let url = Https.httpUrls.getDesignDetail + `?designItemId=${77770}&designPythonOutfitId=${77423}`
				let url = Https.httpUrls.getDesignDetail + `?designItemId=${data.design.designItemId}&designPythonOutfitId=${data.design.designOutfitId}`
				detailData.loadingShow = true
				Https.axiosGet(url).then(
					async (rv: any) => {
						//清除画布JSON数据
						await KeyValueDB.remove('canvasList');
						await KeyValueDB.remove('revocation');
						await KeyValueDB.remove('oppositeRevocation');
						store.commit('DesignDetail/setDesignDetail',rv)
						rv.clothes.forEach((item:any)=>{
							let a
							item.designType='Library'
							if(item.layersObject[0].imageCategory.indexOf("back") == -1){
								a = item.layersObject[0]
								item.layersObject[0] = item.layersObject[1]
								item.layersObject[1] = a
							}
							if(item.color){
								item.color.rgba = {
									r:item.color.r,
									g:item.color.g,
									b:item.color.b,
								}
							}else{
								item.color = {
									// rgba:{
									// 	r:undefined,
									// 	g:undefined,
									// 	b:undefined,
									// }
								}
							}
							if(item.gradient){
								item.color.gradient = item.gradient
							}
							if(item.printObject.prints == null)item.printObject.prints = []
							item.printObject.prints.forEach((element:any) => {
								if(!element.designType){
									element.designType = 'Library'
								}
							});
						})
						detailData.singleOveral.value = rv.singleOverall
						detailData.designDetailShow = true
						// this.deleteShow = false
						setRevocation()
						if(rv.singleOverall == "single"){
							store.commit('DesignDetail/setDesignColthes',rv.clothes[0].id)
						}


						// detailData.loadingShow = false
						resolve(rv)
					}
				).catch(rv=>{
					detailData.loadingShow = false
					resolve(rv)
				})
			})
			
		}
		//撤回
		const setRevocation = async ()=>{//设置撤销
			let itemDetail = JSON.parse(JSON.stringify(detailData.designDetail))
			let revocation:any = JSON.parse((await KeyValueDB.get("revocation") as any) || 'null')
			if(!revocation)revocation = []
			// let oppositeRevocation = JSON.parse((await KeyValueDB.get("oppositeRevocation") as any))
			// if(revocation?.[0]?.designItemId != itemDetail.designItemId || revocation?.[0]?.designItemId == undefined){
			// 	revocation = []
			// }
			revocation.push({designData:itemDetail,position:null})
			detailData.revocationShow = revocation?.length
			await KeyValueDB.set('revocation', JSON.stringify(revocation));
			await KeyValueDB.set('oppositeRevocation',JSON.stringify([]));
		}
		provide('setRevocation',setRevocation)

		const revocation = async ()=>{//撤回
			let oppositeRevocation = JSON.parse((await KeyValueDB.get("oppositeRevocation") as any) || 'null')
			let revocation = JSON.parse((await KeyValueDB.get("revocation") as any) || 'null')
			if(revocation.length <= 1)return
			oppositeRevocation.push(revocation[revocation.length-1])
			revocation.splice(revocation.length-1,1)
			detailData.revocationShow = revocation.length
			// store.commit("DesignDetail/setDesignDetail", revocation[revocation.length-1]);
			if(revocation[revocation.length-1].designData){
				store.commit('DesignDetail/setDesignDetail',revocation[revocation.length-1].designData)
			}else{
				store.commit('DesignDetail/setFrontBack',revocation[revocation.length-1].position)
			}
			store.commit('DesignDetail/setDesignColthes',detailData.selectDetail.id)
			await KeyValueDB.set('oppositeRevocation', JSON.stringify(oppositeRevocation));
			await KeyValueDB.set('revocation', JSON.stringify(revocation));
			// clearSelect()
			detailData.positionKey++
		}
		const oppositeRevocation = async ()=>{//反撤回
			let oppositeRevocation = JSON.parse((await KeyValueDB.get("oppositeRevocation") as any) || 'null')
			let revocation = JSON.parse((await KeyValueDB.get("revocation") as any) || 'null')
			// if(!oppositeRevocation[oppositeRevocation.length-1].designData)return
			if(oppositeRevocation.length < 1)return
			if(oppositeRevocation[oppositeRevocation.length-1]?.designData){
				store.commit('DesignDetail/setDesignDetail',oppositeRevocation[oppositeRevocation.length-1].designData)
			}else if(oppositeRevocation[oppositeRevocation.length-1]?.position){
				store.commit('DesignDetail/setFrontBack',oppositeRevocation[oppositeRevocation.length-1].position)
			}
			store.commit('DesignDetail/setDesignColthes',detailData.selectDetail.id)
			revocation.push(oppositeRevocation[oppositeRevocation.length-1])
			detailData.revocationShow = revocation.length
			oppositeRevocation.splice(oppositeRevocation.length-1,1)
			detailData.oppositeRevocationShow = oppositeRevocation.length
			await KeyValueDB.set('oppositeRevocation', JSON.stringify(oppositeRevocation));
			await KeyValueDB.set('revocation', JSON.stringify(revocation));
			// this.clearSelect()
			detailData.positionKey++
		}
		const setCurrentDetail = (str:string)=>{
			store.commit('DesignDetail/setCurrentDetailType',str)
		}
		const setClothes = async (list:any,str:string)=>{
			let clothesList:any = []
			if(detailData.isEditPattern.value == 'editSketch')await detailDom.canvasBox.submitBase64Data().then((rv)=>{
				detailData.selectDetail.sketchString = rv
			})
			if(detailDom.detailRight?.privewDetail)await (detailDom.detailRight as any).privewDetail()
			if(detailDom.canvasBox && (detailData.currentDetailType != 'sketch' || detailData.isEditPattern.value == 'canvasEditor')){
				// if(detailData.isEditPattern.value !== 'editSketch'){
				// 	let otherDataupDateFrontBackSketch = await updateOtherLayers(detailData.isEditPattern.value == 'canvasEditor'?'all':'single')
				// 	await detailDom.canvasBox.updateOtherLayers(otherData)
				// }
				await detailDom.canvasBox.privewDetail()
				await uploadSelectDetail()
				await uploadElement()
			}
			for(let i = 0;i<list.length;i++){
				detailData.selectDetail
			    let {scale,offset,priority,transpose,rotate,maskUrl,maskMinioUrl} = await (detailDom.model as any).getSubmitData(list[i])
				let newData = list[i]?.newDetail
				// newData[0].location=[
				// 	-233.13985,
				// 	406.90964
				// ]	
				// newData[0].scale=[
				// 0.5,
				// 0.35822305
				// ]	
				let isCurrent = list[i].id == detailData?.selectDetail?.id
				let color = ''
				let gradient = null
				if((detailData.currentDetailType == 'color' || detailData.isEditPattern.value == 'canvasEditor') && isCurrent){
					color = `${newData?.color.rgba.r} ${newData?.color.rgba.g} ${newData?.color.rgba.b}`
					if(newData?.color.gradient){
						gradient = newData?.color.gradient
					}
				}else if(isCurrent){
					color = list[i].color?.rgba?.r?`${list[i].color.rgba.r} ${list[i].color.rgba.g} ${list[i].color.rgba.b}`:''
					gradient = list[i].gradient
				}
				if(detailData.currentDetailType == 'sketch' && newData?.sketch){
					color = detailData.designDetail.clothes?.[0]?.color?.rgba?.r?`${detailData.designDetail.clothes?.[0].color.rgba.r} ${detailData.designDetail.clothes[0].color.rgba.g} ${detailData.designDetail.clothes[0].color.rgba.b}`:''
					detailData.selectDetail.maskUrl = ''
					detailData.selectDetail.maskMinioUrl = ''
				}
				const printObjectToJSON = (list:any)=>{
					if(list?.length > 0){
						list.forEach((item:any)=>{
							if(item.object)item.object = JSON.stringify(item.object)
						})
					}
				}
				let data:any = {
					changed:false,
					color,
					gradient,
					designType:(newData?.sketch && detailData.currentDetailType == 'sketch' && isCurrent && !detailData.isEditPattern.value)?newData?.sketch.designType:list[i].designType,
					id:(newData?.sketch && detailData.currentDetailType == 'sketch' && isCurrent && !detailData.isEditPattern.value)?newData?.sketch.id:list[i].id,
					maskMinioUrl:((newData?.sketch && detailData.currentDetailType == 'sketch') || list[i].sketchString)?'':list[i]?.maskMinioUrl,
					// maskUrl:'',
					maskUrl:list[i]?.maskUrl || '',
					// offset:[
                    //                 -233.13985,
                    //                 406.90964
                    //             ],
					offset,
					transpose,
					rotate,
					partialDesign:list[i].partialDesign,
					// partialDesign:detailData.isEditPattern.value?list[i].partialDesign:{},
					path:(newData?.sketch && detailData.currentDetailType == 'sketch' && isCurrent && !detailData.isEditPattern.value)?newData?.sketch.minIOPath:list[i].minIOPath,
					printObject:((newData?.print?.length>0 && (detailData.currentDetailType == 'print' || detailData.isEditPattern.value == 'canvasEditor')) && isCurrent)?{prints:newData.print}:list[i].printObject?list[i].printObject:{prints:[]},
					priority,
					// scale:[
                    //                 0.5,
                    //                 0.35822305
                    //             ],
					scale:[scale[0]?scale[0]:1,scale[1]?scale[1]:1],
					type:(newData?.sketch && detailData.currentDetailType == 'sketch' && isCurrent && !detailData.isEditPattern.value)?newData?.sketch.level2Type || newData?.sketch.categoryValue:list[i].type,
					sketchString:list[i].sketchString?list[i].sketchString:'',
					trims:((newData?.element?.length>0 && (detailData.currentDetailType == 'element' || detailData.isEditPattern.value == 'canvasEditor')) && isCurrent)?{prints:newData.element}:list[i].trims?.prints?list[i].trims:{prints:[]},
				}
				printObjectToJSON(data.printObject.prints)
				printObjectToJSON(data.trims.prints)
				if((detailData.isEditPattern.value && list[i].color?.gradient) || (!detailData.isEditPattern.value && (list[i].newDetail?.color?.gradient || list[i].color?.gradient))){
					gradient = list[i].newDetail?.color?.gradient || list[i].color.gradient
					gradient.colorImg = await setGradual(gradient,320,700)
					data.gradient = gradient
				}
				clothesList.push(data)
			}
			return clothesList
		}
		const getSubmitData = async (str:string)=>{
			// return
			await new Promise<void>(async (resolve, reject) => {
				let workspace = store.state.Workspace.probjects
				if(!detailData?.selectDetail?.path && !detailData?.selectDetail?.newDetail?.sketch?.minIOPath)return
				let clothes:any
				if(detailData.currentDetailType == 'models'){
					clothes = await setClothes(detailData.designDetail.clothes,str)
				}else{
					clothes = await setClothes([detailData.selectDetail],str)
				}
				let isDefault = detailData.selectDetail.sketchString || (!detailData.selectDetail.id || (detailData.selectDetail?.newDetail?.sketch && detailData.currentDetailType == 'sketch')) 
				let data = {
					designItemId:detailData.designDetail.designItemId,
					designSingleItemDTOList:clothes,
					isPreview:str == 'sub'?false:true,
					// ifSubmit:designItemDetail.isPreview,
					gender:workspace?.sex,
					sketchString:'',
					modelId:(detailData.currentDetailType == 'models' && detailData.designDetail.newModel)?detailData.designDetail.newModel.id:detailData.designDetail.oldModel?detailData.designDetail.oldModel.id:'',
					modelType:(detailData.currentDetailType == 'models' && detailData.designDetail.newModel)?detailData.designDetail.newModel.type:detailData.designDetail.oldModel?detailData.designDetail.oldModel.type:'',
					designType:isDefault?'default':'merge',
					timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,
					processId:userDetail.value.userId,
					probjectId:store.state.Workspace.probjects.id,
				}
				await Https.axiosPost(Https.httpUrls.designSingle, data).then(async (rv)=>{
					let value = {
						currentType : JSON.parse(JSON.stringify(detailData.currentDetailType)),
						rv:rv,
					}
					if(detailData?.designDetail?.newModel)detailData.designDetail.oldModel = JSON.parse(JSON.stringify(detailData.designDetail.newModel))

					// delete detailData.designDetail.newModel
					let el:any = document.querySelector('.molepositon .perview_img')
					let scale = 0
					await new Promise<void>(async (resolve, reject) => {
						if(!detailData.frontBack.body.path)resolve(true)
						const img = new Image();
						img.src = detailData.frontBack.body.path;
						img.onload = () => {
							scale = el.parentNode.offsetWidth / img.width;
							resolve(true)
						};
					})
					value.scale = scale
					store.commit('DesignDetail/setPraeview',value)
					store.commit('DesignDetail/changeCanvasKey')
					// console.log(detailData.selectDetail)
					// if(detailData.selectDetail.sketchString || (detailData.selectDetail?.newDetail?.sketch && detailData.currentDetailType == 'sketch')){
					// 	detailData.canvasKey += 1
					// }
					detailData.selectDetail.sketchString = null
					resolve(true)
					canvasReload()
					// setRevocation()
				}).catch(res=>{ 
					resolve(true)
				});
			})
			
		}
		const submit = async ()=>{
			detailData.loadingShow = true
			let workspace = store.state.Workspace.probjects
			let clothes:any = await setClothes(detailData.designDetail.clothes,'sub')
			let data = {
				designItemId:detailData.designDetail.designItemId,
				designSingleItemDTOList:clothes,
				isPreview:false,
				// ifSubmit:designItemDetail.isPreview,
				gender:workspace?.sex,
				sketchString:'',
				modelId:(detailData.currentDetailType == 'models' && detailData.designDetail.newModel)?detailData.designDetail.newModel.id:detailData.designDetail.oldModel?detailData.designDetail.oldModel.id:'',
				modelType:(detailData.currentDetailType == 'models' && detailData.designDetail.newModel)?detailData.designDetail.newModel.type:detailData.designDetail.oldModel?detailData.designDetail.oldModel.type:'',
				designType:detailData.selectDetail.id?'merge':'default',
				timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,
				processId:userDetail.value.userId,
				probjectId:store.state.Workspace.probjects.id,
			}
			Https.axiosPost(Https.httpUrls.designSingle, data).then(async (rv)=>{
				saveCanvasJSONToSession()
				// store.commit('DesignDetail/setPraeview',rv)
				const sessionCanvasList = await KeyValueDB.get('canvasList');
				const canvasList = sessionCanvasList ? JSON.parse(sessionCanvasList) : []
				for (let i = 0; i < canvasList.length; i++) {
					const index = detailData.designDetail.clothes.findIndex(item => item.id === canvasList[i].id);
					if(index>-1)await detailDom.canvasBox.saveCanvas(canvasList[i])
				}
				let designCollectionList = store.state.HomeStoreModule.designCollectionList
				let likeDesignCollectionList = store.state.HomeStoreModule.likeDesignCollectionList
				designCollectionList.forEach((item:any) => {
					if(item.designItemId == rv.designItemId){
						item.designOutfitUrl = rv.designItemUrl
					}
				});
				likeDesignCollectionList.forEach((item:any) => {
					if(item.designItemId == rv.designItemId){
						item.designOutfitUrl = rv.designItemUrl
					}
				});
				store.commit('setDesignCollectionList',designCollectionList)
				store.commit('setLikeDesignCollectionList',likeDesignCollectionList)
				closeModal()
				detailData.loadingShow = false
			}).catch(res=>{ 
				detailData.loadingShow = false
            });
		}
		const previwe = async ()=>{
			detailData.loadingShow = true
			if((detailData.currentDetailType == 'models' && !detailData.isEditPattern.value) || (detailData.currentDetailType == 'sketch' && !detailData.isEditPattern.value) || detailData.isEditPattern.value == 'editSketch'){
				await getSubmitData('preview')
				if(detailData.currentDetailType == 'models')return detailData.loadingShow = false
				await getSketchSize()
				detailDom.canvasBox.changeSketchUpdateFrontBack = async ()=>{
					await detailDom.canvasBox.privewDetail()
					detailDom?.model?.updateRect()
					await upDateFrontBackSketch()
					detailData.loadingShow = false
				}
			}else{
				//走画布合成图片并且直接分割
				if(detailData.isEditPattern.value !== 'canvasEditor'){
					if(detailDom.detailRight?.privewDetail)await (detailDom.detailRight as any).privewDetail()
					let otherData = await updateOtherLayers('single')
					await detailDom.canvasBox.updateOtherLayers(otherData)
				}
				await detailDom.canvasBox.privewDetail()
				await upDateFrontBackSketch()
				await uploadSelectDetail()
				saveCanvasJSONToSession()
				detailData.loadingShow = false
			}
		}
		const upDateFrontBackSketch = async ()=>{//更新模特身上的分割图
			await new Promise<void>(async(resolve, reject) => {
				let img = new Image()
				img.onload = ()=>{
					let partialDesign = detailData.selectDetail.partialDesign.partialDesignBase64 || detailData.selectDetail.partialDesign.partialDesignPath
					let size = {
						width:img.width,
						height:img.height,
					}
					segmentImage(detailData.selectDetail.maskUrl,partialDesign,size).then(async (rv)=>{
						let front = detailData.frontBack.front[detailData.imgDomIndex]
						let back = detailData.frontBack.back[detailData.imgDomIndex]

						front.oldImageUrl = ''
						front.oldMaskUrl = ''
						back.oldImageUrl = ''
						front.imageUrl = rv.targetFrontUrl
						back.imageUrl = rv.targetBackUrl
						store.commit('DesignDetail/canvasPreviewUpdata',{type:detailData.isEditPattern.value?'all':detailData.currentDetailType,callBack:setRevocation})
						resolve()
					})
				}
				img.src = detailData.selectDetail.path
			})
		}
		const saveCanvasJSONToSession = async ()=>{
			let canvasJSON = detailDom.canvasBox.getCanvasJSON()
			const sessionCanvasList = await KeyValueDB.get('canvasList');
			const list = sessionCanvasList ? JSON.parse(sessionCanvasList) : []
			let index = -1
			list.forEach((item:any,i:number)=>{
				if(item.id == detailData.selectDetail.id){
					index = i
				}
			})
			if(index < 0){
				list.push({id:detailData.selectDetail.id,canvasJSON:canvasJSON})
			}else{
				list[index].canvasJSON = canvasJSON
			}
			await KeyValueDB.set('canvasList', JSON.stringify(list));
		}
		const detailEdit = async (str:any)=>{
			if(str){
				if(detailData.isEditPattern.value && detailData.isEditPattern.value == str){
					// await detailDom.canvasBox.saveCanvas()
					await (detailDom.canvasBox as any).privewDetail()
					if(detailData.isEditPattern.value == 'canvasEditor')await uploadElement()
					detailData.isEditPattern.value = ''
				}else{
					// if(detailData.isEditPattern.value && (str == 'canvasEditor' || str == 'redGreenExample')){
					// 	detailDom.canvasBox.editFront(str)
					// }
					detailDom.canvasBox.editFront(str)
					if(str == 'canvasEditor'){
						if(detailDom.detailRight?.privewDetail)await (detailDom.detailRight as any).privewDetail()
						let otherData = await updateOtherLayers('single')
						await detailDom.canvasBox.updateOtherLayers(otherData)
					}
					detailData.isEditPattern.value = str
				}
			}else{
				detailData.isEditPattern.value = ''
			}
		}
		const getColorName = (color:any)=>{
			let rgb:any = [color.r, color.g, color.b];
			let hsv = rgbToHsv(rgb);
			let data = [{
				h: hsv[0],
				s: hsv[1],
				v: hsv[2],
			}]
			return new Promise((resolve, reject) => {
			    Https.axiosPost(Https.httpUrls.getRgbByHsvBatch, data)
					.then((rv) => {
						if (rv) {
							resolve(rv[0])
						}
					})
					.catch((res) => {
						resolve({name:'--',tcx:'--'})
					});
			})
		}
		const updateOtherLayers = async (str:any='all',type:any='noFirst')=>{//更新到画布图层
			let otherData:any = {}
			if(str == 'all'){
				await uploadSelectDetail()
				otherData = {
					color: detailData.selectDetail.color,
					printObject: detailData.selectDetail.printObject || null,
					trims: detailData.selectDetail.trims || null,
				}	
			}else if(str == 'single'){
				otherData = {
					color: detailData.selectDetail.color,
					printObject: detailData.selectDetail.printObject || null,
					trims: detailData.selectDetail.trims || null,
				}	
				if(detailData.currentDetailType == 'color'){
					let color = detailData.selectDetail.newDetail?.color
					// let colorData:any = await getColorName(color?.rgba)
					if(detailData.selectDetail.newDetail?.color){
						if(color.r){
							color.rgba = {r:color.r,g:color.g,b:color.b,a:color.a}
						}else{
							color.rgba = {}
						}
						otherData.color = color
					}
				}
				if(detailData.currentDetailType == 'print'){
					if(detailDom.detailRight?.privewDetail)await (detailDom.detailRight as any).privewDetail()
					otherData.printObject = {prints:detailData.selectDetail.newDetail?.print || []}
				}
				if(detailData.currentDetailType == 'element'){
					otherData.trims = {prints:detailData.selectDetail.newDetail?.element || []}
				}
			}
			return otherData
		}
		const uploadElement = async ()=>{//取出画布数据更新到detail
			if(detailData.isEditPattern.value == 'canvasEditor'){
				// await detailDom.canvasBox.saveCanvas()
				const allInfo = await (detailDom.canvasBox as any).getCanvasElement()
				let trimsValue = {
					data:allInfo.trims || [],
					str:'element'
				}
				store.commit('DesignDetail/setNewDetail',trimsValue)
				let printValue = {
					data:allInfo.prints || [],
					str:'print'
				}
				store.commit('DesignDetail/setNewDetail',printValue)
				if(allInfo.color?.color?.rgba || allInfo.color?.color?.gradient){
					let value:any = {
						str:'color',
						data:{},
					}
					let canvasColor = allInfo.color.color;
					if(allInfo.color?.color?.rgba){
						let colorData:any = await getColorName(allInfo.color.color?.rgba)
						value.data = {
							hsv:{
								h:colorData.h,
								s:colorData.s,
								v:colorData.v,
							},
							name:colorData.name,
							tcx:colorData.tcx,
							rgba:canvasColor.rgba,
							hex:rgbaToHex([canvasColor.rgba.r,canvasColor.rgba.g,canvasColor.rgba.b]),
						}
					}
					if(canvasColor.gradient){
						value.data.gradient = canvasColor.gradient
					}
					store.commit('DesignDetail/setNewDetail',value)
					if(allInfo.color.color.gradient)detailData.selectDetail.color.gradient = allInfo.color.color.gradient
					if(detailData.currentDetailType == 'color'){
						detailData.detailLeftColorKey++
					}
				}else{
					let value = {
						data:{},
						str:'color'
					}
					store.commit('DesignDetail/setNewDetail',value)
				}
			}
		}
		const uploadSelectDetail = async ()=>{//更新选中的detail
			// await detailDom.canvasBox.saveCanvas()
			const allInfo = await (detailDom.canvasBox as any).getCanvasElement()
			let color:any = {}
			if(allInfo.color?.color?.rgba || allInfo.color?.color?.gradient){
				let canvasColor = allInfo.color.color;
				if(canvasColor?.rgba?.r){
					let colorData:any = await getColorName(allInfo.color.color?.rgba)
					color = {
						hsv:{
							h:colorData.h,
							s:colorData.s,
							v:colorData.v,
						},
						name:colorData.name,
						tcx:colorData.tcx,
						rgba:canvasColor.rgba,
						hex:rgbaToHex([canvasColor.rgba.r,canvasColor.rgba.g,canvasColor.rgba.b]),
					}
				}
				if(canvasColor.gradient){
					color.gradient = canvasColor.gradient
				}
				if(detailData.currentDetailType == 'color'){
					detailData.detailLeftColorKey++
				}
			}
			if(detailData.isEditPattern.value == 'canvasEditor'){
				delete detailData.selectDetail.newDetail
				detailData.selectDetail.trims.prints = allInfo.trims || []
				detailData.selectDetail.printObject.prints = allInfo.prints || []
				detailData.selectDetail.color = color
			}else{
				if(detailData.currentDetailType == 'color'){
					if(detailData.selectDetail.newDetail?.color)delete detailData.selectDetail.newDetail.color
					detailData.selectDetail.color = color
				}
				if(detailData.currentDetailType == 'print'){
					if(detailData.selectDetail.newDetail?.print)delete detailData.selectDetail.newDetail.print
					detailData.selectDetail.printObject.prints = allInfo.prints || []
				}
				if(detailData.currentDetailType == 'element'){
					if(detailData.selectDetail.newDetail?.element)delete detailData.selectDetail.newDetail.element
					detailData.selectDetail.trims.prints = allInfo.trims || []
				}
			}
			
			
		}
		const canvasReload = async ()=>{
			if(detailData.isEditPattern.value){
				await detailDom.canvasBox.saveCanvas()
			}
		}
		const sketchSysToLibrary = ()=>{//系统sketch添加到library更新library
			coverRevocation()
			detailDom.detailLeft.sketchSysToLibrary()
		}
		const coverRevocation = async ()=>{
			let itemDetail = JSON.parse(JSON.stringify(detailData.designDetail))
			let revocation = JSON.parse((await KeyValueDB.get("revocation") as any) || 'null')
			revocation.splice(revocation.length-1,1,{designData:itemDetail,position:null})
			await KeyValueDB.set('revocation', JSON.stringify(revocation));
			await KeyValueDB.set('oppositeRevocation',JSON.stringify([]));
		}
		const setSloganData = (data:any)=>{
			detailData.selectDetail.sketchString = data
			if(detailData.currentDetailType == 'sketch' && detailData.selectDetail?.newDetail?.sketch){
				detailData.selectDetail.newDetail.sketch = null
			}
		}
		onMounted(()=>{
		})
		onBeforeUnmount(async ()=>{
			await KeyValueDB.remove('oppositeRevocation')
			await KeyValueDB.remove('revocation')
			store.commit('DesignDetail/clearDetailData')

		})
		
        return{
			locale,
			...toRefs(detailDom),
			...toRefs(detailData),
            closeModal,
			showDesignDetailModal,
			setCurrentDetail,
			previwe,
			submit,
			revocation,
			oppositeRevocation,
			detailEdit,
			canvasReload,
			sketchSysToLibrary,
			setSloganData,
			updateOtherLayers,//更新到画布图层 再canvasInit中执行
        }
    },
	
	provide() {
		return {
		}
	},
	mounted(){
		let beforeunload =  () => {
			window.removeEventListener('beforeunload',beforeunload)
		}
		window.addEventListener('beforeunload',beforeunload)
		
	},
		
})
</script>
<style lang="less" scoped>
	:deep(.detailText){
		font-size: 1.6rem;
		font-weight: 600;
		
	}
    .designDetailModal{
		position: absolute;
		// top: -100%;
		width: 100.5%;
		height: 100.5%;
		left: 50%;
		top: 50%;
		transform: translate(-50%,-50%);
		z-index: 2;
		:deep(>div){
			> .ant-modal-root{
				> .ant-modal-centered{
					overflow: hidden;
					> .fullScreen{
						> .ant-modal-content{
							box-shadow: none;
							> .ant-modal-body{
								padding: 0;
							}
						}
					}
				}
			}
			:deep(.ant-modal-wrap){
				.ant-modal-body{
					// padding: 0;
				}
				// position: absolute;
				// top: 0;
				// left: 0;
			}
		}
		.content{
			display: flex;
			align-items: flex-start;
			height: 100%;
			width: 100%;
			> .item{
				height: 100%;
				overflow: hidden;
				&.detailLeft{
					width: 30rem;
					// width: 34rem;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					overflow: hidden;
				}
				&.isEditPattern{width: 0px;}
				&.model{
					flex: 1;
					// width: 45rem;
					// width: 50rem;
					margin: 0 8rem;
					// margin: 0 10rem;
					display: flex;
					flex-direction: column;
				}
				&.detailRight{
					width: 30%;
					&.canvas{
						width: 60%;
					}
					display: flex;
					flex-direction: column;
					// padding-bottom: calc(6rem + 1rem);
					overflow: hidden;
					> .contentRight{
						text-align: center;
						display: flex;
						flex: 1;
						flex-direction: column;
						overflow: hidden;
						&.canvas{
							opacity: 0;
							position: absolute;
							flex: auto;
							width: 35vw;
							height: 80vh;
							pointer-events: none;
							transform: translate(100vw,100vh);
						}
						&.active{
							position: relative;
							opacity: 1;
							flex: 1;
							width: auto;
							height: auto;
							pointer-events: auto;
							transform: translate(0,0);
						}
					}
				}
				.btn{
					margin-top: auto;
				}
				> .submit{
					display: flex;
					justify-content: flex-end;
					margin-bottom: 1rem;
					&.bottom{
						margin-top: 1rem;
						margin-bottom: 0;
					}
				}
				> .btn{
					display: flex;
					justify-content: center;
					margin-left: 12rem;
				}
			}
			> .nav{
				margin-right: 5rem;
				overflow: hidden;
				// transition: all .3s;
				&.isEditPattern{width: 0px;margin: 0;}
				> .back_home{
					width: 9rem;
					text-align: center;
					> .gallery_btn{
						width: 6rem;
						height: 6rem;
						margin-top: 2rem;
						border-radius: 50%;
					}
				}
				> .nav_list{
					margin-top: 2.7rem;
					// height: 38rem;
					width: 9rem;
					background: #f4f4f4;
					border-radius: 1.4rem;
					padding: 1.4rem 0;
					> .nav_item{
						text-align: center;
						width: 100%;
						height: calc((38rem - 1.4rem * 2) / 4);
						cursor: pointer;
						display: flex;
						align-items: center;
						flex-direction: column;
						justify-content: center;
						> img{
							width: 4rem;
							height: 3.6rem;
							object-fit: contain;
						}
						&.active{
							background: #bdbdbd;
						}
					}
				}
			}
			
		}
		
	}
</style>