import { asyncDelay, onHomeworkFinish, RandomInt } 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;

    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("skiing_show_firework", () => {
            this.playLocalAudio("sahua");
            let endPos = cc.find("Canvas/bg/bg_could/endPos");
            this.showOneFirework(endPos.getPosition(), endPos.parent, cc.find('paperBase', this.node).children);
        });
        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;
            data.stone = Math.floor(10 * data.right / data.total);
            this.log("total: " + data.total + "      right: " + data.right + "   stone: " + data.stone);
            onHomeworkFinish(data)
        })
    }
    onTouchStart() {
        pg.audio.playLocalAudio(cc.find(`Canvas/res/audio/btn`));
        pg.event.emit("game_start");
    }


    private count: number;
    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);
        }
        //开始  
        this.count = 0;
    }
    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 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, (() => {
            stop = true;
        }))
    }


    async showOneFirework(pos, parentNode, nodeList) {

        for (let i = 0; i < 3; i++) {
            this.showFirework(pos, parentNode, nodeList, 200, 200, 25);
            await asyncDelay(0.1);
        }
    }

    showFirework(pos, parentNode, nodeList, width = 200, height = 500, number = 30) {
        for (let i = 0; i < number; i++) {
            const quad = this.createQuads(pos, parentNode, nodeList);
            const targetX = RandomInt(width / 2, -width / 2);
            const targetY = RandomInt(height);

            cc.tween(quad)
                .by(0.5, { x: targetX })
                .by(3, { x: targetX * 2 })
                .start();

            cc.tween(quad)
                .by(0.5, { y: targetY }, { easing: 'quadOut' })
                .to(4, { y: -parentNode.height * 2 }, { easing: 'quadIn' })
                .removeSelf()
                .start();

            cc.tween(quad)
                .delay(1)
                .to(0.5 + 1 * Math.random(), { opacity: 0 })
                .start();
        }
    }

    createQuads(pos, parentNode, nodeList) {
        const quadBase = cc.instantiate(nodeList[RandomInt(nodeList.length)]);
        // console.log('nodeList', nodeList);
        // console.log('quadBase', quadBase);
        quadBase.x = pos.x;
        quadBase.y = pos.y + 30;
        quadBase.z = pos.z;
        quadBase.angle = RandomInt(180);
        quadBase.parent = parentNode;

        const quad = quadBase.getChildByName('quad');
        quad.x = 0;
        quad.y = 0;
        quad.angle = RandomInt(180);

        const paper = quad.getChildByName('paper');
        paper.scaleX = Math.random() * 0.8 + 0.2;
        paper.scaleY = Math.random() * 0.8 + 0.2;

        quadBase.scaleX = Math.random();
        cc.tween(quadBase)
            .to((1 - quadBase.scaleX) * 0.3, { scaleX: 1 })
            .call(() => {
                const time = Math.random() * 0.2;
                cc.tween(quadBase)
                    .to(0.1 + time, { scaleX: -1 })
                    .to(0.1 + time, { scaleX: 1 })
                    .union()
                    .repeatForever()
                    .start();
            })
            .start();


        return quadBase;
    }



}


