<template>
	<div class="design_compile_content" id="design_compile_content">
		<div class="designOpenrtion_centent" id="designOpenrtionCentent">
			<div class="detail_modal_body_nav">
				<div v-for="item,index in designItemDetail?.clothes" v-show="item.id" :class="{active:item.clothesOpen}" @click="clothesOpen(index)">
					<img :src="item?.path" alt="">
				</div>
			</div>
			<div class="designOpenrtion_imgMask" :style="frontBack?.body?.style">
				<!-- <div 
					v-for="item,index in frontBack.back" 
					:key="item"
					:style="item.style" 
					@touchstart.passive="itemMoveMousedown(index,$event)"
					class="modal_imgItem" 
					@click="setpitch(item,index)" ref="content" >
					<img crossOrigin="anonymous" :src="item.path" class="designOpenrtion_imgItme" draggable="false"> 
				</div> -->
				<div class="designOpenrtion_print" v-for="item,index in frontBack.back" @touchstart.passive="itemMoveMousedown(index,$event)" @click="setpitch(item,index)" :style="frontBack.front[index].style">
					<img :style="item.imageUrl?'':'display:none;'" :src="item.imageUrl" alt="">
				</div>
				<img class="perview_img" :style="'width:'+ frontBack?.body?.layersObject?.[0].imageSize?.[0] +';height:' + frontBack?.body?.layersObject?.[0].imageSize?.[0] +';'"  v-lazy="frontBack?.body?.layersObject?.[0].imageUrl || ''" :key="designItemDetail.designItemUrl">
				<div class="detail_modal_item_front" v-for="item,index in frontBack.front"  @touchstart.passive="itemMoveMousedown(index,$event)" @click="setpitch(item,index)"  :style="item.style">
					<img :src="item.imageUrl" alt="">
				</div>
				<div class="designOpenrtion_btn">
					<ul v-for="item,index in frontBack.front" :key="item" :class="{active:item.designOpenrtionBtn}" class="designOpenrtion_btn" :style="item.style" @touchstart.passive="itemMoveMousedown(index,$event)">
						<li class="designOpenrtion_btn_top" @touchstart.passive="itemSizeMousedown('top',$event)"></li>
						<li class="designOpenrtion_btn_bottom" @touchstart.passive="itemSizeMousedown('bottom',$event)"></li>
						<li class="designOpenrtion_btn_left" @touchstart.passive="itemSizeMousedown('left',$event)"></li>
						<li class="designOpenrtion_btn_right" @touchstart.passive="itemSizeMousedown('right',$event)"></li>
						<!-- <li class="designOpenrtion_rotote" v-rotote.stop="[index,item.transform]"></li> -->
					</ul>
				</div>
			</div>
			<div class="subitOkPreviewBtn" @click="imgClear">{{ $t('LibraryPage.Reset') }}</div>
			<div @click="setPreviewData" class="subitOkPreviewBtn">OK</div>
		</div>
		<div class="designOpenrtion_imgMask_open" @click.stop="deleteBorder"></div>
	</div>
	
</template>

<script >
import { defineComponent, h,createVNode, ref ,computed, inject,nextTick} from "vue";
import { useStore } from "vuex";
import { Https } from "@/tool/https";
export default defineComponent({
    // props: ["frontBack"],
	emits:['setParentLoadingShow','setDesignCoverage','setSubmit'],
    setup(prop) {
        const store = useStore();

		let designItemDetail = computed(()=>{
			return store.state.DesignDetailModule.designItemDetail
		})
		let current = inject('current')//父组件传过来的数据
        let setRevocation = inject('setRevocation')//父组件传过来的数据
		let printZIndex = ref(4)//印花优先级
        let printStyleList = ref([
			{
				centers:{
					left:0,
					top:0,
				},
				style:{
					left:0+"px",
					top:0+"px",
					right:"auto",
					bottom:"auto",
					width:100+'px',
					height:100+'px',
					// zIndex:1,
				},
				transform:{
					scale:1,
					rotateZ:0,
				},
				designOpenrtionBtn:false
			}
		]);
		let direction = ref('')
		let imgDom = ref()
		let imgDomIndex = ref(0)
		let frontBack = ref({})
		let frontBackOld = ref({})
        return {
			designItemDetail,
			current,
			printZIndex,
            printStyleList,
			direction,//判断点击的是li那个边
			imgDom,
			imgDomIndex,
			frontBack,
			setRevocation,
			frontBackOld
        };
    },
    data() {
        return {
            loadingShow:false,//加载中
            store: useStore(),
			setImgSizeTimeout:null
        };
    },
	mounted () {
		window.addEventListener('resize', this.setImgSizeTime);
	},
    methods: {
		init(){
			let DesignParent = this.$parent
			// this.clearModal()
			// console.log(this.current,DesignParent.frontBack);
			this.printStyleList.push({
				centers:{
					left:0,
					top:0,
				},
				style:{
					left:0+"px",
					top:0+"px",
					right:"auto",
					bottom:"auto",
					width:100+'px',
					height:100+'px',
					// zIndex:1,
				},
				transform:{
					scale:1,
					rotateZ:0,
				},
				designOpenrtionBtn:false
			})
			this.setImgSize()
		},
		setImgSizeTime(){
			clearTimeout(this.setImgSizeTimeout)
			this.setImgSizeTimeout = setTimeout(()=>{
				this.setImgSize()
			},300)
		},
		async setImgSize(){
			this.frontBack.body = null
			let designItemDetail = JSON.parse(JSON.stringify(this.store.state.DesignDetailModule.designItemDetail))
			let front = []
			let back = []
			let body
			
			designItemDetail.others.forEach((item) => {
				if(item.type == 'Body'){
					body = item
				}
			});
			let ratio = await this.setPostition(body.layersObject[0]?.imageUrl)
			let frontIndex = 6
			let backIndex = 3
			// let front = 3
			// let back = 3
			designItemDetail.clothes.forEach((v,index)=>{
				for (let i = v.layersObject.length-1; i >= 0; i--) {
					v.layersObject[i].style = {
						top:v.layersObject[i].position?.[0]*ratio+'px',
						left:v.layersObject[i].position?.[1]*ratio+'px',
						width:v.layersObject[i].imageSize?.[0]*ratio+'px',
						height:v.layersObject[i].imageSize?.[1]*ratio+'px',
						// zIndex:zIndex-=1
					}
					v.layersObject[i].centers={
						left:0,
						top:0,
					}
					v.layersObject[i].designOpenrtionBtn = false
					if(v.layersObject[i].imageCategory.indexOf("back") == -1){
						front[index] = v.layersObject[i]
						front[index].style.zIndex = v.priority
						front[index].id = v.id
					}else{
						back[index] = v.layersObject[i]
						back[index].style.zIndex = v.priority
						back[index].id = v.id

						// back[index].style.zIndex = backIndex==0?v.layersObject[i]:backIndex++
					}
					if(this.printZIndex < v.priority){
						this.printZIndex = v.priority
					}
				}
				this.printZIndex++
			})
			let bodyImgWH = document.getElementsByClassName("design_compile_content")[0].getElementsByClassName("perview_img")[0]

			body.style = {
				width:body.layersObject[0].imageSize?.[0]*ratio+'px',
				height:body.layersObject[0].imageSize?.[1]*ratio+'px',
			}
			this.frontBack = {
				front:front,
				back:back,
				body:body,
			}
			this.frontBackOld = JSON.parse(JSON.stringify({
				front:front,
				back:back,
				body:body,
			}))
		},
		imgClear(){
			this.frontBack = JSON.parse(JSON.stringify(this.frontBackOld))
		},
		//按比设置单件衣服宽高位置
		async setPostition(url){
			let img = await loadImage(url)
			let modal_body = document.getElementsByClassName('designOpenrtion_imgMask')[0]
			const num = modal_body?.offsetHeight / img.height;
			function loadImage(url) {
				return new Promise((resolve, reject) => {
					const img = new Image();
					img.onload = () => {
						resolve(img)
						img.remove()
					};
					img.onerror = reject;
					img.src = url;
				});
			}
			return num
		},
		clear(){
			window.removeEventListener('resize', this.setImgSizeTime);
		},
		setpitch(item,index){
			this.frontBack.front.forEach((v)=>{
				v.designOpenrtionBtn = false
			})
			this.frontBack.front[index].designOpenrtionBtn = true
			this.frontBack.front[index].style.zIndex = this.printZIndex++
			this.frontBack.back[index].style.zIndex = this.printZIndex
			this.clothesOpenActive(index)
		},
		// 设置移动
		itemMoveMousedown(index,e){
			this.imgDomIndex = index
			this.frontBack.front.forEach((v)=>{
				v.designOpenrtionBtn = false
			})
			this.clothesOpenActive(index)
			let event = e||window.event
			this.imgDom = document.getElementsByClassName('design_compile_content')[0].getElementsByClassName("detail_modal_item_front")[this.imgDomIndex]
			this.frontBack.front[index].designOpenrtionBtn = true
			this.frontBack.front[index].style.zIndex = this.printZIndex++
			this.frontBack.back[index].style.zIndex = this.printZIndex
			let imgDomWH = this.imgDom.getBoundingClientRect()
			let left = Number(this.frontBack.front[index].style.left.replace(/px/g,''))
			let top = Number(this.frontBack.front[index].style.top.replace(/px/g,''))
			this.frontBack.front[index].centers.left = imgDomWH.x+event.changedTouches[0].pageX - this.imgDom.getBoundingClientRect().left-left
			this.frontBack.front[index].centers.top = imgDomWH.y+event.changedTouches[0].pageY - this.imgDom.getBoundingClientRect().top-top
			document.addEventListener("touchend", this.touchend);
			document.addEventListener("touchmove", this.moveMousemove);
		},
		//设置尺寸
		itemSizeMousedown(direction,event){
			this.direction = direction
			this.imgDom = document.getElementsByClassName('design_compile_content')[0].getElementsByClassName("detail_modal_item_front")[this.imgDomIndex]
			this.frontBack.front[this.imgDomIndex].designOpenrtionBtn = true
			let imgDomWH = this.imgDom.getBoundingClientRect()
			let li = document.getElementsByClassName('design_compile_content')[0].getElementsByClassName("designOpenrtion_btn_top")[0].offsetWidth/2
			if(this.direction == 'right' || this.direction == 'bottom'){
				this.frontBack.front[this.imgDomIndex].centers.left = imgDomWH.x+event.changedTouches[0].pageX - this.imgDom.getBoundingClientRect().left-li
				this.frontBack.front[this.imgDomIndex].centers.top = imgDomWH.y+event.changedTouches[0].pageY - this.imgDom.getBoundingClientRect().top-li
			}else{
				this.frontBack.front[this.imgDomIndex].centers.left = imgDomWH.x+event.changedTouches[0].pageX - this.imgDom.getBoundingClientRect().left+imgDomWH.width-li
				this.frontBack.front[this.imgDomIndex].centers.top = imgDomWH.y+event.changedTouches[0].pageY - this.imgDom.getBoundingClientRect().top+imgDomWH.height-li
				this.frontBack.front[this.imgDomIndex].centers.right = this.imgDom.parentNode.offsetWidth -imgDomWH.width - this.imgDom.offsetLeft
				this.frontBack.front[this.imgDomIndex].centers.bottom = this.imgDom.parentNode.offsetHeight -imgDomWH.height - this.imgDom.offsetTop
			}
			
			document.addEventListener("touchend", this.sizeMouseup);
			document.addEventListener("touchmove", this.sizeMousemove);
		},
		//鼠标移动
		moveMousemove(e) {
			let imgDomWH = this.imgDom.getBoundingClientRect()
			let parentNode = document.getElementsByClassName('design_compile_content')[0].getElementsByClassName("designOpenrtion_imgMask")[0].getBoundingClientRect()
			let x = (e.changedTouches[0].pageX - this.frontBack.front[this.imgDomIndex].centers.left)+'px'
			let y = ( e.changedTouches[0].pageY - this.frontBack.front[this.imgDomIndex].centers.top)+'px'
			this.frontBack.front[this.imgDomIndex].style.left = x
			this.frontBack.front[this.imgDomIndex].style.top = y
			// if(x.replace(/px/g,'') >= parentNode.width - imgDomWH.width){
			// 	this.frontBack.front[this.imgDomIndex].style.left = parentNode.width - imgDomWH.width+'px'
			// }
			// if(x.replace(/px/g,'') <= 0){
			// 	this.frontBack.front[this.imgDomIndex].style.left = 0+'px'
			// }
			// if(y.replace(/px/g,'') >= parentNode.height - imgDomWH.height){
			// 	this.frontBack.front[this.imgDomIndex].style.top = parentNode.height - imgDomWH.height+'px'
			// }
			// if(y.replace(/px/g,'') <= 0){
			// 	this.frontBack.front[this.imgDomIndex].style.top = 0+'px'
			// }
		},

		sizeMousemove(e) {
			let imgDomWH = this.imgDom.getBoundingClientRect()
			let parentNode =this.imgDom.parentNode
			let width = imgDomWH.width
			let height = imgDomWH.height
			let w,h
			let num = height/width
			//判断移动四个边
			if(this.direction == 'right'){
				w = (e.changedTouches[0].pageX -imgDomWH.left)
				h = (e.changedTouches[0].pageX -imgDomWH.left)*num
				width = w+'px'
				// height = w*num+'px'
			}else if(this.direction == 'top'){
				num = width/height
				this.frontBack.front[this.imgDomIndex].style.top = 'auto'
				// this.printStyleList[this.imgDomIndex].style.left = 'auto'
				// this.frontBack.front[this.imgDomIndex].style.bottom = parentNode.offsetHeight -this.imgDom.offsetHeight - this.imgDom.offsetTop+'px'
				this.frontBack.front[this.imgDomIndex].style.bottom = this.frontBack.front[this.imgDomIndex].centers.bottom+'px'
				w = (e.changedTouches[0].pageX -imgDomWH.left)*num
				h = (this.frontBack.front[this.imgDomIndex].centers.top - e.changedTouches[0].pageY)
				
				height = h+'px'
				// width = h*num+'px'
			}else if(this.direction == 'bottom'){
				num = width/height
				h = (e.changedTouches[0].pageY -imgDomWH.top)
				height = h+'px'
				// width = h*num+'px'
			}else if(this.direction == 'left'){
				w = (this.frontBack.front[this.imgDomIndex].centers.left - e.changedTouches[0].pageX)
				this.frontBack.front[this.imgDomIndex].style.left = 'auto'
				this.frontBack.front[this.imgDomIndex].style.right = this.frontBack.front[this.imgDomIndex].centers.right+'px'
				width = w+'px'
				// height = w*num+'px'
			}
			//判断尺寸是否到边
			this.frontBack.front[this.imgDomIndex].style.width = width
			this.frontBack.front[this.imgDomIndex].style.height = height

		},
		//鼠标抬起
		sizeMouseup(e){
			this.frontBack.front[this.imgDomIndex].style={
				right:'auto',
				left:this.imgDom.offsetLeft+'px',
				bottom:'auto',
				top:this.imgDom.offsetTop+'px',
				height:this.imgDom.offsetHeight+'px',
				width:this.imgDom.offsetWidth+'px',
				zIndex:this.printZIndex
			}
			this.frontBack.back[this.imgDomIndex].style.zIndex = this.printZIndex
			document.removeEventListener("touchend", this.sizeMouseup);
			document.removeEventListener("touchmove", this.sizeMousemove);
		},
		touchend(e) {

			document.removeEventListener("touchend", this.touchend);
			document.removeEventListener("touchmove", this.moveMousemove);
		},
		clearModal(){
			this.printZIndex = 2//点击图片z-index
			this.imgDomIndex = 0//点击图片下标
			this.clothes = []
			this.printStyleList.splice(1,this.printStyleList.length-1)
		},
		capitalizeFirstLetter(str) {
			return str.charAt(0).toUpperCase() + str.slice(1);
		},
		setPreviewData(){
			this.$emit('setSubmit','preview');
		},
		deleteBorder(){
			this.frontBack?.front?.forEach((item)=>{
				item.designOpenrtionBtn = false
			})
		},
		clothesOpen(index){
			this.imgDomIndex = index
			this.clothesOpenActive(index)
			this.setpitch('',index)
		},
		clothesOpenActive(index){
			this.designItemDetail.clothes.forEach((item)=>{
				item.clothesOpen = false
			})
			this.designItemDetail.clothes[index].clothesOpen = true
		},
		sort(arr){
			arr.sort((a, b) => {
				var a_num = a.style.zIndex;
				var b_num = b.style.zIndex;
				return a_num - b_num;
			});
			return arr
		},
		async setPreview(data){
			let ratio = this.frontBack.body.layersObject[0].imageSize[0]/this.frontBack.body.style.width.replace(/px/g,'')
			let designItemDetail = this.store.state.DesignDetailModule.designItemDetail
			// this.frontBack.back.sort((a, b) => {
			// 	var a_num = a.style.zIndex;
			// 	var b_num = b.style.zIndex;
			// 	return a_num - b_num;
			// });
			
			let arr = this.sort(JSON.parse(JSON.stringify(this.frontBack.front)))
			
			let num = 10
			arr.forEach((item)=>{
				item.priority = num++
			})
			data.designSingleItemDTOList.forEach((item)=>{
				let front = arr
				let imageCategory1
				if(arr.length > 1){
					imageCategory1 = arr[1].imageCategory
				}
				arr.forEach((i)=>{
					if(item.id == i.id){
						let y = ((i?.style?.top.replace(/px/g,'')*ratio).toFixed(0) - i?.position[0])
						let x = ((i?.style?.left.replace(/px/g,'')*ratio).toFixed(0) - i?.position[1])
						// let scale = i?.imageSize?Number(((i?.style?.width.replace(/px/g,'')*ratio)/(i?.imageSize[0]/i.scale)).toFixed(2)):1
						let scaleWidth = i?.imageSize?Number(((i?.style?.width.replace(/px/g,'')*ratio)/(i?.imageSize[0]/i.scale[0])).toFixed(2)):1
						let scaleHeight = i?.imageSize?Number(((i?.style?.height.replace(/px/g,'')*ratio)/(i?.imageSize[1]/i.scale[1])).toFixed(2)):1
						item.scale = [scaleWidth,scaleHeight]
						let top = y == 0 ? item.offset[1]:y+item.offset[1]
						let left = x == 0 ? item.offset[0]:x+item.offset[0]
						item.offset = [left,top]
						item.priority = i.priority
						// item.offset = [(i?.style?.left.replace(/px/g,'')*ratio).toFixed(0),(i?.style?.top.replace(/px/g,'')*ratio).toFixed(0)]
					}
				})
				if(arr.length > 1 && item.type == this.capitalizeFirstLetter(imageCategory1)){
					item.scale = front?.imageSize?Number(((front?.style?.width.replace(/px/g,'')*ratio)/front?.imageSize[0]).toFixed(2)):1
				}
			})
			Https.axiosPost(Https.httpUrls.designSingle, data).then(
                (rv) => {
					let designItemDetail = JSON.parse(JSON.stringify(this.store.state.DesignDetailModule.designItemDetail))
					designItemDetail.designItemUrl = rv.designItemUrl
					designItemDetail.ifSubmit = true
					designItemDetail.currentFullBodyView = rv.currentFullBodyView
					rv.clothes.forEach((item)=>{
						designItemDetail.clothes.forEach((i)=>{
							if(item.id === i.id){
								i.layersObject = item.layersObject
								i.priority = item.layersObject[0].priority
							}
						})
					})
					this.$emit('setDesignCoverage');
					this.store.commit("setDesignItemDetail", designItemDetail);
					this.setRevocation(designItemDetail,data)
					this.clear()
                }
            ).catch(res=>{ 
				this.$emit('setParentLoadingShow');
            });
		},
    },
});
</script>

<style lang="less" scoped>
.designOpenrtion_modal {
	// max-width: 1440px;
	-moz-user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
	-khtml-user-select: none;
	user-select: none;
	.ant-modal-body{
		padding: calc(4rem*1.2) calc(5rem*1.2) calc(0rem*1.2)!important;
		// height: calc(65vh - 6.calc(4rem*1.2));
		height: calc(65rem*1.2);
		display: flex;
		overflow-y: hidden;
		flex-direction: column;
	}
	.ant-modal-content{
		border-radius: calc(1rem*1.2);
		overflow: hidden;
	}
}
.design_compile_content {
	// background: #f2f3fb;
	// padding-bottom: 2.calc(9rem*1.2);
	display: flex;
	flex-direction: column;
	height: 100%;
	width: 100%;	
	.designOpenrtion_centent{
		// flex: 1;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-content: space-around;
		flex-wrap: nowrap;
		margin: 0 auto;
		// overflow: hidden;
		justify-content: space-between;
		position: relative;
		user-select:none;
		z-index: 2;
		position: relative;
		&.active{
			flex-direction: row;
		}
		.designOpenrtion_imgMask{
			width: auto;
			height: auto;
			position: relative;
			// height: 100%;
			// overflow: hidden;
			height: calc(100% - 1.2rem - 4.8rem - 20%);
			margin: 0 auto;
			>img{
				z-index: 2;
				position: relative;
			}
			>div{
				position: absolute;
				width: 100%;
				height: 100%;
				top: 0;
			}
		}
		.detail_modal_body_nav{
			display: flex;
			position: relative;
			top: 0;
			left: 50%;
			z-index: 999;
			transform: translate(-50%,-0%);
			transition: all .3s;
			justify-content: center;
			margin-bottom: calc(1rem*1.2);
			>div{
				width: calc(4rem*1.2);
				height: calc(4rem*1.2);
				cursor: pointer;
				text-align: center;
				margin-left: calc(.3rem*1.2);
				img{
					// width: 100%;
					height: 100%;
					max-width: 100%;
					object-fit: cover;
				}
				&.active{
					border: 2px solid rgba(0,0,0,0.4);
					img{
						transform: scale(.8);
						opacity: .8;
					}
				}
			}
			>div:nth-child(1){
				margin-left: calc(0rem*1.2);
			}
		}
		.designOpenrtion_print,.detail_modal_item_front{
			z-index: 1;
			img{
				width: 100%;
				height: 100%;
				float: left;
				user-select:none;
				-webkit-user-drag: none;
			}
			.modal_imgItem{
				position: absolute;
				overflow: hidden;
				top: 0;
				
			}
		}
		.designOpenrtion_print{
			z-index: 1 !important;
		}
		.designOpenrtion_btn{
			z-index: 9999;
			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(1.5rem*1.2);
					height: calc(1.5rem*1.2);
					padding: calc(1rem*1.2);
					background-color: rgb(20, 188, 255);
					position: absolute;
					pointer-events: none;
					z-index: 2;
				}
				&.active{
					opacity: 1;
					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%;
				}
			}
		}
		.subitOkPreviewBtn{
			z-index: 2;
			margin-bottom: calc(1rem*1.2);
			width: calc(10rem*1.2);
			text-align: center;
			bottom: 0;
			position: relative;
		}
	}
	.designOpenrtion_imgMask_open{
			position: absolute;
			width: 100%;
			height: 100%;
		}
}
</style>