

import { layers } from "../views/layers";
import { RES } from "../RES";

let inited = false;
let _toast: Toast;
let _parent: FYGE.Container;
let startY: number
let endY: number
const initToast = () => {
    if (!inited) {
        inited = true;
        _toast = new Toast();
        _parent = layers.toastLayer;
        _toast.alpha = 0;
        _toast.x = layers.stageOffsetX - _parent.x + (layers.stageWidth - _toast.width) / 2;
        var h = _toast.height;
        var y = layers.stageOffsetY - _parent.y;
        startY = y - h;
        endY = y + (layers.stageHeight - h) / 2;
    }
}
export const showToast = (msg: string) => {
    initToast();
    _toast.show(msg)
    _parent.addChild(_toast);
    FYGE.Tween.removeTweens(_toast);
    FYGE.Tween.get(_toast)//动画看需求
        .set({ y: startY, alpha: 1 })
        .to({ y: endY }, 500, FYGE.Ease.quartOut)
        .wait(800)
        .to({ alpha: 0 }, 300)
        .call(() => {
            _parent.removeChild(_toast);
        })
}

/**
 * 对于之前淘宝小程序遇到的问题，需要销毁，否则会出问题
 */
export const destroyToast = () => {
    if (inited && _toast && !_toast.destroyed) {
        _toast.destroy();
        _toast = null;
        _parent = null;
        inited = false;
    }
}

/**
 * toast类，不对外导出，适配居中有问题，有时间改
 * 自身居中，
 */
class Toast extends FYGE.Container {
    msg: FYGE.TextField;
    bg: FYGE.Sprite;
    PADDING = 40;
    constructor() {
        super();
        this.mouseChildren = false;
        this.mouseEnable = false;
        var toastBgTexture: FYGE.Texture = RES.getRes("toastBg.png");
        this.bg = new FYGE.Sprite(toastBgTexture);
        // this.bg.x = (750 - 460) / 2// (layers.stageWidth - this.bg.width) / 2
        this.addChild(this.bg);
        this.msg = new FYGE.TextField();
        this.msg.size = 28;
        this.msg.fillColor = "0xffffff";
        this.msg.text = "";
        this.msg.verticalAlign = FYGE.VERTICAL_ALIGN.MIDDLE;
        this.msg.textHeight = toastBgTexture.height;
        this.msg.textAlign = FYGE.TEXT_ALIGN.CENTER;
        this.addChild(this.msg)
    }
    /**
     * 显示时调用
     * @param msg 
     */
    show(msg: string) {
        this.msg.text = msg;
        //文本居中适配
        this.msg.x = (this.bg.width - this.msg.textWidth) / 2//(layers.stageWidth - this.msg.textWidth) / 2;
        //是否需要根据文本宽度缩放背景
        // this.bg.width = Math.min(this.msg.textWidth + this.PADDING * 2, 523);
        //背景居中适配，由于上面一行注释，那这行就构造函数里只执行一次吧
        // this.bg.x = (layers.stageWidth - this.bg.width) / 2
    }

    destroy() {
        FYGE.Tween.removeTweens(this);
        super.destroy();
        this.msg = null
        this.bg = null;
    }

}