window.bTurnsNumber = false;
window.calorie = 0
window.turnsNum = 0
window.direction = 1

window.turnsNumber = function (turns){
    if(window.bTurnsNumber)
    {
        console.log("turnsNumber:",turns);
        if(window.isAndroid)
        window.hardWare = turns
        else if(window.isiOS)
        window.hardWare = JSON.parse(turns)
        window.calorie = window.hardWare.calorie
        window.turnsNum = window.hardWare.turnsnumber
        window.direction = window.hardWare.direction
    }
}

window.submitScoreResponse = function(response){
    console.log('submitScoreResponse:',response)
}

window.submitScoreOnError= function(response){
    console.log('submitScoreOnError:',response)
}

var GameStates = require('GameStates');
cc.Class({
    extends: cc.Component,

    properties: {
        bg:cc.Node,
        rankPanel:cc.Node,
        monthRankContent:cc.Node,
        legendRankContent:cc.Node,
        crownFrame:[cc.SpriteFrame],
        numberFrame:[cc.SpriteFrame],
        rankList:[cc.Prefab],
        headFrame:[cc.SpriteFrame],
        myRank:cc.Node,
        bgsound:{
            default:[],
            type: cc.AudioClip
        },
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        // var str = '{"myRanking":{"nickName":"甲","portraits":"ht89dd&im2865.jpg","rank":1,"score":1000,"userId":14624607179958807},"rankingList":[{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12001.jpg","rank":1,"score":1000,"userId":14624607179958807},{"nickName":"乙","portraits":"https://dn-qn.move-it.club/syshead12009.jpg","rank":2,"score":800,"userId":11618408636521789},{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12006.jpg","rank":3,"score":700,"userId":22978961616130}]}'
        
        this.isAndroid = false;
        this.isiOS = false;
        window.isiOS = false
        window.isAndroid = false;
        console.log('平台信息=',navigator.userAgent);
        this.isAndroid = Boolean(navigator.userAgent.match(/android/ig));
        window.isAndroid = this.isAndroid
        this.isIphone = Boolean(navigator.userAgent.match(/iphone|ipod/ig));
        this.isIpad = Boolean(navigator.userAgent.match(/ipad/ig));

        if(this.isIphone || this.isIpad)
        {
            this.isiOS = true;
            window.isiOS = true
        }
        
        if(this.isAndroid)
        {
            console.log('当前平台是：android')
        }
        else if(this.isiOS)
        {
            console.log('当前平台是：ios')
        }
        else
        {
            console.log('当前平台未检测到')
        }
    },

    start () {
        // if(cc.sys.localStorage.getItem('levelNum')==null || cc.sys.localStorage.getItem('levelNum')==''){
        //     cc.sys.localStorage.setItem('levelNum',1)
        // }
        this.node.getChildByName('Dot0').runAction(cc.repeatForever(cc.sequence(cc.delayTime(0),cc.fadeIn(0),cc.delayTime(1.5),cc.fadeOut(0),cc.delayTime(0.5))))
        this.node.getChildByName('Dot1').runAction(cc.repeatForever(cc.sequence(cc.delayTime(0.5),cc.fadeIn(0),cc.delayTime(1),cc.fadeOut(0),cc.delayTime(0.5))))
        this.node.getChildByName('Dot2').runAction(cc.repeatForever(cc.sequence(cc.delayTime(1),cc.fadeIn(0),cc.delayTime(0.5),cc.fadeOut(0),cc.delayTime(0.5))))
        //关卡音乐
        cc.audioEngine.play(this.bgsound[0],true)
        // setInterval(function(){
        //     window.turnsNum++
        //     cc.log(window.turnsNum)
        // }.bind(this),500)
    },
    gameBegin(){
        if(this.isAndroid)
        {
            console.log('isSendData')
             window.eventJsBridge.isSendData(true)
        }
        else if(this.isiOS)
        {
            console.log('isSendData')
            window.webkit.messageHandlers.isSendData.postMessage(true);
        }
        GameStates.levelNum = 1
        GameStates.gameTime = new Date()
        GameStates.carlNum = window.calorie
        GameStates.turnsNum = window.turnsNum
        this.bg.active = false
        var sceneName = 'GameScene'
        cc.director.preloadScene(sceneName,this.onProgress.bind(this),this.onLoaded.bind(this))
    },
    onProgress(completedCount,totalCount){
        let _loadingNextStep = (completedCount / totalCount * 100);
        this.node.getChildByName('ProgressBar').getComponent(cc.ProgressBar).progress = (_loadingNextStep/100)
    },
    onLoaded(){
        cc.director.loadScene('GameScene')
    },
    gameBack(){
        if(this.isAndroid)
        {
           window.eventJsBridge.goBack()
        }
        else if(this.isiOS)
        {
            window.webkit.messageHandlers.goBack.postMessage(null)
        }
    },
    onDestroy(){
        cc.audioEngine.stopAllEffects()
    },
    preloadScene (sceneName, onLoaded) {
        var info = cc.director._getSceneUuid(sceneName);
        if (info) {
        cc.director.emit(cc.Director.EVENT_BEFORE_SCENE_LOADING, sceneName);
        cc.loader.load({ uuid: info.uuid, type: 'uuid' },
        
                (completedCount, totalCount, item) => {
                    cc.log("已完成Items:" + completedCount);cc.log()
                    cc.log("全部Items:" + totalCount);
                    cc.log("当前Item:" + item.url);
                    let _loadingNextStep = (completedCount / totalCount * 100);
                    cc.log("加载进度:" + _loadingNextStep);
                    this.node.getChildByName('ProgressBar').getComponent(cc.ProgressBar).progress = (_loadingNextStep/100)
                    // cc.log(this.node.getChildByName('ProgressBar').getComponent(cc.ProgressBar).progress,(_loadingNextStep/100))
                    if(Math.floor(_loadingNextStep)==100){
                        cc.director.loadScene('GameScene')
                    }                    
                }        
                , function (error, asset) {
                    if (error) {
                    }
                    if (onLoaded) {
                        onLoaded(error, asset);
                    }
                });
            }
            else {
                onLoaded(new Error());
            }
    },
    gameRank(){
        this.rankPanel.active = true
        this.monthRank()
    },
    closeRank(){
        this.rankPanel.active = false
    },
    legendRank(){
        this.rankPanel.getChildByName('legendRank').active = true
        this.rankPanel.getChildByName('monthRank').active = false
        this.rankPanel.getChildByName('edgePanel').getChildByName('monthBtn0').active = true
        this.rankPanel.getChildByName('edgePanel').getChildByName('monthBtn1').active = false
        this.rankPanel.getChildByName('edgePanel').getChildByName('legendBtn0').active = false
        this.rankPanel.getChildByName('edgePanel').getChildByName('legendBtn1').active = true
        this.rankPanel.getChildByName('edgePanel').getChildByName('point1').active = true
        this.rankPanel.getChildByName('edgePanel').getChildByName('point').active = false
        
        var str = '{"myRanking":{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12001.jpg","rank":1,"score":1000,"userId":14624607179958807},'+
        '"rankingList":[{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12001.jpg","rank":1,"score":1000,"userId":14624607179958807},'+
        '{"nickName":"乙","portraits":"https://dn-qn.move-it.club/syshead12009.jpg","rank":2,"score":800,"userId":11618408636521789},'+
        '{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12006.jpg","rank":3,"score":700,"userId":22978961616130},'+
        '{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12001.jpg","rank":4,"score":1000,"userId":14624607179958807},'+
        '{"nickName":"乙","portraits":"https://dn-qn.move-it.club/syshead12009.jpg","rank":5,"score":800,"userId":11618408636521789},'+
        '{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12006.jpg","rank":6,"score":700,"userId":22978961616130},'+
        '{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12001.jpg","rank":7,"score":1000,"userId":14624607179958807},'+
        '{"nickName":"乙","portraits":"https://dn-qn.move-it.club/syshead12009.jpg","rank":8,"score":800,"userId":11618408636521789},'+
        '{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12006.jpg","rank":9,"score":700,"userId":22978961616130},'+
        '{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12001.jpg","rank":10,"score":1000,"userId":14624607179958807},'+
        '{"nickName":"乙","portraits":"https://dn-qn.move-it.club/syshead12009.jpg","rank":11,"score":800,"userId":11618408636521789},'+
        '{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12006.jpg","rank":12,"score":700,"userId":22978961616130}]}'
        
        var self = this
        this.monthRankContent.removeAllChildren()
        this.legendRankContent.removeAllChildren()
        if(this.isAndroid)
        {
           console.log('getRankingList2')
           window.eventJsBridge.getRankingList(2)
        }
        else if(this.isiOS)
        {
            console.log('getRankingList2')
            window.webkit.messageHandlers.getRankingList.postMessage(2);
        }
        window.rankingResponse= function(response){
            console.log('rankin:',response)
            if(self.isAndroid)
            window.ranking = response
            else if(self.isiOS)
            window.ranking = JSON.parse(response)
            var myRank = window.ranking.myRanking
            var rankingList = window.ranking.rankingList
            // var myRank = JSON.parse(str).myRanking
            // var rankingList = JSON.parse(str).rankingList
            self.rankingList = rankingList
            self.myRank.getChildByName('name').getComponent(cc.Label).string = myRank.nickName
            self.myRank.getChildByName('score').getComponent(cc.Label).string = myRank.score+'分'
            self.myRank.getChildByName('rank').getComponent(cc.Label).string = myRank.rank
            if(!myRank.sex){
                myRank.sex = 1
            }
            if(myRank.portraits.substring(myRank.portraits.length-4,myRank.portraits.length)=='.png' || myRank.portraits.substring(myRank.portraits.length-4,myRank.portraits.length)=='.jpg')
            cc.loader.load({url: myRank.portraits}, function (err, frame) {  
                if(err)
                self.myRank.getChildByName('mask').getChildByName('head').getComponent(cc.Sprite).spriteFrame = self.headFrame[myRank.sex-1]
                else
                self.myRank.getChildByName('mask').getChildByName('head').getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(frame)
            })
            else
            cc.loader.load({url: myRank.portraits, type: 'png'}, function (err, frame) {  
                if(err)
                self.myRank.getChildByName('mask').getChildByName('head').getComponent(cc.Sprite).spriteFrame = self.headFrame[myRank.sex-1]
                else
                self.myRank.getChildByName('mask').getChildByName('head').getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(frame)
            })
            console.log(rankingList)
            //排序
            for(var m=0;m<rankingList.length-1;m++){
                for(var n=0;n<rankingList.length-1;n++){
                    var namenum = parseInt(rankingList[n].rank)
                    var namenum1 = parseInt(rankingList[n+1].rank)
                    if(namenum>namenum1){
                        var rankList = rankingList[n]
                        rankingList[n] = rankingList[n+1]
                        rankingList[n+1] = rankList
                    }
                }
            }
            //加载
            var i = 0
            self.legendRankContent.height = rankingList.length*120
            self.rankListarr = []
            var showRankingList = function(){
                if(!rankingList[i].sex){
                    rankingList[i].sex = 1
                }
                if(rankingList[i].portraits.substring(rankingList[i].portraits.length-4,rankingList[i].portraits.length)=='.png' || rankingList[i].portraits.substring(rankingList[i].portraits.length-4,rankingList[i].portraits.length)=='.jpg')
                cc.loader.load({url: rankingList[i].portraits}, function (err, frame) {  
                    if(err)
                    rankingList[i].frame =  self.headFrame[rankingList[i].sex-1]
                    else
                    rankingList[i].frame =  new cc.SpriteFrame(frame)
                    i++
                    self.topindex = 0
                    if(i<rankingList.length)
                    showRankingList()
                    else
                    self.showrankListarr(self.legendRankContent)
                })
                else
                cc.loader.load({url: rankingList[i].portraits, type: 'png'}, function (err, frame) {  
                    if(err)
                    rankingList[i].frame =  self.headFrame[rankingList[i].sex-1]
                    else
                    rankingList[i].frame =  new cc.SpriteFrame(frame)
                    i++
                    self.topindex = 0
                    if(i<rankingList.length)
                    showRankingList()
                    else
                    self.showrankListarr(self.legendRankContent)
                })
            }
            showRankingList()
        }
    },
    monthRank(){
        this.rankPanel.getChildByName('legendRank').active = false
        this.rankPanel.getChildByName('monthRank').active = true
        this.rankPanel.getChildByName('edgePanel').getChildByName('monthBtn0').active = false
        this.rankPanel.getChildByName('edgePanel').getChildByName('monthBtn1').active = true
        this.rankPanel.getChildByName('edgePanel').getChildByName('legendBtn0').active = true
        this.rankPanel.getChildByName('edgePanel').getChildByName('legendBtn1').active = false
        this.rankPanel.getChildByName('edgePanel').getChildByName('point').active = true
        this.rankPanel.getChildByName('edgePanel').getChildByName('point1').active = false
        var str = '{"myRanking":{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12001.jpg","rank":1,"score":1000,"userId":14624607179958807},'+
        '"rankingList":[{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12001.jpg","rank":1,"score":1000,"userId":14624607179958807},'+
        '{"nickName":"乙","portraits":"https://dn-qn.move-it.club/syshead12009.jpg","rank":2,"score":800,"userId":11618408636521789},'+
        '{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12006.jpg","rank":3,"score":700,"userId":22978961616130},'+
        '{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12001.jpg","rank":4,"score":1000,"userId":14624607179958807},'+
        '{"nickName":"乙","portraits":"https://dn-qn.move-it.club/syshead12009.jpg","rank":5,"score":800,"userId":11618408636521789},'+
        '{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12006.jpg","rank":6,"score":700,"userId":22978961616130},'+
        '{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12001.jpg","rank":7,"score":1000,"userId":14624607179958807},'+
        '{"nickName":"乙","portraits":"https://dn-qn.move-it.club/syshead12009.jpg","rank":8,"score":800,"userId":11618408636521789},'+
        '{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12006.jpg","rank":9,"score":700,"userId":22978961616130},'+
        '{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12001.jpg","rank":10,"score":1000,"userId":14624607179958807},'+
        '{"nickName":"乙","portraits":"https://dn-qn.move-it.club/syshead12009.jpg","rank":11,"score":800,"userId":11618408636521789},'+
        '{"nickName":"甲","portraits":"https://dn-qn.move-it.club/syshead12006.jpg","rank":12,"score":700,"userId":22978961616130}]}'
        
        var self = this
        this.monthRankContent.removeAllChildren()
        this.legendRankContent.removeAllChildren()
        if(this.isAndroid)
        {
           console.log('getRankingList1')
           window.eventJsBridge.getRankingList(1)
        }
        else if(this.isiOS)
        {
            console.log('getRankingList1')
            window.webkit.messageHandlers.getRankingList.postMessage(1);
        }
        window.rankingResponse= function(response){
            console.log('rankin:',response)
            if(self.isAndroid)
            window.ranking = response
            else if(self.isiOS)
            window.ranking = JSON.parse(response)
            var myRank = window.ranking.myRanking
            var rankingList = window.ranking.rankingList
            // var myRank = JSON.parse(str).myRanking
            // var rankingList = JSON.parse(str).rankingList
            self.rankingList = rankingList
            self.myRank.getChildByName('name').getComponent(cc.Label).string = myRank.nickName
            self.myRank.getChildByName('score').getComponent(cc.Label).string = myRank.score+'分'
            self.myRank.getChildByName('rank').getComponent(cc.Label).string = myRank.rank
            if(!myRank.sex){
                myRank.sex = 1
            }
            if(myRank.portraits.substring(myRank.portraits.length-4,myRank.portraits.length)=='.png' || myRank.portraits.substring(myRank.portraits.length-4,myRank.portraits.length)=='.jpg')
            cc.loader.load({url: myRank.portraits}, function (err, frame) {  
                if(err)
                self.myRank.getChildByName('mask').getChildByName('head').getComponent(cc.Sprite).spriteFrame = self.headFrame[myRank.sex-1]
                else
                self.myRank.getChildByName('mask').getChildByName('head').getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(frame)
            })
            else
            cc.loader.load({url: myRank.portraits, type: 'png'}, function (err, frame) {  
                if(err)
                self.myRank.getChildByName('mask').getChildByName('head').getComponent(cc.Sprite).spriteFrame = self.headFrame[myRank.sex-1]
                else
                self.myRank.getChildByName('mask').getChildByName('head').getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(frame)
            })
            console.log(rankingList)
            //排序
            for(var m=0;m<rankingList.length-1;m++){
                for(var n=0;n<rankingList.length-1;n++){
                    var namenum = parseInt(rankingList[n].rank)
                    var namenum1 = parseInt(rankingList[n+1].rank)
                    if(namenum>namenum1){
                        var rankList = rankingList[n]
                        rankingList[n] = rankingList[n+1]
                        rankingList[n+1] = rankList
                    }
                }
            }
            //加载
            var i = 0
            self.monthRankContent.height = rankingList.length*120
            self.rankListarr = []
            var showRankingList = function(){
                if(!rankingList[i].sex){
                    rankingList[i].sex = 1
                }
                if(rankingList[i].portraits.substring(rankingList[i].portraits.length-4,rankingList[i].portraits.length)=='.png' || rankingList[i].portraits.substring(rankingList[i].portraits.length-4,rankingList[i].portraits.length)=='.jpg')
                cc.loader.load({url: rankingList[i].portraits}, function (err, frame) {  
                    if(err)
                    rankingList[i].frame =  self.headFrame[rankingList[i].sex-1]
                    else
                    rankingList[i].frame =  new cc.SpriteFrame(frame)
                    i++
                    self.topindex = 0
                    if(i<rankingList.length)
                    showRankingList()
                    else
                    self.showrankListarr(self.monthRankContent)
                })
                else
                cc.loader.load({url: rankingList[i].portraits, type: 'png'}, function (err, frame) {  
                    if(err)
                    rankingList[i].frame =  self.headFrame[rankingList[i].sex-1]
                    else
                    rankingList[i].frame =  new cc.SpriteFrame(frame)
                    i++
                    self.topindex = 0
                    if(i<rankingList.length)
                    showRankingList()
                    else
                    self.showrankListarr(self.monthRankContent)
                })
            }
            showRankingList()
        }
    },
    showrankListarr(content){   
        var self = this     
        for(var j=0;j<10;j++){
            if(j>=this.rankingList.length)
            return
            var rankList = cc.instantiate(self.rankList[0])
            rankList.index = j
            rankList.parent = content
            rankList.y = -j*120-70
            if(j==0)
            self.topItem = rankList
            if(j==9)
            self.bottomItem = rankList
            var rankingList = this.rankingList
            cc.log(rankingList,rankList.index,self.topindex)
            rankList.getChildByName('mask').getChildByName('head').getComponent(cc.Sprite).spriteFrame = rankingList[(rankList.index+self.topindex)].frame
            rankList.getChildByName('name').getComponent(cc.Label).string = rankingList[(rankList.index+self.topindex)].nickName
            rankList.getChildByName('score').getComponent(cc.Label).string = rankingList[(rankList.index+self.topindex)].score
            rankList.getChildByName('rank').getComponent(cc.Label).string = rankingList[(rankList.index+self.topindex)].rank
            if((rankList.index+self.topindex)<3){
                rankList.getChildByName('crown').active = true
                rankList.getChildByName('number').active = true
                rankList.getChildByName('crown').getComponent(cc.Sprite).spriteFrame = self.crownFrame[(rankList.index+self.topindex)]
                rankList.getChildByName('number').getComponent(cc.Sprite).spriteFrame = self.numberFrame[(rankList.index+self.topindex)]
                rankList.getChildByName('num').active = false
                rankList.getChildByName('rank').active = false
            }
            else{
                rankList.getChildByName('crown').active = false
                rankList.getChildByName('number').active = false
                rankList.getChildByName('num').active = true
            }
            self.rankListarr.push(rankList)
        }
    },
    update(){
        if(this.rankPanel.getChildByName('legendRank').active)
        var height = this.legendRankContent.parent.parent.getComponent(cc.ScrollView).getContentPosition().y
        else
        var height = this.monthRankContent.parent.parent.getComponent(cc.ScrollView).getContentPosition().y
        if(height>(420+120*(this.topindex+1)) && this.topindex<this.rankingList.length-10){
            this.topindex++
            this.topItem.y = this.bottomItem.y-120
            this.bottomItem = this.topItem
            var n = (this.topItem.index+1)>9?0:this.topItem.index+1
            this.topItem = this.rankListarr[n]
            var rankList = this.bottomItem
            var rankingList = this.rankingList
            cc.log(this.topItem.y)
            rankList.getChildByName('mask').getChildByName('head').getComponent(cc.Sprite).spriteFrame = rankingList[this.topindex+9].frame
            rankList.getChildByName('name').getComponent(cc.Label).string = rankingList[(this.topindex+9)].nickName
            rankList.getChildByName('score').getComponent(cc.Label).string = rankingList[(this.topindex+9)].score
            rankList.getChildByName('rank').getComponent(cc.Label).string = rankingList[(this.topindex+9)].rank
            if((this.topindex+9)<3){
                rankList.getChildByName('crown').active = true
                rankList.getChildByName('number').active = true
                rankList.getChildByName('crown').getComponent(cc.Sprite).spriteFrame = this.crownFrame[(this.topindex+9)]
                rankList.getChildByName('number').getComponent(cc.Sprite).spriteFrame = this.numberFrame[this.topindex+9]
                rankList.getChildByName('num').active = false
                rankList.getChildByName('rank').active = false
            }
            else{
                rankList.getChildByName('crown').active = false
                rankList.getChildByName('number').active = false
                rankList.getChildByName('num').active = true
                rankList.getChildByName('rank').active = true
            }
        }
        if(height<(300+120*(this.topindex+1)) && this.topindex>0){
            this.topindex--
            this.bottomItem.y = this.topItem.y+120
            this.topItem = this.bottomItem
            var n = (this.bottomItem.index-1)<0?9:this.bottomItem.index-1
            this.bottomItem = this.rankListarr[n]
            var rankList = this.topItem
            var rankingList = this.rankingList
            cc.log(rankingList[this.topindex])
            rankList.getChildByName('mask').getChildByName('head').getComponent(cc.Sprite).spriteFrame = rankingList[this.topindex].frame
            rankList.getChildByName('name').getComponent(cc.Label).string = rankingList[(this.topindex)].nickName
            rankList.getChildByName('score').getComponent(cc.Label).string = rankingList[(this.topindex)].score
            rankList.getChildByName('rank').getComponent(cc.Label).string = rankingList[(this.topindex)].rank
            if((this.topindex)<3){
                rankList.getChildByName('crown').active = true
                rankList.getChildByName('number').active = true
                rankList.getChildByName('crown').getComponent(cc.Sprite).spriteFrame = this.crownFrame[(this.topindex)]
                rankList.getChildByName('number').getComponent(cc.Sprite).spriteFrame = this.numberFrame[this.topindex]
                rankList.getChildByName('num').active = false
                rankList.getChildByName('rank').active = false
            }
            else{
                rankList.getChildByName('crown').active = false
                rankList.getChildByName('number').active = false
                rankList.getChildByName('num').active = true
                rankList.getChildByName('rank').active = true
            }
        }78
    }
});
