import { store } from "../../../main";
import { configOpt } from './toolConfig';
import _ from "lodash"
const { line} = configOpt;

/* 节点操作监听事件 */
export const myEvents = (graph,mindmapDataUseFun) => {
		/* 节点双击编辑 */
		graph.on('node:dblclick', ({ node, e }) => {
			// 节点当前设置的样式同步到编辑区

			const { text, rect} = node.attrs;
			const edit_area = document.createElement('div');
			edit_area.contentEditable = "true";
			edit_area.id = "editable-wrapper";
			edit_area.style.position = "absolute";
			edit_area.style.outline = "none";
			edit_area.style.padding = "4px";
			edit_area.style.boxSizing = "border-box";
			$('#sand-chart-container')[0].appendChild(edit_area);

			const position = node.position();
      const size = node.size();
      const pos = graph.localToGraph(position);
      const zoom = graph.zoom();
      let width = size.width,height = size.height;

			edit_area.innerText = text.text || text.textWrap.text || ' ';
			// 开启editText的事务 
			graph.startBatch('editText')
			node.attr('text/textWrap/text', '');

			edit_area.style.left = `${pos.x}px`;
			edit_area.style.top = `${pos.y}px`;
			edit_area.style.width = `${width * zoom}px`;
			// edit_area.style.height = `${height}px`;

			edit_area.style.lineHeight = `${text.lineHeight * zoom}px`;
			edit_area.style.textAlign = `center`;
			edit_area.style.fontSize = `${text.fontSize * zoom}px`;
			edit_area.style.fontWeight = `${text.fontWeight}px`;
			edit_area.style.color = `${text.fill}`;

		
			edit_area.focus();
			if (window.getSelection) {
				const range = document.createRange();
				const selection = window.getSelection();
				range.selectNodeContents(edit_area);
				selection.removeAllRanges();
				selection.addRange(range);
			}

			// 动态增加框的高度
			edit_area.oninput = () => {
				const domH = (edit_area.getBoundingClientRect().height) /zoom;
				node.size(width,domH > 50 ? domH : 50);
			}

			//失焦后设置内容
			edit_area.onblur = () => {
				let newval = edit_area.innerText.replace(/(\n[\s\t]*\r*\n)/g,'\n');


				node.attr('text/textWrap/text', newval);
				node.attr('text/text', newval);
				// 关闭editText的事务
				graph.stopBatch('editText')

				if(node.shape.indexOf('mindmap')!==-1){
					if(!mindmapDataUseFun) return 
					const mindmapDataUse=mindmapDataUseFun().mindmapDataUse
					let ids = node.id.split('-')
					let mindmapDataIndex = mindmapDataUse.findIndex(mindmap => mindmap.mindmapData.id == ids[0])
					let mindMapDataCurrent = mindmapDataUse[mindmapDataIndex]?mindmapDataUse[mindmapDataIndex].mindmapData:{}

					let findId = ids[0]
					for (let i = 1; i < ids.length; i++) {
						const element = ids[i];
						findId = findId+'-'+element
						mindMapDataCurrent=mindMapDataCurrent.children.find(it => it.id==findId)
					}
					mindMapDataCurrent.label = newval
				}

				const domH = (edit_area.getBoundingClientRect().height) /zoom;
				node.size(width,domH > 50 ? domH : 50);

				$('#sand-chart-container')[0].removeChild(edit_area);
			}
		})
		/* 鼠标移入移出控制连接桩 */
		graph.on('node:mouseenter', ({ node, e }) => {
			for(let i of document.querySelectorAll(`g[data-cell-id="${node.id}"] .x6-port-body`)) {
				i.style.display = 'block'
			}
		})
	
		graph.on('node:mouseleave', ({ node, e }) => {
			for(let i of document.querySelectorAll(`g[data-cell-id="${node.id}"] .x6-port-body`)) {
				i.style.display = 'none'
			}
		})

		/* 节点右键 */
		graph.on('node:contextmenu',({node,e}) => {
			graph.resetSelection(node);
			const dom = $('#contextMenu-wrapper')[0];
			dom.style.left = e.clientX-3 + 'px';
			dom.style.top = e.clientY-3 + 'px';
		})

		/* 选中事件 */
		// graph.on('cell:selected',({cell,options}) => {
		// 	//节点
		// 	if(cell.shape === 'rect') {
		// 		const { key } = cell.data;

		// 		const options = setSelectedOptions(cell.attrs,key);
		// 		//设置toolbar状态
		// 		store.commit('sand/SET_SELECT_STATUS',{
		// 			key,
		// 			options
		// 		});
		// 	}else if(cell.isEdge()) {

		// 		const { line } = cell.attrs;
		// 		//高亮选中
		// 		// cell.attr('line', { stroke: '#f00', strokeWidth: 3 });
		// 		//设置toolbar状态
		// 		store.commit('sand/SET_SELECT_STATUS',{
		// 			key: 'line',
		// 			options: {
		// 				line: {
		// 					width: line.strokeWidth,
		// 					color: line.stroke,
		// 				}
		// 			}
		// 		});
		// 	}
		// })
		
		/* 点击空白区域清空选区 屏蔽工具栏 */
		// graph.on('blank:click',() => {
		// 	graph.cleanSelection();
		// 	// store.commit('sand/SET_SELECT_STATUS',{key:'default'});
		// 	store.commit('sand/SET_SELECT_CELLS',[]);

		// 	if($('#editable-wrapper')[0]) $('#editable-wrapper')[0].blur();
		// })

		const changeSelection=_.debounce((selected)=> {
			store.commit('sand/SET_SELECT_CELLS',selected)
		},50)

		/* 监听选中事件 */
		graph.on('selection:changed',({selected}) => {
			changeSelection(selected)
		})

		/* 监听选中事件 */
		graph.on('edge:mouseenter', ({ cell }) => {
			if(cell.store.data.shape=="mindmap-edge"){
				// 思维导图的边
			}else{
				cell.addTools([
					{
						name: 'source-arrowhead',
						args: {
							attrs:{
								d: 'M 8 -6 -8 0 8 6 Z',
								fill: line.color
							}
						}
					},
					{
						name: 'target-arrowhead',
						args: {
							attrs:{
								d: 'M -8 -6 8 0 -8 6 Z',
								fill: line.color
							}
						}
					},
					{
						name:"vertices",
						args:{
							addable:false,
							removable:false
						}
					},
					{
						name: 'segments'
					}
				])
			}

		})
		
		graph.on('edge:mouseleave', ({ cell }) => {
			if(cell.store.data.shape=="mindmap-edge"){
				// 思维导图的边
			}else{
				cell.removeTools()
			}
		})
}

/* 绑定键盘事件 */
export const bindKey = (graph,mindmapDataUseFun) => {
	 // 删除
	graph.bindKey(['delete', 'backspace'], () => {
		deleteNodes(graph,mindmapDataUseFun)
		return false
	}, 'keydown');

	/* cv */
	graph.bindKey('ctrl+c', () => {
		// 去除思维导图的节点
		const select_cell = graph.getSelectedCells().filter(it => it.shape.indexOf('mindmap')==-1);
		if (select_cell.length) {
			graph.copy(select_cell)
		}
		return false
	});

	graph.bindKey('ctrl+v', () => {
		if (!graph.isClipboardEmpty()) {
			const select_cell = graph.paste({ offset: 30 })
			graph.cleanSelection()
			graph.select(select_cell)
		}
		return false
	});

	graph.bindKey('ctrl+z', () => {
		if(graph.canUndo()){
			graph.undo()
		}
		return false
	});
	graph.bindKey('ctrl+y', () => {
		if(graph.canRedo()){
			graph.redo()
		}
		return false
	});
}

/* 右键事件 */
export const contextEvent = (graph,key,mindmapDataUseFun) => {
	switch (key) {
		case 'copy':
			nodeCopyAndPaste(graph);
			break;
		case 'del': 
			deleteNodes(graph,mindmapDataUseFun);
			break;
	}
}

/* 复制粘贴节点 */
const nodeCopyAndPaste = (graph) => {
	const select_cell = graph.getSelectedCells();
	if (select_cell.length) {
		graph.copy(select_cell);
		const copy_cell = graph.paste({ offset: 30 });
		graph.cleanSelection();
		graph.select(copy_cell);
	}
}

/* 关联三种基础图形选中样式 */
// const setSelectedOptions = ({ rect, text }, key) => {
// 	return ['rect','date'].includes(key) ? {
// 		text: { //文本设置
// 			size: text.fontSize,
// 			fontWeight: text.fontWeight, //
// 			color: text.fill
// 		},
// 		border: { //线框设置
// 			// isDash: 0, // 0实 1虚线
// 			width: rect.strokeWidth,
// 			fill: rect.fill,
// 			borderColor: rect.stroke,
// 		},

// 	} : key === 'text' ? {
// 		text: { //文本设置
// 			size: text.fontSize,
// 			fontWeight: text.fontWeight,
// 			color: text.fill
// 		},
// 	}: {}
// }

const deleteNodes=(graph,mindmapDataUseFun)=>{
	const select_cell = graph.getSelectedCells();
	let delete_cells=[]
	if(!mindmapDataUseFun){
		delete_cells = select_cell
		if (delete_cells.length) {
			// 移除工具
			delete_cells.forEach(item => item.removeTools());
			graph.removeCells(delete_cells)
		}
		return 
	}
	let mindmapCell=[]
	for (let i = 0; i < select_cell.length; i++) {
		const cell = select_cell[i];
		if(cell.shape == "mindmap-edge"){
			continue
		}else if(cell.shape.indexOf('mindmap')!=-1){
			mindmapCell.push(cell)
			// 拿到该节点的所有子节点
			let Successors = graph.getSuccessors(cell) 
			mindmapCell = [...mindmapCell,...Successors]
		}
		delete_cells.push(cell)
	}
	// 去重
	const uniqueArr = mindmapCell.filter((item, index) => mindmapCell.findIndex(i => i.id === item.id) === index);

	delete_cells = [...delete_cells,...uniqueArr]
	if (delete_cells.length) {
		// 移除工具
		delete_cells.forEach(item => item.removeTools());
		graph.removeCells(delete_cells)
	}
	const mindmapAssistData = mindmapDataUseFun()

	let shouldOperations=[]
	mindmapAssistData.mindmapDataUse.map((item,index)=>{
		let levelIds = uniqueArr.filter(mindMap => mindMap.id.startsWith(item.mindmapData.id)).map(mindMap => mindMap.id)
		if(!(levelIds && levelIds.length>0)) return 
		let mindMapIds=[...levelIds]
		for (let i = 0; i < levelIds.length; i++) {
			const element = levelIds[i]
			mindMapIds=mindMapIds.filter( id => id.indexOf(element) !=0 || id==element)
		}
		shouldOperations.push(mindMapIds)
	})

	mindmapAssistData.deletedMindmapData.push([])
	shouldOperations.map(it =>{
		it.map(it1 =>{
			deleteMindmapData(it1,mindmapAssistData)
		})
	})
}

const deleteMindmapData=(id,data)=>{

	let ids = id.split('-')
	let mindmapDataIndex = data.mindmapDataUse.findIndex(mindmap => mindmap.mindmapData.id == ids[0])
	if(ids.length==1){
		let spliceData=data.mindmapDataUse.splice(mindmapDataIndex,1)
		// 备份删除掉的数据
		data.deletedMindmapData[data.deletedMindmapData.length-1].push(spliceData)
		return 
	}

	let mindmapData = data.mindmapDataUse[mindmapDataIndex].mindmapData
	let findId = ids[0]
	for (let i = 1; i < ids.length-1; i++) {
		const element = ids[i];
		findId = findId+'-'+element
		if(!(mindmapData && mindmapData.children)){
			return 
		}
		mindmapData=mindmapData.children.find(it => it.id==findId)
	}
	let endId = ids[ids.length-1]
	if(!(mindmapData && mindmapData.children)){
		return 
	}
	let endIndex = mindmapData.children.findIndex(it => it.id == findId+'-'+endId)
	let spliceData=mindmapData.children.splice(endIndex,1)
	data.deletedMindmapData[data.deletedMindmapData.length-1].push(spliceData)
}