import { store } from "../../../main";

/* 节点操作监听事件 */
export const myEvents = (graph) => {

		/* 节点双击编辑 */
		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";
			$('#flow-container')[0].appendChild(edit_area);

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

			// const edit_area =  $('#editable-wrapper')[0];

			edit_area.innerText = text.text || text.textWrap.text || ' ';
			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);
				// node.size(width,domH > height ? domH : height);

			}

			//失焦后设置内容
			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);
				
				const domH = (edit_area.getBoundingClientRect().height) /zoom;
				node.size(width,domH > 50 ? domH : 50);
				
				$('#flow-container')[0].removeChild(edit_area);
			}


			// node.addTools({
			// 	name: 'node-editor',
			// 	args: {
			// 		event: e,
			// 		attrs: {
			// 			fontSize: text.fontSize,
			// 			color: text.fill,
			// 			backgroundColor: rect.fill === 'transparent' ? '#fff' : rect.fill,
			// 		},
			// 	},
			// })
		})

		/* 鼠标移入移出控制连接桩 */
		graph.on('node:mouseenter', ({ node, e }) => {
			// console.log(node)
			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.select(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}) => {
			// console.log(cell)
			//节点
			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_CELL',null);

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

		/* 监听选中事件 */
		graph.on('selection:changed',({selected}) => {
			
			selected.length ? store.commit('sand/SET_SELECT_CELL',selected[0]) : store.commit('sand/SET_SELECT_CELL',null);
		})
}

/* 绑定键盘事件 */
export const bindKey = (graph) => {
	 // 删除
	graph.bindKey(['delete', 'backspace'], () => {
		const select_cell = graph.getSelectedCells();
			if (select_cell.length) {
				// 移除工具
				select_cell.forEach(item => item.removeTools());
				graph.removeCells(select_cell)

				//重置工具栏
				store.commit('sand/SET_SELECT_STATUS',{key:'default'});
				store.commit('sand/SET_SELECT_CELL',null);
			}
			return false
	}, 'keydown');

	/* cv */
	graph.bindKey('ctrl+c', () => {
		const select_cell = graph.getSelectedCells();
		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
	});
}

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

/* 删除节点 清空选区*/
const nodeDelete = (graph) => {
	const select_cell = graph.getSelectedCells();
	console.log(select_cell)
	if (select_cell.length) {

		// 移除工具
		select_cell.forEach(item => item.removeTools());
		graph.removeCells(select_cell);

		//重置工具栏
		store.commit('sand/SET_SELECT_STATUS',{key:'default'});
		store.commit('sand/SET_SELECT_CELL',null);
	}
}
/* 复制粘贴节点 */
const nodeCopyAndPaste = (graph) => {
	const select_cell = graph.getSelectedCells();
	// console.log(select_cell)
	// return
	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
		},
	}: {}
}