import { asyncDelay, onHomeworkFinish } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import Game from "./Game";
import pg from "./pg";
import OptionItem from "./OptionItem";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    @property(cc.Node)
    public item: cc.Node;

    private roundIdx = 0;
    private btn_laba: cc.Node;
    private layout: cc.Node;


    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
        this._imageResList.push({ url: this.data.pic_url });
        this._imageResList.push({ url: this.data.pic_url_2 });
    }

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

    addPreloadAnima() {

    }

    onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initListener();
        pg.event.emit("mouse_start_play", { voice: Game.getIns().aniEnter.audioUrl, time: Game.getIns().aniEnter.time });
    }

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

    initView() {
        pg.event.emit("mouse_num", this.data.item.groupArr.length);
        this.layout = cc.find("layout", this.node);
        this.initBtn();
        this.showGame();
    }
    initListener() {
        pg.event.on("mrbr05_click_right", () => {
            this.roundIdx++;
            pg.event.emit("mouse_add", () => { });
            this.showGame();
        })
        pg.event.on("mouse_start_play_success", () => {
            this.playLaba();
        })

        this.btn_laba = cc.find("btn_laba", this.node);
        this.btn_laba.on(cc.Node.EventType.TOUCH_END, this.playLaba, this);
    }
    initBg() {
        const bgNode = cc.find('Canvas/bg');
        bgNode.scale = this._mapScaleMax;
    }

    initBtn() {


    }

    // update (dt) {},

    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);
            });
        })
    }

    private gameOver() {
        setTimeout(() => {
            let mouse_end = pg.view.find(this, "mouse_end");
            mouse_end.active = true;
            mouse_end.getComponent("mrbr05_mouse_end").play().then(() => {
                onHomeworkFinish();
            })
        }, 1800);
    }
    private updateRound() {
        let round = cc.find("top/label", this.node);
        let rIdx = this.roundIdx;
        if (rIdx > this.data.item.groupArr.length) rIdx = this.data.item.groupArr.length;
        round.getComponent(cc.Label).string = (rIdx + 1) + "/" + this.data.item.groupArr.length;
    }
    /**
    * 2: y;600   x:280  -280
    * 3: y:600   x:380  0  -380
    * 4: y:610 400   x: -380 120 -120  380
    * 
    */
    private getItemPos(num) {
        let pos1 = [cc.v2(-280, 600), cc.v2(280, 600)];
        let pos2 = [cc.v2(-380, 550), cc.v2(-0, 550), cc.v2(380, 550)];
        let pos3 = [cc.v2(-380, 610), cc.v2(-120, 400), cc.v2(120, 610), cc.v2(380, 400)];
        if (num == 2) return pos1;
        else if (num == 3) return pos2;
        else if (num == 4) return pos3;

    }
    private showGame() {
        if (this.roundIdx >= this.data.item.groupArr.length) {
            this.gameOver();
            return;
        }
        this.updateRound();
        this.showProp();

    }
    private showProp() {
        this.layout.removeAllChildren();
        let data = this.data.item.groupArr[this.roundIdx].questionArr[0];
        cc.assetManager.loadRemote(data.audio_url, async (err, audioClip) => {
            this.btn_laba.audioClip = audioClip;
            if (this.roundIdx > 0) this.playLaba();
        });
        let pos = this.getItemPos(data.answerArr.length);
        let sc = [1, 0.88, 0.85]
        for (let i = 0; i < data.answerArr.length; i++) {
            let dt = data.answerArr[i];
            let item = cc.instantiate(this.item);
            item.getComponent(OptionItem).initItem(dt, data.answerType);
            this.layout.addChild(item);
            this.itemShow(item, pos[i]);
            item.scale = sc[data.answerArr.length - 2];
        }
    }
    private itemShow(item, pos) {
        item.x = pos.x;
        cc.tween(item)
            .to(1, { position: cc.v2(pos.x, pos.y) })
            .start();
    }
    private async playLaba() {
        if (!this.btn_laba.audioClip) return;
        let img_1 = this.btn_laba.getChildByName("img_1");
        let img_2 = this.btn_laba.getChildByName("img_2");
        let img_3 = this.btn_laba.getChildByName("img_3");
        cc.Tween.stopAllByTarget(img_1);
        cc.Tween.stopAllByTarget(img_2);
        cc.Tween.stopAllByTarget(img_3);
        img_1.opacity = 255;
        img_2.opacity = 255;
        img_3.opacity = 255;
        pg.audio.playAudio(this.btn_laba.audioClip, () => {
            cc.Tween.stopAllByTarget(img_1);
            cc.Tween.stopAllByTarget(img_2);
            cc.Tween.stopAllByTarget(img_3);
            img_1.scale = 0.6;
            img_1.opacity = 0;
            img_2.scale = 0.6;
            img_2.opacity = 0;
            img_3.scale = 0.6;
            img_3.opacity = 0;
        });
        cc.tween(img_1).repeatForever(cc.tween().to(1, { scale: 1, opacity: 0 }).to(0, { scale: 0.6, opacity: 255 })).start();
        await this.awaitTime(333)
        cc.tween(img_2).repeatForever(cc.tween().to(1, { scale: 1, opacity: 0 }).to(0, { scale: 0.6, opacity: 255 })).start();
        await this.awaitTime(333)
        cc.tween(img_3).repeatForever(cc.tween().to(1, { scale: 1, opacity: 0 }).to(0, { scale: 0.6, opacity: 255 })).start();
    }

    private async awaitTime(t) {
        let time = t;
        return new Promise(function (resolve, reject) {
            setTimeout(() => {
                resolve("");
                return true;
            }, time);
        })
    }
}
