import { asyncDelay, onHomeworkFinish, RandomInt } from "../script/util_sn02_playAudio";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_sn02_playAudio";
import Game, { FISH_OUT, GAME_STATE, Option } from "./tool/Game_sn02_playAudio";
import pg from "./tool/pg_sn02_playAudio";

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

    @property(cc.Node)
    layout_game: cc.Node = null;
    @property(cc.Node)
    layout_sc: cc.Node = null;
    @property(cc.Node)
    pro_time: cc.Node = null;
    @property(cc.Node)
    card: cc.Node = null;
    @property(cc.Node)
    bg_img: cc.Node = null;
    @property(cc.Node)
    btn_playall: cc.Node = null;
    @property(cc.Node)
    label_title: cc.Node = null;
    @property(cc.Node)
    label_t2: cc.Node = null;

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

    }
    initEvent() {
        pg.event.on("game_start", () => {
            this.gameStart();
        });
        pg.event.on("check_next_question", () => {
            // this.checkClickEnd();
        });
    }


    private intervalId;
    private playLaba() {

        // this.btn_laba.active = false;
        // this.play_laba.active = true;
        // let btn_laba1 = this.play_laba.getChildByName("btn_laba1");
        // let btn_kaba2 = this.play_laba.getChildByName("btn_laba2");
        // let btn_kaba3 = this.play_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;
        //         this.btn_laba.active = true;
        //         this.play_laba.active = false;
        //     }
        // }, 150)
        // pg.audio.playAudioByUrl(Game.getIns().getCurrentPage().audioUrl, (() => {
        //     stop = true;
        // }))
    }



    gameStart() {
        Game.getIns().state = GAME_STATE.RUNNING;
        this.showQuestion();
        this.playLaba();
    }
    private wordItams: cc.Node[];
    private chipPos = [];
    private showQuestion() {

        let op = Game.getIns().getCurrentPage().optionList;
        op.forEach((dt, idx) => {
            let item = cc.instantiate(this.card);
            this.initItem(item, dt, idx);
            item.data = dt;
            item.parent = this.layout_sc;
        })
        this.showLeft();
        this.btn_playall.on(cc.Node.EventType.TOUCH_END, this.onPlayAll, this);
        cc.find("label_len", this.btn_playall).getComponent(cc.Label).string = "(" + op.length + ")";
        cc.find("scrollView", this.layout_game).on("scroll-began", () => {
            this.playLocalAudio("gun");
        })
    }
    private playAll = false;
    private onPlayAll() {
        this.playAll = true;
        if (this.isPlayAudio) return;
        this.autoPlayAudio();
    }
    private autoPlayAudio() {
        let op = Game.getIns().getCurrentPage().optionList[this.itemIdx];
        if (!op) return;
        pg.audio.playAudioByUrl(Game.getIns().getCurrentPage().optionList[this.itemIdx].audioUrl, (id) => {
            this.itemAudioId = id;
            this.updateTime();
        }).then(() => {
            if (this.playAll) {
                this.itemIdx++;
                this.autoPlayAudio();
            }
        });
        this.showLeft();
        this.updateItems();
    }
    private itemAudioId;
    private itemIdx = 0;
    private initItem(item, data, idx) {
        let btn_play = cc.find("btn_play", item);
        let btn_stop = cc.find("btn_stop", item);
        let num_normal = cc.find("num_normal", item);
        let desc_normal = cc.find("desc_normal", item);
        let num = cc.find("num", item);
        let desc = cc.find("desc", item);

        num_normal.getComponent(cc.Label).string = "" + (idx + 1);
        num.getComponent(cc.Label).string = "" + (idx + 1);

        desc_normal.getComponent(cc.Label).string = data.text;
        desc.getComponent(cc.Label).string = data.text;

        btn_play.on(cc.Node.EventType.TOUCH_END, () => {
            btn_stop.active = true;
            btn_play.active = false;
            if (this.itemAudioId) cc.audioEngine.stopEffect(this.itemAudioId);
            let progress = cc.find("progress", this.pro_time).getComponent(cc.Sprite);
            cc.Tween.stopAllByTarget(progress);
        })
        btn_stop.on(cc.Node.EventType.TOUCH_END, () => {
            cc.audioEngine.stopAllEffects();
            btn_stop.active = false;
            btn_play.active = true;
            pg.audio.playAudioByUrl(data.audioUrl, (id) => {
                this.itemAudioId = id;
                this.updateTime();
            }).then(() => {
                btn_stop.active = true;
                btn_play.active = false;
                if (this.playAll) {
                    this.itemIdx++;
                    this.autoPlayAudio();
                }
            });
            this.itemIdx = idx;
            this.showLeft();
            this.updateItems();
        })

    }
    private updateItems() {
        this.layout_sc.children.forEach((item, idx) => {
            let btn_play = cc.find("btn_play", item);
            let btn_stop = cc.find("btn_stop", item);
            let num_normal = cc.find("num_normal", item);
            let desc_normal = cc.find("desc_normal", item);
            let num = cc.find("num", item);
            let desc = cc.find("desc", item);

            btn_play.active = this.itemIdx == idx;
            btn_stop.active = this.itemIdx != idx;
            num_normal.active = this.itemIdx != idx;
            desc_normal.active = this.itemIdx != idx;
            num.active = this.itemIdx == idx;
            desc.active = this.itemIdx == idx;
        })
    }

    private showLeft() {
        let data = Game.getIns().getCurrentPage().optionList[this.itemIdx];
        this.label_title.getComponent(cc.Label).string = data.text;
        this.label_t2.getComponent(cc.Label).string = data.desc;
        pg.view.setNetImg(this.bg_img, data.picUrl, { w: 305, h: 382 })
    }
    private itemDuration = 0;
    private updateTime() {
        let label_start = cc.find("label_start", this.pro_time);
        let label_end = cc.find("label_end", this.pro_time);
        let progress = cc.find("progress", this.pro_time).getComponent(cc.Sprite);
        this.itemDuration = cc.audioEngine.getDuration(this.itemAudioId);
        progress.fillRange = 0;
        cc.tween(progress).to(this.itemDuration, { fillRange: 1 }).start();
        label_start.getComponent(cc.Label).string = "00:00";
        label_end.getComponent(cc.Label).string = this.formatSeconds(this.itemDuration);
        this.startCount = 0;
        this.isPlayAudio = true;
    }
    private startCount = 0;
    private isPlayAudio = false;
    update(dt) {
        if (Game.getIns().state != GAME_STATE.RUNNING) return;
        if (this.startCount >= this.itemDuration || !this.isPlayAudio) {
            this.isPlayAudio = false;
            this.startCount = 0;
            return;
        }

        this.startCount = this.startCount + dt;
        let count = Math.floor(this.startCount);
        let str = this.formatSeconds(count);
        let label_start = cc.find("label_start", this.pro_time);
        label_start.getComponent(cc.Label).string = str;
    }

    private sendData(score) {
        return new Promise(res => {
            let upData: any = {
                word_count: this.data.word_count || 0,
                sentence_count: this.data.sentence_count || 0,
                zi_count: this.data.zi_count || 0,
                score: score,
            };
            let recordList = pg.hw.getRecord();
            if (recordList && recordList.length > 0) {
                upData.recordList = recordList
            }
            let mid = cc.find('middleLayer');
            if (!mid) return;
            const middleLayer = mid.getComponent('middleLayer');
            console.log('upload->' + JSON.stringify(upData))
            middleLayer.onHomeworkFinish(upData, () => {
                res('');
            })
        })
    }
    private gameOver() {
        Game.getIns().state = GAME_STATE.OVER;
        this.sendData(this.data.questions.length * 3).then(() => {
            let mid = cc.find('middleLayer');
            if (!mid) return;
            const middleLayer = mid.getComponent('middleLayer');
            middleLayer.saveGolds(this.data.questions.length * 3); // 保存金币数量; num 是获得金币的数量，数字类
            middleLayer.goNextPage(); //跳转到下一页
        })
        this.log("over~~~~~")
    }




















    private setTouchPos(e) {
        let location = e.getLocation();
        let size = cc.view.getCanvasSize();
        let scale = (size.width / size.height) / (1920 / 1080);
        if (scale > 1) {
            let width = size.width / size.height * 1080;
            let pos = location.sub(cc.v2(width / 2, 1080 / 2))
            e.target.setPosition(pos)
        } else {
            let height = size.height / size.width * 1920;
            let pos = location.sub(cc.v2(1920 / 2, height / 2))
            e.target.setPosition(pos)
        }
    }

    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 getBoxPos(idx) {
        let box1 = [{ x: 90, y: 88, angle: 65 }, { x: -95, y: 90, angle: 110 }, { x: 24, y: 120, angle: 80 }, { x: -40, y: 80, angle: 95 }]
        return box1[idx];
    }


    private checkRoundEnd() {
        Game.getIns().addPage();
        if (!Game.getIns().getCurrentPage()) {
            // this.gameOver();
        } else {
            this.playLocalAudio("next");
            this.gameStart();
        }

    }




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

    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 bgmId;
    playLocalBgmAudio(audioName = "bgm") {
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        return new Promise((resolve, reject) => {
            this.bgmId = cc.audioEngine.playMusic(audio.clip, true);
            cc.audioEngine.setFinishCallback(this.bgmId, () => { resolve(this.bgmId); });
        })
    }
    stopBgmAdudio() {
        cc.audioEngine.pauseMusic();
    }
    resumeBgmMusic() {
        cc.audioEngine.resumeMusic();
    }

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




