// 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 { 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 taskState from "../DH/taskState"
import TaskManager from "../JuQingChat/TaskManager"
import GMManager from "../Manager/GMManager"
import UserManager from "../Manager/UserManager"
import PrefabManage, { GameType } from "../PrefabManager/PrefabManage"
import GetAward from "../SCommon/GetAward"
import TimeManger from "./TimeManger"

const { ccclass, property } = cc._decorator;

enum QuanTou {
    up = 1,
    down,
    left,
    right
}

enum GameState {
    kong,
    ready,
    playAnim,

}

@ccclass
export default class ZouCeHuaScript extends cc.Component {

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

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

    @property(cc.ProgressBar)
    bloodProgress: cc.ProgressBar = null;

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

    @property(cc.Label)
    bloodProgressLab: cc.Label = null;

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

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

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}
    CurGameState = GameState.kong
    haoganIndex = 100;
    haoganMax = 100;

    daijiAnim = 'daiji'
    randIndex = -1
    dongzuoAnims = ['shang1', 'xia1', 'you1', 'zuo1']
    recoveryAnims = ['shang2', 'xia2', 'you2', 'zuo2']
    aidaAnims = ['shang aida', 'xia aida', 'you aida', 'zuo aida']

    guideIndex = 0
    xinshouGuide = false
    isStartGame = false;
    changeActionDt = 0
    changeActionFixDt = 1
    hitAttck = 2

    tm: TimeManger = new TimeManger();
    onLoad() {
        // super.onLoad()
        // 

        // let gm = GMManager.getToggleStatus_CEHUA()
        // if(gm){
        this.hitAttck = 20
        // }
        let timeNode = this.node.getChildByName('timeNode')
        timeNode.active = false

        // let array = UserManager.getFirstInGameArray()
        let array = []
        // if(array.indexOf('ZouCeHua') >= 0){
        //     this.xinshouGuide = false
        // }else{
        this.xinshouGuide = true
        this.guideIndex = 0
        array[array.length] = 'ZouCeHua'
        // UserManager.setFirstInGameArray(array)
        // }


        // this.setGameType(GameType.ZouCeHua)
        // this.stopTimer()
        EventMgr.onEvent_custom(ryw_Event.timeOut, (tab) => {
            this.gameEndAnim()
        }, this);
    }

    onDestroy(): void {
        this.isStartGame = false

    }

    gameEndAnim() {
        // this.stopTimer()
        this.isStartGame = false
        let resultNode = this.node.getChildByName('resultNode')
        resultNode.getChildByName('successNode').active = false
        resultNode.getChildByName('failNode').active = false
        this.CurGameState = GameState.kong
        if (this.haoganIndex <= 0) {


            //失败
            this.renwuNode.active = false
            this.node.getChildByName('shibaiNode').active = true

            this.showCehuaQiPao('对不起大佬,我再也不敢了', () => {
                //
                // resultNode.active = true
                // resultNode.getChildByName('successNode').active = true
                PrefabManage.loadPrefabByType(GameType.SuccessGetMoney, null, (prefab) => {
                    prefab.getComponent('SuccessGetMoney').setViewDate('策划')
                })
            })

        } else {
            //成功
            this.playNode("daiji", true)
            this.showCehuaQiPao('给你机会你不中用啊', () => {

                resultNode.active = true
                resultNode.getChildByName('failNode').active = true

            })

        }

    }


    start() {
        this.zourenNode.active = false
        this.playNode("daiji", true)

        if (this.xinshouGuide) {
            this.showCehuaQiPao('就凭你?看我身法', () => {
                this.guideAnim()
                this.zourenNode.active = true
                this.CurGameState = GameState.ready

            })
        } else {
            this.showCehuaQiPao('就凭你?看我身法', () => {
                this.daojishiAnim()



            })
        }


        // this.pauseTime()

    }


    playNode(anim, isLoop) {
        this.renwuNode.getComponent(sp.Skeleton).setAnimation(0, anim, isLoop)
    }
    playQuanNode(anim, callFunc) {
        this.quantouNode.active = true
        this.quantouNode.getComponent(sp.Skeleton).setAnimation(0, anim, false)
        this.scheduleOnce(() => {
            this.quantouNode.active = false
            if (callFunc) {
                callFunc()
            }
        }, 0.3)
    }
    zourenClickNode(event, data) {
        if (this.CurGameState == GameState.kong) {
            return
        }
        if (this.CurGameState == GameState.playAnim) {
            return
        }

        this.isStartGame = false

        this.CurGameState = GameState.playAnim
        let num = Number(data)
        let animArray = ['shanggouquan', 'xiagouquan', 'zuogouquan', 'yougouquan']
        let anim = animArray[num - 1]
        let isRight = false
        if (num - 1 == this.randIndex) {
            isRight = true
        }
        // this.quantouNode.active = true
        //挥拳打人
        this.node.getChildByName('dianjixiaoguo').active = false

        if (this.xinshouGuide && this.guideIndex < 4) {
            Common5.playEffect("GameRes/sound/怼策划/揍她/打中音效")
            let aidaAnim = this.aidaAnims[this.randIndex]
            this.playQuanNode(anim, () => {
                this.renwuNode.getComponent(sp.Skeleton).setAnimation(0, aidaAnim, false)
                this.scheduleOnce(() => {
                    this.guideIndex++
                    if (this.guideIndex < 4) {
                        this.guideAnim()
                        this.CurGameState = GameState.ready
                    } else {
                        //倒计时3秒
                        this.daojishiAnim()
                    }

                }, 0.3)
            })
            return
        }
        if (isRight) {
            //被打
            Common5.playEffect("GameRes/sound/怼策划/揍她/打中音效")

            this.haoganIndex -= this.hitAttck
            let aidaAnim = this.aidaAnims[this.randIndex]
            this.playQuanNode(anim, () => {
                this.renwuNode.getComponent(sp.Skeleton).setAnimation(0, aidaAnim, false)
                this.scheduleOnce(() => {
                    this.bloodSubAnim()
                    this.randAnim()
                    this.CurGameState = GameState.ready
                }, 0.3)
            })
        } else {
            //打空
            this.playQuanNode(anim, () => {
                this.randAnim()
                this.CurGameState = GameState.ready
            })

        }
    }


    protected update(dt: number): void {

        if (!this.isStartGame) {
            return
        }

        //
        this.changeActionDt += dt
        if (this.changeActionDt >= this.changeActionFixDt) {
            this.changeActionDt = 0
            this.randAnim()
            this.CurGameState = GameState.ready
        }
    }


    daojishiAnim() {
        this.zourenNode.active = true
        for (let i = 0; i < this.zourenNode.childrenCount; i++) {
            let node = this.zourenNode.children[i]
            node.active = true

        }

        this.node.getChildByName('dianjixiaoguo').active = false


        let timeNode = this.node.getChildByName('timeNode')
        timeNode.active = true
        timeNode.getChildByName('3Node').active = true
        timeNode.getChildByName('2Node').active = false
        timeNode.getChildByName('1Node').active = false


        this.playNode("daiji", true)
        cc.tween(timeNode)
            .delay(1.0)
            .call(() => {
                timeNode.getChildByName('3Node').active = false
                timeNode.getChildByName('2Node').active = true
            })
            .delay(1.0)
            .call(() => {
                timeNode.getChildByName('2Node').active = false
                timeNode.getChildByName('1Node').active = true
            })
            .delay(1.0)
            .call(() => {
                timeNode.active = false

                // this.recoveryTime()
                this.randAnim()
                this.CurGameState = GameState.ready
                this.isStartGame = true

                this.tm.init(100, this.node.getChildByName("addTime").getChildByName("time").getComponent(cc.Label));
                this.tm.setTitle("")
                this.tm.setRotNode(this.node.getChildByName("addTime"));
            })
            .start()
    }


    bloodSubAnim() {
        //this.haoganIndex++
        let haogandu = this.bloodLab
        haogandu.setPosition(cc.v2(0, 300))

        haogandu.active = true
        haogandu.opacity = 255
        cc.tween(haogandu)
            .to(0.5, { y: 400, opacity: 0 })
            .call(() => {
                this.setProgress()

            })
            .start()

    }

    //给你机会你不中用啊
    //对不起大佬,我再也不敢了

    showCehuaQiPao(str, callFunc?: Function) {

        Common5.playEffect("GameRes/sound/怼策划/揍她/" + str)


        let qipaoNode = this.qipao
        qipaoNode.scale = 0
        qipaoNode.active = true
        qipaoNode.stopAllActions()
        qipaoNode.getChildByName("str").getComponent(cc.Label).string = str


        cc.tween(qipaoNode)
            .to(0.2, { scale: 1 })

            .delay(2)
            .to(0.2, { scale: 0 })
            .call(() => {


                if (callFunc) {
                    callFunc()
                }
            })
            .start()
    }


    setProgress() {
        let index = this.haoganIndex / this.haoganMax
        this.bloodProgress.progress = index

        let lab = this.bloodProgress.node.getChildByName('lab').getComponent(cc.Label)
        lab.string = '血量:' + this.haoganIndex

        if (this.haoganIndex <= 0) {

            this.gameEndAnim()
        }

    }

    randAnim() {

        this.isStartGame = true
        this.changeActionDt = 0

        let random = Common5.getRandomNum(0, 4)
        this.randIndex = random
        let anim = this.dongzuoAnims[this.randIndex]
        this.playNode(anim, false)

    }


    guideAnim() {

        for (let i = 0; i < this.zourenNode.childrenCount; i++) {
            let node = this.zourenNode.children[i]
            node.active = false
        }

        this.zourenNode.children[this.guideIndex].active = true
        this.node.getChildByName('dianjixiaoguo').active = true

        let random = this.guideIndex
        this.randIndex = random
        let anim = this.dongzuoAnims[this.randIndex]
        this.playNode(anim, false)

    }

    jizhongAnim() {

    }


    meijizhongAnim() {

    }

    guideStep() {

    }



    exitGameClickEvent(event) {
        Common5.playEffect("CommonRes/sound/按键点击")
        if (event.target['isClick']) {
            return
        }
        event.target['isClick'] = true


        this.node.removeFromParent()
        this.node.destroy()
    }

    addTimeClickEvent(event) {
        Common5.playEffect("CommonRes/sound/按键点击")

        let tab = {
            onClose: (finish) => {
                if (finish) {

                    // this.reportKey(()=>{
                    //     GameReport.ADReport('失败加时',1)
                    // })
                    User.setShowAdNum(User.getShowAdNum() + 1)
                    Common5.ReportDY("inLevel", `任务${TaskManager.getCurUnLockMainTaskId()}-AD-揍策划失败加时`)
                    // Common5.ReportDY("inLevel", "揍策划-AD-失败加时");

                    // this.addTimeGame()
                    let resultNode = this.node.getChildByName('resultNode')
                    resultNode.active = false
                    // this.pauseTime()
                    this.daojishiAnim()


                } else {

                    // this.reportKey(()=>{
                    //     GameReport.ADReport('失败加时',0)
                    // })

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

            }
        }
        AppPlatform.playVideo_custom(tab)

    }

    chakanGiftClickEvent(event) {
        Common5.playEffect("CommonRes/sound/按键点击")

        if (event.target['isClick']) {
            return
        }
        event.target['isClick'] = true

        // let data =  User.getCehuaGuide()
        // data.zoucehua = true
        // User.setCehuaGuide(data)
        PrefabManage.loadPrefabByType(GameType.taskState, null, (node) => {
            node.getComponent(taskState).showSuccess("成功", () => {
                UserManager.addMoney(User.getMyLevel() * 10)
                this.node.removeFromParent()
                this.node.destroy()
            })
        })


        // let goodArray = [{ goodId: 1403, goodNum: 1 }]
        // PrefabManage.loadPrefabByType(GameType.GetAward, null, (prefabNode) => {
        //     prefabNode.getComponent(GetAward).initView(goodArray, () => {
        //         this.node.removeFromParent()
        //         this.node.destroy()
        //     });
        // }, true)


    }

    onBtnAddTimeClick() {
        EventMgr.emitEvent_custom(ryw_Event.stopTimeTick);
        let tab = {
            onClose: (finish) => {
                User.setShowAdNum(User.getShowAdNum() + 1)
                Common5.ReportDY("inLevel", `任务${TaskManager.getCurUnLockMainTaskId()}-AD-揍策划失败加时`)
                if (finish) {
                    this.tm.add(60);
                }
                else {

                }
                // EventMgr.emitEvent_custom(ryw_Event.startTimeTick);
            }, onFailed: () => {

            }
        }
        AppPlatform.playVideo_custom(tab)
    }
    // update (dt) {}
}