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

import { ryw_Event } from "../../FrameWork/Event/EventEnum";
import EventMgr from "../../FrameWork/Event/EventMgr";
import User from "../../FrameWork/User/User";
import Common5 from "../../Platform/th/Common5";
import UiBase from "../GameBase/UiBase";
import TaskManager, { MainTaskIdEnum } from "../JuQingChat/TaskManager";
import LevelUpManager from "../Manager/LevelUpManager";
import MiShuManager from "../Manager/MiShuManager";
import NewGuideScript from "../NewGuide/NewGuideScript";
import PrefabManage, { GameType } from "../PrefabManager/PrefabManage";

const {ccclass, property} = cc._decorator;

@ccclass
export default class ChallengeGame extends UiBase {

    @property(cc.Sprite)
    zhujueIcon: cc.Sprite = null;

    @property(cc.Sprite)
    difangIcon: cc.Sprite = null;

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

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

    @property(cc.Node)
    zhujueSpine: cc.Node = null;
    @property(cc.Node)
    clickNode: cc.Node = null;

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

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

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

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

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

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

    @property(cc.Label)
    mishuLab: cc.Label = null;
    @property(cc.Label)
    mishuJiachengLab: cc.Label = null;

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

    @property(cc.Node)
    copyLabDi: cc.Node = null;
    @property(cc.Node)
    zhujueHeadNode: cc.Node = null;
    @property(cc.Node)
    difangHeadNode: cc.Node = null;

    // LIFE-CYCLE CALLBACKS:

    startGameX = -295
    endGameX = 295
    
    // onLoad () {}
    configDate = null

    myStack = 0
    myBoold = 0
    difangStack = 0
    difangBoold = 0
    difangBooldFix = 0
    myBooldFix = 0
    dtTime = 0
    isStartGame = false
    spineClick = 0
    spineScaleTime= 1
    clickTimeOutEvent = null
    challengeType = '' //first second
    playLJFEffect = true
    setViewDate(configDate, challengeType){
        console.log(challengeType, 'challengeType+++++++++==')
        this.configDate = configDate
        this.challengeType = challengeType
    }

    onDestroy(){
        cc.audioEngine.stopMusic()
    }

    start () {
        // Common5.loadRemoteAudioEffect('sound/炒饭音效')  

        Common5.loadRemoteAudioEffect('sound/diandiandian/男主战斗打击') 
        Common5.loadRemoteAudioEffect('sound/diandiandian/战斗胜利') 
        Common5.loadRemoteAudioEffect('sound/diandiandian/战斗失败') 
        // Common5.loadRemoteAudioEffect('sound/diandiandian') 
        // Common5.loadRemoteAudioEffect('sound/diandiandian') 


        this.node.getChildByName('秘书加成').active = true
        this.refreshView()
        this.openTouchEvent(this.clickNode)
        EventMgr.onEvent_custom(ryw_Event.challengeRestart,()=>{
            this.restartGame()
        },this)

        EventMgr.onEvent_custom(ryw_Event.challengeQuit,()=>{ 
            if(cc.isValid(this.node, true)){
                this.node.removeFromParent()
                this.node.destroy()
            }
         
        },this)

        EventMgr.onEvent_custom(ryw_Event.challengeAllQuit,()=>{
            if(cc.isValid(this.node, true)){
                this.node.removeFromParent()
                this.node.destroy()
            }
        },this)


        let mainTaskInfo:any = TaskManager.getCurUnLockMainTaskInfo()
        let mainId = mainTaskInfo.Id
        
        if(mainId == MainTaskIdEnum.MainTask_503 && Common5.TaskGuide503){
            Common5.TaskGuide503 = false
            this.node.getChildByName('descLab').active = true
            let node = this.node.getChildByName('kaishi')
            this.guideView([node])
        }
    }
   

    restartGame(){
        this.node.getChildByName('kaishi').active = true
        this.node.getChildByName('秘书加成').active = true
        this.node.getChildByName('exitRoom').active = true
        this.node.getChildByName('clickNode').active = false
        this.node.getChildByName('touxiang').active = false
        this.endGame.active = false
        this.endSpine.active = false
        this.refreshView()
        this.openTouchEvent(this.clickNode)
    }


    openTouchEvent(node) {
        node.on(cc.Node.EventType.TOUCH_START, this.touchStartNode, this)

        node.on(cc.Node.EventType.TOUCH_END, this.onNodeClick, this)
    }

    closeTouchEvent(node: cc.Node) {
        node.off(cc.Node.EventType.TOUCH_START, this.touchStartNode, this)

        node.off(cc.Node.EventType.TOUCH_END, this.onNodeClick, this)
    }
    
    touchStartNode(){

    }
    //失败 失败持续
    //胜利 胜利持续
    //男主  spineAttack:['待机', '攻击1','攻击2','攻击3' ],

    // {challengeId:0,headUrl:'challenge/head/街头龙哥', spineUrl:'Spine/challenge/龙哥/龙哥', 
    // posiArray:[200, -102],spineAttack:['待机', '攻击'],booldNum:7800, name:'街头龙哥',iconUrl:'challenge/街头龙哥',   attackNum:260, moneyReward:500 },
  
    refreshView(){
        //预加载胜利失败动画
        Common5.addUrlSprite_custom('challenge/head/男主', this.zhujueIcon)
        Common5.addUrlSprite_custom(this.configDate.headUrl,this.difangIcon)

        this.difangSpine.setPosition(cc.v2(this.configDate.posiArray[0], this.configDate.posiArray[1]))
        Common5.playRemoteSpine(this.difangSpine,this.configDate.spineUrl,this.configDate.spineName,this.configDate.spineAttack[0])
        Common5.playRemoteSpine(this.zhujueSpine,'Spine/challenge/男主3','男主', '待机')

     

        this.difangStack = this.configDate.attackNum
        this.difangBoold = this.configDate.booldNum



        let shouyi = LevelUpManager.getCurClickIncome()
        this.myStack = shouyi
        if(shouyi*30>=this.difangBoold){
            this.myBoold = this.difangBoold
        }else{
            this.myBoold = shouyi*30
        }

        this.difangBooldFix = this.difangBoold
        this.myBooldFix = this.myBoold


        this.scheduleOnce(()=>{
            Common5.loadRemoteSpine('Spine/challenge','胜利')
            Common5.loadRemoteSpine('Spine/challenge','失败')
        },1.0)

        this.scheduleOnce(()=>{
            PrefabManage.preloadPrefabByType(GameType.ChallengeSuccess)
            PrefabManage.preloadPrefabByType(GameType.ChallengeFail)
        },2.0)

        let mishuNum = MiShuManager.getUnLockNum()
        let percent = MiShuManager.getMishuAllClickInCome() 
        
        this.mishuLab.string = ''+mishuNum
        this.mishuJiachengLab.string = Common5.getNumberChangeHanzi(percent*100,'1',1)+'%'

        this.changeView()

      
    }

    guideView(nodeArray,opacity = -1){
        PrefabManage.loadPrefabByType(GameType.GuideMskNode, null, (prefab)=>{
            // prefab.zIndex = 199
            let guideNodeArray = nodeArray
            let firstNode = guideNodeArray.shift()
            prefab.getComponent(NewGuideScript).setBindNode(firstNode, guideNodeArray)
            if(opacity!=-1){
                prefab.getComponent(NewGuideScript).setOpacityMaskNode(opacity)
            }
        })
    }
    

    onNodeClick(event){
        clearTimeout(this.clickTimeOutEvent);
        this.spineClick++

        this.difangBoold -= this.myStack 
        this.attackLab('difang', this.myStack)
 
        // Common5.playRemoteAudioEffect('sound/diandiandian/龙卷风打斗') 
        if(this.spineClick<4){
            Common5.playRemoteAudioEffect('sound/diandiandian/男主战斗打击') 
        }else{
            if(this.playLJFEffect){
                this.playLJFEffect = false
                Common5.playRemoteAudioEffect('sound/diandiandian/龙卷风打斗', true) 
            }
           
        }
        if(this.spineClick == 1 ){
            Common5.playRemoteSpine(this.zhujueSpine,'Spine/challenge/男主3','男主', '攻击1')
            this.zhujueSpine.getComponent(sp.Skeleton).timeScale = 1

        }
        if(this.spineClick == 4 ){
            Common5.playRemoteSpine(this.zhujueSpine,'Spine/challenge/男主3','男主', '攻击2')
            this.zhujueSpine.getComponent(sp.Skeleton).timeScale = 1.2

        }
        if(this.spineClick == 12){
            Common5.playRemoteSpine(this.zhujueSpine,'Spine/challenge/男主3','男主', '攻击3')
            this.zhujueSpine.getComponent(sp.Skeleton).timeScale = 1.5

        }
        
        this.clickTimeOutEvent = setTimeout(() => {
            this.spineClick = 0
            Common5.playRemoteSpine(this.zhujueSpine,'Spine/challenge/男主3','男主', '待机')
            this.playLJFEffect = true
            cc.audioEngine.stopAllEffects();
        }, 500);

        this.changeView()
        this.endGameResult()

    }


    changeView(){
        //console.log(this.myBoold, this.difangBoold)
        this.proLabMy.string =Common5.getNumberChangeHanzi(this.myBoold)+ '/'+Common5.getNumberChangeHanzi(this.myBooldFix)
        
        this.proLabDi.string = Common5.getNumberChangeHanzi(this.difangBoold)+'/'+Common5.getNumberChangeHanzi(this.difangBooldFix)
            //progress
        this.progressBarM.progress = this.myBoold/this.myBooldFix
        this.progressBarD.progress = this.difangBoold/this.difangBooldFix
        //
    
        let movex = this.endGameX-this.startGameX
        let movePercent = (this.myBooldFix-this.myBoold)/this.myBooldFix
        let movePercent2 = (this.difangBooldFix-this.difangBoold)/this.difangBooldFix

        this.zhujueHeadNode.x = this.startGameX+movex*movePercent2
        this.difangHeadNode.x = this.startGameX+movex*movePercent

        let mainTaskInfo: any = TaskManager.getCurUnLockMainTaskInfo()
        let mainId = mainTaskInfo.Id
        if (mainId == MainTaskIdEnum.MainTask_506) {
            if (MiShuManager.getUnLockNum() >= 2 && User.getMyLevel() >= 100) {
                
            }else{
                this.myBoold = 0
            }
        }
    }

    protected update(dt: number): void {
        if(this.isStartGame){
            this.dtTime+=dt
            if(this.dtTime>=0.3){
                this.dtTime = 0
                //地方攻击一次
                this.myBoold -= this.difangStack 
                this.changeView()
                this.attackLab('self', this.difangStack)
                this.endGameResult()
            }
        }
     
    }

    attackLab(type, attack){
        let copyNode:cc.Node = null
        if(type == 'self'){
            //创建自己
            copyNode = cc.instantiate(this.copyLabMy)
            copyNode.parent = this.copyLabMy.parent
        }else{
            copyNode = cc.instantiate(this.copyLabDi)
            copyNode.parent = this.copyLabDi.parent
        }
        copyNode.active = true
        copyNode.getComponent(cc.Label).string ='-'+ Common5.getNumberChangeHanzi(attack)
        let posi = copyNode.getPosition()
        cc.tween(copyNode)
        .to(0.5, {y:posi.y+100, opacity:100})
        .call(()=>{
            copyNode.removeFromParent()
            copyNode.destroy()
        })
        .start()
    }

    gameStart(event){
        event.target.active = false
        this.node.getChildByName('exitRoom').active = false
        this.node.getChildByName('clickNode').active = true
        this.node.getChildByName('touxiang').active = true
        //开启攻击定时器
        Common5.playRemoteAudioMusic('sound/diandiandian/战斗背景音')  

        this.isStartGame = true
        Common5.playRemoteSpine(this.difangSpine,this.configDate.spineUrl,this.configDate.spineName,this.configDate.spineAttack[1])

        if(this.configDate.spineAttack.length>2){
            this.difangSpineTX.active = true
            Common5.playRemoteSpine(this.difangSpineTX,this.configDate.spineUrl,this.configDate.spineName,this.configDate.spineAttack[2])
        }

        this.difangSpine.getComponent(sp.Skeleton).timeScale = 2
        if(this.configDate.spineName == '洛北辰'){
            this.difangSpine.getComponent(sp.Skeleton).timeScale = 3
        }else{
            this.difangSpine.getComponent(sp.Skeleton).timeScale = 2
        }

    }

    endGameResult(){
        if(this.myBoold<=0 || this.difangBoold<=0){
            this.isStartGame = false
            this.closeTouchEvent(this.clickNode)
           
            this.node.getChildByName('clickNode').active = false
            this.node.getChildByName('descLab').active = false

            this.scheduleOnce(()=>{
                this.difangSpineTX.active = false
                Common5.playRemoteSpine(this.zhujueSpine,'Spine/challenge/男主3','男主', '待机')
                Common5.playRemoteSpine(this.difangSpine,this.configDate.spineUrl,this.configDate.spineName,this.configDate.spineAttack[0])
                this.endGame.active = true
                this.endSpine.active = true
                this.endGame.scale = 0.1
                this.endSpine.scale = 0.1
               
                if(this.difangBoold<=0){
                    //胜利
                    Common5.playRemoteSpine(this.endSpine,'Spine/challenge','胜利','胜利', false)
                }else if(this.myBoold<=0){
                    //失败
                    Common5.playRemoteSpine(this.endSpine,'Spine/challenge','失败','失败', false)
                }
              
                this.scheduleOnce(()=>{
                    if(this.difangBoold<=0){
                        //胜利
                        Common5.playRemoteSpine(this.endSpine,'Spine/challenge','胜利','胜利持续')
                        Common5.playRemoteAudioEffect('sound/diandiandian/战斗胜利') 
                    }else if(this.myBoold<=0){
                        //失败
                        Common5.playRemoteSpine(this.endSpine,'Spine/challenge','失败','失败持续')
                        Common5.playRemoteAudioEffect('sound/diandiandian/战斗失败') 
                    }

                    this.scheduleOnce(()=>{
                        this.endSpine.active = false
                        this.endGame.active = false
                        
                        if(this.difangBoold<=0){
                        
                            PrefabManage.loadPrefabByType(GameType.ChallengeSuccess, null, (prefab)=>{
                                prefab.getComponent('ChallengeSuccess').setViewDate(this.challengeType, this.configDate)
                            })
                            //this.checkFinshTask(this.configDate)
                        }else if(this.myBoold<=0){
                            
                            PrefabManage.loadPrefabByType(GameType.ChallengeFail)
                            
                        }
                    },0.5)
                },0.6)
    
                cc.tween(this.endGame)
                .to(0.3, {scale:1},{easing:'elasticOut'})
                .start()

                cc.tween(this.endSpine)
                .to(0.3, {scale:1},{easing:'elasticOut'})
                .start()
            },0.5)
     
    
            // @property(cc.Node)
            // endGame: cc.Node = null;
        
            // @property(cc.Node)
            // endSpine: cc.Node = null;
          
        

        }
    }


    touxiangGameClick(){
        this.myBoold = 0
        this.endGameResult()
    }

    // update (dt) {}
}