// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import Game, { GAME_STATE, Option } from "../tool/Game";
import pg from "../tool/pg";
pg.event.clear();
const { ccclass, property } = cc._decorator;

enum GUN_STATE {
    WAIT = 1,
    SHUT_MIDDLE,
    SHUT_LEFT,
    SHUT_RIGHT
}
enum FISH_STATE {
    NORMAL = 1,
    BREAK,
    FALL,
}
@ccclass
export default class layout_game extends cc.Component {
    // private btn_laba: cc.Node;

    // private countDown: number = 999;
    @property(cc.Node)
    item_word: cc.Node = null;
    @property(cc.Node)
    item_pic: cc.Node = null;
    @property(cc.Node)
    layout_same: cc.Node = null;
    @property(cc.Node)
    img_player: cc.Node = null;
    private rightNum;
    private wrongNum;

    onLoad() {
        this.rightNum = 0;
        this.initEvent();
    }
    protected onDestroy(): void {
        cc.Tween.stopAll();
        cc.audioEngine.stopAll();
    }

    private initEvent() {
        pg.event.on("game_start", () => {
            this.rightNum = 0;
            this.wrongNum = 0;
            this.initView();
        });
        pg.event.on("connon_move_ground", () => {

        });
    }
    private gameStart() {
    }
    private initView() {
        let page = Game.getIns().getCurrentPage();
        let list = page.optionList.concat();
        list = JSON.parse(JSON.stringify(list));
        list.sort((A, B) => { return Math.random() < 0.5 });
        this.layout_same.removeAllChildren();
        let isPic = this.checkIsAllPic(list) && list.length == 4;
        list.forEach((data, idx) => {
            data.id = idx;
            if (data.type == "txt") {
                let word = cc.instantiate(this.item_word);
                this.layout_same.addChild(word);
                word.setPosition(0, 0);
                this.initWordItem(word, data);
            } else {
                let pic = cc.instantiate(this.item_pic);
                this.layout_same.addChild(pic);
                pic.setPosition(0, 0);
                this.initPicItem(pic, data);
                pic.width = isPic ? 262 : 580;
            }
        });
        this.layout_same.getComponent(cc.Layout).paddingLeft = isPic ? 30 : 0;
        cc.find("bg_ornament", this.node).active = isPic;
        cc.find("bg_ornament2", this.node).active = !isPic;
        let img_player = cc.find("Canvas/player/img_player");
        let start = cc.find("Canvas/bg/bg_could/startPos");
        img_player.y = -330;
        img_player.scale = 1;
    }
    private initWordItem(item, data) {
        item.data = data;
        let desc = cc.find("question", item);
        desc.getComponent(cc.Label).string = data.txt;
        item.on(cc.Node.EventType.TOUCH_END, () => {
            if (data.touchRight) return;
            this.onItem(data, item);
        }, this);
    }
    private initPicItem(item: cc.Node, data) {
        item.data = data;
        let img = cc.find("question", item);
        let touch = cc.find("touch", item);
        pg.view.setNetImg(img, data.picUrl, { w: 245, h: 195 });
        touch.on(cc.Node.EventType.TOUCH_END, () => {
            if (data.touchRight) return;
            this.onItem(data, item);
        }, this);
    }
    private onItem(data, item) {
        if (this.touch || Game.getIns().isOver) return;
        this.touch = true;
        if (data.right) {
            data.touchRight = true;
            this.rightNum++;
            item.opacity = 0;
            pg.audio.playAudioByUrl(data.audioUrl, () => {
                let pag = Game.getIns().getCurrentPage()
                if (this.rightNum >= pag.rNum) {
                    Game.getIns().player.addRight();
                    this.layout_same.removeAllChildren();
                    cc.find("bg_ornament", this.node).active = false;
                    cc.find("bg_ornament2", this.node).active = false;
                    this.clickRight().then(() => {
                        pg.event.emit("game_time_over");
                    });
                } else {
                    pg.event.emit("play_laba_audio");
                }
                this.touch = false;
            })
        } else {
            this.wrongNum++;
            pg.audio.playAudioByUrl(data.audioUrl);
            this.clickError().then(() => {
                if (this.wrongNum >= 2) {
                    pg.event.emit("game_time_over");
                }
                this.touch = false;
            })
        }
    }
    private count;
    private arrowAction;
    update(dt) {
        // if (this.arrowAction) return;
        // this.count = this.count - dt;
        // if (this.count <= 0) {
        //     this.showArrow();
        // }
    }

    private touch;
    private checkIsAllPic(data) {
        let count = 0;
        data.forEach((item) => {
            if (item.type == "img") count++;
        })
        return count == data.length;
    }
    private clickRight() {
        return new Promise((resolve, reject) => {
            let img_player = cc.find("Canvas/player/img_player");
            let endPos = cc.find("Canvas/bg/bg_could/endPos");
            let start = cc.find("Canvas/bg/bg_could/startPos");
            cc.tween(img_player)
                .delay(0.1)
                .call(() => { this.playLocalAudio("huaxue"); })
                .to(1, { y: endPos.y, scale: 0.16 })
                .call(() => { pg.event.emit("skiing_show_firework") })
                .delay(3)
                .call(() => { return resolve('') })
                .start();
        })
    }
    private clickError() {
        return new Promise((resolve, reject) => {
            let img_player = cc.find("Canvas/player/img_player");
            let errorPos = cc.find("Canvas/bg/bg_could/errorPos");
            let start = cc.find("Canvas/bg/bg_could/startPos");
            let startPos = start.getPosition();
            cc.tween(img_player).to(1, { y: errorPos.y, scale: 0.65 })
                .delay(1)
                .call(() => { this.playLocalAudio("error"); })
                .to(1, { y: startPos.y, scale: 1 })
                .call(() => {
                    return resolve('')
                })
                .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); });
        })
    }

}