import { asyncDelay, onHomeworkFinish } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import Game, { FISH_OUT, GAME_STATE, Option } from "./tool/Game";
import pg from "./tool/pg";

const { ccclass, property } = cc._decorator;

export function getDegree(p1, p2) {
    let vector = p2.sub(p1);
    let degree = Math.atan(vector.y / vector.x) / Math.PI * 180;
    if (vector.x >= 0) {
        if (vector.y < 0) {
            degree += 360;
        }
    } else {
        if (vector.y > 0) {
            degree += 180;
        } else {
            degree = 180 + degree;
        }
    }
    return -(-degree + 90);//角度计算方法
}
let win: any = window;
let courseware = win.courseware;
enum GUN_STATE {
    WAIT = 1,
    SHUT_MIDDLE,
    SHUT_LEFT,
    SHUT_RIGHT
}
enum FISH_STATE {
    NORMAL = 1,
    BREAK,
    FALL,
}
enum TIPS_STATE {
    GOOD = 1,
    TRY,
    COM,
}
@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    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.initEvent();
    }
    protected onDestroy(): void {
        pg.event.clear();
    }

    @property(cc.Node)
    res: cc.Node = null;
    @property(cc.Node)
    layout_player: cc.Node = null;
    @property(cc.Node)
    layout_balloon: cc.Node = null;
    @property(cc.Node)
    layout_cannon: cc.Node = null;
    @property(cc.Node)
    btn_laba: cc.Node = null;

    _cantouch = null;
    initData() {
        Game.getIns().init(this.data);
        Game.getIns().reset();
        // 所有全局变量 默认都是null 
        this._cantouch = true;
    }
    private layout_start: cc.Node;
    private audioId: any;

    private countDown: number = 999999;
    private timeCount: number;
    private startCount = 15;
    async initView() {
        cc.audioEngine.stopAllEffects();
        this.layout_start = pg.view.find(this, "layout_start");
        let touch = pg.view.find(this, "layout_start/touch");

        this.layout_start.active = true;
        let desc = this.layout_start.getChildByName("desc");
        desc.getComponent(cc.Label).string = Game.getIns().questionText;
        this.audioId = await pg.audio.playAudioByUrl(Game.getIns().question.audio, () => { }, (audioId) => {
            if (audioId > -1 && Game.getIns().state == GAME_STATE.RUNNING) pg.audio.stopAudio(audioId);
        });
        if (this.audioId > -1 && Game.getIns().state == GAME_STATE.RUNNING) {
            cc.audioEngine.stopAllEffects();
            pg.audio.stopAudio(this.audioId);
        }
        touch.on(cc.Node.EventType.TOUCH_END, () => {
            cc.audioEngine.stopAllEffects();
            pg.audio.stopAudio(this.audioId);
            pg.audio.playAudioByUrl(Game.getIns().question.audio);
        })
        if (Game.getIns().title) {
            cc.find("layout_info/bg_title/title", this.node).getComponent(cc.Label).string = Game.getIns().title;
        }
    }
    initEvent() {
        pg.view.touchOn(pg.view.find(this.layout_start, 'btn_start'), this.onTouchStart, this);
        this.btn_laba.on(cc.Node.EventType.TOUCH_END, this.playLaba, this);

        pg.event.on("game_start", () => {
            this.gameStart();
            this.playLaba();
        });
        pg.event.on("play_laba_audio", () => {
            this.playLaba();
        });
        pg.event.on("game_time_over", () => {
            // alert("game_time_over")
            //这里的事件会发送的很早。但是我们需要等待动画执行完了之后再开始后续的内容
            Game.getIns().addPage();
            if (!Game.getIns().isOver) return pg.event.emit("game_start");
            //发送给上端最后的数据
            // alert("game_finish")
            // int  total  
            // int  right
            // int[]  scores   
            // let player = { right: Game.getIns().player.score, error: Game.getIns().player.error }
            Game.getIns().state = GAME_STATE.OVER;
            let data: any = {};
            data.total = Game.getIns().getTotla;
            data.right = Game.getIns().player.right;
            data.scores = Game.getIns().player.voices;
            this.log("total: " + data.total + "      right: " + data.right);
            onHomeworkFinish(data)
        })
    }
    onTouchStart() {
        pg.audio.playLocalAudio(cc.find(`Canvas/res/audio/btn`));
        pg.event.emit("game_start");
    }


    private count: number;
    private list: Option[];
    private fishs: cc.Node[];
    gameStart() {
        Game.getIns().state = GAME_STATE.RUNNING;
        //游戏开始小鱼出现等等
        this.layout_start.active = false;
        if (this.audioId > -1 && Game.getIns().state != GAME_STATE.WAIT) {
            cc.audioEngine.stopAllEffects();
            pg.audio.stopAudio(this.audioId);
        }
        //开始  

        // //根据数据随机热气球
        // let page = Game.getIns().getCurrentPage();
        // let list = page.optionList.concat();
        // list = JSON.parse(JSON.stringify(list));
        // list.sort((A, B) => { return Math.random() < 0.5 });
        // Game.getIns().player.addScore(this.list.length);
        this.count = 0;
        this.lastCount = null;
        this.fishs = [];
        this.viewFishs = [];
        this.touchFishs = [];
        //根据顺序生成对应的鱼。
        //顺序根据时间来进行跳动。当顺序跳动之后，就会产生新的鱼。
    }
    private lastCount: number;
    private viewFishs: Option[];
    private touchFishs: Option[];
    update(dt) {
        if (Game.getIns().state != GAME_STATE.RUNNING) return;
        // if (this.fishLen < 5) this.count++;
        // let fish = this.getFishByCount(this.count);
        // if (fish) this.fishs.push(fish);
    }

    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 intervalId;
    private playLaba() {
        let btn_kaba2 = this.btn_laba.getChildByName("btn_laba2");
        let btn_kaba3 = this.btn_laba.getChildByName("btn_laba3");
        btn_kaba2.active = true;
        btn_kaba3.active = true;

        let count = 0;
        if (this.intervalId) clearInterval(this.intervalId);
        let stop = false;
        this.intervalId = setInterval(() => {
            count++;
            btn_kaba2.active = count % 3 == 1;
            btn_kaba3.active = count % 3 == 2;
            if (stop && count % 3 == 2) clearInterval(this.intervalId);
        }, 150)

        pg.audio.playAudioByUrl(Game.getIns().getCurrentPage().audio).then(() => { stop = true; })
    }

}


