import {Api, Helper} from '../../utility';
import PropsPanel from './PropsPanel';
import Tree from './Tree';

class Menu {
	static instance = null;
	
	static getInstance() {
		if(!Menu.instance || !(Menu.instance instanceof Menu)) {
			Menu.instance = new Menu();
		}

		return Menu.instance;	
	}
	
	constructor() {
		this.target = null;
		this.container = null;
		this.report = null;
		this.hasMenu = false;
		this.isShowMenu = false;
		this.api = new Api();
	}
	
	setProps(newProps) {
		Object.assign(this, newProps);
	}
	
	getProp(prop) {
		return this[prop];
	}
	
	getMouseCoordinate() {
		return {x: this.target.clientX, y: this.target.clientY};
	}
	
	showMenu() {
		if(!this.hasMenu) {
			this.createMenu();
		} else {
			this.updateMenu();
		}
	}
	
	createMenu() {
		const {x, y} = this.getMouseCoordinate();
		const api = this.api;
		const that = this;

		let menu = "";

		$.when(api.getTemplete('menu-tmpl')).done(function(tml) {
			menu = Helper.getInstance().handleTemplete(tml, {style: 'position:absolute;left:'+x+'px;top:'+y+'px;display:block'}, 'menu-tmpl');
            $('body').append(menu);
			that.setProps({hasMenu: true, isShowMenu: true, container: $('#menu')});
			that.bindEvent($('#menu'));
		});
	}
	
	updateMenu() {
		const {x, y} = this.getMouseCoordinate();
		const menu = $('#menu');
		
		if(menu) {
			menu.css({left: x, top: y, display: 'block'});
			this.setProps({isShowMenu: true});
		}
	}
	
	hideMenu() {
		const menu = $('#menu');
		
		if(menu) {
			menu.css('display', 'none');
			this.setProps({isShowMenu: false});
		}
	}
	
	bindEvent(container) {
		const $container = this.container;

        $container.off('click', 'a').on('click', 'a', function(e) {
			const $this = $(this);
			const type = $this.text();
			
			switch(type) {
				case '删除':
					Menu.getInstance().delReportElement();
					$this.parents('#menu').css('display', 'none');
					break;
				default:
					break;
			}	
			// $this.css('outline-style', 'none');
		});
	}
	
	delReportElement() {
		const report = this.report ? this.report : null;
		if(report && report._currToElem) {
			if(report._currToElem.getClassName()=="SubReport"){
				//这是单独针对一个子报表的问题
				report.subReportId="";
			}
			report.delElementFromChunk(report._currToElem);
			report._currToElem = null;
			report.repaint();
			Tree.getInstance().render();
			PropsPanel.getInstance().render();
		}
	}
}

export default Menu;