<template>
	<div class="editFrontBack_center">
		<!-- <div class="editFrontBack_center_btn editFrontBack_center_item" :class="{spread:spreadState}">
			<i class="icon iconfont icon-chehui" @click="historyState('')"></i>
			<i class="icon iconfont icon-fanchehui" @click="historyState('reverse')"></i>
			<i class="icon iconfont icon-bianji" @click="setOperation('pencil')" :class="{active:canvasState == 'pencil'}"></i>
			<div class="editFrontBack_center_btn_colorRed" @click="setOperationColor('rgb(255,0,0)')" :class="{active:(canvasState != 'eraser' && rgba == 'rgb(255,0,0)')}" title="front">front</div>
			<div class="editFrontBack_center_btn_colorGreen" @click="setOperationColor('rgb(0,255,0)')" :class="{active:(canvasState != 'eraser' && rgba == 'rgb(0,255,0)')}" title="back">back</div>
			<div class="editFrontBack_center_btn_colorWhite" @click="setOperation('eraser')" :class="{active:canvasState == 'eraser'}" title="background">background</div>
			<input type="range" v-show="canvasState != 'move'" @input="setPencilWidth" min="1" max="50" v-model="canvasPencilWidth[canvasState]">
		</div> -->
		<div class="exportCanvasBox_center_box">
			<div class="exportCanvasBox_center">
				<div class="editFrontBack_bgImg" v-show="loadingShow">
					<img :src="imgData?.undividedLayer" alt="">
				</div>
				<div class="editFrontBack_pencilbtn" v-show="loadingShow" :style="frontBackCanvasObj.pencilbtnStyle" style="display: block;"></div>

			</div>
			<!-- <div class="editFrontBack_pencilbtn" v-show="loadingShow" :style="pencilbtnStyle"></div> -->
<!-- 
			<div class="editFrontBack_pencilbtn" v-show="loadingShow" :style="frontBackCanvasObj.pencilbtnStyle" style="display: block;"></div>
			{{frontBackCanvasObj.pencilbtnStyle}} -->
		</div>
	</div>
</template>
<script>
import { defineComponent, ref, reactive, inject, onMounted, nextTick, toRefs, onBeforeUnmount, watch, computed } from "vue";
import { formatTime,segmentImage } from "@/tool/util";
import { exportSele,JSRectUpdata,JSchangeType,JScanvasMouseDown,JSSetRemoveImage,JScreateCheck,JSSetTexture } from "@/tool/canvasDrawing";
import { getMousePosition } from "@/tool/mdEvent";
import { useStore } from "vuex";
import { useI18n } from "vue-i18n";
export default defineComponent({
    components: {
    },
	// emits: ['setSloganData'],
	props:['patchData','imgDomIndex'],
    setup(props,{emit}) {
        const store = useStore();
        let presentState = ref('paypal');
        let loadingShow = ref(false);
        let { t } = useI18n();
        // let canvas = new frontBackCanvasObjCopy();
        let canvas = null;
		let frontBackCanvasObj = inject('frontBackCanvasObj')
		let ratio = [1,1]
		let exportWH = 0
		let imgData = ref()
		let pencilbtnStyle = ref({
			background:'',
			width:0+'px',
			height:0+'px',
			display:'none',
			left:0+'px',
			top:0+'px',
		})
		let selectDetail = computed(()=>store.state.DesignDetailCopy.selectDetail)

		// let a = computed(()=>{
		// 	console.log(123);
		// 	return props.patchData
		// })
		watch(()=>pencilbtnStyle.value.background,(newVal)=>{
			frontBackCanvasObj.brushwork.color = newVal
			frontBackCanvasObj.setPencilColor()
		})
		onMounted(()=>{
			props.patchData.front.imageUrl=  ''
			clearTimeout(setTimeSubmit)
			// init(props.patchData.front[props.imgDomIndex],'')
		})
		let canvasBtn = reactive({
			canvasState:'move',
			canvasPencilWidth:{
				pencil:20,
				eraser:20,
			},
			spreadState:false,
		})
		let canvasWH = ref(0);
		
		let reverseCanvasState = ref([])//存放canvas操作
		let normalCanvasState = ref([])//存放canvas操作

		let down = false
		let init = (data,index)=>{
			normalCanvasState.value = []
			reverseCanvasState.value = []
			ratio = [1,1]
			imgData.value = data
			nextTick(()=>{
				let canvasBox = document.querySelector(".editFrontBack_center .exportCanvasBox_center");
				let editFrontBack_bgImg = document.querySelector(".editFrontBack_center .editFrontBack_bgImg");
				document.removeEventListener('mousemove', mouseMove);
				document.removeEventListener('touchmove', touchmove);
				let img = new Image();
				img.onload = async function(){
					loadingShow.value = true
					let scale = img.width/img.height
					let height = canvasBox.offsetHeight;
					canvasWH.value = height
					canvasBox.style.width = height * scale+'px'
					
					let wScale = 1
					let hScale = 1
					let styleWidth = Number(data.style.width.split('px')[0])
					let styleHeight = Number(data.style.height.split('px')[0])
					if(styleWidth>styleHeight){
						hScale = styleHeight/styleWidth
						exportWH = img.width
					}else{
						wScale = styleWidth/styleHeight
						exportWH = img.height
					}
					editFrontBack_bgImg.style.width = canvasWH.value * wScale+'px'
					editFrontBack_bgImg.style.height = canvasWH.value * hScale+'px'
					ratio = [wScale,hScale]
					// canvas = frontBackCanvasObj.canvasInit(canvasBox,{
					// 	width:canvasWH.value * wScale,
					// 	height:canvasWH.value * hScale,
					// })
					await frontBackCanvasObj.canvasInit(canvasBox,{
						width:canvasWH.value * wScale,
						height:canvasWH.value * hScale,
					},data.maskUrl,'',{})
					// undividedLayer
					canvas = frontBackCanvasObj.canvas

					frontBackCanvasObj.setOperation('pencil')
					pencilbtnStyle.value.background = rgba.value
					// console.log(frontBackCanvasObj,frontBackCanvasObj.setPencilWidth);
					frontBackCanvasObj.setPencilWidth()
					fabric.Object.prototype.cornerSize = 10
					fabric.Object.prototype.transparentCorners = false 
					// await frontBackCanvasObj.addPartImg({minioUrl:data.maskUrl},'',{opacity: 0.5})

					// await new Promise((resolve, reject) => {
					// 	fabric.Image.fromURL(data.maskUrl, function(img) {
					// 		// 设置背景图对象的宽度和高度与 canvas 相同
					// 		canvas.add(img)
					// 		resolve('')
					// 	},{ crossOrigin: "Anonymous" });
					// })
					
					
					//画布上移动
					// canvas.on("mouse:move", event =>setCanvasMove(event));
					canvas.on('mouse:up', (event)=> {
						updateCanvasState('mouseUp')
					});
					document.addEventListener('mousemove', mouseMove);
					document.addEventListener('touchmove', touchmove);
					createSetTimeSubmit()
					img.remove()
				}
				img.src = data.maskUrl
				
			})
        }
		const setBackground = (value)=>{
			if(value == 'background'){
				frontBackCanvasObj.setOperation('eraser')
			}else{
				frontBackCanvasObj.setOperation('pencil')
				frontBackCanvasObj.brushwork.color = value
				frontBackCanvasObj.pencilColor()
			}
		}
		let updateCanvasState = (str) =>{
			if(str != 'mouseUp'){
				// editFrontBackPencilbtn.value.style.display = 'none'
			}else{
				clearTimeout(setTimeSubmit)
				setTimeSubmit = setTimeout(()=>{
					createSetTimeSubmit()
				},1000)
			}
		}
		let setClone = ()=>{
			let canvasBox = document.querySelector(".editFrontBack_center .exportCanvasBox_center");
			let oldCanvasDom = canvasBox.querySelector('.canvas-container')
			let oldCanvasDom1 =  canvasBox.querySelector('canvas')
			if(oldCanvasDom)oldCanvasDom.remove()
			if(oldCanvasDom1)oldCanvasDom1.remove()
			loadingShow.value = false
		}
		let rgba = ref('#ff0000')
		let mouseMove = (event)=>{
			let e = getMousePosition(event,false)
			setCanvasMove(e)
		}
		let touchmove = (event)=>{
			let e = getMousePosition(event,true)
			setCanvasMove(e)
		}
		let setCanvasMove = (event)=>{
			if(canvas.isDrawingMode && canvas){
				canvas.setCursor('none');
			}
			let canvasCenterBox = document.querySelector(".editFrontBack_center .exportCanvasBox_center_box");
			if(!canvasCenterBox)return
			let parentX = event.clientX - canvasCenterBox.getBoundingClientRect().left
			let parentY = event.clientY - canvasCenterBox.getBoundingClientRect().top
			pencilbtnStyle.value.left = parentX + "px"
			pencilbtnStyle.value.top =  parentY+'px'
		}
		let mousedown = (e)=>{
			if(e.target instanceof HTMLCanvasElement){
				down = true
			}
		}
		let mouseup = (e)=>{
			if(down){
				nextTick(()=>{
					createSetTimeSubmit()
				})
			}
			down = false
		}	
		let setTimeSubmit = null
		let createSetTimeSubmit = ()=>{
			setSubmit()
		}
		//撤回
		
		let setSubmit = async ()=>{
			// let data = await frontBackCanvasObj.allExport()
			let data = await frontBackCanvasObj.detailSubmit()
			// props.props.patchData.front[imgDomIndex].imageUrl = data
			let mark = data
			let full = props.patchData.front[props.imgDomIndex].undividedLayer
			let size = {
				width: Math.round(exportWH * ratio[0]),
				height: Math.round(exportWH * ratio[1]),
			}
			segmentImage(mark,full,size).then((rv)=>{
				props.patchData.front[props.imgDomIndex].imageUrl = rv.targetFrontUrl
				props.patchData.back[props.imgDomIndex].imageUrl = rv.targetBackUrl
				props.patchData.front[props.imgDomIndex].maskUrl = data
				store.commit('DesignDetailCopy/updataDetailItem',{maskUrl:data})
			})
		}
		onBeforeUnmount(()=>{
			frontBackCanvasObj.canvasClear()
			document.removeEventListener('mousemove', mouseMove);
			document.removeEventListener('touchmove', touchmove);
			document.removeEventListener('mousedown', mousedown);
			document.removeEventListener('mouseup', mouseup);
		})
        return {
			frontBackCanvasObj,
            presentState,
			loadingShow,
			imgData,
			pencilbtnStyle,
            t,
			...toRefs(canvasBtn),
			setBackground,
			init,
			setSubmit,
			setClone,
        };
    },
    data() {
        return {
        };
    },
    mounted() {},
    methods: {
       
    },
});
</script>
<style lang="less" scoped>
.editFrontBack_center{
	position: relative;
	// width: calc(512px / 2);
	// width: 256px;
	height: 100%;
	width: 100%;
	display: flex;
	flex-direction: column;
	// height: calc(512px / 2);
	margin: 0 auto;
	.editFrontBack_center_item{
		// position: relative;
		background: #ffffff;
		position: absolute;
		
		display: flex;
		border: 0.2rem solid #c4c4c4;
		width: 35rem;
		border-radius: 4px; /* 设置圆角半径 */
		flex-wrap: wrap;
		align-items: center;
		.editFrontBack_center_btn_item{
			display: flex;
			align-items: center;
			padding: 1rem 0;
			
		}
	}
	.editFrontBack_center_btn{
		z-index: 2;
		left: 50%;
		// transform: translate(-50%,-135%);
		// transition: all .3s;
		padding: 1rem 1.5rem;
		transform: translate(-50%,0);
		position: relative;
		width: 100%;
		flex-direction: row;
		input{
			// width: 100%;
			flex: 1;
			max-width: 30%;
		}
		.icon-xiala{
			position: absolute;	
			width: 2rem;
			bottom: 0;
			transform: translate(-50%, 90%);
			left: 50%;
			width: 6rem;
			background: #fff;
			text-align: center;
			cursor: pointer;
			&.icon-xiala::before{
				transition: all .3s;
			}
			&.btnRotate::before{
				transform: rotate(180deg);
				display: block;
			}
		}
		.editFrontBack_center_btn_colorRed,.editFrontBack_center_btn_colorGreen,.editFrontBack_center_btn_colorWhite{
			width: 9rem;
			line-height: 3rem;
			text-align: center;
			height: 3rem;
			border-radius: 4px;
			margin: 0 .5rem;
			cursor: pointer;
			padding: .5rem 1;
			border: 1px solid rgba(0,0,0,.5);
			&.active{
				border: 2px solid;
				border-radius: .4rem;
			}
		}
		.editFrontBack_center_btn_colorRed{
			background: rgba(255,0,0);
		}
		.editFrontBack_center_btn_colorGreen{
			background: rgba(0,255,0);
		}
		.editFrontBack_center_btn_colorWhite{
			background: rgba(255,255,255);
		}
		i{
			font-size: 2.5rem;
			cursor: pointer;
			width: 4rem;
			height: 4rem;
			display: flex;
			align-items: center;
			justify-content: center;
			&.active{
				border: 1px solid;
				border-radius: .4rem;
			}
		}
		&.spread{
			transform: translate(-50%,0);
		}
	}
	.exportCanvasBox_center_box{
		height: 100%;
		flex: 1;
		position: relative;
		overflow: hidden;
		width: 100%;
		background: #e6e6e6;
		cursor: auto;
		&:hover{
			cursor: none;
		}
		.editFrontBack_pencilbtn{
			position: absolute;
			z-index: 1;
			border-radius: 50%;
			border: 1px solid #000;
			pointer-events: none;
			transform: translate(-50%,-50%);
		}
	}
	.exportCanvasBox_center{
		margin: 0 auto;
		overflow: hidden;
		height: 100%;
		position: relative;
		// overflow: scroll;
		cursor: none;
		:deep(.canvas-container){
			left: 50%;
			top: 50%;
			transform: translate(-50%,-50%);
			// opacity: .5;
			// background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC);
		}
		.editFrontBack_bgImg{
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%,-50%);
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 100%;
			z-index: 2;
			pointer-events:none;
			opacity: .5;
			img{
				height: 100%;
				width: 100%;
			}
		}
		
	}
	.exportCanvasBox_center:hover{
		.editFrontBack_center_btn{
			transform: translate(-50%,-101%);
			&.spread{
				transform: translate(-50%,0);
			}
		}
	}
}
</style>