
const { ccclass, property, executeInEditMode, playOnFocus } = cc._decorator;

/**
 * Z字飘落效果
 * @author 薛鸿潇
 */
@ccclass
@executeInEditMode()
@playOnFocus()
export default class ZPathFalling extends cc.Component {
    @property({ displayName: '自动播放' }) private play_on_load: boolean = true;
    @property({ displayName: '完成回调', type: cc.Component.EventHandler }) public onComplete: cc.Component.EventHandler = new cc.Component.EventHandler();
    /** 编辑器预览 */
    private _edit_play: boolean = false;
    @property({ displayName: '编辑器预览' })
    get edit_play(): boolean {
        if (this._edit_play && !this.edit_playing) {
            this.edit_playing = true;
            this.play();
        }
        return this._edit_play;
    }
    set edit_play(v: boolean) {
        this._edit_play = v;
        if (!v) this.stop();
    }
    /** 编辑器是否正在播放 */
    private edit_playing = false;
    onLoad() {

    }

    start() {
        if (CC_EDITOR) {
            this.edit_play && this.play();
        } else {
            this.play_on_load && this.play();
        }
    }

    /** z字落地术 */
    private play() {
        // z字三点式
        let end_pos1 = this.node.getPosition();
        let end_pos2 = this.node.getPosition();
        let end_pos3 = this.node.getPosition();
        // 左右坐标
        if (this.node.x >= 0) {
            // 在右边，左飘
            end_pos1.x -= this.node.width * 3;
            end_pos2.x -= this.node.width * 1;
            end_pos3.x -= this.node.width * 2;
        } else {
            // 在左边，右飘
            end_pos1.x += this.node.width * 3;
            end_pos2.x += this.node.width * 1;
            end_pos3.x += this.node.width * 2;
        }
        // 下落
        end_pos1.y -= this.node.height / 2;
        end_pos2.y -= this.node.height;
        end_pos3.y -= this.node.height * 1.2;
        // // 上下坐标
        // if (this.node.y <= -200) {
        //     // 在下面
        //     end_pos1.y += this.node.height / 1;
        //     end_pos2.y += this.node.height * 1.5;
        //     end_pos3.y += this.node.height * 2;
        // } else {
        //     // 在上面
        //     end_pos1.y -= this.node.height / 2;
        //     end_pos2.y -= this.node.height;
        //     end_pos3.y -= this.node.height * 1.2;
        // }
        let pos1 = cc.tween().to(0.5, { position: end_pos1 }, { easing: 'cubicOut' })
        let pos2 = cc.tween().to(0.5, { position: end_pos2 }, { easing: 'cubicOut' })
        let pos3 = cc.tween().to(0.5, { position: end_pos3 }, { easing: 'cubicOut' })
        let call1 = cc.tween().call(() => {
            this.edit_playing = false;
            this.edit_play = false;
            this.onComplete.handler && this.onComplete.emit([this.node]);
        })
        cc.tween(this.node).then(pos1).then(pos2).then(pos3).then(call1).start();
    }
    /** 停止动画 */
    private stop() {
        this.edit_playing = false;
        this.node.stopAllActions();
    }
    // update (dt) {}
}
