import baseTool from '../../util/baseTool';
import { tpl } from './toastTpl'
const Toast = (($) => {
    const TPL = tpl,
        DefaultConfig = {
            direction: 'right',
            tpl: TPL,
            title: '',
            content: '我是内容我是内容我是内容我是内容我是内容我是内容'
        };
    class Toast {
        constructor(config) {
            this._config = this._getConfig(config);
            this._element = this._config.node;
            this._element.Toast = this;
            this._addEvent();
        }
        
        _getConfig(config) {
            return $.extend({}, DefaultConfig, config);
        }
        
        position() {
            let direction = this._config.direction;
            let $toast = this.$toast;
            let el = this._element,
                $el = $(el);
            let toastWidth = $toast[0].offsetWidth,
                toastHeight = $toast[0].offsetHeight;
            let offsetTop = $el.offset().top,
                offsetLeft = $el.offset().left;
            let eleWidth = el.offsetWidth,
                eleHeight = el.offsetHeight;
            let left = 0;
            let top = 0;
            switch (direction) {
                case 'left':
                    left = offsetLeft - toastWidth;
                    top = offsetTop - toastHeight / 2 + eleHeight / 2;
                    break;
                case 'right':
                    left = offsetLeft + eleWidth;
                    top = offsetTop - toastHeight / 2 + eleHeight / 2;
                    break;
                case 'top':
                    left = offsetLeft - toastWidth / 2 + eleWidth / 2;
                    top = offsetTop - toastHeight;
                    break;
                case 'bottom':
                    left = offsetLeft - toastWidth / 2 + eleWidth / 2;
                    top = offsetTop + eleHeight;
                    break;
            }
            $toast.css({
                left: left + 'px',
                top: top + 'px'
            })
        }
        
        _addEvent() {
            let $el = $(this._element);
            $el.on('mouseover.toast', (e) => {
                
                let $toast = $(template.render(this._config.tpl, this._config));
                $('body').append($toast);
                this.$toast = $toast;
                this.$toast.css('z-index', baseTool.getToolTipIndex());
                this.position();
                this.$toast.addClass('show');
            }).on('mouseout.toast', (e) => {
                this.$toast.removeClass('show');
                this.$toast[0].outerHTML = '';
            })
        }
        
        dispose() {
            $(this._element).off('mouseover.toast').off('mouseout.toast');
            this._element.Toast = null;
        }
    }
    return Toast;
})($);
export default Toast;