import Game, { FISH_OUT, GAME_STATE, Item, Option } from "../tool/GameNS16_ns16_mole";
import pg from "../tool/pg_ns16_mole";

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);//角度计算方法
}
@ccclass
export default class NewClass extends cc.Component {
    @property(cc.Node)
    res: cc.Node = null;
    @property(cc.Node)
    layout_player: cc.Node = null;
    @property(cc.Node)
    layout_robot: cc.Node = null;

    @property(cc.Node)
    item: cc.Node = null;
    @property(cc.Node)
    layout_card: cc.Node = null;

    onLoad() {
        pg.event.on("game_start", () => {
            this.gameStart();
        })
        pg.view.visible(pg.view.find(this.layout_card, 'bg_card_cover'), false)
        this.initLayout();
    }

    private data: Item;
    private count: number;
    private list: Option[];
    private fishs: cc.Node[];
    private holes: Array<any>;
    private right: Array<Option>;
    gameStart() {
        //游戏开始。允许出鱼
        let page = Game.getIns().getCurrentPage();
        this.right = [];
        this.data = page;
        let list = page.optionList.concat();
        list = JSON.parse(JSON.stringify(list));
        list.sort((A, B) => { return Math.random() < 0.5 });
        //将list进行随机或者直接每次随机抽
        this.list = list;
        this.holes = [];
        this.count = 0;
        this.robotFishTime = null;
        this.fishs = [];
        // 播放内容
        this.showCard().then(() => {
            Game.getIns().state = GAME_STATE.RUNNING;
        })
    }
    initLayout() {
        // 平台处理
        let posOrg = cc.v2(-424, 95)
        let posSpace = cc.v2(280, -250)
        for (let i = 0; i < 8; i++) {
            let node = cc.instantiate(this.item);
            node.active = true;
            this.node.addChild(node);
            node.x = posOrg.x + posSpace.x * (i % 4)
            node.y = posOrg.y + posSpace.y * Math.floor(i / 4)
            this.updateItem(node, null);
            pg.view.touchOn(pg.view.find(node, 'mask/mouse_normal'), this.onTouchItem, this);
        }
    }
    showCard() {
        return new Promise((resolve, reject) => {
            let card = this.layout_card.getChildByName('bg_card_cover');
            card.scale = 1;
            card.x = 0;
            card.y = 15;
            card.opacity = 0;
            card.active = true;
            // 执行翻转动画  飞向底部
            let bg_card_small = this.layout_card.getChildByName('bg_card_small');
            let pos = cc.v2(bg_card_small.x, bg_card_small.y);
            let bg_card = pg.view.find(card, "bg_card")
            bg_card.active = false;
            cc.tween(card).to(0.5, { opacity: 255 }).delay(0.5).to(0.3, { scaleX: 0 }).call(() => {
                bg_card.active = true;
                pg.view.setNetImg(pg.view.find(bg_card, "img"), this.data.img, { w: 480, h: 300 })
            }).to(0.3, { scaleX: 1 }).call(() => {
                pg.event.on('game_play_laba_successed', () => {
                    cc.tween(card).to(0.3, { x: pos.x, y: pos.y, scale: 0.3 }).call(() => {
                        resolve('');
                    }).start();
                })
                pg.event.emit('game_play_laba')
            }).start();
        });
    }
    private touching: boolean;
    scaleTo0() {
        let nodes = this.node.children.filter(item => item.data);
        nodes.forEach(node => {
            // nodes进行隐藏
            cc.tween(pg.view.find(node, 'mask')).to(1, { scale: 0 }).call(() => {
                node.data = null
            }).start();
        })
    }
    stopAllAni() {
        let nodes = this.node.children.filter(item => item.data);
        nodes.forEach(node => {
            let mouse_normal = pg.view.find(node, "mask/mouse_normal");
            let mouse_right = pg.view.find(node, "mask/mouse_right");
            let mouse_wrong = pg.view.find(node, "mask/mouse_wrong");
            cc.Tween.stopAllByTarget(mouse_normal)
            cc.Tween.stopAllByTarget(mouse_right)
            cc.Tween.stopAllByTarget(mouse_wrong)
        })
    }
    updateItem(item, data: Option) {
        if (item.data) return;
        item.data = data;
        pg.view.find(item, 'mask').scale = 1;
        let mouse_normal = pg.view.find(item, "mask/mouse_normal");
        let mouse_right = pg.view.find(item, "mask/mouse_right");
        let mouse_wrong = pg.view.find(item, "mask/mouse_wrong");
        let img_add = pg.view.find(item, 'img_add')
        pg.view.visible(img_add, false);
        if (!data) {
            mouse_normal.active = false;
            mouse_right.active = false;
            mouse_wrong.active = false;
        } else {
            console.log(data.picUrl)
            if (data.type == 'txt') {
                pg.view.visible(pg.view.find(mouse_normal, 'img'), false)
                pg.view.visible(pg.view.find(mouse_right, 'img'), false)
                pg.view.visible(pg.view.find(mouse_wrong, 'img'), false)
                pg.view.visible(pg.view.find(mouse_normal, 'text'), true)
                pg.view.visible(pg.view.find(mouse_right, 'text'), true)
                pg.view.visible(pg.view.find(mouse_wrong, 'text'), true)
                pg.view.setString(pg.view.find(mouse_normal, 'text'), data.txt);
                pg.view.setString(pg.view.find(mouse_right, 'text'), data.txt);
                pg.view.setString(pg.view.find(mouse_wrong, 'text'), data.txt);
            } else {
                pg.view.visible(pg.view.find(mouse_normal, 'img'), true)
                pg.view.visible(pg.view.find(mouse_right, 'img'), true)
                pg.view.visible(pg.view.find(mouse_wrong, 'img'), true)
                pg.view.visible(pg.view.find(mouse_normal, 'text'), false)
                pg.view.visible(pg.view.find(mouse_right, 'text'), false)
                pg.view.visible(pg.view.find(mouse_wrong, 'text'), false)
                pg.view.setNetImg(pg.view.find(mouse_normal, 'img'), data.picUrl, { w: 160, h: 95 })
                pg.view.setNetImg(pg.view.find(mouse_right, 'img'), data.picUrl, { w: 160, h: 95 })
                pg.view.setNetImg(pg.view.find(mouse_wrong, 'img'), data.picUrl, { w: 160, h: 95 })
            }
            //执行出老鼠的动画
            let startPos = cc.v2(10, -114);
            let endPos = cc.v2(10, 110)
            mouse_normal.position = cc.v3(startPos);
            mouse_normal.active = true;
            mouse_right.active = false;
            mouse_wrong.active = false;
            this.playLocalAudio('out');
            cc.Tween.stopAllByTarget(mouse_normal);
            cc.tween(mouse_normal).to(1, { y: endPos.y }).delay(3).to(1, { y: startPos.y }).call(() => {
                item.data = null
            }).start();
        }
    }
    playAddOne(item) {
        return new Promise((resolve, reject) => {
            let img_add = pg.view.find(item, 'img_add')
            pg.view.visible(img_add, true);
            img_add.position = cc.v3(cc.v2(135, 70));
            cc.tween(img_add).by(0.5, { y: 80 }).delay(1).call(() => {
                pg.view.visible(img_add, false);
                resolve("")
            }).start();
        });
    }
    robotAddOne() {
        return new Promise((resolve, reject) => {
            let text = pg.view.find(this.layout_robot, 'text')
            pg.view.visible(text, true);
            text.position = cc.v3(cc.v2(-9, 30));
            this.playLocalAudio('add')
            cc.tween(text).by(0.5, { y: 20 }).delay(3).call(() => {
                pg.view.visible(text, false);
                resolve("")
            }).start();
        });
    }
    //开始点击     点击角色
    async onTouchItemNormal(item, isRobot) {
        // this.touching = true;
        let data = item.data;
        if (!data) return;
        if (data.touching) return;
        if (this.right.some(op => op.id == data.id)) return;
        data.touching = true;
        let mouse_normal = pg.view.find(item, "mask/mouse_normal");
        let mouse_right = pg.view.find(item, "mask/mouse_right");
        let mouse_wrong = pg.view.find(item, "mask/mouse_wrong");
        // 点击之后判断对错。
        if (data.right) {

            this.right.push(data);
            let isOver = this.right.length >= Game.getIns().getCurrentPageRight()
            if (isOver) {
                Game.getIns().state = GAME_STATE.OVER;
                this.stopAllAni();
            }
            mouse_normal.active = false;
            mouse_right.active = true;
            mouse_wrong.active = false;
            // +1动画
            if (isRobot) {
                cc.tween(this.layout_robot).to(0.2, { scale: 1.15 }).to(0.2, { scale: 1.0 }).start();
                this.robotAddOne();
            }
            let startPos = cc.v2(10, -114);
            this.playLocalAudio('right')
            this.playAddOne(item).then(() => {
                pg.audio.playAudioByUrlThen(data.audioUrl).then(() => {
                    if (isOver) {
                        this.scaleTo0();
                    } else {
                        let orgPos = cc.v2(mouse_right);
                        cc.tween(mouse_normal).to(0.5, { y: startPos.y }).call(() => { }).start();
                        cc.tween(mouse_right).delay(0.5).to(0.5, { y: startPos.y }).call(() => {
                            mouse_right.x = orgPos.x;
                            mouse_right.y = orgPos.y;
                            mouse_right.active = false;
                            item.data.touching = false;
                            item.data = null
                        }).start();
                    }
                    if (isRobot) {
                        Game.getIns().robot.addScore();
                    } else {
                        Game.getIns().player.addScore();
                    }
                    if (isOver) {
                        return pg.event.emit("game_time_over");
                    }
                })
            })
        } else {
            this.playLocalAudio('error');
            mouse_normal.active = false;
            mouse_right.active = false;
            mouse_wrong.active = true;
            let startPos = cc.v2(10, -114);
            let orgPos = cc.v2(mouse_wrong);
            cc.tween(mouse_normal).to(0.5, { y: startPos.y }).call(() => {
                // item.data = null
            }).start();
            cc.tween(mouse_wrong).delay(1.5).to(0.5, { y: startPos.y }).call(() => {
                mouse_wrong.x = orgPos.x;
                mouse_wrong.y = orgPos.y;
                mouse_wrong.active = false;
                item.data.touching = false;
                item.data = null
            }).start();
            if (isRobot) {
                Game.getIns().robot.addError();
            } else {
                Game.getIns().player.addError();
            }
            // this.scheduleOnce(() => {
            //     // if (this.right >= Game.getIns().getCurrentPageRight()) {
            //     //     return pg.event.emit("game_time_over");
            //     // }
            // }, 1)
        }
    }
    async onTouchItem(e) {
        let item = e.target.parent.parent;
        this.onTouchItemNormal(item, false)
    }
    async onTouchRobot(e) {
        let item = e.target.parent.parent;
        this.onTouchItemNormal(item, true)
    }
    //机器人随机钓鱼
    private robotFishTime;
    async onRobotFishing() {
        this.layout_robot.active = !Game.getIns().singleGame;
        if (Game.getIns().singleGame) return;
        let nowTime = new Date().getTime();
        if (!this.robotFishTime) this.robotFishTime = nowTime;
        let time = 1000;//过1s再来一次
        if (nowTime - this.robotFishTime > time) {
            this.robotFishTime = nowTime;
            let nodes = this.node.children.filter(node => !!node.data);
            let node = nodes[Math.floor(Math.random() * nodes.length)];
            if (node.data && node.data.right) {
                let item = pg.view.find(node, 'mask/mouse_normal')
                this.onTouchRobot({ target: item });
            } else {
                let item = pg.view.find(node, 'mask/mouse_normal')
                this.onTouchRobot({ target: item });
            }
        }
    }
    getMouse() {
        let list = this.list.filter(li => this.right.every(op => op.id != li.id))
        list = JSON.parse(JSON.stringify(list));
        return list[Math.floor(Math.random() * list.length)]
    }
    getEmptyHole() {
        let list = this.node.children.filter(item => !item.data);
        return list[Math.floor(Math.random() * list.length)];
    }
    private updateTime: number;
    private updateCratTime: number;
    update(dt) {
        let nowTime = new Date().getTime();
        if (!this.updateTime) this.updateTime = nowTime;
        if (nowTime - this.updateTime < 1000) return;
        this.updateTime = nowTime;
        if (Game.getIns().state != GAME_STATE.RUNNING) return;
        this.onRobotFishing()
        if (!this.updateCratTime) this.updateCratTime = nowTime - 500;
        if (nowTime - this.updateCratTime < 500) return;
        let mouse = this.getMouse();
        // 选择一个洞
        let hole = this.getEmptyHole();
        if (!hole) return;
        // 出现
        this.updateItem(hole, mouse);
    }

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

