import { asyncDelay, onHomeworkFinish, RandomInt } from "../script/util_TXZS_G_005";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_TXZS_G_005";
import Game, { FISH_OUT, GAME_STATE, Option } from "./tool/Game_TXZS_G_005";
import pg from "./tool/pg_TXZS_G_005";
import CardItem from "./CardItem_TXZS_G_005";

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(...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();
        // this.startTime();
        // this.updateTop();
    }
    protected onDestroy(): void {
        cc.Tween.stopAll();
        pg.event.clear();
    }

    @property(cc.Node)
    layout_game: cc.Node = null;
    @property(cc.Node)
    card_item: cc.Node = null;
    @property(cc.Node)
    card_up: cc.Node = null;
    @property(cc.Node)
    card_down: cc.Node = null;
    @property(cc.Node)
    label_time: cc.Node = null;
    @property(cc.Node)
    layout_final: cc.Node = null;

    private tryData: Array<Option>;
    private timeSecond;
    private assessCount;
    initData() {
        Game.getIns().init(this.data);
        Game.getIns().reset();
        this.tryData = [];
        // 所有全局变量 默认都是null 
        this.startSecond = false;
        this.timeSecond = 0;
        this.assessCount = 0;
    }
    private layout_start: cc.Node;
    private audioId: any;

    async initView() {
        cc.audioEngine.stopAllEffects();
        this.layout_start = pg.view.find(this, "layout_start");

        this.layout_start.active = true;

        if (Game.getIns().title) {
            cc.find("layout_info/label_title", this.node).getComponent(cc.Label).string = Game.getIns().title;
        }
    }
    initEvent() {
        // this.btn_laba.on(cc.Node.EventType.TOUCH_END, this.playLaba, this);
        // this.btn_record.on(cc.Node.EventType.TOUCH_END, this.onTouchRecord, this);
        // this.btn_recording.on(cc.Node.EventType.TOUCH_END, this.onTouchRecordEnd, this);
        cc.find("layout_info/btn_return", this.node).on(cc.Node.EventType.TOUCH_END, this.exitGame, this);
        cc.find("btn_close", this.layout_final).on(cc.Node.EventType.TOUCH_END, this.onCloseFinal, this);
        cc.find("btn_restart", this.layout_final).on(cc.Node.EventType.TOUCH_END, this.onRestart, this);
        pg.event.on("game_start", () => {
            this.gameStart();
        });
        pg.event.on("check_next_question", () => {
            this.checkRoundEnd();
        });
    }
    private exitGame() {
        const middleLayer = cc.find('middleLayer')?.getComponent('middleLayer');
        if (middleLayer) {
            // 有些模板需要在返回时上报数据，直接把数据作为参数传入就可以了
            middleLayer.exitGame(null);//this.resData
        } else {
            console.log("==触发返回事件==");
        }
    }
    private onRestart() {
        this.playLocalAudio("btn");
        this.layout_final.active = false;
        this.label_time.getComponent(cc.Label).string = "00:00";
        pg.event.clear();
        this.onLoadEnd();
    }
    private onCloseFinal() {
        this.playLocalAudio("btn");
        this.layout_final.active = false;
    }


    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() {
        Game.getIns().state = GAME_STATE.RUNNING;
        this.startSecond = true;
        this.layout_start.active = false;
        this.showQuestion();
        this.updateTop();
    }
    private showQuestion() {
        let question = Game.getIns().getCurrentPage();
        this.card_down.removeAllChildren();
        this.card_up.removeAllChildren();
        if (!question || !question.optionList) return;
        question.optionList.forEach((item, idx) => {
            let card = cc.instantiate(this.card_item);
            let layout = idx < question.optionList.length / 2 ? this.card_up : this.card_down;
            card.active = true;
            card.getComponent(CardItem).showCard(item);
            layout.addChild(card);
        });
        this.card_down.getComponent(cc.Layout).spacingX = this.card_down.children.length == 4 ? 120 : 200;
        this.card_up.getComponent(cc.Layout).spacingX = this.card_down.children.length == 4 ? 120 : 200;
        this.card_down.getComponent(cc.Layout).updateLayout();
        this.card_up.getComponent(cc.Layout).updateLayout();
        Game.getIns().dispelCount = question.optionList.length;
        this.scheduleOnce(() => {
            this.card_down.children.forEach((ch) => {
                pg.event.emit("card_back", ch.getComponent(CardItem).data.id);
            });
            this.card_up.children.forEach((ch) => {
                pg.event.emit("card_back", ch.getComponent(CardItem).data.id);
            })
            Game.getIns().isCanClick = true;
        }, 2)

    }

    private checkRoundEnd() {
        Game.getIns().addPage();
        if (!Game.getIns().getCurrentPage()) {
            this.showFind();
        } else {
            this.playLocalAudio("next").then(() => {
                Game.getIns().isCanClick = false;
                // this.startTime();
                this.gameStart();
            });
        }

    }


    // private nextstar(isRight = true) {
    //     this.starData = Game.getIns().getCurrentPage();
    //     if (this.starData) {
    //         this.star_node.active = true;
    //         this.gameStart(isRight)
    //     } else {
    //         this.startSecond = false;
    //         this.gameOver();
    //         this.showFind();
    //     }
    // }


    private updateTop() {
        let round = cc.find("layout_info/bg_number/round", this.node);
        round.getComponent(cc.Label).string = `${Game.getIns().getCurrentPage().page}/${Game.getIns().total}`;
    }
    private startSecond: boolean;

    update(dt) {
        if (Game.getIns().state != GAME_STATE.RUNNING) return;
        if (!this.startSecond) return;
        this.timeSecond = this.timeSecond + dt;
        let count = Math.ceil(this.timeSecond);
        let str = this.formatSeconds(count);
        this.label_time.getComponent(cc.Label).string = str;
    }
    private formatSeconds(value) {
        var secondTime = parseInt(value);// 秒
        var minuteTime = 0;// 分
        var hourTime = 0;// 小时
        if (secondTime > 59) {//如果秒数大于60，将秒数转换成整数
            //获取分钟，除以60取整数，得到整数分钟
            minuteTime = Math.floor(secondTime / 60);
            //获取秒数，秒数取佘，得到整数秒数
            secondTime = Math.floor(secondTime % 60);
            //如果分钟大于60，将分钟转换成小时
            // if (minuteTime > 60) {
            //     //获取小时，获取分钟除以60，得到整数小时
            //     hourTime = minuteTime / 60;
            //     //获取小时后取佘的分，获取分钟除以60取佘的分
            //     minuteTime = minuteTime % 60;
            // }
        }
        var result = (secondTime < 10 ? "0" + secondTime : secondTime) + "";

        if (minuteTime > 0) {
            result = "" + (minuteTime < 10 ? "0" + minuteTime : minuteTime) + ":" + result;
        } else {
            result = "00:" + result
        }
        // if (hourTime > 0) {
        //     result = "" + hourTime + "小时" + result;
        // }
        return result;
    }


    private async startTime() {
        this.layout_start.active = true;
        for (let i = 3; i >= 0; i--) {
            let target = cc.find("layout_start/text_" + i, this.node);
            if (i == 0) this.playLocalAudio("go")
            else this.playLocalAudio("count")
            await this.startTextAction(target);
        }
        this.gameStart();
    }
    private startTextAction(target) {
        return new Promise((resolve, reject) => {
            target.scale = 1;
            target.active = true;
            target.opacity = 255;
            cc.tween(target).to(1, { scale: 0.5, opacity: 0 }).call(() => { target.active = false; return resolve("") }).start();
        })
    }
    private showFind() {
        this.playLocalAudio("wancheng");
        this.startSecond = false;
        this.layout_final.scale = 0.3;
        this.layout_final.active = true;
        let count = cc.find("count", this.layout_final);
        let time = cc.find("time", this.layout_final);
        time.getComponent(cc.Label).string = this.formatSeconds(this.timeSecond);
        count.getComponent(cc.Label).string = "" + Game.getIns().failCount;
        cc.tween(this.layout_final).to(0.3, { scale: 1 }).start();
    }





    // 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;
    //     cc.audioEngine.stopAllEffects();
    //     let count = 0;
    //     if (this.intervalId) clearInterval(this.intervalId);
    //     let stop = false;
    //     this.intervalId = setInterval(() => {
    //         count++;
    //         btn_kaba3.active = count % 3 == 2;
    //         if (stop && count % 3 == 2) {
    //             clearInterval(this.intervalId);
    //             btn_kaba2.active = false;
    //             btn_kaba3.active = false;
    //         }
    //     }, 150)

    //     pg.audio.playAudioByUrl(this.starData.audioUrl, (() => {
    //         stop = true;
    //     }))
    // }



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



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


