<template>
	<div class="design_compile_content" id="design_compile_content">
		<div class="designOpenrtion_centent" id="designOpenrtionCentent">
			<div class="detail_modal_body_title">
				<div class="detail_modal_body_nav">
				<div v-for="item,index in designItemDetail?.clothes" v-show="item.id" :class="{active:designShowIndex.value == index}" @click="clothesOpen(item,index)">
					<img :src="item?.path" alt="">
				</div>
			</div>
			</div>
			<div class="designOpenrtion_imgMask">
				<canvas ref="canvasDom" ></canvas>
			</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,reactive, ref ,computed, inject,nextTick, onMounted} from "vue";
// import { LoadingOutlined } from "@ant-design/icons-vue";
import { useStore } from "vuex";
// import { Modal,message } from 'ant-design-vue';
import { Https } from "@/tool/https";
export default defineComponent({
	emits: ['setDesignCoverage', 'setSubmit'],
    // props: ["frontBack"],
    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 designShowIndex = reactive({value:-1})
		let frontBack = reactive({})
		let frontBackOld = reactive({})
		let canvasFontBackMove = reactive({
			back:[],
			front:[],
		})

		let setPostition = async (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.onerror = reject;
					img.src = url;
				});
			}
			return num
		}
		let computeZindex = (designItemDetail)=>{
			let arr = designItemDetail.clothes
			arr.sort((a, b) => {
				var a_num = a.priority;
				var b_num = b.priority;
				return a_num - b_num;
			});
			designItemDetail.clothes = arr
			return designItemDetail
		}
		let setImgSize = async ()=>{
			let designItemDetail = JSON.parse(JSON.stringify(store.state.DesignDetailModule.designItemDetail))
			let front = []
			let back = []
			let body
			designItemDetail.others.forEach((item) => {
				if(item.type == 'Body'){
					body = item
				}
			});
			let ratio = await setPostition(body.layersObject[0]?.imageUrl)
			designItemDetail = computeZindex(designItemDetail)
			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',
					}
					v.layersObject[i].centers={
						left:0,
						top:0,
					}
					v.scale = ratio
					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
					}
					if(printZIndex < v.priority){
						printZIndex = v.priority
					}
				}
				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',
			}
			frontBack = {
				front:front,
				back:back,
				body:body,
			}
			frontBackOld = JSON.parse(JSON.stringify({
				front:front,
				back:back,
				body:body,
			}))
			setCanvas(frontBack)
		}
		let canvas = reactive({})
		let setCanvas = (frontBack)=>{
			let canvasBox = document.querySelector('.design_compile_content .designOpenrtion_imgMask')
			var canvasDom = document.createElement('canvas')
			console.log(canvasDom);
			canvasBox.innerHTML = ''; // 清空原有内容
			canvasBox.appendChild(canvas);
			canvas = reactive(null) 
			canvas = new fabric.Canvas(canvasDom.value, {
				backgroundColor: "rgba(255,255,255,1)",
				// fill: '#ffde7d',
				selection: false, //设置多选
				width: Number(frontBack?.body?.style.width.match(/\d+(\.\d+)?/)[0]),
				height: Number(frontBack?.body?.style.height.match(/\d+(\.\d+)?/)[0]),
				isDrawingMode: false, // 开启绘图模式
			});
			canvas.clear();
			canvasFontBackMove = reactive({
				back:[],
				front:[],
			})
			console.log(canvas.getObjects());
			let fontBackMove = []
			canvas.on('selection:cleared', ()=>{
				designShowIndex.value = -1
			})
			frontBack.back.forEach((item) => {
				if(!item.imageUrl){
					return
				}
				fabric.Image.fromURL(item.imageUrl, (img) => {
					img.set({
						left: Number(item.style.left.match(/\d+(\.\d+)?/)[0]),
						top: Number(item.style.top.match(/\d+(\.\d+)?/)[0]),
						scaleX: Number(item.style.width.match(/\d+(\.\d+)?/)[0])/img.width,
						scaleY: Number(item.style.height.match(/\d+(\.\d+)?/)[0])/img.height,
						evented : false,
						// selectable: false
					});
					canvas.add(img);
					canvasFontBackMove.back.push({id:item.id,img:img})
				});
			});
			fabric.Image.fromURL(frontBack?.body?.layersObject?.[0].imageUrl || '', (img) => {
                img.set({
                    left: 0,
                    top: 0,
                    // width: Number(frontBack?.body?.style.width.match(/\d+(\.\d+)?/)[0]) * scale,
                    // height: Number(frontBack?.body?.style.height.match(/\d+(\.\d+)?/)[0]) * scale,
                    scaleX: Number(frontBack?.body?.style.width.match(/\d+(\.\d+)?/)[0])/img.width,
                    scaleY: Number(frontBack?.body?.style.height.match(/\d+(\.\d+)?/)[0])/img.height,
					evented : false,
					// selectable: false
                });
				canvas.add(img);
            });
			frontBack.front.forEach((item) => {
				console.log(item);
				if(!item.imageUrl){
					return
				}
				fabric.Image.fromURL(item.imageUrl, (img) => {
					img.set({
						left: Number(item.style.left.match(/\d+(\.\d+)?/)[0]),
						top: Number(item.style.top.match(/\d+(\.\d+)?/)[0]),
						scaleX: Number(item.style.width.match(/\d+(\.\d+)?/)[0])/img.width,
						scaleY: Number(item.style.height.match(/\d+(\.\d+)?/)[0])/img.height,
						// selectable: false
					});
					canvas.add(img);
					canvasFontBackMove.back.forEach((backItem) => {
						if(backItem && backItem.id == item.id){
							img.on('moving', function() {
								// 计算第二个矩形应该移动的距离
								// 更新第二个矩形的位置
								backItem.img.set({
									left: img.left,
									top: img.top,
									width: img.width,
									height: img.height,
									scaleX: img.scaleX,
									scaleY: img.scaleY,
								});

							});
							img.on('scaling', function(e) {
								backItem.img.set({
									left: img.left,
									top: img.top,
									width: img.width,
									height: img.height,
									scaleX: img.scaleX,
									scaleY: img.scaleY,
								});
							});
							canvas.renderAll();
						}
					})
					canvasFontBackMove.front.push({id:item.id,img:img})
				});
			});
			
			var objects = canvas.getObjects();

		}
		let clothesOpen = (item,index)=>{
			setCanvas(frontBack)
			// setpitch(item,index)
			// designShowIndex.value = index
		}
		let setpitch = (item,index)=>{
			console.log(canvas.discardActiveObject);
			canvas.discardActiveObject();
			// this.designItemDetail.clothes.forEach((item)=>{
			// 	item.clothesOpen = false
			// })
			// this.designItemDetail.clothes[index].clothesOpen = true
			// console.log(canvas.getActiveObject());
			for (const iterator in canvasFontBackMove) {
				canvasFontBackMove[iterator].forEach((canvasItem,canvasIndex) => {
					if(canvasItem.id == item.id){
						// var rect1Index = canvas.getObjects().indexOf(canvasItem.img);
						if(iterator == 'front'){
							canvas.moveTo(canvasItem.img,canvas.getObjects().length)
							canvas.setActiveObject(canvasItem.img);
						}else{
							canvas.moveTo(0)
							// canvas.moveTo(canvasItem.img,canvasFontBackMove[iterator].length-1)
						}
					}
				});
			}
			// canvas.setDepth(object1, canvas.getObjects().indexOf(object2) + 1);
		}
        return {
			designItemDetail,
			current,
			printZIndex,
			designShowIndex,
			frontBack,
			setRevocation,
			frontBackOld,
			canvasFontBackMove,
			setImgSize,
			clothesOpen,
        };
    },
    data() {
        return {
            loadingShow:false,//加载中
            store: useStore(),
        };
    },
	mounted () {
		
	},
    methods: {
		init(){
			this.setImgSize()
		},
		// async setImgSize(){
		// 	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.scale = ratio
		// 			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,
		// 	}))
		// 	this.setCanvas(this.frontBack)
		// },
		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.onerror = reject;
					img.src = url;
				});
			}
			return num
		},
		
	
		capitalizeFirstLetter(str) {
			return str.charAt(0).toUpperCase() + str.slice(1);
		},
		setPreviewData(){
			this.$emit('setSubmit','preview');
		},
		deleteBorder(){
			this.frontBack?.front?.forEach((item)=>{
				item.designOpenrtionBtn = false
			})
		},
		
		clothesOpenActive(index){
			
		},



		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++
				item.similarity = false//新增衣服传的是衣服id会存在两件衣服id相同所以设置为false让每次赋值都是不一样的
			})
			data.designSingleItemDTOList.forEach((item)=>{
				let front = arr
				let imageCategory1
				if(arr.length > 1){
					imageCategory1 = arr[1].imageCategory
				}
				for (let index = 0; index < arr.length; index++) {
					if(item.id == arr[index].id && !arr[index].similarity){
						let y = ((arr[index]?.style?.top.replace(/px/g,'')*ratio).toFixed(0) - arr[index]?.position[0])
						let x = ((arr[index]?.style?.left.replace(/px/g,'')*ratio).toFixed(0) - arr[index]?.position[1])
						let scale = arr[index]?.imageSize?Number(((arr[index]?.style?.width.replace(/px/g,'')*ratio)/(arr[index]?.imageSize[0]/arr[index].scale)).toFixed(2)):1
						item.scale = scale
						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 = 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(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
				}
			})
			// return
			Https.axiosPost(Https.httpUrls.designSingle, data).then(
                (rv) => {
					this.$parent.loadingShow = false
					let designItemDetail = JSON.parse(JSON.stringify(this.store.state.DesignDetailModule.designItemDetail))
					rv.clothes.forEach((i)=>{
						i.similarity = false//新增衣服传的是衣服id会存在两件衣服id相同所以设置为false让每次赋值都是不一样的
					})
					designItemDetail.designItemUrl = rv.designItemUrl
					designItemDetail.ifSubmit = true
					designItemDetail.currentFullBodyView = rv.currentFullBodyView
					designItemDetail.clothes.forEach((item)=>{
						for (let index = 0; index < rv.clothes.length; index++) {
							if(rv.clothes[index].id === item.id && !rv.clothes[index].similarity){
								item.layersObject = rv.clothes[index].layersObject
								item.priority = rv.clothes[index].layersObject[0].priority
								rv.clothes[index].similarity = true
								break
							}
						}
					})
					this.$emit('setDesignCoverage');
					this.store.commit("setDesignItemDetail", designItemDetail);
					this.setRevocation(designItemDetail,data)
                }
            ).catch(res=>{ 
            });
		},
    },
});
</script>

<style lang="less" scoped>
.designOpenrtion_modal {
	// max-width: 1440px;
	.ant-modal-body{
		padding: calc(4rem*1.2) calc(5rem*1.2) calc(0rem*1.2)!important;
		// height: calc(65vh - 6.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.9rem*1.2);
	display: flex;
	flex-direction: column;
	height: 100%;
	width: 100%;	
	.designOpenrtion_centent{
		flex: 1;
		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;
			>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(1rem*1.2);
					height: calc(1rem*1.2);
					background-color: rgb(20, 188, 255);
					position: absolute;
					pointer-events: none;
				}
				&.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>