import { asyncDelay, onHomeworkFinish, playDragonBoneAnimation, RandomInt } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import Game, { FISH_OUT, GAME_STATE, Option } from "./tool/Game_op72_single";
import pg from "./tool/pg_op72_single";
import op72_ResultLayer from "./op72_single_ResultLayer";
import { NetworkHelper } from "./NetworkHelper_op72_single";
import op_72_plus_LoadingLayer from "../prefab/LoadingLayer/op72_single_LoadingLayer";
import { GameServer } from "./server_op72_single";

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() {

    }

    @property(cc.Node)
    loadingLayer: cc.Node = null;
    @property(cc.Node)
    dbCat: cc.Node = null;
    @property(cc.Node)
    item_1: cc.Node = null;
    @property(cc.Node)
    item_pic: cc.Node = null;
    @property(cc.Node)
    layout_word: cc.Node = null;
    @property(cc.Node)
    layout_box: cc.Node = null;
    @property(cc.Node)
    layout_game: cc.Node = null;

    onLoadEnd() {
        cc.macro.ENABLE_MULTI_TOUCH = false;//禁用多指操作
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考

        cc.audioEngine.stopAllEffects();
        // this.loadingLayer.active = true;
        // let loading = this.loadingLayer.getComponent(op_72_plus_LoadingLayer);
        // loading.setMaxPlayerNumber(5);
        // this.initNetworkListener();
        this.initData();
        // this.catPlayAni(Game.getIns().loadingAudio);
        // this.dbCat.setPosition(96, 40);
        // loading.onLoadFinished(() => {
        this.dbCat.setPosition(96, 160);
        this.initView();
        this.initEvent();
        // });
    }
    protected onDestroy(): void {
        pg.event.clear();
    }

    private initData() {
        Game.getIns().init(this.data);
        Game.getIns().reset();
        // 所有全局变量 默认都是null 
    }
    private audioId: any;
    private initView() {
        this.catPlayAni(Game.getIns().beginAudio, () => {
            this.startCountTime();
            this.gameStart();
        })
    }
    private initEvent() {
        cc.find("btnCheckCat", this.dbCat).on(cc.Node.EventType.TOUCH_END, this.onCat, this);
    }
    private onCat() {
        this.catPlayAni(Game.getIns().waitAudio, () => {
        })
    }
    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)
        let leaf_ske = cc.find("leaf_ske", this.node);
        leaf_ske.active = true;
        playDragonBoneAnimation(leaf_ske, "normal", 1);
        cc.audioEngine.stopAllEffects();
        this.catPlayAni(Game.getIns().endAudio, () => {
            // this.dbCat.active = false;
            // this.stopCountTime();
            // this.sendServerData();
            // this.showResultLayer();
        })
    }

    private gameStart() {
        Game.getIns().state = GAME_STATE.RUNNING;
        this.dbCat.active = true;
        this.showQuestion();
        this.playLocalAudio("ding");
    }
    // private questions;
    // private cardInfo;
    // private initGameData() {
    //     this.questions = [];
    //     let question = Game.getIns().getCurrentPage();
    //     for (let i = 0; i < question.optionList.length; i++) {
    //         this.questions[i] = question.optionList[i];
    //     }
    // }

    private showQuestion(show = true) {
        this.isClick = true;
        let question = Game.getIns().getCurrentPage();
        this.layout_box.removeAllChildren();
        question.contentArr.forEach((data, idx) => {
            let word = cc.find("word_" + (idx + 1), this.layout_word);
            word.getComponent(cc.Label).string = data;
            word.active = true;
            word.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
            word.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
            word.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
            word.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);

            let obj: any = {};
            obj.text = data;
            obj.pos = word.getPosition();
            word.data = obj;
            let box = cc.instantiate(this.item_1);
            this.layout_box.addChild(box);
            let text = cc.find("word", box);
            box.data = data;
            text.getComponent(cc.Label).string = "";

            // text.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
            // text.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
            // text.on(cc.Node.EventType.TOUCH_END, this.onBoxTouchEnd, this);
            // text.on(cc.Node.EventType.TOUCH_CANCEL, this.onBoxTouchEnd, this);
        })
        pg.view.setNetImg(this.item_pic, question.picUrl, { w: 443, h: 278 })

        let len = this.layout_box.children.length
        if (len > 8) {
            let scale = 1;
            if (len < 11) scale = 0.8;
            else if (len < 13) scale = 0.65;
            else scale = 0.55;
            this.layout_box.children.forEach((ch) => {
                ch.scale = scale;
            })
        }
        this.layout_box.getComponent(cc.Layout).updateLayout();
    }
    private onBoxTouchEnd(e) {
        let target: cc.Node = e.target;
        let data = target.data;
        data.nodeWord.active = true;
        target.parent = data.parent;
        target.setPosition(0, 5);
        target.getComponent(cc.Label).string = "";
        target.active = false;
    }
    private onTouchCancel(e) {
        let target: cc.Node = e.target;
        this.playWrongAudio();
        target.parent = this.layout_word;
        let data = target.data;
        target.setPosition(data.pos);
    }
    private isClick;
    private onTouchStart(e) {
        if (!this.isClick) return;
        let target: cc.Node = e.target;
        target.parent = this.node;
        this.setTouchPos(e);
    }
    private onTouchMove(e) {
        if (!this.isClick) return;
        let target: cc.Node = e.target;
        this.setTouchPos(e);
    }
    private onTouchEnd(e) {
        if (!this.isClick) return;
        let target: cc.Node = e.target;
        let data = target.data;
        let item: any = this.layout_box.children.find((ch) => {
            let dis = this.getDistances(target, ch);
            let w = cc.find("word", ch);
            if (dis < 65 && w.getComponent(cc.Label).string == "") {
                return ch;
            }
            return null;
        })
        if (!item || item.data != data.text) {
            target.parent = this.layout_word;
            target.setPosition(data.pos);
            this.playWrongAudio();
            return;
        }
        target.active = false;
        target.parent = this.layout_word;
        target.setPosition(data.pos);

        let word = cc.find("word", item);
        word.getComponent(cc.Label).string = data.text;
        // word.data = data;
        // word.data.nodeWord = target;
        // word.data.parent = item;
        word.active = true;
        this.isClick = true;
        this.playLocalAudio("right");
        if (this.checkNext()) {
            if (this.checkIsRight()) {
                this.checkGameOver();
            } else {
                this.showQuestion();
            }
        }
    }


    private playWrongAudio() {
        this.isClick = false;
        let random = Math.floor(Math.random() * 3);
        playDragonBoneAnimation(this.dbCat, "begin", -1);
        this.playLocalAudio("wrong" + random).then(() => {
            playDragonBoneAnimation(this.dbCat, "normal", -1);
            this.isClick = true;
        });
    }

    private checkIsRight() {
        let str = "";
        this.layout_box.children.forEach((ch) => {
            let word = cc.find("word", ch);
            str += word.getComponent(cc.Label).string;
        })
        return str == Game.getIns().getCurrentPage().txt;
    }

    private checkNext() {
        let count = 0;
        this.layout_box.children.forEach((ch) => {
            let word = cc.find("word", ch);
            if (word.getComponent(cc.Label).string == "") count++;
        })
        return count == 0;
    }
    private checkGameOver() {
        Game.getIns().addPage();
        if (!Game.getIns().getCurrentPage()) {
            this.gameOver();
            onHomeworkFinish({});
        } else {
            console.log("over");
            this.playLocalAudio("huri").then(() => {
                this.layout_word.children.forEach((ch) => {
                    ch.getComponent(cc.Label).string = "";
                })
                this.gameStart();
            });
            return;
        }
    }

    //根据两点获取距离
    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) {
        if (Game.getIns().state != GAME_STATE.RUNNING) return;
        // if (this.touching) return;
    }

    private catPlayAni(url, cb = null) {
        playDragonBoneAnimation(this.dbCat, "begin", -1);
        pg.audio.playAudioByUrl(url).then(() => {
            playDragonBoneAnimation(this.dbCat, "normal", -1);
            if (cb) {
                cb();
            }
        })
    }

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

    // }



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


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




















    private _gameStartTime: number;
    private _gameDuration: number;

    sendServerData() {
        this.networkHelper.sendFrame({
            type: "complete",
            duration: this._gameDuration,
            uuid: this.playerId,
        });
    }

    showResultLayer() {
        const resultNode = cc.find("resultNode");
        resultNode.active = true;
        const resultLayer = resultNode.getComponent(op72_ResultLayer);
        resultLayer.setFinishAudioList(Game.getIns().finishAudioList);
    }

    log(str) {
        const node = cc.find("middleLayer");
        if (node) {
            node.getComponent("middleLayer").log(str);
        } else {
            cc.log(str);
        }
    }

    server;
    isRoomOwner;
    playerId;
    allPlayerList;
    networkHelper: NetworkHelper;
    async initNetworkListener() {
        this.log("initNetworkListener");
        this.networkHelper = new NetworkHelper();

        this.networkHelper.on("playerJoin", (event) => {
            if (this.server) {
                this.server.onPlayerJoin({ data: { joinPlayerId: event.playerId } });
            }
            cc.log("playerJoin" + JSON.stringify(event));
        });
        this.networkHelper.on("playerLeave", (event) => {
            cc.log("playerLeave" + JSON.stringify(event));
        });
        this.networkHelper.on("playerOffLine", (event) => {
            cc.log("playerOffLine" + JSON.stringify(event));
            cc.find("Canvas/PlayerOffLineLayer").active = true;
            this.networkHelper.leaveRoom();
        });
        this.networkHelper.on("gameStart", (event) => { });

        this.networkHelper.on("frameEvent", (event) => {
            event.data.frame.items.forEach((item) => {
                if (this.server) {
                    this.server.onFrameEvent(item.data);
                }
                if (item.data.type == "all_player_info") {
                    item.data.playerData.forEach((player) => {
                        if (!this.allPlayerList) {
                            this.allPlayerList = [];
                        }

                        if (
                            !this.allPlayerList.find(
                                (listPlayer) => listPlayer.uuid == player.uuid
                            )
                        ) {
                            this.allPlayerList.push({
                                uuid: player.uuid,
                                name: player.name,
                                headUrl: player.headUrl,
                            });
                        }

                        this.loadingLayer.getComponent(op_72_plus_LoadingLayer).addPlayer(
                            player.name,
                            player.uuid == this.playerId,
                            player.headUrl,
                            player.uuid
                        );
                    });
                } else if (item.data.type == "player_complete") {
                    this.log("player_complete");
                    const resultNode = cc.find("resultNode");
                    const resultLayer = resultNode.getComponent(op72_ResultLayer);
                    item.data.playerData.sort((a, b) => {
                        return a.duration - b.duration;
                    });
                    item.data.playerData.forEach((player) => {
                        if (player.complete) {
                            resultLayer.addPlayerResult(
                                player.headUrl,
                                player.uuid == this.playerId,
                                player.name,
                                player.duration,
                                player.uuid
                            );
                        }
                    });
                    if (item.data.playerData.find(player => player.uuid == this.playerId && player.complete)) {
                        item.data.playerData.sort((a, b) => {
                            return a.duration - b.duration;
                        });
                        const idx = item.data.playerData.findIndex(player => player.uuid == this.playerId);
                        this.onHomeworkFinish({
                            rank: idx + 1,
                            duration: this._gameDuration
                        });
                    }
                }
            });
        });

        do {
            this.playerId = await this.networkHelper.init("op_09_plus", 5);
            if (this.playerId === null) {
                console.log("onDestroy");
                this.networkHelper.onDestroy();
            }
            console.log("this.playerId = " + this.playerId);
        } while (this.playerId === null);

        const room = this.networkHelper.room;
        if (this.playerId == room.roomInfo.owner) {
            this.log("房主");
            this.isRoomOwner = true;
            this.server = new GameServer(5, this.networkHelper);
            await this.networkHelper.startFrameSync();
            this.server.addPlayer({
                uuid: this.playerId,
                isAI: false,
            });
            this.server.startMatch();
        }
        await this.initHeadImgAndName();
    }

    async initHeadImgAndName() {
        const playerInfo = {
            playerHeadUrl: "http://staging-teach.cdn.ireadabc.com/0751c28419a0e8ffb1f0e84435b081ce.png",
            playerName: "test",
        };
        const middleLayer = cc.find("middleLayer");
        if (middleLayer) {
            const middleLayerComponent = middleLayer.getComponent("middleLayer");
            if (middleLayerComponent.getUserInfo && middleLayerComponent.getHeadUrl) {
                const kidInfo = await middleLayerComponent.getUserInfo();
                const playerHeadUrl = middleLayerComponent.getHeadUrl(kidInfo.avatar_url || kidInfo.id);
                playerInfo.playerHeadUrl = playerHeadUrl;
                playerInfo.playerName = kidInfo.nick_name || '拼读达人';
            }
        }
        this.networkHelper.sendFrame({
            type: "playerInfo",
            playerId: this.playerId,
            playerName: playerInfo.playerName,
            playerHeadUrl: playerInfo.playerHeadUrl,
        });
    }

    finish: boolean;
    onHomeworkFinish(data) {
        if (!this.finish) {
            onHomeworkFinish(data);
            this.finish = true;
        }
    }
    startCountTime() {
        this._gameStartTime = new Date().getTime();
    }

    stopCountTime() {
        const duration = new Date().getTime() - this._gameStartTime;
        this.log("duration = " + (duration / 1000).toFixed(2));
        this._gameDuration = duration;
    }


}

