import { asyncDelay, onHomeworkFinish, RandomInt } from "../script/util_hy02_paopao";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_hy02_paopao";
import Game, { FISH_OUT, GAME_STATE, Option } from "./tool/Game_hy02_paopao";
import pg from "./tool/pg_hy02_paopao";

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;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
        this._imageResList.push(...this.data.questions.map(question => {
            return { url: question.image };
        }));
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
        this._audioResList.push({ url: this.data.questionTextAudio });
        this._audioResList.push({ url: this.data.bgAudio });
        this._audioResList.push(...this.data.questions.map(question => {
            return { url: question.audio };
        }));
    }

    addPreloadAnima() {

    }

    onLoadEnd() {
        cc.macro.ENABLE_MULTI_TOUCH = false;//禁用多指操作
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initEvent();
    }
    protected onDestroy(): void {
        pg.event.clear();
    }

    @property(cc.Node)
    layout_topic: cc.Node = null;
    @property(cc.Node)
    layout_option: cc.Node = null;
    @property(cc.Node)
    item: cc.Node = null;
    @property(cc.Node)
    item2: cc.Node = null;
    @property(cc.Node)
    layer_back: cc.Node = null;
    @property(cc.Node)
    layer_right: cc.Node = null;



    initData() {
        Game.getIns().init(this.data);
        Game.getIns().reset();
        // 所有全局变量 默认都是null 
        this.touch = false;
    }
    private audioId: any;
    private touch: boolean;
    async initView() {
        cc.audioEngine.stopAllEffects();
        this.gameStart(false);
    }
    initEvent() {

        pg.event.on("game_start", () => {
            this.gameStart();
        });
        pg.event.on("game_time_over", () => {
            this.checkRoundEnd();
        });
        pg.event.on("mouse_06_num_game_end", () => {
            // if (Game.getIns().dispelCount <= 0) {
            //     // pg.event.emit("check_next_question");
            //     this.checkRoundEnd();
            // }
        });

    }
    private resetGame() {
        cc.audioEngine.stopAllEffects();
        this.playLocalAudio("again");
        this.initData();
        pg.event.emit("mouse_06_num", Game.getIns().getRightNum());
        this.gameStart();
    }



    private gameOver() {
        Game.getIns().state = GAME_STATE.OVER;
        let data: any = {};
        data.total = Game.getIns().total;
        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)
    }

    gameStart(showBack = true) {
        this.count = 0;
        this.showQuestion();
    }


    private topic = 220;
    private option = -280;

    private showQuestion(show = true) {
        this.touch = false;
        Game.getIns().state = GAME_STATE.RUNNING;
        let question = Game.getIns().getCurrentPage();

        this.playLocalAudio("show");

        this.layout_topic.removeAllChildren();
        this.layout_topic.y = 600;
        let top = cc.instantiate(this.item2);
        if (question.type == "img") {
            let img = cc.find("img", top);
            pg.view.setNetImg(img, question.image, { w: 550, h: 400 });
        } else {
            let desc = cc.find("desc", top);
            desc.getComponent(cc.Label).string = "" + question.text;
        }
        let img_voice = cc.find("img_voice", top);
        if (question.audio == "") {
            img_voice.active = false;
        } else {
            img_voice.active = true;
        }


        top.active = true;
        top.parent = this.layout_topic;
        this.layout_option.removeAllChildren();
        this.layout_option.y = -600;
        question.optionList.forEach((dt) => {
            let item = cc.instantiate(this.item);
            let desc = cc.find("desc", item);
            desc.getComponent(cc.Label).string = "" + dt.txt;
            item.data = dt;
            item.on(cc.Node.EventType.TOUCH_END, this.onItem, this);
            item.active = true;
            item.parent = this.layout_option;
        })

        cc.tween(this.layout_topic).to(0.5, { y: this.topic }).start();
        cc.tween(this.layout_option).to(0.5, { y: this.option }).call(() => { this.touch = true; }).start();

        // pg.event.emit("npc_voice_play_voice_start");
        pg.event.emit("img_voice_play_voice_start");
        pg.audio.playAudioByUrl(question.audio).then(() => {
            // pg.event.emit("npc_voice_play_voice_end");
            pg.event.emit("img_voice_play_voice_end");
        })


    }

    private onItem(e) {
        if (!this.touch) return;
        this.touch = false;
        let target = e.target;
        let data = target.data;
        if (!data.right) {
            this.playLocalAudio("error");
            cc.tween(target).to(0.1, { angle: 10 }).to(0.1, { angle: 0 }).to(0.1, { angle: -10 })
                .to(0.1, { angle: 10 }).to(0.1, { angle: 0 }).to(0.1, { angle: -10 }).to(0.1, { angle: 0 })
                .call(() => {
                    this.touch = true;
                })
                .start();
            return;
        }
        this.playLocalAudio("right");
        let bg = cc.find("pp", target);
        let pp = cc.find("pp2", target);
        bg.active = false;
        pp.active = true;

        cc.tween(pp).to(0.7, { opacity: 0 }).start();

        this.checkRoundEnd();


    }

    //根据两点获取距离
    private getDistance(p1, p2) {
        let temp = p1.sub(p2);
        let dis = Math.abs(temp.mag());
        return dis;
    }
    private getDistances(p1, p2) {
        //转换世界坐标查看距离
        let ps2 = p2.convertToWorldSpaceAR(cc.v2(0, 0));
        let ps1 = p1.convertToWorldSpaceAR(cc.v2(0, 0));
        let temp = ps1.sub(ps2);
        let dis = Math.abs(temp.mag());
        return dis;
    }
    private count: number;
    update(dt) {

    }







    //根据两点获取角度
    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) || 0;//角度计算方法
    }
    private checkRoundEnd() {
        Game.getIns().addPage();
        if (!Game.getIns().getCurrentPage()) {
            pg.time.delayCall(1.2, () => {
                this.layer_right.active = true;
                pg.event.emit("layer_right_show_excellent");
                this.gameOver();
            });
        } else {
            this.playLocalAudio("next").then(() => {
                this.showQuestion();
            });
        }
    }



    playLocalAudio(audioName, cb = null) {
        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);
            });
        })
    }

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



