import { asyncDelay, onHomeworkFinish, RandomInt } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import Game, { GAME_STATE, Option, Question } from "./tool/dg10Game";
import pg from "./tool/pgdg10";

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() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initEvent();
        this.startTime();
        this.updateTop();
    }
    protected onDestroy(): void {
        pg.event.clear();
    }

    @property(cc.Node)
    layout_game: cc.Node = null;
    @property(cc.Node)
    layout_tip: cc.Node = null;
    @property(cc.Node)
    btn_laba: cc.Node = null;
    @property(cc.Node)
    btn_record: cc.Node = null;
    @property(cc.Node)
    btn_recording: cc.Node = null;
    @property(cc.Node)
    label_time: cc.Node = null;
    @property(cc.Node)
    layout_final: cc.Node = null;

    private starData: Question;
    private tryData: Array<Question>;
    private countDown: number = 999999;
    private timeCount: number;
    private startCount = 15;
    private timeSecond;
    private assessCount;
    initData() {
        Game.getIns().init(this.data);
        Game.getIns().reset();
        this.tryData = [];
        this.timers = []
        this.starData = null;
        // 所有全局变量 默认都是null 
        this.starData = Game.getIns().getCurrentPage();
        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);
        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();
        });
    }
    private onRestart() {
        this.playLocalAudio("btn");
        this.layout_final.active = false;
        this.label_time.getComponent(cc.Label).string = "00:00";
        let layout_play = this.layout_game.getChildByName('layout_play')
        layout_play.removeAllChildren();
        this.onLoadEnd();
    }
    private onCloseFinal() {
        this.playLocalAudio("btn");
        this.layout_final.active = false;
    }
    private pendantMove() {
        let could = cc.find("bg/could", this.node);
        let seabed = cc.find("bg/seabed", this.node);
        cc.tween(seabed).by(1.5, { x: -150 }).start();
        cc.tween(could).by(1.5, { x: -150 }).start();
    }
    private intervalId;
    private stopLaba() {
        cc.audioEngine.stopAllEffects();
        if (this.intervalId) clearInterval(this.intervalId);
        let btn_kaba2 = this.btn_laba.getChildByName("btn_laba2");
        btn_kaba2.active = false;
    }
    private playLaba() {
        let btn_kaba2 = this.btn_laba.getChildByName("btn_laba2");
        btn_kaba2.active = true;
        cc.audioEngine.stopAllEffects();
        let count = 0;
        if (this.intervalId) clearInterval(this.intervalId);
        let stop = false;
        this.intervalId = setInterval(() => {
            count++;
            btn_kaba2.active = count % 2 == 0;
            if (stop && count % 2 == 1) {
                clearInterval(this.intervalId);
                btn_kaba2.active = false;
            } else {

            }
        }, 150)

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

    private gameOver() {
        Game.getIns().state = GAME_STATE.OVER;
        let data: any = {};
        data.total = Game.getIns().total;
        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.playLaba();
        this.updateTop();
        this.bubbleCreate();
    }
    private bubbleCreate() {
        let layout_play = this.layout_game.getChildByName('layout_play')
        layout_play.removeAllChildren();
        let layout_pop = this.layout_game.getChildByName('layout_pop')
        let btn_fish = this.layout_game.getChildByName('btn_fish')
        let item = this.layout_game.getChildByName('item')

        let list = this.starData.options;
        for (let i = 0; i < 10; i++) {
            list.sort(() => Math.random() < 0.5 ? 1 : -1)
        }
        let startPos = pg.view.coverPosition(btn_fish, layout_play)
        let layouts = layout_pop.getChildByName("layout_" + list.length)
        list.forEach((li, index) => {
            let targetPos = pg.view.coverPosition(layouts.children[index], layout_play);
            // 获取设置item位置
            let it = cc.instantiate(item)
            it.active = true;
            it.opacity = 0;
            it.scale = 0.2;
            layout_play.addChild(it)
            it.x = startPos.x;
            it.y = startPos.y;
            this.updateItem(it, li)
            cc.tween(it)
                .delay(index * 0.2)
                .call(() => {
                    this.playLocalAudio('fish_bubble')
                })
                .to(0.3, { x: targetPos.x, y: targetPos.y, scale: 1, opacity: 255 })
                .start()
        })
    }
    updateItem(item, data: Option) {
        item.data = data;
        let btn_poper = pg.view.find(item, "btn_poper")
        let btn_poper_break = pg.view.find(item, "btn_poper_break")
        let title = pg.view.find(item, "title")
        let img = pg.view.find(item, "img")
        let img_single = pg.view.find(item, "img_single")
        let desc = pg.view.find(item, "desc")

        switch (data.type) {
            case "text":
                pg.view.setString(title, data.text)
                pg.view.visible(title, true)
                pg.view.visible(img, false)
                pg.view.visible(img_single, false)
                pg.view.visible(desc, false)
                break;
            case "img":
                pg.view.setNetImg(img_single, data.image, { w: 280, h: 280 })
                pg.view.visible(title, false)
                pg.view.visible(img, false)
                pg.view.visible(img_single, true)
                pg.view.visible(desc, false)
                break;
            case "img_text":
                pg.view.setNetImg(img, data.image, { w: 280, h: 200 })
                pg.view.setString(desc, data.text)
                pg.view.visible(title, false)
                pg.view.visible(img_single, false)
                pg.view.visible(img, true)
                pg.view.visible(desc, true)
                break;
            default:
                break;
        }
        pg.view.visible(btn_poper, true);
        pg.view.visible(btn_poper_break, false);
        pg.view.touchOn(item, this.onTouchItem, this);
    }
    private touching: boolean;
    private timers: Array<any>;
    onTouchItem(e) {
        if (this.touching) return;
        this.touching = true;
        let item = e.target;
        let data = item.data;
        if (this.starData.inRight(data)) {
            this.touching = false;
            return;
        }
        this.scheduleOnce(() => {
            this.touching = false;
        }, 0.6)
        this.assessCount++;
        this.stopLaba();
        if (data.right) {
            let btn_poper = pg.view.find(item, "btn_poper")
            let btn_poper_break = pg.view.find(item, "btn_poper_break")
            pg.view.visible(btn_poper, false);
            pg.view.visible(btn_poper_break, true);
            this.starData.addRight(data);
            this.playLocalAudio('fish_right')
            if (this.starData.checkRight()) {
                this.scheduleOnce(() => {
                    this.nextstar();
                }, 0.8)
            }
        } else {
            this.playLocalAudio('fish_error')
            cc.tween(item).by(0.1, { x: -10 }).by(0.1, { x: 10 }).by(0.1, { x: 10 }).by(0.1, { x: -10 }).start();
        }
    }

    private updateTips(state?: TIPS_STATE) {
        if (!state) {
            this.layout_tip.active = false;
            return;
        }
        this.layout_tip.active = true;
        let img_co = pg.view.find(this.layout_tip, 'img_co');
        let img_gj = pg.view.find(this.layout_tip, 'img_gj');
        let img_ta = pg.view.find(this.layout_tip, 'img_ta');
        img_co.active = false;
        img_gj.active = false;
        img_ta.active = false;
        let img = null;
        switch (state) {
            case TIPS_STATE.COM:
                img = img_co;
                // this.playLocalAudio("co");
                break;
            case TIPS_STATE.GOOD:
                img = img_gj;
                this.playLocalAudio("excellent");

                break;
            case TIPS_STATE.TRY:
                img = img_ta;
                this.playLocalAudio("tryagain");
                break;
        }
        img.scale = 1;
        img.active = true;
        // cc.tween(img).to(0.5, { scale: 1 }).delay(2).call(() => {
        //     this.layout_tip.active = false;
        // }).start();
    }


    private nextstar() {
        Game.getIns().addPage();
        this.starData = Game.getIns().getCurrentPage();
        if (this.starData) {
            this.playLocalAudio('fish_next')
            this.gameStart()
        } else {
            this.startSecond = false;
            this.gameOver();
            this.showFinal();
        }
    }

    private checkWords(data) {
        const sentences = data.result.sentences;
        for (let i = 0; i < sentences.length; i++) {
            const details = sentences[i].details;
            const isSuccess = details.some(item => item.overall <= 40);
            if (isSuccess) {
                return false;
            }
        }
        return true;
    }





    private updateTop() {
        let round = cc.find("layout_info/bg_number/round", this.node);
        round.getComponent(cc.Label).string = `${this.starData.id}/${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() {
        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 showFinal() {
        this.playLocalAudio('wancheng')
        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 = "" + this.assessCount;
        cc.tween(this.layout_final).to(0.3, { scale: 1 }).start();
    }







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


