// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        rankScrollView: cc.Node,
        _viewitemTemp: null,
        _content: null,

        SignAtlas: {
            default: null,
            type: cc.SpriteAtlas,
        },

        passNode: { //分数超越节点
            default: null,
            type: cc.Node
        }
    },

    // LIFE-CYCLE CALLBACKS:
    ctor() {
        this.rankArr = new Array();;
        this.passIndex = 0;
    },

    onLoad() {
        this._viewlist = this.node.getChildByName("PHB").getChildByName("rankScrollView");
        this._content = this.rankScrollView.getChildByName("view").getChildByName("content");

        if (this._viewitemTemp == null || this._viewitemTemp == 'undefined') {
            this._viewitemTemp = this._content.children[0];
            this._content.removeChild(this._viewitemTemp);
        }

        this.showFriendRank();
        this.PHB = this.node.getChildByName("PHB");
        this.MYPHB = this.node.getChildByName("MYPHB");
        this.PassNode = this.node.getChildByName("PassNode");
    },

    start() {
        this.userhead = "";
        var self = this;
        this.GetUserHead();
        wx.onMessage(function (data) {
            console.log(data.method, data.data)
            switch (data.method) {
                case 'updateRank': {
                    break;
                }
                case 'showMyRank': {
                    self.PHB.active = false;
                    self.MYPHB.active = true;
                    self.PassNode.active = false;
                    self.showFriendRank();

                    break;
                }
                case 'showGroupRank': {
                    break;
                }
                case 'hideRank': {
                    self.PHB.active = false;
                    self.MYPHB.active = false;
                    self.PassNode.active = false;
                    break;
                }
                case 'showFriendRank': {
                    var show = data.data == "true";

                    self.PHB.active = show;
                    self.MYPHB.active = !show;
                    self.PassNode.active = false;

                    self.showFriendRank();

                    break;
                }
                case 'fillRankList': { //填充rank数组，用做检测超越好友需求
                    self.fillRankList();
                    break;
                }
                case 'checkPass': { //检测超越了谁
                    //console.log(data.data);
                    self.PHB.active = false;
                    self.MYPHB.active = false;
                    self.checkPass(data.data);
                    break;
                }
            }
        })
    },

    packHeadImg(data) {
        var headlist = data.split('/');
        var len = headlist.length;
        if (len === 0 || len === 1) {
            return data;
        }
        var headimg = "";
        for (var i = 0; i < len - 1; ++i) {
            headimg += headlist[i] + '/';
        }
        headimg += '132';
        return headimg;
    },

    createImage(sprite, url) {
        let image = wx.createImage();
        image.onload = function () {
            let texture = new cc.Texture2D();
            texture.initWithElement(image);
            texture.handleLoadedTexture();
            sprite.spriteFrame = new cc.SpriteFrame(texture);
        };
        image.src = url;
    },

    // bubbleSort(arr) {
    //     for (var i = 1; i < arr.length; i++) {
    //         for (var r = 0; r < arr.length - i; r++) {
    //             if (parseInt(arr[r].score) < parseInt(arr[r + 1].score)) {
    //                 arr[r] = [arr[r + 1], arr[r + 1] = arr[r]][0];
    //             }
    //         }
    //     }
    // },

    bubbleSort(arr) {
        var len = arr.length;
        for (var i = 0; i < len; i++) {
            for (var j = 0; j < len - 1 - i; j++) {
                if (parseInt(arr[j].score) < parseInt(arr[j + 1].score)) { //相邻元素两两对比
                    var temp = arr[j + 1]; //元素交换
                    arr[j + 1] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        return arr;
    },

    onClickRankItem: function (event) {
        //var strIndex = event.target.getChildByName("ranknum").getComponent(cc.Label).string;
        //this.node.getChildByName("PHB").getChildByName("IndexPos").getComponent(cc.Label).string = "名次：" + strIndex;
        //this.node.getChildByName("PHB").getChildByName("PlayScore").getComponent(cc.Label).string = event.target.getChildByName("score").getComponent(cc.Label).string;
        //this.node.getChildByName("PHB").getChildByName("headimg").getComponent(cc.Sprite).spriteFrame = event.target.getChildByName("headimg").getComponent(cc.Sprite).spriteFrame;
    },

    addRank(/*data*/) {
        /*
        var rankArr = new Array();
        for (var index = 0; index < data.length; ++index) {
            var openid = data[index].openid;
            var nickname = data[index].nickname;
            var headimg = this.packHeadImg(data[index].avatarUrl);
            var score = '0';
            var driLevel = '0';
            if (!this.IsEmpty(data[index].KVDataList)) {
                for (var num = 0; num < data[index].KVDataList.length; ++num) {
                    if (data[index].KVDataList[num].key == 'driLevel') {
                        driLevel = data[index].KVDataList[num].value;
                    } else {
                        score = data[index].KVDataList[num].value;
                    }
                }
                if (data[index].KVDataList.length == 2) {
                    rankArr.push({ openid: openid, nickname: nickname, headimg: headimg, score: score, driLevel: driLevel });
                }
            }
            // if (!this.IsEmpty(data[index].KVDataList)) {
            //     score = data[index].KVDataList[0].value;
            //     rankArr.push({ openid: openid, nickname: nickname, headimg: headimg, score: score });
            // }
        }
        this.bubbleSort(rankArr);*/

        //this.node.getChildByName("PHB").active = true;
        this._content.removeAllChildren();
        //for (var n = 0; n < 5; ++n) {         

        for (var index = 0; index < this.rankArr.length; ++index) {
            var node = cc.instantiate(this._viewitemTemp);
            node.getChildByName('ranknum').getComponent(cc.Label).string = index + 1;

            if (index < 3) {
                node.getChildByName('ranknunbg' + index).active = true;
                node.getChildByName('ranknum').active = false;
            }

            node.getChildByName('username').getComponent(cc.Label).string = this.rankArr[index].nickname;
            this.createImage(node.getChildByName('headimg').getComponent(cc.Sprite), this.rankArr[index].headimg);
            node.getChildByName('score').getComponent(cc.Label).string = this.rankArr[index].score;

            node.getChildByName('CheckMark').active = ((index % 2) != 0);
            this._content.addChild(node);

            node.getChildByName("levelSgin").active = false;
            var level = parseInt(this.rankArr[index].driLevel);
            if (level != 'NAN' && level > 0) {
                node.getChildByName("levelSgin").active = true;
                node.getChildByName("levelSgin").getComponent(cc.Sprite).spriteFrame = this.SignAtlas.getSpriteFrame('c' + level);
            } else {
                node.getChildByName("levelSgin").active = false;
            }

            // if (index == 0) {
            //     node.getComponent(cc.Toggle).check();

            //     var strIndex = node.getChildByName("ranknum").getComponent(cc.Label).string;
            //     this.node.getChildByName("PHB").getChildByName("IndexPos").getComponent(cc.Label).string = "名次：" + strIndex;
            //     this.node.getChildByName("PHB").getChildByName("PlayScore").getComponent(cc.Label).string = node.getChildByName("score").getComponent(cc.Label).string;
            //     this.createImage(this.node.getChildByName("PHB").getChildByName("headimg").getComponent(cc.Sprite), rankArr[index].headimg);
            // }

            if (this.isMySelf(this.rankArr[index].headimg)) {
                this.node.getChildByName("PHB").getChildByName("itemMy").getChildByName('ranknum').active = true;
                this.node.getChildByName("PHB").getChildByName("itemMy").getChildByName('headimg').active = true;
                this.node.getChildByName("PHB").getChildByName("itemMy").getChildByName('score').active = true;
                this.node.getChildByName("PHB").getChildByName("itemMy").getChildByName('username').active = true;
                this.node.getChildByName("PHB").getChildByName("itemMy").getChildByName('headSprite').active = true;
                this.node.getChildByName("PHB").getChildByName("itemMy").getChildByName('ranknum').getComponent(cc.Label).string = index + 1;
                this.node.getChildByName("PHB").getChildByName("itemMy").getChildByName('username').getComponent(cc.Label).string = this.rankArr[index].nickname;
                this.createImage(this.node.getChildByName("PHB").getChildByName("itemMy").getChildByName('headimg').getComponent(cc.Sprite), this.rankArr[index].headimg);
                this.node.getChildByName("PHB").getChildByName("itemMy").getChildByName('score').getComponent(cc.Label).string = this.rankArr[index].score;

                var level = parseInt(this.rankArr[index].driLevel);
                if (level != 'NAN' && level > 0) {
                    this.node.getChildByName("PHB").getChildByName("itemMy").getChildByName("levelSgin").active = true;
                    this.node.getChildByName("PHB").getChildByName("itemMy").getChildByName("levelSgin").getComponent(cc.Sprite).spriteFrame = this.SignAtlas.getSpriteFrame('c' + level);
                } else {
                    this.node.getChildByName("PHB").getChildByName("itemMy").getChildByName("levelSgin").active = false;
                }


                //node.getComponent(cc.Toggle).interactable = true;
                //node.getComponent(cc.Toggle).check();
                //node.getComponent(cc.Toggle).interactable = false;
                var strIndex = node.getChildByName("ranknum").getComponent(cc.Label).string;
                this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("myNode").getChildByName("ranknum").getComponent(cc.Label).string = index + 1;
                this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("myNode").getChildByName("username").getComponent(cc.Label).string = this.rankArr[index].nickname;
                this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("myNode").getChildByName("score").getComponent(cc.Label).string = this.rankArr[index].score;
                this.createImage(this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("myNode").getChildByName("headimg").getComponent(cc.Sprite), this.rankArr[index].headimg);
                this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("myNode").active = true;

                level = parseInt(this.rankArr[index].driLevel);
                if (level != 'NAN' && level > 0) {
                    this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("myNode").getChildByName("levelSgin").active = true;
                    this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("myNode").getChildByName("levelSgin").getComponent(cc.Sprite).spriteFrame = this.SignAtlas.getSpriteFrame('c' + level);
                } else {
                    this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("myNode").getChildByName("levelSgin").active = false;
                }

                this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("leftNode").active = false;
                if (index > 0) {
                    var strIndex = node.getChildByName("ranknum").getComponent(cc.Label).string;
                    this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("leftNode").getChildByName("ranknum").getComponent(cc.Label).string = index;
                    this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("leftNode").getChildByName("username").getComponent(cc.Label).string = this.rankArr[index - 1].nickname;
                    this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("leftNode").getChildByName("score").getComponent(cc.Label).string = this.rankArr[index - 1].score;
                    this.createImage(this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("leftNode").getChildByName("headimg").getComponent(cc.Sprite), this.rankArr[index - 1].headimg);
                    this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("leftNode").active = true;

                    var level = parseInt(this.rankArr[index - 1].driLevel);
                    if (level != 'NAN' && level > 0) {
                        this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("leftNode").getChildByName("levelSgin").active = true;
                        this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("leftNode").getChildByName("levelSgin").getComponent(cc.Sprite).spriteFrame = this.SignAtlas.getSpriteFrame('c' + level);
                    }
                    else {
                        this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("leftNode").getChildByName("levelSgin").active = false;
                    }
                }

                this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("rightNode").active = false;
                if (index < this.rankArr.length - 1) {
                    var strIndex = node.getChildByName("ranknum").getComponent(cc.Label).string;
                    this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("rightNode").getChildByName("ranknum").getComponent(cc.Label).string = index + 2;
                    this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("rightNode").getChildByName("username").getComponent(cc.Label).string = this.rankArr[index + 1].nickname;
                    this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("rightNode").getChildByName("score").getComponent(cc.Label).string = this.rankArr[index + 1].score;
                    this.createImage(this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("rightNode").getChildByName("headimg").getComponent(cc.Sprite), this.rankArr[index + 1].headimg);
                    this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("rightNode").active = true;

                    var level = parseInt(this.rankArr[index + 1].driLevel);
                    if (level != 'NAN' && level > 0) {
                        this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("rightNode").getChildByName("levelSgin").active = true;
                        this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("rightNode").getChildByName("levelSgin").getComponent(cc.Sprite).spriteFrame = this.SignAtlas.getSpriteFrame('c' + level);
                    }
                    else {
                        this.node.getChildByName("MYPHB").getChildByName("rootNode").getChildByName("rightNode").getChildByName("levelSgin").active = false;
                    }
                }
            }

        }
        //}

        //rankArr = null;

    },

    showFriendRank() {
        var self = this;
        var scorekey = self.getCurWeekScoreValue();
        wx.getFriendCloudStorage({
            keyList: [scorekey, 'driLevel'],
            success: function (res) {
                // 转发成功          
                //self.addRank(res.data);
                // console.error(res);
                this.rankArr.splice(0, this.rankArr.length);
                for (var index = 0; index < res.data.length; ++index) {
                    var openid = res.data[index].openid;
                    var nickname = res.data[index].nickname;
                    var headimg = this.packHeadImg(res.data[index].avatarUrl);
                    var score = '0';
                    var driLevel = '0';
                    if (!this.IsEmpty(res.data[index].KVDataList)) {
                        for (var num = 0; num < res.data[index].KVDataList.length; ++num) {
                            if (res.data[index].KVDataList[num].key == 'driLevel') {
                                driLevel = res.data[index].KVDataList[num].value;
                            } else {
                                score = res.data[index].KVDataList[num].value;
                            }
                        }
                        if (res.data[index].KVDataList.length == 2) {
                            this.rankArr.push({ openid: openid, nickname: nickname, headimg: headimg, score: score, driLevel: driLevel });
                        }
                    }
                }
                this.bubbleSort(this.rankArr);

                self.addRank(/*res.data*/);
            }.bind(this),
            fail: function (res) {
                // 转发失败
                // console.error(res);
            },
            complete: function (res) {
                // console.error(res);
            }
        })
    },

    isMySelf: function (strAvt) {
        return this.userhead == strAvt;
    },

    GetUserHead() {
        var self = this;
        wx.getUserInfo({
            openIdList: ['selfOpenId'],
            success: function (res) {
                self.userhead = self.packHeadImg(res.data[0].avatarUrl);
            }
        })
    },

    //填充rankList
    fillRankList: function () {
        var self = this;
        var scorekey = self.getCurWeekScoreValue();
        wx.getFriendCloudStorage({
            keyList: [scorekey, 'driLevel'],
            success: function (res) {
                // 转发成功          
                this.rankArr.splice(0, this.rankArr.length);
                for (var index = 0; index < res.data.length; ++index) {
                    var openid = res.data[index].openid;
                    var nickname = res.data[index].nickname;
                    var headimg = this.packHeadImg(res.data[index].avatarUrl);
                    var score = '0';
                    var driLevel = '0';
                    if (!this.IsEmpty(res.data[index].KVDataList)) {
                        for (var num = 0; num < res.data[index].KVDataList.length; ++num) {
                            if (res.data[index].KVDataList[num].key == 'driLevel') {
                                driLevel = res.data[index].KVDataList[num].value;
                            } else {
                                score = res.data[index].KVDataList[num].value;
                            }
                        }
                        if (res.data[index].KVDataList.length == 2) {
                            this.rankArr.push({ openid: openid, nickname: nickname, headimg: headimg, score: score, driLevel: driLevel });
                        }
                    }
                }
                this.bubbleSort(this.rankArr);

                //重置超越index
                this.passIndex = this.rankArr.length - 1;

                //console.log(this.rankArr);
            }.bind(this),
            fail: function (res) {
                // 转发失败
            },
            complete: function (res) {
            }
        })
    },

    //超越提示
    checkPass: function (score) {
        if (this.passIndex >= 0 && score > parseInt(this.rankArr[this.passIndex].score)) {
            this.passNode.getComponent(cc.Animation).play();
            this.node.getChildByName("PassNode").active = true;
            console.log("超越了" + this.rankArr[this.passIndex].nickname);

            this.createImage(this.passNode.getChildByName("PassSprite").getComponent(cc.Sprite), this.rankArr[this.passIndex].headimg);
            this.passIndex--;
        }
    },

    _hide() {
        // let moveTo = cc.moveTo(0.5, 0, 1000);
        // this.display.runAction(moveTo);
    },

    getCurWeekScoreValue() {
        return this.getNowFormatDate();
    },

    getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        // var month = date.getMonth() + 1;
        // if (month >= 1 && month <= 9) {
        // 	month = "0" + month;
        // }
        var week = this.Getweek();
        var currentdate = year + seperator1 + week;
        return currentdate;
    },

    // getNowFormatDate() {
    //     var date = new Date();
    //     var seperator1 = "-";
    //     var year = date.getFullYear();
    //     var month = date.getMonth() + 1;
    //     if (month >= 1 && month <= 9) {
    //         month = "0" + month;
    //     }
    //     var week = this.getMonthWeek();
    //     var currentdate = year + seperator1 + month + seperator1 + week;
    //     return currentdate;
    // },

    getMonthWeek() {
        var date = new Date(),
            w = date.getDay(),
            d = date.getDate();
        return Math.ceil(
            (d + 7 - w) / 7
        );
    },

    Getweek(dateString) {
        var da = '';
        if (dateString == undefined) {
            var now = new Date();
            var now_m = now.getMonth() + 1;
            now_m = (now_m < 10) ? '0' + now_m : now_m;
            var now_d = now.getDate();
            now_d = (now_d < 10) ? '0' + now_d : now_d;
            da = now.getFullYear() + '-' + now_m + '-' + now_d;
        } else {
            da = dateString; //日期格式2015-12-30
        }
        var date1 = new Date(da.substring(0, 4), parseInt(da.substring(5, 7)) - 1, da.substring(8, 10)); //当前日期
        var date2 = new Date(da.substring(0, 4), 0, 1); //1月1号
        //获取1月1号星期（以周一为第一天，0周一~6周日）
        var dateWeekNum = date2.getDay() - 1;
        if (dateWeekNum < 0) {
            dateWeekNum = 6;
        }
        if (dateWeekNum < 4) {
            //前移日期
            date2.setDate(date2.getDate() - dateWeekNum);
        } else {
            //后移日期
            date2.setDate(date2.getDate() + 7 - dateWeekNum);
        }
        var d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);
        var year = date1.getFullYear();
        var week = Math.ceil((d + 1) / 7);
        return week;
    },

    IsEmpty(obj) {//判断是否为空
        if (typeof obj == "undefined" || obj == null || obj == "") {
            return true;
        } else {
            return false;
        }
    },
    // update (dt) {},
});
