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

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    @property(cc.Node)
    layout_start: cc.Node = null;
    @property(cc.Node)
    layout_finish: cc.Node = null;
    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
        this._imageResList.push({ url: this.data.pic_url });
        this._imageResList.push({ url: this.data.pic_url_2 });
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
        // this._audioResList.push({ url: this.data.audio_url });
        let arr = [];
        this.data.questions.forEach(question => {
            question.options.forEach(op => {
                arr.push({ url: op.audio })
            })
        })
        this._audioResList.push(...arr);
    }

    addPreloadAnima() {

    }

    onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initEvent();
        this.log("statr!!!!!!!!!!!!!")

        this.initStart().then(() => {
            this.gameStart()
        })
    }
    protected onDestroy(): void {
        pg.event.clear();
    }

    initData() {
        Game.getIns().init(this.data);
        Game.getIns().reset();
        this.touching = null;
        pg.event.emit('mouse_05_num', Game.getIns().getFishList().length)
    }
    private audioId: any;
    async initView() {
        let boat_left = pg.view.find(this, 'layout_bottom/boat_left')
        let boat_right = pg.view.find(this, 'layout_bottom/boat_right')
        pg.view.setString(pg.view.find(boat_left, 'text'), Game.getIns().boatLeft.text)
        pg.view.setString(pg.view.find(boat_right, 'text'), Game.getIns().boatRight.text)
    }
    initEvent() {
        pg.view.touchOn(pg.view.find(this, 'layout_bottom/boat_left/boat'), this.onTouchBoatLeft, this)
        pg.view.touchOn(pg.view.find(this, 'layout_bottom/boat_right/boat'), this.onTouchBoatRight, this)
    }
    onTouchBoatLeft() {
        let voice = pg.view.find(this, 'layout_bottom/boat_left/boat/voice')
        let count = 0;
        voice.active = true;
        function func() {
            pg.view.find(voice, 'v1').active = count % 4 == 1;
            pg.view.find(voice, 'v2').active = count % 4 == 2;
            pg.view.find(voice, 'v3').active = count % 4 == 3;
            count++;
        }
        this.schedule(func, 0.3)
        pg.audio.playAudioByUrlThen(Game.getIns().boatLeft.audio).then(() => {
            this.unschedule(func)
            pg.view.find(voice, 'v1').active = false;
            pg.view.find(voice, 'v2').active = false;
            pg.view.find(voice, 'v3').active = false;
            voice.active = false;
        })
    }
    onTouchBoatRight() {
        let voice = pg.view.find(this, 'layout_bottom/boat_right/boat/voice')
        let count = 0;
        voice.active = true;
        function func() {
            pg.view.find(voice, 'v1').active = count % 4 == 1;
            pg.view.find(voice, 'v2').active = count % 4 == 2;
            pg.view.find(voice, 'v3').active = count % 4 == 3;
            count++;
        }
        this.schedule(func, 0.3)
        pg.audio.playAudioByUrlThen(Game.getIns().boatRight.audio).then(() => {
            this.unschedule(func)
            pg.view.find(voice, 'v1').active = false;
            pg.view.find(voice, 'v2').active = false;
            pg.view.find(voice, 'v3').active = false;
            voice.active = false;
        })
    }

    private resetGame() {
        cc.audioEngine.stopAllEffects();
        this.playLocalAudio("again");
        this.initData();
        this.gameStart();
    }
    private onAgain() {
        this.layout_finish.active = false;
        this.resetGame();
    }
    private onNext() {
        const middleLayer = cc.find('middleLayer');
        if (middleLayer) {
            const mc = middleLayer.getComponent('middleLayer');
            // // 切换下一页
            mc.goNextPage();
        }
    }
    private initStart() {
        return new Promise((resolve, reject) => {
            this.layout_start.active = true;
            cc.find("layout_top/label_title", this.node).getComponent(cc.Label).string = Game.getIns().title;
            pg.event.emit("mouse_09_num", Game.getIns().total);
            let start_ske = cc.find("layout_start/start_ske", this.node);
            pg.load.loadDB(start_ske, { ske: Game.getIns().aniEnter.ske.url, tex: Game.getIns().aniEnter.tex.url, png: Game.getIns().aniEnter.png.url }).then((animationName) => {
                if (animationName && animationName != "") {
                    let db = start_ske.getComponent(dragonBones.ArmatureDisplay);
                    let anis = db.getAnimationNames(db.armatureName);
                    db.playAnimation(anis[0], 0);
                    cc.tween(start_ske).by(0.5, { x: -500 }).call(() => {
                        pg.audio.playAudioByUrl(Game.getIns().startAudio).then(() => {
                            cc.tween(start_ske).delay(1).by(0.5, { x: 500 }).call(() => {
                                this.layout_start.active = false;
                                resolve('');
                            }).start();
                        });
                    }).start();
                } else {
                    this.layout_start.active = false;
                    resolve('');
                }
            })
        });
    }
    private showFinal() {
        this.playLocalAudio("finish");
        let layout_finish = cc.find("layout_finish", this.node);
        layout_finish.active = true;
        let finish_db = cc.find("finish_db", layout_finish);
        let btn_again = cc.find("btn_again", layout_finish);
        let btn_next = cc.find("btn_next", layout_finish);
        btn_again.on(cc.Node.EventType.TOUCH_END, this.onAgain, this);
        btn_next.on(cc.Node.EventType.TOUCH_END, this.onNext, this);
        finish_db.active = true;
        btn_again.active = false;
        btn_next.active = false;
        finish_db.getComponent(dragonBones.ArmatureDisplay).playAnimation("newAnimation", 1);
        this.playLocalAudio("finish").then(() => {
            finish_db.active = false;
            btn_again.active = true;
            btn_next.active = true;
        });
    }
    gameStart() {
        pg.audio.playLocalAudio(cc.find(`Canvas/res/audio/btn`));
        if (this.audioId > -1) {
            cc.audioEngine.stopAllEffects();
        }
        Game.getIns().state = GAME_STATE.RUNNING;
        this.initFishs();
    }
    initFishs() {
        // 出现鱼
        let fishList = Game.getIns().getFishList();
        let layout_fish = pg.view.find(this, 'layout_bottom/layout_fish')
        let fishs_left = pg.view.find(this, 'layout_bottom/boat_left/fishs')
        let fishs_right = pg.view.find(this, 'layout_bottom/boat_right/fishs')
        layout_fish.removeAllChildren();
        fishs_left.removeAllChildren();
        fishs_right.removeAllChildren();
        let item = pg.view.find(this, 'layout_bottom/item')
        for (let i = 0; i < 10; i++) {
            fishList.sort((A, B) => {
                return 0.5 - Math.random();
            })
        }
        fishList.forEach((fish, index) => {
            let node = cc.instantiate(item);
            layout_fish.addChild(node);
            this.scheduleOnce(() => {
                this.updateItem(node, fish);
            }, index * 12)
        });
    }
    updateItem(item, data: Option) {
        item.data = data;
        console.log(data);
        let text = pg.view.find(item, 'layout_text/text')
        pg.view.setString(text, data.txt)
        let count = data.id % 10 + 1;
        for (let i = 1; i <= 10; i++) {
            let fishNode = pg.view.find(item, `fish/fish_${i}`)
            fishNode.active = i == count
        }
        item.active = false;
        //左往右
        if (Math.random() < 0.5) {
            item.x = -(1920 / 2 + Math.random() * 200)
            item.y = -315 - Math.random() * 150;
            item.scaleX = -1;
            text.scaleX = -1;
            item.active = true;
            cc.tween(item).repeatForever(cc.tween().by(21 * 3, { x: 1920 + 400 }).call(() => {
                item.scaleX = -item.scaleX;
                text.scaleX = -text.scaleX;
            }).by(21 * 3, { x: - 1920 - 400 }).call(() => {
                item.scaleX = -item.scaleX;
                text.scaleX = -text.scaleX;
            })).start();
        } else {
            item.x = 1920 / 2 + Math.random() * 200
            item.y = -315 - Math.random() * 150;
            item.scaleX = 1;
            text.scaleX = 1;
            item.active = true;
            cc.tween(item).repeatForever(cc.tween().by(21 * 3, { x: -1920 - 400 }).call(() => {
                item.scaleX = -item.scaleX;
                text.scaleX = -text.scaleX;
            }).by(21 * 3, { x: 1920 + 400 }).call(() => {
                item.scaleX = -item.scaleX;
                text.scaleX = -text.scaleX;
            })).start();
        }
        item.on(cc.Node.EventType.TOUCH_START, this.onItemTouchStart, this);
        item.on(cc.Node.EventType.TOUCH_MOVE, this.onItemTouchMove, this);
        item.on(cc.Node.EventType.TOUCH_END, this.onItemTouchEnd, this);
        item.on(cc.Node.EventType.TOUCH_CANCEL, this.onItemTouchCancel, this);
    }
    private setTouchPos(e) {
        let item = e.target;
        let location = e.getLocation();
        cc.Tween.stopAllByTarget(item);
        let pos = location.sub(cc.v2(1920 / 2, 1080 / 2));
        item.x = pos.x;
        item.y = pos.y;
    }
    private touching: any;
    onItemTouchStart(e) {
        if (this.touching) return;
        let target: cc.Node = e.target;
        let data: Option = target.data;
        this.setTouchPos(e);
        this.touching = data;
        this.playLocalAudio("fish")
    }
    onItemTouchMove(e) {
        let target: cc.Node = e.target;
        let data = target.data;
        if (!this.touching) return;
        if (this.touching.id != data.id) return;
        this.setTouchPos(e);
    }
    onItemTouchEnd(e) {
        let target: cc.Node = e.target;
        let data = target.data;
        if (!this.touching) return;
        if (this.touching.id != data.id) return;
        // let rect = cc.rect(target.x, target.y, target.width, target.height);
        let rect = cc.rect(target.x, target.y, 50, 50);

        let boat_left = pg.view.find(this, 'layout_bottom/boat_left')
        let boat_right = pg.view.find(this, 'layout_bottom/boat_right')
        let leftRect = cc.rect(boat_left.x - boat_left.width / 2, boat_left.y - boat_left.height / 2, boat_left.width, boat_left.height);
        let rightRect = cc.rect(boat_right.x - boat_right.width / 2, boat_right.y - boat_right.height / 2, boat_right.width, boat_right.height);

        let isRight = false;
        let currentRect = null;
        let parent = null;
        let netLeft = false;
        if (rect.intersects(leftRect)) {
            parent = boat_left;
            netLeft = true;
            isRight = !!Game.getIns().boatLeft.isChild(data);
            isRight && Game.getIns().boatLeft.setRight(data);
            currentRect = leftRect;
        } else if (rect.intersects(rightRect)) {
            parent = boat_right;
            netLeft = false;
            isRight = !!Game.getIns().boatRight.isChild(data);
            isRight && Game.getIns().boatRight.setRight(data);
            currentRect = rightRect;
        }
        if (!currentRect) {
            this.playLocalAudio('error')
            if (target.x > 0) {
                target.runAction(cc.jumpBy(1, cc.v2(1300, -1000), 1000, 1))
            } else {
                target.runAction(cc.jumpBy(1, cc.v2(-1300, -1000), 1000, 1))
            }
            this.scheduleOnce(() => {
                this.touching = null;
                this.updateItem(target, data);
            }, 1.5)
            return;
        }
        if (isRight) {
            let item = target;
            let lastArea = 100;
            this.playLocalAudio('right').then(() => {
                if (data.audioUrl) {
                    pg.audio.playAudioByUrlThen(data.audioUrl).then(() => {
                        this.touching = null;
                    })
                } else {
                    this.touching = null;
                }
            })
            let fishs_left = pg.view.find(this, 'layout_bottom/boat_left/fishs')
            let fishs_right = pg.view.find(this, 'layout_bottom/boat_right/fishs')
            if (netLeft) {
                item.x = item.x + 442;
                item.y = item.y - boat_left.y;
                item.parent = fishs_left;
            } else {
                item.x = item.x - 452;
                item.y = item.y - boat_right.y;
                item.parent = fishs_right;
            }
            if (item.scaleX == -1) {
                // 计算当前坐标距离最左侧的距离
                let space = currentRect.width - ((rect.x + rect.width) - currentRect.x) - lastArea / 5;
                let time = space / 10;
                cc.tween(item).by(time, { x: space }).start();
            } else {
                // 计算当前坐标距离最左侧的距离
                let space = rect.x - currentRect.x - lastArea;
                let time = space / 10;
                cc.tween(item).by(time, { x: -space }).start();
            }
            item.off(cc.Node.EventType.TOUCH_START, this.onItemTouchStart, this);
            item.off(cc.Node.EventType.TOUCH_MOVE, this.onItemTouchMove, this);
            item.off(cc.Node.EventType.TOUCH_END, this.onItemTouchEnd, this);
            item.off(cc.Node.EventType.TOUCH_CANCEL, this.onItemTouchCancel, this);
            pg.event.emit('mouse_05_add')
        } else {
            this.playLocalAudio('error')
            if (target.x > 0) {
                target.runAction(cc.jumpBy(1, cc.v2(1300, -1000), 1000, 1))
            } else {
                target.runAction(cc.jumpBy(1, cc.v2(-1300, -1000), 1000, 1))
            }
            this.scheduleOnce(() => {
                this.touching = null;
                this.updateItem(target, data);
            }, 1.5)
        }
        //判断是否结束了
        if (Game.getIns().boatLeft.isAllRight() && Game.getIns().boatRight.isAllRight()) {
            this.showGameOver();
        }
    }
    onItemTouchCancel() {

    }


    private showGameOver() {
        this.showFinal();
        // let gameover = cc.find("gameover", this.node);
        // gameover.scale = 3;
        // gameover.active = true;
        // this.playLocalAudio("gameover");
        // cc.tween(gameover).to(0.3, { scale: 1 })
        //     .delay(2)
        //     .call(() => {
        //         gameover.active = false;
        //         //发送给上端最后的数据
        //         // alert("game_finish")
        //         let player = { right: Game.getIns().player.score, error: Game.getIns().player.error }
        //         onHomeworkFinish(player)
        //         this.log("player: " + JSON.stringify(player));
        //     }).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); });
        })
    }
}


