import { ryw_Event } from "../../FrameWork/Event/EventEnum";
import EventMgr from "../../FrameWork/Event/EventMgr";
import GameReport from "../../FrameWork/Report/ZyZyReport";
import User from "../../FrameWork/User/User";
import AppPlatform from "../../FrameWork/Util/AppPlatform";
import Common5 from "../../Platform/th/Common5";
import LevelUpManager from "../Manager/LevelUpManager";
import UserManager from "../Manager/UserManager";
import PrefabManage, { GameType } from "../PrefabManager/PrefabManage";
import GameBase from "../SCommon/GameBase";
import GetAward from "../SCommon/GetAward";
import FoShanDianHanManager from "./FoShanDianHanManager";
import NoteLines from "./NoteLines";

const { ccclass, property } = cc._decorator;
@ccclass
export default class FoShanDianHan extends GameBase {
    @property(cc.Node)
    renSpine: cc.Node = null;

    @property(cc.Node)
    jiKongStr: cc.Node = null;


    @property(cc.Node)
    failNode: cc.Node = null;


    @property(cc.Node)
    heiPing: cc.Node = null;

    @property(cc.Node)
    shuziSpine: cc.Node = null;

    // isStartGame:boolean = false
    gameState: string = 'none'//游戏状态
    musicDuration: number = 0//歌曲长度
    timePassed: number = 0//已过时长
    nodeSlideLength: number = 0//移动的距离
    nodePerfectTime: number = 0//移动的完美时间
    gameSpeed: number = 1000//note速度,单位:像素每秒
    beatMap = []//该轨道的所有note的谱面
    missTime: number = 0.2
    recordCollisionNodeTab = []
    allYinFuNum: number = 0
    jiZhongYinFuNum: number = 0
    jiKongNum: number = 0

    jiXuYouXiTimer: number = 0

    public static instance = null
    public static getInstance() {
        return FoShanDianHan.instance
    }
    onLoad() {
        super.onLoad()
        Common5.stopMusic()

        FoShanDianHan.instance = this
        cc.macro.ENABLE_MULTI_TOUCH = true;
        cc.director.getCollisionManager().enabled = true;
        // cc.director.getCollisionManager().enabledDebugDraw = true;

        this.initData()




        //注册键盘监听函数
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
    }


    onDestroy() {
        super.onDestroy()
    }
    start() {
        Common5.playEffect("GameRes/ui/foShanDianHan/sound/女轻哼-御姐笑")
        this.nodeSlideLength = 700//Math.abs(this.startNode.x-this.endNode.x)
        this.nodePerfectTime = this.nodeSlideLength / this.gameSpeed;
        // this.gameStart()

        this.setStartBtn(1)

        EventMgr.onEvent_custom(ryw_Event.ExitBtnEvent, () => {
            if (User.getStatistics('smallgamefsdhCurGoLevel') > 0) {
                PrefabManage.loadPrefabByType(GameType.SuccessGetMoney, null, (prefab) => {
                    prefab.getComponent('SuccessGetMoney').setViewDate("", 1, 5)
                })
            }
        }, this)
    }
    onKeyDown(event) {
        switch (event.keyCode) {
            case cc.macro.KEY.a:
                this.onBtnClickZSZY();
                break;
            case cc.macro.KEY.s:
                this.onBtnClickHSQJ();
                break;
            case cc.macro.KEY.d:
                this.onBtnClickJJFZ();
                break;
            default:
                ;
        }
    }
    setStartBtn(index) {
        if (index == 1) {
            this.node.getChildByName("startNode").active = true
            this.node.getChildByName("startNode").getChildByName("btnStart").active = true
            this.node.getChildByName("startNode").getChildByName("btnRestart").active = false
        } else if (index == 2) {
            this.node.getChildByName("startNode").active = true
            this.node.getChildByName("startNode").getChildByName("btnRestart").active = true
            this.node.getChildByName("startNode").getChildByName("btnStart").active = false
        } else if (index == 0) {
            this.node.getChildByName("startNode").active = false
        } else if (index == 4) {
            this.node.getChildByName("startNode").active = false
            this.initData(true)
            this.gameStart()
        }
    }
    onBtnStartClick() {
        this.reportKey(() => {
            GameReport.BtnsReport('开始游戏')
        })

        Common5.playEffect("CommonRes/sound/按键点击")
        this.setStartBtn(0)
        this.initData()
        this.gameStart()
    }
    initData(isJiXu?) {
        this.initBars(FoShanDianHanManager.getSongInfo().beatMap)//可配参数
        this.node.getChildByName("nvSpr").active = true
        this.node.getChildByName("nvSpine").active = false
        this.node.getChildByName("qiPao1").active = true
        this.node.getChildByName("qiPao2").active = false

        this.gameState = 'none'
        this.recordCollisionNodeTab = []
        this.timePassed = 0
        this.allYinFuNum = 0
        this.jiZhongYinFuNum = isJiXu ? this.jiZhongYinFuNum : 0
        this.jiKongNum = 0
        this.refreshJiKongStr()
    }
    addAllYinFuNum() {
        this.allYinFuNum += 1
        // console.log('allYinFuNum==',this.allYinFuNum)
    }
    addJiZhongYinFuNum() {
        this.jiZhongYinFuNum += 1
        // console.log('jiZhongYinFuNum==',this.jiZhongYinFuNum)
    }
    addJiKongNum() {
        this.jiKongNum += 1
    }
    refreshJiKongStr() {
        let num = this.jiZhongYinFuNum//this.allYinFuNum-this.jiZhongYinFuNum
        this.jiKongStr.getComponent(cc.Label).string = `击中数:${num}`

    }

    initBars(beatMap) {//初始化各个轨道
        var numOfBars = beatMap.length;
        for (var bar = 0; bar < numOfBars; bar++) {
            var newNoteBar = this.node.getChildByName("NoteLine_" + bar)
            newNoteBar.getComponent(NoteLines).beatMap = beatMap[bar];
            newNoteBar.getComponent(NoteLines).initData()
            newNoteBar.name = 'NoteLine_' + bar;
        }
    }
    gameStart() {
        this.musicDuration = this.node.getComponent(cc.AudioSource).getDuration();

        cc.tween(this.node)
            .delay(0.5)
            .call(() => {
                Common5.playEffect("GameRes/ui/foShanDianHan/sound/倒计时")
                this.shuziSpine.active = true
                this.shuziSpine.getComponent(sp.Skeleton).setAnimation(0, 'shuzi', false)
            })
            .delay(3.5)
            .call(() => {
                this.shuziSpine.active = false
                this.node.getComponent(cc.AudioSource).play()//播放音乐
                this.gameState = 'playing';//设置游戏状态为playing
            })
            .start()
    }
    update(dt) {
        if (this.gameState === 'playing') {
            if (this.musicDuration - this.timePassed < 0.2) {
                this.gameState = 'finish';
                // PrefabManage.loadPrefabByType(GameType.FinishPanel,null,(prefabNode)=>{
                //     // CallFunc(prefabNode)
                // })
                console.log("游戏结束===")
                cc.tween(this.node)
                    .delay(2)
                    .call(() => {
                        // let num = this.allYinFuNum-this.jiZhongYinFuNum
                        Common5.showInterstitialAd()
                        if (this.jiZhongYinFuNum < 140) {
                            this.failNode.active = true
                        } else {
                            this.node.getChildByName("qiPao1").active = false
                            this.node.getChildByName("qiPao3").active = true
                            this.scheduleOnce(() => {
                                User.setStatistics('smallgamefsdhCurGoLevel', User.getStatistics('smallgamefsdhCurGoLevel') + 1)
                                this.showAward()
                            }, 1.5)
                        }
                    })
                    .start()

            }
            this.timePassed = this.getComponent(cc.AudioSource).getCurrentTime();//记录音乐播放的时间	
            // //miss信息三秒消失
            // if(GameDefine.lastNoteJudgement === 'miss')
            // {
            // 	GameDefine.timer += dt;
            // }else{
            // 	GameDefine.timer=0;
            // }
            // if(GameDefine.timer>3)
            // {
            // 	this.node.getChildByName('comboLabel').getComponent(cc.Label).string = '';
            // }
        }
    }
    checkJiZhong(nameStr, spineStr) {
        let tab = this.recordCollisionNodeTab
        for (let i = 0; i < tab.length; i++) {
            if (tab[i].name == nameStr) {
                tab[i]['isCollider'] = false
                // let node = tab[i]
                // node.removeFromParent()
                // node.destroy()

                tab.splice(i, 1)

                Common5.playEffect("GameRes/ui/foShanDianHan/sound/击鼓声")
                let jizhongSpine = this.node.getChildByName(nameStr).getChildByName('jiZhongSpine')
                let copySpine = cc.instantiate(jizhongSpine)
                copySpine.parent = jizhongSpine.parent
                copySpine.setPosition(jizhongSpine.getPosition())
                copySpine.active = true
                copySpine.stopAllActions()
                copySpine.getComponent(sp.Skeleton).setAnimation(0, spineStr, false)
                cc.tween(copySpine)
                    .delay(0.3)
                    .removeSelf()
                    .start()
                this.addJiZhongYinFuNum()
                this.refreshJiKongStr()

                break
            }
        }
        // console.log("checkJiZhong===",tab)
    }

    onBtnClickZSZY() {
        this.checkJiZhong('NoteLine_0', 2)

        this.renSpine.stopAllActions()
        this.renSpine.getComponent(sp.Skeleton).setAnimation(0, 'shang', false)
        cc.tween(this.renSpine)
            .delay(0.5)
            .call(() => {
                this.renSpine.getComponent(sp.Skeleton).setAnimation(0, 'daiji', true)
            })
            .start()
    }

    onBtnClickHSQJ() {
        this.checkJiZhong('NoteLine_1', 1)

        this.renSpine.stopAllActions()
        this.renSpine.getComponent(sp.Skeleton).setAnimation(0, 'xia', false)
        cc.tween(this.renSpine)
            .delay(0.43)
            .call(() => {
                this.renSpine.getComponent(sp.Skeleton).setAnimation(0, 'daiji', true)
            })
            .start()
    }
    onBtnClickJJFZ() {
        this.checkJiZhong('NoteLine_2', 3)

        this.renSpine.stopAllActions()
        this.renSpine.getComponent(sp.Skeleton).setAnimation(0, 'zhong', false)
        cc.tween(this.renSpine)
            .delay(0.33)
            .call(() => {
                this.renSpine.getComponent(sp.Skeleton).setAnimation(0, 'daiji', true)
            })
            .start()
    }

    onBtnFailBuQu() {
        Common5.playEffect("CommonRes/sound/按键点击")
        // this.node.removeFromParent()
        // this.node.destroy()

        this.reportKey(() => {
            GameReport.BtnsReport('不去')
        })

        this.failNode.active = false
        this.setStartBtn(2)
    }
    onBtnFailQu() {
        Common5.playEffect("CommonRes/sound/按键点击")
        let guangXiaoCallFunc = () => {
            for (let i = 0; i < 4; i++) {
                this.heiPing.getChildByName("guangxiao" + i).active = true
                cc.tween(this.node)
                    .delay(0.25 * i)
                    .call(() => {
                        Common5.playEffect("GameRes/ui/foShanDianHan/sound/打击音效(受击)")
                        this.heiPing.getChildByName("guangxiao" + i).active = true
                        this.heiPing.getChildByName("guangxiao" + i).getComponent(sp.Skeleton).setAnimation(0, String(i + 1), false)
                    })
                    .delay(0.2)
                    .call(() => {
                        this.heiPing.getChildByName("guangxiao" + i).active = false
                    })
                    .start()
            }
        }
        let tab = {
            onClose: (finish) => {
                if (finish) {

                    this.reportKey(() => {
                        GameReport.ADReport('去接受惩罚', 1)
                    })
                    Common5.ReportDY("inLevel", '佛山电翰-AD-去接受惩罚');
                    this.failNode.active = false
                    this.setStartBtn(4)
                    // this.heiPing.active = true
                    // cc.tween(this.node)

                    //     .call(() => {
                    //         guangXiaoCallFunc()
                    //     })
                    //     .delay(3)
                    //     .call(() => {
                    //         Common5.playEffect("GameRes/ui/foShanDianHan/sound/喘气(女)")
                    //         // this.heiPing.getChildByName("qiPao").active = true
                    //         this.heiPing.active = false
                    //         // this.node.getChildByName("nvSpr").active = false
                    //         // this.node.getChildByName("nvSpine").active = true
                    //         this.node.getChildByName("qiPao1").active = false
                    //         this.node.getChildByName("qiPao2").active = true
                    //     })
                    //     .delay(3)
                    //     .call(() => {
                    //         this.showAward()
                    //     })
                    //     .start()
                }
                else {
                    this.reportKey(() => {
                        GameReport.ADReport('去接受惩罚', 0)
                    })
                    Common5.showTips_custom("广告未观看完");
                }
            }, onFailed: () => {

            }
        }
        AppPlatform.playVideo_custom(tab)
    }
    showAward() {
        // Common5.playMusic("CommonRes/sound/游戏背景音");
        // let goodArray = [{goodId:1407, goodNum:1}]
        // PrefabManage.loadPrefabByType(GameType.GetAward,null,(prefabNode)=>{
        //     prefabNode.getComponent(GetAward).initView(goodArray, ()=>{
        this.setStartBtn(2)
        //     });
        // },true)

    }
    // onBtnSuccessLingQu(){

    // }
    // onBtnSuccessSanBeiLingQu(){
    //     let tab = {
    //         onClose: (finish)=>{
    //             if (finish) {
    //                 Common5.ReportDY("inLevel", '佛山电翰-AD-双倍领取');

    //             }
    //             else{
    //                 Common5.showTips_custom("广告未观看完");
    //             }
    //         },onFailed:()=>{

    //         }
    //     }
    //     AppPlatform.playVideo_custom(tab)
    // }
}