<template>
    <div class="molepositon" :class="{active:!imgDesignImg}">
		<div class="designOpenrtion_imgMask" v-if="frontBack?.body?.path" :style="frontBack?.body?.style">
			<div class="designOpenrtion_print" v-for="item,index in frontBack.back" @mousedown.stop="itemMoveMousedown(index,getMousePosition($event,false))" @touchstart.passive="itemMoveMousedown(index,getMousePosition($event,true))" @click="setpitch(item,index)" :style="frontBack.front[index].style">
				<img :style="item.imageUrl?'':'display:none;'" :src="item.imageUrl" alt="">
			</div>
			<img class="perview_img" ref="detailBody" :src="frontBack?.body?.path" :style="'width:'+ frontBack?.body?.layersObject?.[0].imageSize?.[0] +';height:' + frontBack?.body?.layersObject?.[0].imageSize?.[0] +';'"  v-lazy="frontBack?.body?.layersObject?.[0].imageUrl || ''">
			<div  class="detail_modal_item_front"  v-for="item,index in frontBack.front"  @mousedown.stop="itemMoveMousedown(index,getMousePosition($event,false))" @touchstart.passive="itemMoveMousedown(index,getMousePosition($event,true))" @click="setpitch(item,index)"  :style="item.style">
				<img :src="item.imageUrl" alt="">
			</div>
			<div class="designOpenrtion_btnBox">
				<ul v-for="item,index in frontBack.front" :key="item" :class="{active:item.designOpenrtionBtn}" class="designOpenrtion_btn" :style="item.style" @mousedown.stop="itemMoveMousedown(index,getMousePosition($event,false))" @touchstart.passive="itemMoveMousedown(index,getMousePosition($event,true))">
					<li class="designOpenrtion_btn_top" @mousedown.stop="itemSizeMousedown('top',getMousePosition($event,false))" @touchstart.passive="itemSizeMousedown('top',getMousePosition($event,true))"></li>
					<li class="designOpenrtion_btn_bottom" @mousedown.stop="itemSizeMousedown('bottom',getMousePosition($event,false))" @touchstart.passive="itemSizeMousedown('bottom',getMousePosition($event,true))"></li>
					<li class="designOpenrtion_btn_left" @mousedown.stop="itemSizeMousedown('left',getMousePosition($event,false))" @touchstart.passive="itemSizeMousedown('left',getMousePosition($event,true))"></li>
					<li class="designOpenrtion_btn_right" @mousedown.stop="itemSizeMousedown('right',getMousePosition($event,false))" @touchstart.passive="itemSizeMousedown('right',getMousePosition($event,true))"></li>
				</ul>
			</div>
		</div>
		<div class="designOpenrtion_imgMask" v-else>
			<img :src="selectDetail.undividedLayer" alt="">
		</div>
    </div>
	<div class="molepositon" :class="{active:imgDesignImg}">
		<div class="designOpenrtion_imgMask">
			<div class="detail_modal_item_front">
				<img :src="designDetail.designItemUrl" alt="">
			</div>
		</div>
	</div>
</template>
<script lang="ts">
import { defineComponent,computed,inject,watch,nextTick,createVNode,toRefs, reactive} from 'vue'
// import setDesignItem from '@/component/Detail/setDesignItem2.vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Https } from "@/tool/https";
import { useStore } from "vuex";
import { useI18n } from 'vue-i18n'
import { getMousePosition } from "@/tool/mdEvent";
import { Modal,message } from 'ant-design-vue';
import newFollowVue from '@/component/Account/message/newFollow.vue';
export default defineComponent({
    components:{
    },
	props:{
	    imgDesignImg:{
            default:false,
			type:Boolean,
		}
	},
	emits:['canvasReload'],
    setup(props,{emit}) {
		const {t} = useI18n()
        const store = useStore();
		const detailData = reactive({
			frontBack:computed(()=>store.state.DesignDetailCopy.frontBack),
			designDetail:computed(()=>store.state.DesignDetailCopy.designDetail),
			isEditPattern:inject('isEditPattern') as any,
			singleOveral:inject('singleOveral') as any,
			detailBody:null as any,
		})
		const selectItem = reactive({
		    selectDetail:computed(()=>store.state.DesignDetailCopy.selectDetail),
		    imgDomIndex:-1,
		    printZIndex:store.state.DesignDetailCopy.printZIndex,
			imgDom:null as any,
			direction:'',
		})
		watch(()=>selectItem.selectDetail,(newValue,oldValue)=>{
			if(newValue.id == oldValue?.id)return
			selectItem.imgDomIndex = detailData.frontBack.front.findIndex((item:any)=>item.id == newValue.id)
		},{immediate: true,})
		watch(()=>detailData.frontBack?.body?.path,(newVal)=>{
			
			let sacle = 0
			const img = new Image();
			img.onload = () => {
				// resolve(img)
				sacle = detailData.detailBody.parentNode.offsetWidth / img.width
				detailData.frontBack.front.forEach((item:any,index:number) => {
					for (const key in item.style) {
						if(key == 'zIndex')return
						let value = item.style[key]
						if(typeof value !== 'number'){
							value = value.replace('px','')
							item.style[key] = value
						}else{
							item.style[key] = value*sacle+'px'
						}
						// item.style[key] = value*sacle+'px'
					}
					for (const key in detailData.frontBack.back[index].style) {
						if(key == 'zIndex')return
						let value = detailData.frontBack.back[index].style[key]
						if(typeof value !== 'number'){
							value = value.replace('px','')
							detailData.frontBack.back[index].style[key] = value
						}else{
							detailData.frontBack.back[index].style[key] = value*sacle+'px'
						}
						// detailData.frontBack.back[index].style[key] = value*sacle+'px'
					}
				});
			};
			img.src = newVal;
		},{immediate: true,})
		const getDetailListDom = reactive({
			libraryList:null as any,
		})

		//设置尺寸
		const itemSizeMousedown = (direction:any,event:any)=>{
			selectItem.direction = direction
			selectItem.imgDom = document.getElementsByClassName('molepositon')[0].getElementsByClassName("detail_modal_item_front")[selectItem.imgDomIndex]
			detailData.frontBack.front[selectItem.imgDomIndex].designOpenrtionBtn = true
			let imgDomWH = selectItem.imgDom.getBoundingClientRect()
			let li = (document.getElementsByClassName('molepositon')[0].getElementsByClassName("designOpenrtion_btn_top")[0] as any).offsetWidth/2
			if(selectItem.direction == 'right' || selectItem.direction == 'bottom'){
				detailData.frontBack.front[selectItem.imgDomIndex].centers.left = imgDomWH.x+event.offsetX-li
				detailData.frontBack.front[selectItem.imgDomIndex].centers.top = imgDomWH.y+event.offsetY-li
			}else{
				detailData.frontBack.front[selectItem.imgDomIndex].centers.left = imgDomWH.x+event.offsetX+imgDomWH.width-li
				detailData.frontBack.front[selectItem.imgDomIndex].centers.top = imgDomWH.y+event.offsetY+imgDomWH.height-li
			}
			
			document.addEventListener('mousemove', sizeMouseMove);
			document.addEventListener('touchmove', sizeTouchmove);
			document.addEventListener('mouseup', sizeMouseup);
			document.addEventListener('touchend', sizeMouseup);
		}
		const sizeMouseMove = (event:any)=>{
			let e = getMousePosition(event,false)
			sizeMouseMoveOperation(e)
		}
		const sizeTouchmove = (event:any)=>{
			let e = getMousePosition(event,true)
			sizeMouseMoveOperation(e)
		}
		const sizeMouseup = (e:any)=>{
			detailData.frontBack.front[selectItem.imgDomIndex].style={
				right:'auto',
				left:selectItem.imgDom.offsetLeft+'px',
				bottom:'auto',
				top:selectItem.imgDom.offsetTop+'px',
				height:selectItem.imgDom.offsetHeight+'px',
				width:selectItem.imgDom.offsetWidth+'px',
				zIndex:selectItem.printZIndex
			}
			detailData.frontBack.back[selectItem.imgDomIndex].style.zIndex = selectItem.printZIndex
			document.removeEventListener('mousemove',sizeMouseMove)
			document.removeEventListener('touchmove',sizeTouchmove)
			document.removeEventListener('mouseup',sizeMouseup) 
			document.removeEventListener('touchend',sizeMouseup) 
		}
		const sizeMouseMoveOperation = (e:any)=> {
			let imgDomWH = selectItem.imgDom.getBoundingClientRect()
			let parentNode =selectItem.imgDom.parentNode
			let width = imgDomWH.width
			let height = imgDomWH.height
			let w,h
			let num = height/width
			//判断移动四个边
			if(selectItem.direction == 'right'){
				w = (e.clientX - detailData.frontBack.front[selectItem.imgDomIndex].centers.left)
				h = (e.clientX - detailData.frontBack.front[selectItem.imgDomIndex].centers.left)*num
				width = w+'px'
				// height = w*num+'px'
			}else if(selectItem.direction == 'top'){
				num = width/height
				detailData.frontBack.front[selectItem.imgDomIndex].style.top = 'auto'
				// this.printStyleList[selectItem.imgDomIndex].style.left = 'auto'
				detailData.frontBack.front[selectItem.imgDomIndex].style.bottom = parentNode.offsetHeight -imgDomWH.height - selectItem.imgDom.offsetTop+'px'
				w = (e.clientX - detailData.frontBack.front[selectItem.imgDomIndex].centers.left)*num
				h = (detailData.frontBack.front[selectItem.imgDomIndex].centers.top - e.clientY)
				
				height = h+'px'
				// width = h*num+'px'
			}else if(selectItem.direction == 'bottom'){
				num = width/height
				h = (e.clientY - detailData.frontBack.front[selectItem.imgDomIndex].centers.top)
				height = h+'px'
				// width = h*num+'px'
			}else if(selectItem.direction == 'left'){
				detailData.frontBack.front[selectItem.imgDomIndex].style.left = 'auto'
				detailData.frontBack.front[selectItem.imgDomIndex].style.right = parentNode.offsetWidth -imgDomWH.width - selectItem.imgDom.offsetLeft+'px'
				w = (detailData.frontBack.front[selectItem.imgDomIndex].centers.left - e.clientX)
				
				width = w+'px'
				// height = w*num+'px'
			}
			//判断尺寸是否到边
			detailData.frontBack.front[selectItem.imgDomIndex].style.width = width
			detailData.frontBack.front[selectItem.imgDomIndex].style.height = height
		}
		// 设置移动
		const mouseMove = (event:any)=>{
			let e = getMousePosition(event,false)
			mouseMoveOperation(e)
		}
		const touchmove=(event:any)=>{
			let e = getMousePosition(event,true)
			mouseMoveOperation(e)
		}
		const mouseup = (e:any)=> {
			document.removeEventListener('mousemove',mouseMove)
			document.removeEventListener('touchmove',touchmove)
			document.removeEventListener('mouseup',mouseup) 
			document.removeEventListener('touchend',mouseup) 
		}
		const mouseMoveOperation = (e:any)=>{
			let imgDomWH = selectItem.imgDom.getBoundingClientRect()
			let parentNode = document.getElementsByClassName('molepositon')[0].getElementsByClassName("designOpenrtion_imgMask")[0].getBoundingClientRect()
			let x = (e.clientX - detailData.frontBack.front[selectItem.imgDomIndex].centers.left)+'px'
			let y = ( e.clientY - detailData.frontBack.front[selectItem.imgDomIndex].centers.top)+'px'
			detailData.frontBack.front[selectItem.imgDomIndex].style.left = x
			detailData.frontBack.front[selectItem.imgDomIndex].style.top = y
		}
		const clothesOpenActive = (index:number)=>{
			// this.designItemDetail.clothes.forEach((item)=>{
			// 	item.clothesOpenItem = false
			// })
			// if(index != -1){
			// 	this.designItemDetail.clothes[index].clothesOpenItem = true
			// }
		}
		const itemMoveMousedown = async (index:any,e:any)=>{
			let isOpen = false
			let isModal = false
			await new Promise((resolve, reject) => {
				if(
					detailData.isEditPattern.value && 
					selectItem.selectDetail?.id && 
					(detailData.frontBack.front[index].id != selectItem.selectDetail.id)
				){
					isModal = true
					Modal.confirm({
						title: t('collectionModal.jsContent2'),
						icon: createVNode(ExclamationCircleOutlined),
						okText: 'Yes',
						cancelText: 'No',
						mask:false,
						centered:true,
						onOk() {
							resolve(true)
							isOpen = true
						},
						onCancel(){
							resolve(false)
							isOpen = false
						}
					});
				}else{
					resolve(true)
					isModal = false
				}
			}).then((rv)=>{
			})
			if(isOpen){
				store.commit('DesignDetailCopy/setDesignColthes',detailData.frontBack.front[index].id)
				emit('canvasReload')	
				return 
			}						
			
			if(isModal)return						
			store.commit('DesignDetailCopy/setDesignColthes',detailData.frontBack.front[index].id)
			selectItem.imgDomIndex = index
			detailData.frontBack.front.forEach((v:any)=>{
				v.designOpenrtionBtn = false
			})
			clothesOpenActive(index)
			let event = e||window.event
			selectItem.imgDom = document.getElementsByClassName('molepositon')[0].getElementsByClassName("detail_modal_item_front")[selectItem.imgDomIndex]
			detailData.frontBack.front[index].designOpenrtionBtn = true
			detailData.frontBack.front[index].style.zIndex = selectItem.printZIndex++
			detailData.frontBack.back[index].style.zIndex = selectItem.printZIndex
			let imgDomWH = selectItem.imgDom.getBoundingClientRect()
			let left = Number(detailData.frontBack.front[index].style.left.replace(/px/g,''))
			let top = Number(detailData.frontBack.front[index].style.top.replace(/px/g,''))
			detailData.frontBack.front[index].centers.left = imgDomWH.x+event.offsetX-left
			detailData.frontBack.front[index].centers.top = imgDomWH.y+event.offsetY-top

			document.addEventListener('mousemove', mouseMove);
			document.addEventListener('touchmove', touchmove);
			document.addEventListener('mouseup', mouseup);
			document.addEventListener('touchend', mouseup);
		}
		const sort = (arr:any)=>{
			arr.sort((a:any, b:any) => {
				var a_num = a.style.zIndex;
				var b_num = b.style.zIndex;
				return a_num - b_num;
			});
			return arr
		}
		const getSubmitData = (value:any)=>{
			let parentNode = document.getElementsByClassName('molepositon')[0].getElementsByClassName("designOpenrtion_imgMask")[0].getBoundingClientRect()
			let ratio = detailData.frontBack.body.layersObject[0].imageSize[0]/parentNode.width
			// let arr:any = sort(detailData.frontBack.front)
			let arr:any = sort(JSON.parse(JSON.stringify(detailData.frontBack.front)))
			let num = 10
			arr.forEach((item:any)=>{
				item.priority = num++
			})
			let data:any = {
				scale:null,
				offset:null,
				priority:'',
				maskUrl:'',
				maskMinioUrl:'',
			}
			let state = false
			for (let index = 0; index < arr.length; index++) {
				if(value.id == arr[index].id){
					state = true
					let y = ((arr[index]?.style?.top.replace(/px/g,'')*ratio).toFixed(0) as any - arr[index]?.position[0])
					let x = ((arr[index]?.style?.left.replace(/px/g,'')*ratio).toFixed(0) as any - arr[index]?.position[1])
					let scaleWidth = arr[index]?.imageSize?Number(((arr[index]?.style?.width.replace(/px/g,'')*ratio)/(arr[index]?.imageSize[0]/arr[index].scale[0])).toFixed(2)):1
					let scaleHeight = arr[index]?.imageSize?Number(((arr[index]?.style?.height.replace(/px/g,'')*ratio)/(arr[index]?.imageSize[1]/arr[index].scale[1])).toFixed(2)):1
					// let widthScale = (arr[index].style.width.replace(/px/g,'')/arr[index].style.height.replace(/px/g,'')).toFixed(2)
					data.scale = [scaleWidth,scaleHeight]
					let top = y == 0 ? value.layersObject[0].offset[1]:y+value.layersObject[0].offset[1]
					let left = x == 0 ? value.layersObject[0].offset[0]:x+value.layersObject[0].offset[0]
					data.offset = [left?left:0,top?top:0]
					// data.offset = [left?left:0,top?top:0]
					data.maskUrl = arr[index].maskUrl
					data.maskMinioUrl = arr[index].maskMinioUrl
					// data.priority = arr[index].style.zIndex
					data.priority = arr[index].priority
					arr[index].similarity = true
					// item.offset = [(arr[index]?.style?.left.replace(/px/g,'')*ratio).toFixed(0),(i?.style?.top.replace(/px/g,'')*ratio).toFixed(0)]
					break
				}
			}
			if(!state){
				data.scale = [1,1]
				data.offset = [0,0]
				data.priority = 10+arr.length
			}
			return data
		}
		const deleteNav = ()=>{

		}
		const setpitch = (item:any,index:any)=>{
			detailData.frontBack.front.forEach((v:any)=>{
				v.designOpenrtionBtn = false
			})
			detailData.frontBack.front[index].designOpenrtionBtn = true
			detailData.frontBack.front[index].style.zIndex = selectItem.printZIndex++
			detailData.frontBack.back[index].style.zIndex = selectItem.printZIndex
			clothesOpenActive(index)
		}
		const updataPosition = ()=>{
			let url = detailData.frontBack?.body?.path
			let sacle = 0
			const img = new Image();
				img.onload = () => {
					let dom:any = document.querySelector('.molepositon .perview_img')
					// resolve(img)
					sacle = dom.parentNode.offsetWidth / img.width
					detailData.frontBack.front.forEach((item:any,index:number) => {
						for (const key in item.style) {
							if(key == 'zIndex')return
							item.style[key] = item.style[key]*sacle+'px'
						}
						for (const key in detailData.frontBack.back[index].style) {
							if(key == 'zIndex')return
							detailData.frontBack.back[index].style[key] = detailData.frontBack.back[index].style[key]*sacle+'px'
						}
					});
				};
				img.src = url;
		}
        return{
			...toRefs(detailData),
			...toRefs(selectItem),
			...toRefs(getDetailListDom),
			
			itemSizeMousedown,
			itemMoveMousedown,
			deleteNav,
			setpitch,
			getSubmitData,
			getMousePosition,
			updataPosition,
        }
    },
	directives:{
		detailBody:{
			mounted (el,data:any) {
				let sacle = 0
				const img = new Image();
				img.onload = () => {
					// resolve(img)
					sacle = el.parentNode.offsetWidth / img.width
					data.instance.frontBack.front.forEach((item:any,index:number) => {
						for (const key in item.style) {
							if(key == 'zIndex')return
							item.style[key] = item.style[key]*sacle+'px'
						}
						for (const key in data.instance.frontBack.back[index].style) {
							if(key == 'zIndex')return
							data.instance.frontBack.back[index].style[key] = data.instance.frontBack.back[index].style[key]*sacle+'px'
						}
					});
				};
				img.src = data.value;
			},
			updated (el,data:any) {
				let sacle = 0
				const img = new Image();
				img.onload = () => {
					// resolve(img)
					sacle = el.parentNode.offsetWidth / img.width
					console.log(sacle,123)
					data.instance.frontBack.front.forEach((item:any,index:number) => {
						for (const key in item.style) {
							if(key == 'zIndex')return
							console.log(item.style[key].replace(/px/g,''))
							item.style[key] = item.style[key].replace(/px/g,'')*sacle+'px'
							// console.log(item.style[key])
						}
						for (const key in data.instance.frontBack.back[index].style) {
							if(key == 'zIndex')return
							data.instance.frontBack.back[index].style[key] = data.instance.frontBack.back[index].style[key].replace(/px/g,'')*sacle+'px'
						}
					});
				};
				img.src = data.value;
			}
		}
	},
	provide() {
		return {
		}
	},
		
})
</script>
<style lang="less" scoped>
    .molepositon{
		// width: 30rem;
		// width: calc(66 * .470rem);
		width: calc(66 * .457rem);
		height: 66rem;
		display: flex;
		flex-direction: column;
		// margin: auto 0;
		// padding-top: 3rem;
		position: relative;
		display: none;
		&.active{
			display: block;
			z-index: 2;
		}
		> .designOpenrtion_imgMask{
			width: auto;
			height: auto;
			position: relative;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			>img{
				z-index: 2;
				position: relative;
				width: 100%;
				height: auto;
				// height: 100%;
				// object-fit: contain;
			}
			>div{
				position: absolute;
				top: 0;
			}
			.designOpenrtion_print{
				img{
					object-fit: cover;
				}
			}
			.detail_modal_item_front,.designOpenrtion_print{
				z-index: 2;
				height: 100%;
				width: 100%;
				img{
					width: 100%;
					height: 100%;
					// width: 100%;
					// height: auto;
					float: left;
					user-select:none;
					-webkit-user-drag: none;
				}
				.modal_imgItem{
					position: absolute;
					overflow: hidden;
					top: 0;
					
				}
			}
			.designOpenrtion_print{
				z-index: 1 !important;
			}
			> .designOpenrtion_btnBox{
				z-index: 99;
				width: 100%;
				height: 100%;
				left: 0;
				ul{
					list-style: none;
					// width: 100%;
					// height: 100%;
					position: absolute;
					top: 0;
					left: 0;
					box-sizing: border-box;
					border: 2px solid rgb(20, 188, 255);
					padding: 0;
					-webkit-user-drag: none;
					user-select:none;
					opacity: 0;
					margin: 0;
					
					li{
						cursor: pointer;
						// border-radius: 50%;
						width: calc(2rem*1.2);
						height: calc(2rem*1.2);
						background-color: rgb(20, 188, 255);
						position: absolute;
						pointer-events: none;
					}
					&.active{
						opacity: 1;
						z-index: 999 !important;
						li{
							pointer-events: auto;
						}
					}
					.designOpenrtion_btn_top,.designOpenrtion_btn_bottom{
						left: 50%;
						transform: translate(-50%,-50%) ;
						cursor: n-resize;
					}
					.designOpenrtion_btn_top{
						top: 0;
					}
					.designOpenrtion_btn_bottom{
						top: 100%;
					}
					.designOpenrtion_btn_left,.designOpenrtion_btn_right{
						top: 50%;
						transform: translate(-50%,-50%) ;
						cursor: e-resize;
					}
					.designOpenrtion_btn_left{
						left: 0;
					}
					.designOpenrtion_btn_right{
						left: 100%;
					}
					.designOpenrtion_rotote{
						top: 50%;
						left: 50%;
						transform: translate(-50%,-50%);
						width: 0;
						height: 0;
					}
					.designOpenrtion_rotote::after{
						position: absolute;
						content: "";
						background-color: #14bcff;
						width: 2px;
						height: 30px;
						left: 50%;
						bottom: 0;
						transform: translateX(-50%);
					}
					.designOpenrtion_rotote::before{
						position: absolute;
						content: "";
						background-color: #14bcff;
						top: calc(50% - 30px);
						left: 50%;
						transform: translate(-50%,-50%) ;
						width: calc(1.5rem*1.2);
						height: calc(1.5rem*1.2);
						border-radius: 50%;
					}
				}
			}
		}
	}
</style>