import { asyncDelay, asyncPlayDragonBoneAnimation, getSpriteFrimeByUrl, onHomeworkFinish } from "../script/util_DG23";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_DG23";
import Boy from "../script/items/boy_DG23";
import TouchLogic from "../script/items/TouchLogic_DG23";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    @property(cc.Node)
    root: cc.Node = null;
    @property(cc.Node)
    boyNode: cc.Node = null;
    @property(cc.Node)
    btn_start: cc.Node = null;
    @property(cc.Node)
    btn_restart: cc.Node = null;

    @property(cc.Node)
    minpao: cc.Node = null;

    @property(cc.Node)
    bigpao: cc.Node = null;

    @property(cc.Node)
    ppNode: cc.Node = null;

    @property(cc.Node)
    leftBox: cc.Node = null;
    @property(cc.Node)
    leftStrNode: cc.Node = null;
    @property(cc.Node)
    leftPicNode: cc.Node = null;

    @property(cc.Node)
    leftGuideNode: cc.Node = null;

    @property(cc.Node)
    rightBox: cc.Node = null;
    @property(cc.Node)
    rightStrNode: cc.Node = null;
    @property(cc.Node)
    rightPicNode: cc.Node = null;
    @property(cc.Node)
    rightGuideNode: cc.Node = null;

    @property(cc.Node)
    candleNode: cc.Node = null;
    @property(cc.Node)
    banNode: cc.Node = null;
    @property(cc.Node)
    btn_quit: cc.Node = null;
    roundIndex: number;
    resultStr: any;
    resultPic: any;
    letfStr: any;
    rightStr: any;
    letfPic: any;
    rightPic: any;
    private _touchRight: Function;

    addPreloadImage() {

    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
        this._audioResList.push({ url: this.data.audio_url_guide });
    }

    addPreloadAnima() {

    }

    async onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initBg();
        this.initData();
        this.initView();
        this.initListener();
    }

    _cantouch = null;
    initData() {
        // 所有全局变量 默认都是null 
        this._cantouch = true;
    }

    initView() {

        this.playLocalAudio("btn")
        this.root.active = false;
        this.btn_start.active = false;
        this.btn_quit.active = false;
        this.btn_restart.active = false;

        this.leftBox.active = false;
        this.rightBox.active = false;
        this.bigpao.active = false;
        this.minpao.active = false;

        this.leftGuideNode.active = false;
        this.rightGuideNode.active = false;

        this.roundIndex = 0;

        this.boyNode.x = cc.winSize.width;
        this.boyNode.active = true;
        this.boyNode.scaleX = 0.65;
        this.boyNode.getComponent(Boy).playRun(-1);
        cc.tween(this.boyNode).to(3, { x: 600 }).call(() => {
            this.boyNode.getComponent(Boy).playtalk(-1);
            this.playAudioByUrl(this.data.audio_url_guide, () => {

                this.btn_start.active = true;

            })
        }).start()

    }

    initBg() {
        const bgNode = cc.find('Canvas/bg');
        bgNode.scale = this._mapScaleMax;

        this.boyNode.active = false;
        cc.tween(this.btn_start).to(0.3, { scale: 1.1 }).to(0.2, { scale: 1 }).delay(1).union().repeatForever().start();
        cc.tween(this.btn_quit).to(0.3, { scale: 1.1 }).to(0.2, { scale: 1 }).delay(1).union().repeatForever().start();
        cc.tween(this.btn_restart).to(0.3, { scale: 1.1 }).to(0.2, { scale: 1 }).delay(1).union().repeatForever().start();

        this.btn_start.on("click", this.onClickStart, this)

        this.btn_restart.on("click", this.initView, this)
        this.btn_quit.on("click", () => {
            this.playLocalAudio("btn")
            this.playLocalAudio("btn")
            if (!cc.find('middleLayer')) {
                console.log("==点击了下一页按钮==")
                return;
            }
            const middleLayer = cc.find('middleLayer').getComponent('middleLayer');
            middleLayer.goNextPage();  // 跳转到下一页
        }, this)

    }


    onClickStart() {

        this.playLocalAudio("btn")
        this.boyNode.scaleX = -0.65;
        this.log("playRun start")
        this.boyNode.getComponent(Boy).playRun(-1);
        this.btn_start.active = false;

        asyncPlayDragonBoneAnimation(this.ppNode, "normal", -1);

        asyncPlayDragonBoneAnimation(this.candleNode, "smoke", -1)

        cc.tween(this.boyNode).to(1, { x: cc.winSize.width }).call(() => {
            this.doRound()

        }).start();

    }
    doEndLogic() {

        cc.log("doEndLogic---")
        this.playLocalAudio("endstar")
        this.root.active = false;
        this.btn_restart.active = true;
        this.btn_quit.active = true;

    }
    async doRound() {

        if (this.roundIndex >= this.data.group_arr.length) {
            this.doEndLogic();
            return
        }
        this.initRoudData();
        this.initRoundView();

        this.leftBox.x -= cc.winSize.width;
        this.rightBox.x += cc.winSize.width;
        this.root.active = true;
        cc.tween(this.leftBox).by(1, { x: cc.winSize.width }).start();
        cc.tween(this.rightBox).by(1, { x: -cc.winSize.width }).start();
        await asyncDelay(0.5);
        this.playLocalAudio("boxin");
        await asyncDelay(1);
        this.playLocalAudio("guidin")
        await asyncDelay(1);
        await this.rightAction();
        await this.leftAcation();
        await asyncDelay(1);
        await this.playResultAni();
        await this.playOutAni();
        await asyncDelay(1);
        this.roundIndex++;
        this.doRound();

    }
    async rightAction() {
        if (this.rightStr) {
            this.rightGuideNode.active = true;
            this.rightGuideNode.opacity = this.roundIndex == 0 ? 255 : 0;
            this.rightGuideNode.getComponent(TouchLogic).checkAnge(145, () => {
                this._touchRight && this._touchRight();
                this.playLocalAudio("click");
                this.rightGuideNode.active = false;
            })
        }
        await this.touchCheck();
        cc.log("check done");
        await asyncPlayDragonBoneAnimation(this.rightBox, "normal", 1);
        this.banNode.x -= 180;
        asyncPlayDragonBoneAnimation(this.candleNode, "fire", 1);
        this.playLocalAudio("lotspp")
        this.minpao.active = true;
        await asyncPlayDragonBoneAnimation(this.ppNode, "right", 1);
        asyncPlayDragonBoneAnimation(this.ppNode, "normal", -1);
        this.playLocalAudio("phappy");
        await asyncDelay(1);
        this.minpao.active = false;
    }
    async leftAcation() {
        if (this.letfStr) {
            this.leftGuideNode.active = true;
            this.leftGuideNode.opacity = this.roundIndex == 0 ? 255 : 0;
            this.leftGuideNode.getComponent(TouchLogic).checkAnge(30, () => {
                this._touchRight && this._touchRight();
                this.playLocalAudio("click");
                this.leftGuideNode.active = false;
            })
        }
        await this.touchCheck();
        cc.log("check done");
        await asyncPlayDragonBoneAnimation(this.leftBox, "normal", 1);
        this.playLocalAudio("lotspp")
        this.minpao.active = true;
        await asyncPlayDragonBoneAnimation(this.ppNode, "right", 1);
        asyncPlayDragonBoneAnimation(this.ppNode, "normal", -1);
        this.playLocalAudio("phappy");
        await asyncDelay(1);
        this.minpao.active = false;
    }

    touchCheck() {
        return new Promise((resolve) => {
            this._touchRight = resolve;
        })
    }

    playResultAni() {
        this.bigpao.active = true;
        this.bigpao.y = -100;
        return new Promise((resolve) => {
            this.playLocalAudio("bigpp")
            cc.tween(this.bigpao).to(1, { y: 300, scale: 1 }).call(async () => {
                let pp = this.bigpao.getChildByName("aninode");
                pp.active = true;
                this.playLocalAudio("pigppbom")
                await asyncPlayDragonBoneAnimation(pp, "newAnimation", 1);
                resolve("")
            }).start();
        })
    }
    playOutAni() {
        this.bigpao.active = false;
        cc.tween(this.leftBox).by(1, { x: -cc.winSize.width }).call(() => {
            this.leftBox.x += cc.winSize.width;
            this.leftBox.active = false;
        }).start();
        cc.tween(this.rightBox).by(1, { x: cc.winSize.width }).call(() => {
            this.rightBox.x -= cc.winSize.width;
            this.rightBox.active = false;
        }).start();

        this.banNode.x += 180;
        asyncPlayDragonBoneAnimation(this.candleNode, "smoke", -1);

    }

    initRoudData() {

        let data = this.data.group_arr[this.roundIndex];
        this.resultStr = data.text_arr[0].value;
        this.resultPic = data.image_arr[0].value;

        this.rightStr = data.group_arr[0]?.text_arr[0]?.value;
        this.letfStr = data.group_arr[0]?.text_arr[1]?.value;

        this.rightPic = data.group_arr[0]?.image_arr[0]?.value;
        this.letfPic = data.group_arr[0]?.image_arr[1]?.value;
    }
    initRoundView() {

        if (this.resultStr) {

            this.bigpao.getChildByName("lb").getComponent(cc.Label).string = this.rightStr;

        }

        if (this.resultPic) {

            getSpriteFrimeByUrl(this.rightPic, (spf) => {
                this.bigpao.getChildByName("icon").getComponent(cc.Sprite).spriteFrame = spf;
            })

        }

        if (this.rightStr) {
            this.rightBox.active = true;
            this.rightStrNode.getComponent(cc.Label).string = this.rightStr;
        }

        if (this.letfStr) {
            this.leftBox.active = true;
            this.leftStrNode.getComponent(cc.Label).string = this.letfStr;
        }

        if (this.rightPic) {
            getSpriteFrimeByUrl(this.rightPic, (spf) => {
                this.rightPicNode.getComponent(cc.Sprite).spriteFrame = spf;
                this.rightPicNode.scale = Math.min(210 / this.rightPicNode.width, 270 / this.rightPicNode.height)

            })
        }

        if (this.letfPic) {
            getSpriteFrimeByUrl(this.letfPic, (spf) => {
                this.leftPicNode.getComponent(cc.Sprite).spriteFrame = spf;

                this.leftPicNode.scale = Math.min(210 / this.leftPicNode.width, 270 / this.leftPicNode.height)

            })
        }



    }
    initListener() {

    }

    playLocalAudio(audioName) {
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        return new Promise((resolve, reject) => {
            const id = cc.audioEngine.playEffect(audio.clip, false);
            cc.audioEngine.setFinishCallback(id, () => {
                resolve(id);
            });
        })
    }
}
