import { 
	exportSele,
	JSRectUpdata,
	JSchangeType,
	JScanvasMouseDown,
	JScanvasMouseMove,
	JScreateCheck,
	JSSetTexture,
	JSSetRemoveImage,
 } from "@/tool/canvasDrawing";
class myCanvas {
	constructor() {
		this.canvasDomParent = null;
		this.canvas = null;
		this.canvasDom = null;
		this.pencilBtn = null;
		this.pencilType = null;
		this.keyDown = [];//键盘按下
		this._clipboard = null; //剪切板
		this.isLoadCanvas = false//撤回或者反撤回false为撤回
		this.reverseCanvasState=[];//撤回
		this.normalCanvasState=[];//反撤回
		this.canvasState = {}//当前内容
		this.pencilList = {
			textFontFamilyList:[
				{ value: 'Arial', name: 'select font' },
				{ value: 'EN_slogan_art1', name: 'select font' },
				{ value: 'EN_slogan_art2', name: 'select font' },
				{ value: 'EN_slogan_art3', name: 'select font' },
				{ value: 'EN_slogan_art4', name: 'select font' },
				{ value: 'EN_slogan_art5', name: 'select font' },
				{ value: 'EN_slogan_art6', name: 'select font' },
				{ value: 'EN_slogan_art7', name: 'select font' },
				{ value: '微软雅黑', name: '请选择字体' },
				{ value: 'CN_slogan_art1', name: '请选择字体' },
				{ value: 'CN_slogan_art2', name: '请选择字体' },
				{ value: 'CN_slogan_art3', name: '请选择字体' },
				{ value: 'CN_slogan_art4', name: '请选择字体' },
				{ value: '华文行楷', name: '请选择字体' },
				{ value: '隶书', name: '请选择字体' },
			],
			brushList:[
				{
					value:'PencilBrush',
					url:'/image/brush/PencilBrush.jpg'
				},{
					value:'Marking',
					url:'/image/brush/PencilBrush-2.jpg'
				},{
					value:'InkBrush',
					url:'/image/brush/InkBrush.jpg'
				},{
					value:'CrayonBrush',
					url:'/image/brush/CrayonBrush.jpg'
				},{
					value:'RibbonBrush',
					url:'/image/brush/RibbonBrush.jpg'
				},{
					value:'MarkerBrush',
					url:'/image/brush/MarkerBrush.jpg'
				},{
					value:'WritingBrush',
					url:'/image/brush/WritingBrush.jpg'
				},{
					value:'LongfurBrush',
					url:'/image/brush/LongfurBrush.jpg'
				},{
					value:'SpraypaintBrush',
					url:'/image/brush/SpraypaintBrush.jpg'
				},
			]

		}
	}
	canvasInit(dom, val) {
		this.canvasDomParent = dom;
		this.canvasClear()
		var canvasDom = document.createElement("canvas");
		this.canvasDomParent.appendChild(canvasDom);
		this.canvas = new fabric.Canvas(canvasDom, {
			backgroundColor: "rgba(255, 255, 255)",
			width: val.width?val.width:this.canvasDomParent.getBoundingClientRect().width,
			height: val.height?val.height:this.canvasDomParent.getBoundingClientRect().height,
			isDrawingMode: val.isDrawingMode, // 开启绘图模式
			selectionFullyContained: true,
			selectionKey:'ctrlKey',
			includeDefaultValues: false,//尚未测试 精简导出JSON
		});

		if(!fabric.Object.prototype.controls.deleteControl){//设置元素删除
			JSSetRemoveImage(this.deleteObject)
		}else{
			fabric.Object.prototype.controls.deleteControl.mouseUpHandler = this.deleteObject
		}

		this.canvas.on("object:modified", ()=>{
			this.updateCanvasState('')
		});

		this.canvasKeyDown = this.canvasKeyDown.bind(this);
        this.canvasKeyUp = this.canvasKeyUp.bind(this);
		document.addEventListener("keydown", this.canvasKeyDown);
		document.addEventListener("keyup", this.canvasKeyUp);
		initAligningGuidelines(this.canvas,true)
		JSchangeType(this.canvas,'init')
		// this.canvas.on('mouse:up', function(event) {
		// 	if(this.canvasState != 'move')this.updateCanvasState('')
		// });
		this.canvas.on("object:added", (event)=>{
			if(!this.isLoadCanvas)this.updateCanvasState('')
		});
		return this.canvas
	}

	canvasKeyUp(event){
		this.keyDown = this.keyDown.filter(function(item) {
			return event.code !== item;
		})
	}
	canvasKeyDown(event){
		if(this.keyDown.indexOf(event.key)>-1){
		}else{
			this.keyDown.push(event.code)
			if(event.key === 'Enter' && operation.value == 'fold'){
				foldEnd('Enter')
			}else if(event.key === 'Delete'){
				deleteObject()
			}else if(this.keyDown.indexOf('ControlLeft') > -1 && this.keyDown.indexOf('KeyZ') > -1 && this.keyDown.indexOf('ShiftLeft') > -1){
				this.historyState('reverse')
			}else if(this.keyDown.indexOf('ControlLeft') > -1 && this.keyDown.indexOf('KeyZ') > -1){
				this.historyState('')
			}else if(this.keyDown.indexOf('ControlLeft') > -1 && this.keyDown.indexOf('KeyC') > -1){
				this.copy()
			}else if(this.keyDown.indexOf('ControlLeft') > -1 && this.keyDown.indexOf('KeyV') > -1){
				this.paste()
			}
		}
	}
	canvasClear(){
		let oldCanvasDom = this.canvasDomParent.querySelector('.canvas-container')
		let oldCanvasDom1 =  this.canvasDomParent.querySelector('canvas')
		if(oldCanvasDom)oldCanvasDom.remove()
		if(oldCanvasDom1)oldCanvasDom1.remove()
		this.reverseCanvasState=[];//撤回
		this.normalCanvasState=[];//反撤回
		document.removeEventListener("keydown", this.canvasKeyDown);
		document.removeEventListener("keyup", this.canvasKeyUp);
	
	}
	//删除选中元素
	deleteObject = ()=> {
		if(!this.canvas.getActiveObjects()){
			return
		}
		let target = this.canvas.getActiveObjects()
		target.forEach((item)=>{
			this.canvas.fxRemove(item, {
				onComplete:()=>{
					this.canvas.discardActiveObject(); // 丢弃当前选中的对象
					this.canvas.renderAll(); // 重新渲染 Canvas
				}
			})
			this.canvas.FX_DURATION = 300
		})
		this.updateCanvasState('remove')
	}
	//复制粘贴
	copy(canvas){
		var activeObject = this.canvas.getActiveObject();
		if(!activeObject){
			return
		}
		activeObject.clone((cloned)=>{
			this._clipboard = cloned;
		})
	}
	paste = () => {//粘贴
		if(!this._clipboard){
			return
		}
		this._clipboard.clone(clonedObj => {
			this.canvas.discardActiveObject() // 取消选择

			// 设置新内容的坐标位置
			clonedObj.set({
					left: clonedObj.left + 10,
					top: clonedObj.top + 10,
					evented: true
				})

			if (clonedObj.type === 'activeSelection') {
					// 活动选择需要一个对画布的引用
					clonedObj.canvas = canvas;
					clonedObj.forEachObject((obj)=>{
						this.canvas.add(obj)
					})

					clonedObj.setCoords()
				} else {
					this.canvas.add(clonedObj)
				}
				this._clipboard.top += 10
				this._clipboard.left += 10
				this.canvas.setActiveObject(clonedObj)
				this.canvas.requestRenderAll()
		})
		this.updateCanvasState()
	}

	//撤回反撤回
	//设置画布监听修改添加事件，用来做撤回功能
	updateCanvasState(str){
		const canvasAsJson = JSON.stringify(this.canvas.toJSON());
		if(str == 'loadingCompleted'){
			// this.reverseCanvasState.push(canvasAsJson);
		}
		this.normalCanvasState.push(canvasAsJson);
		if (this.isLoadCanvas) {
			this.reverseCanvasState = []
			this.isLoadCanvas = false;
			this.canvasState = canvasAsJson
		}
	}
	//撤回
	historyState(str){
		if(str == 'reverse' && this.reverseCanvasState.length > 0){//反撤回
			let obj = this.reverseCanvasState.pop()
			// this.canvasState = this.reverseCanvasState[this.reverseCanvasState.length-1]
			this.canvasState = obj 
			this.normalCanvasState.push(obj);
		}else if(str == '' && this.normalCanvasState.length > 1){
			let obj = this.normalCanvasState.pop()
			this.canvasState = this.normalCanvasState[this.normalCanvasState.length-1]
			this.reverseCanvasState.push(obj);
			this.isLoadCanvas = true;
		}else{
			return
		}
		this.canvas.loadFromJSON(this.canvasState, () => {this.isLoadCanvas = false;});
		
	}
}

export default new myCanvas()