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

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>;
    gameStart() {
        //游戏开始。允许出鱼
        let page = Game.getIns().getCurrentPage();
        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(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(3).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) {
        if (this.touching) return;
        // this.touching = true;
        let data = item.data;

        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");
        // 点击之后判断对错。
        Game.getIns().state = GAME_STATE.OVER;
        this.stopAllAni();
        if (data.right) {
            this.playLocalAudio('right');
            mouse_normal.active = false;
            mouse_right.active = true;
            mouse_wrong.active = false;
            // +1动画
            if (isRobot) {
                this.robotAddOne();
            }
            this.playAddOne(item).then(() => {
                this.scaleTo0();
                if (isRobot) {
                    Game.getIns().robot.addScore();
                } else {
                    Game.getIns().player.addScore();
                }
                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 nodes = this.node.children.filter(item => item.data);
            nodes.forEach(node => {
                cc.tween(pg.view.find(node, "mask/mouse_normal")).to(0.5, { y: startPos.y }).call(() => {
                    item.data = null
                }).start();
            })
            this.scheduleOnce(() => {
                if (isRobot) {
                    Game.getIns().robot.addError();
                } else {
                    Game.getIns().player.addError();
                }
                return pg.event.emit("game_time_over");
            }, 2)
        }
    }
    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 = 5000;//level来确定触发捕鱼的间隔时间。
        if (nowTime - this.robotFishTime > time) {
            this.robotFishTime = nowTime + 4000;//过1s再来一次
            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 });
            }
        }
    }
    getMouse() {
        return this.list[Math.floor(Math.random() * this.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); });
        })
    }
}
