import { asyncDelay, onHomeworkFinish, RandomInt } from "../script/util_sn04_classify";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_sn04_classify";
import Game, { FISH_OUT, GAME_STATE, Option } from "./tool/Game_sn04_classify";
import pg from "./tool/pg_sn04_classify";

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

    @property(cc.Node)
    layout_game: cc.Node = null;
    @property(cc.Node)
    layout_box: cc.Node = null;
    @property(cc.Node)
    layout_card: cc.Node = null;
    @property(cc.Node)
    label_time: cc.Node = null;
    @property(cc.Node)
    card_box: cc.Node = null;
    @property(cc.Node)
    card_boximg: cc.Node = null;
    @property(cc.Node)
    card_img: cc.Node = null;
    @property(cc.Node)
    card_txt: 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;
        this.gameCount = Game.getIns().time;
    }
    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 async showQuestion() {


        this.layout_card.getComponent(cc.Layout).enabled = true;

        this.wordItams = [];
        this.layout_box.removeAllChildren();
        this.layout_card.removeAllChildren();

        let ques = Game.getIns().getList();
        ques.forEach((q) => {
            if (q.type == "img") {
                let itemBox = cc.instantiate(this.card_boximg);
                itemBox.parent = this.layout_box;
                pg.view.setNetImg(cc.find("img", itemBox), q.image, { w: 190, h: 140 });
                itemBox.data = q;
                this.wordItams.push(itemBox);
            } else {
                let itemBox = cc.instantiate(this.card_box);
                itemBox.parent = this.layout_box;
                cc.find("desc", itemBox).getComponent(cc.Label).string = q.text;
                itemBox.data = q;
                this.wordItams.push(itemBox);
            }
        });
        let qe = Game.getIns().getCardInfo();
        qe.forEach((op) => {
            let card = op.type == "img" ? cc.instantiate(this.card_img) : cc.instantiate(this.card_txt);
            if (op.type == "img") {
                let img = cc.find("img", card);
                pg.view.setNetImg(img, op.picUrl, { w: 250, h: 190 });
            } else {
                let desc = cc.find("desc", card);
                desc.getComponent(cc.Label).string = op.txt;
            }
            card.parent = this.layout_card;

            card.data = op;

            card.off(cc.Node.EventType.TOUCH_START, this.onItemTouchStart, this);
            card.off(cc.Node.EventType.TOUCH_MOVE, this.onItemTouchMove, this);
            card.off(cc.Node.EventType.TOUCH_END, this.onItemTouchEnd, this);

            card.on(cc.Node.EventType.TOUCH_START, this.onItemTouchStart, this);
            card.on(cc.Node.EventType.TOUCH_MOVE, this.onItemTouchMove, this);
            card.on(cc.Node.EventType.TOUCH_END, this.onItemTouchEnd, this);

        })
        this.layout_box.getComponent(cc.Layout).spacingX = ques.length >= 4 ? 90 : 200;
        await pg.time.asyncDelay(0.1);
        this.layout_card.getComponent(cc.Layout).enabled = false;
        this.layout_card.children.forEach((card) => {
            let data = card.data;
            data.x = card.x;
            data.y = card.y;
        })

    }

    onItemTouchStart(e) {
        if (this.isFinish) return;
        this.playLocalAudio("click");
        // if (this.checkRoundOver()) return;
        let target: cc.Node = e.target;
        let data = target.data;
        //已经成功的方块要拒绝掉
        // if (this.checkSuccess(target, data)) return;
        target.parent = this.node;
        // target.setPosition(AP);
        this.setTouchPos(e);
    }
    onItemTouchMove(e) {
        if (this.isFinish) return;
        // if (this.checkRoundOver()) return;
        let target: cc.Node = e.target;
        let data = target.data;
        //已经成功的方块要拒绝掉
        this.setTouchPos(e);
    }
    onItemTouchEnd(e) {
        if (this.isFinish) return;
        cc.audioEngine.stopAllEffects()
        // if (this.checkRoundOver()) return;
        let target: cc.Node = e.target;
        let data = target.data;
        let itemBg = this.wordItams.find((bg) => {
            // let dis = this.getDistances(target.getPosition(), bg.getPosition());
            let dis = this.getDistances(target, bg);
            // if (dis < 100 && bg.sortId == data.id) {
            if (dis < bg.width / 2 + 20) {
                return bg;
            }
            return null;
        })

        if (!itemBg) {
            target.parent = this.layout_card;
            target.x = data.x;
            target.y = data.y;
            return;
        }
        if (itemBg.data.page != data.page) {
            this.playLocalAudio("error");
            let img_pro = cc.find("img_pro", target);
            img_pro.active = true;
            cc.tween(target).to(0.2, { angle: 15 }).to(0.2, { angle: -15 }).to(0.2, { angle: 15 }).to(0.2, { angle: -15 }).to(0.2, { angle: 0 }).to(0.2, { x: data.x, y: data.y }).call(() => {
                target.parent = this.layout_card;
                img_pro.active = false;
            }).start();
            return;
        }

        let bg_bar_font = cc.find("bg_bar_font", itemBg);
        let bg_bar_img = cc.find("bg_bar_img", itemBg);
        bg_bar_img.active = true;
        bg_bar_font.active = false;

        let ice_img = cc.find("ice_img", target);
        let ice_melt = cc.find("ice_melt", target);
        let img_dian = cc.find("img_dian", target);
        ice_img.active = false;
        ice_melt.active = true;
        img_dian.active = true;

        target.off(cc.Node.EventType.TOUCH_START, this.onItemTouchStart, this);
        target.off(cc.Node.EventType.TOUCH_MOVE, this.onItemTouchMove, this);
        target.off(cc.Node.EventType.TOUCH_END, this.onItemTouchEnd, this);

        this.playLocalAudio("right");
        cc.tween(target).delay(1.5).to(0.2, { opacity: 0 }).call(() => {
            target.parent = null;
            target.destroy();
            bg_bar_font.active = true;
            bg_bar_img.active = false;
            if (this.layout_card.children.length <= 0) {
                this.rundEnd();
            }
        }).start();


        // let bg_box = cc.find("bg_box", itemBg);
        // let pos = this.getBoxPos(bg_box.children.length);
        // target.parent = bg_box;
        // target.x = pos.x;
        // target.y = pos.y;
        // target.angle = pos.angle;
        // this.playLocalAudio("right");
        // pg.event.emit("mouse_08_add");
    }

    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 getChipPos(zIndex) {
        for (let i = 0; i < this.chipPos.length; i++) {
            let chip = this.chipPos[i];
            if (chip.zIndex == zIndex) {
                return chip;
            }
        }
        return null;
    }
    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 checkOver() {
        let count = 0;
        this.layout_box.children.forEach((box) => {
            let bg_box = cc.find("bg_box", box);
            count += bg_box.children.length;
        })
        return count >= Game.getIns().getCardInfo().length;
    }

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

    }

    private rightCount: number;
    private errorCount: number;
    private totalCount: number;

    addRightCount() {
        if (!this.rightCount) this.rightCount = 0;
        this.rightCount++;
    }
    addErrorCount() {
        if (!this.errorCount) this.errorCount = 0;
        this.errorCount++;
    }
    setTotalCount(val) {
        this.totalCount = val;
    }
    sendData() {
        return new Promise(res => {
            if (!this.totalCount) this.totalCount = this.rightCount + this.errorCount;
            if (!this.totalCount) console.error('未设置总计数');
            if (this.totalCount && !this.rightCount && !this.errorCount) {
                this.rightCount = this.totalCount;
                this.errorCount = 0;
            }
            let upData: any = {
                right_count: this.rightCount || 0,
                wrong_count: this.errorCount || 0,
                total_count: this.totalCount || 0,
            };
            upData.score = upData.right_count || 0;
            let recordList = pg.hw.getRecord();
            if (recordList && recordList.length > 0) {
                upData.result = recordList
            }
            console.log('upload->' + JSON.stringify(upData))
            if (!cc.find('middleLayer')) return;
            const middleLayer = cc.find('middleLayer').getComponent('middleLayer');
            middleLayer.onHomeworkFinish(upData, () => {
                res('');
            })
        })
    }

    gameOver() {
        this.setTotalCount(Game.getIns().len);
        this.sendData().then(() => {
            if (!cc.find('middleLayer')) return;
            const middleLayer = cc.find('middleLayer');
            if (middleLayer) {
                const middleLayerComponent = middleLayer.getComponent('middleLayer');
                middleLayerComponent.goNextPage();
                return;
            } else {
                console.log("[onFinish] middleLayer not found")
            }
        })
    }
    private rundEnd() {
        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.gameOver();
        this.log("over~~~~~")
    }



    private gameCount;
    private playCount = true;
    update(dt) {
        if (Game.getIns().state != GAME_STATE.RUNNING) return;
        if (!this.gameCount || this.gameCount <= 0) {
            this.isFinish = true;
            this.rundEnd();
            return;
        }
        if (this.gameCount < 3 && this.playCount) {
            this.playCount = false;
            this.playLocalAudio("count").then(() => {
                this.playCount = true;
            });
        }
        this.gameCount = this.gameCount - dt;
        let count = Math.ceil(this.gameCount);
        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;
    }

    playLocalAudio(audioName) {
        let noStop = audioName == "count";
        // if (!noStop) this.stopBgmAdudio();
        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);
                // if (!noStop) this.resumeBgmMusic(); 
            });
        })
    }
    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;
    }
}



