import { Node, sp, _decorator } from 'cc';
import { BaseLayer } from '../../common/BaseLayer';
import { cocosUtil } from '../../utils/cocosUtil';
import { constants } from '../data/constants';
import { msgac } from '../data/msgac';
import { audioManager } from '../manager/audioManager';
import { designManager } from '../manager/designManager';
import { eventManager } from '../manager/eventManager';
import { resManager } from '../manager/resManager';
import { sdkManager } from '../manager/sdkManager';
const { ccclass, property } = _decorator;

@ccclass('FightFailLayer')
export class FightFailLayer extends BaseLayer {

    btnLifeBack: Node;
    bodySkeleton: sp.Skeleton;

    monsterId: number;

    onLoad() {
        super.onLoad();

        this.monsterId = this.obj.monsterId;
        if (!this.monsterId) {
            this.monsterId = 1;
        }

        this.btnLifeBack = this.getNodeByPath("btns/btnLifeBack");
        this.bodySkeleton = this.getNodeByPath("body").getComponent(sp.Skeleton);

        this.initUI();

        audioManager.instance.playEffect(constants.audioNames.lose);

        sdkManager.instance.addLevelCount();
        sdkManager.instance.sendEventLevelEnd(false);
    }

    initUI() {
        this.initEffect();

        let row = designManager.instance.getRowById(constants.tableName.monster, this.monsterId);
        let path = constants.bundles.common.spine.roleDir + "/" + row.body + "/" + row.body;
        resManager.instance.loadAsset(constants.bundles.common.name, path, sp.SkeletonData, () => { }, (err, skeletonData) => {
            if (err) {
                return;
            }
            this.bodySkeleton.skeletonData = skeletonData;
            this.bodySkeleton.setAnimation(0, constants.animations.attack, true);
        });
    }

    initEffect() {
        cocosUtil.tweenScaleBreath(this.btnLifeBack);
    }

    onButtonClick(node: Node, name: string) {
        switch (name) {
            case "btnLifeBack":
                this.onClickBtnLifeBack(node);
                break;
            case "btnNext":
                this.onClickBtnNext(node);
                break;
            default:
                break;
        }
    }

    onClickBtnNext(node: Node) {
        this.closeLayer();
        eventManager.instance.send(msgac.levelRestart);
    }

    onClickBtnLifeBack(node: Node) {
        sdkManager.instance.openAd((st: number) => {
            if (st != 1) {
                return;
            }
            this.closeLayer();
            eventManager.instance.send(msgac.lifeBack);
        });
    }

}

