<template>
    <a-modal
        class="liquefaction generalModel"
        v-model:visible="liqufeaction"
        :footer="null"
        width="50%"
        :maskClosable="false"
        :centered="true"
        :closable="false"
        wrapClassName="#app"
        :keyboard="false"
    >
		<div class="generalModel_btn">
			<div class="generalModel_closeIcon" @click.stop="cancelDsign()">
				<i class="fi fi-rr-cross-small"></i>
			</div>
		</div>
		
		<div class="liquefaction_center">
			
		</div>
    </a-modal>
	<!-- <div class="mark_loading" v-show="loadingShow">
		<a-spin size="large" />
	</div> -->
</template>
<script>
import { defineComponent, ref, reactive, watch, onMounted, nextTick, toRefs } from "vue";
import { Https } from "@/tool/https";
import { formatTime } from "@/tool/util";
import { setCookie, getCookie } from "@/tool/cookie";
import { Modal, message } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import allOrder from "@/component/Pay/allOrder.vue";
import creditsDetail from "@/component/Pay/creditsDetail.vue";
import { exportSele,JSRectUpdata,JSchangeType,JScanvasMouseDown,JSSetRemoveImage,JScreateCheck,JSSetTexture } from "@/tool/canvasDrawing";
import { useI18n } from "vue-i18n";
import { getMousePosition } from "@/tool/mdEvent";
export default defineComponent({
    components: {
		creditsDetail,
		allOrder,
    },
	emits: ['setSloganData'],
    setup(props,{emit}) {
        let presentState = ref('paypal');
        let liqufeaction = ref(false);
        let loadingShow = ref(false);
        let { t } = useI18n();
        let canvas = reactive({});
		let scale = 2;
		let ratio = [1,1]
		let exportWH = 512
		let pencilbtnStyle = ref({
			background:'',
			width:0+'px',
			height:0+'px',
			display:'none',
			left:0+'px',
			top:0+'px',
		})
		let canvasBtn = reactive({
			canvasState:'move',
			canvasPencilWidth:{
				pencil:4,
				eraser:4,
			},
			spreadState:false,
		})
		let canvasWH = ref(0);
		onMounted(()=>{
		})
		let exportUrl = ''
		let reverseCanvasState = ref([])//存放canvas操作
		let normalCanvasState = ref([])//存放canvas操作
		let canvasState = ref()//存放canvas操作
		let keyDown = []//监听键盘的 keydown 和 keyup 事件
		let init = (data)=>{
			console.log(data);
			console.log(123);
        }
		let canvasKeyDown = (event) => {
			if(keyDown.indexOf(event.key)>-1){
			}else{
				keyDown.push(event.code)
				if(keyDown.indexOf('ControlLeft') > -1 && keyDown.indexOf('KeyZ') > -1 && keyDown.indexOf('ShiftLeft') > -1){
					historyState('reverse')
				}else if(keyDown.indexOf('ControlLeft') > -1 && keyDown.indexOf('KeyZ') > -1){
					historyState('')
				}
			}
		}
		let canvasKeyUp = (event) =>{
				keyDown = keyDown.filter(function(item) {
					return event.code !== item;
				})
				
			}
		let clearCanvas = ()=>{
		    canvasBtn.canvasState = 'move'
		    canvasBtn.spreadState = false
			document.removeEventListener("keydown", canvasKeyDown);
			document.removeEventListener("keyup", canvasKeyUp);
		}
		let rgba = 'rgba(0, 0, 0, 1)'
		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.setCursor('none');
			}
			let canvasCenterBox = document.querySelector(".liquefaction .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 setOperation = (str)=>{
			canvasBtn.canvasState = str
			if(str == 'move'){
				setMove()
				pencilbtnStyle.value.display = `none`
			}else if(str == 'pencil'){
				setPencil()
				pencilbtnStyle.value.display = `block`
			}else if(str == 'eraser'){
				setEraser()
				pencilbtnStyle.value.display = `block`
			}
		}
		let setMove = ()=>{
			canvas.isDrawingMode = false
			canvas.forEachObject((obj) =>obj.selectable = true);
		}
		let setPencil = ()=>{
			canvas.isDrawingMode = true//开启绘画模式
			canvas.freeDrawingBrush = new fabric.PencilBrush(canvas,{});
			canvas.freeDrawingBrush.width = Number(canvasBtn.canvasPencilWidth[canvasBtn.canvasState]);
			canvas.freeDrawingBrush.color = rgba
			pencilbtnStyle.value.background = rgba
			canvas.freeDrawingBrush.isEraser = false
			setPencilWidth()
		}
		let setEraser = ()=>{
			canvas.isDrawingMode = true
			let eraser = new fabric.EraserBrush(canvas)
            canvas.freeDrawingBrush = eraser
			canvas.requestRenderAll();
			canvas.freeDrawingBrush.isEraser = true
			pencilbtnStyle.value.background = `rgb(255,255,255)`
			canvas.freeDrawingBrush.width = Number(canvasBtn.canvasPencilWidth[canvasBtn.canvasState]);
			setPencilWidth()
		}
		let deleteObj = ()=> {
			// if(!canvas.getActiveObjects()){
			// 	return
			// }
			let target = canvas.getActiveObjects()
			target.forEach((item)=>{
				canvas.fxRemove(item, {
					onComplete(){
					canvas.discardActiveObject(); // 丢弃当前选中的对象
					canvas.renderAll(); // 重新渲染 Canvas
					}
				})
				canvas.FX_DURATION = 300
			})
		}
		let setTimeOutWidth
		let setPencilWidth = ()=>{//切换颜色给铅笔设置颜色
			clearTimeout(setTimeOutWidth)
			setTimeOutWidth = setTimeout(()=>{
				canvas.freeDrawingBrush.width = Number(canvasBtn.canvasPencilWidth[canvasBtn.canvasState])
				pencilbtnStyle.value.height = canvasBtn.canvasPencilWidth[canvasBtn.canvasState]+'px'
				pencilbtnStyle.value.width = canvasBtn.canvasPencilWidth[canvasBtn.canvasState]+'px'
			},300)
		}
		let updateCanvasState = (str) =>{
			if(str != 'mouseUp'){
			}
			const canvasAsJson = JSON.stringify(canvas.toJSON());
			normalCanvasState.value.push(canvasAsJson);
		}
		//撤回
		let historyState = (str)=> {
			if(str == 'reverse' && reverseCanvasState.value.length > 0){//反撤回
				let obj = reverseCanvasState.value.pop()
				// canvasState.value = reverseCanvasState.value[reverseCanvasState.value.length-1]
				canvasState.value = obj 
				normalCanvasState.value.push(obj);
			}else if(str == '' && normalCanvasState.value.length > 1){
				let obj = normalCanvasState.value.pop()
				canvasState.value = normalCanvasState.value[normalCanvasState.value.length-1]
				reverseCanvasState.value.push(obj);
			}else{
				return
			}
			canvas.loadFromJSON(canvasState.value, () => {});
		}
		let setSubmit = ()=>{
			var allObjects = canvas.getObjects('path');
			// if(allObjects.length == 0){
			// 	return message.info(t('addDetails.jsContent1'))
			// }
			var canvasDom = document.createElement("canvas");
			let exportCanvas = new fabric.Canvas(canvasDom, {
				backgroundColor: "rgba(255, 255, 255,1)",
				width: exportWH * ratio[0],
				height: exportWH * ratio[1],
				isDrawingMode: false, // 开启绘图模式
			});
			canvas.backgroundImage.clone((back)=>{
				back.set({
					scaleX:1,
					scaleY:1,
					left:back.left*scale,
					top:back.top*scale ,
				})
				exportCanvas.backgroundImage = back
				allObjects.forEach((item,index)=>{
					// let obj = fabric.util.object.clone(item);
					if(item.type == 'circle')return
					let obj 
					item.clone((cloned)=>{
						obj = cloned
					})
					obj.set(
						{
							scaleX:(item.scaleX?item.scaleX:1)*scale,
							scaleY:(item.scaleY?item.scaleY:1)*scale,
							left:item.left*scale,
							top:item.top*scale,
						}
					)
					exportCanvas.add(obj)
				})
				let data = exportCanvas.toDataURL('jpg')
				cancelDsign()
				clearCanvas()
				emit('setSloganData',data)
			})
		}
		let cancelDsign = ()=>{
			document.removeEventListener('keydown',canvasKeyDown);
			document.removeEventListener('keyup', canvasKeyUp);
			liqufeaction.value = false
		}
        return {
            presentState,
            liqufeaction,
			loadingShow,
            t,
			pencilbtnStyle,
			...toRefs(canvasBtn),
			init,
			setOperation,
			setPencilWidth,
			historyState,
			setSubmit,
			cancelDsign,
        };
    },
    data() {
        return {
        };
    },
    mounted() {},
    methods: {
       
    },
});
</script>
<style lang="less" scoped>
.liquefaction {
    
}
</style>