cc.Class({
    extends: cc.Component,

    properties: {
        content: cc.Node,
        prefab: cc.Prefab,
        GoldBG: cc.SpriteFrame,
        GoldMedal: cc.SpriteFrame,
        SilverMedal: cc.SpriteFrame,
        BronzeMedal: cc.SpriteFrame,
    },

    onLoad() {
        this.nodes = [];
        this.ranklist = cc.find("Canvas/ranklist");
        this.info = cc.find("Canvas/info");
    },
    finished: function () {
        // console.log("动画回调了吗",this.Transcendnode);
        if (this.Transcendnode != null) {
            this.Transcendnode.active = false;
        }
    },

    getFriend: function () {
        this.removeAll();
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            wx.getFriendCloudStorage({
                keyList: ['score'],
                success: function (res) {
                    //添加排行榜为 自己的条目在下面
                    this.testListView(this.initData(res.data));
                    this.addMyItem();
                }.bind(this),
                fail: function (res) {
                    console.error(res);
                }.bind(this)
            });

        } else {
            this.testListView(this.initData(null));
            //添加排行榜为 自己的条目在下面
            this.addMyItem();
        }



    },

    removeAll: function () {
        for (var i = 0; i < this.nodes.length; i++) {
            if (this.nodes[i] != null) {
                this.nodes[i].destroy();
            }
        }
        this.nodes = [];
    },

    //获取到当前名字
    getRanking: function (callback) {
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            wx.getFriendCloudStorage({
                keyList: ['score'],
                success: function (res) {
                    this.initData(res.data, callback);
                }.bind(this),
                fail: function (res) {
                    console.error(res);
                }.bind(this)
            });

        } else {
            this.initData(null, callback);
        }
    },

    initData: function (data, callback) {

        var list = [
            {
                name: "汉堡店",
                id: 9527,
                Price: 100,
                Fluctuate: "15%",
                TotalPossession: 3500
            },
            {
                name: "汉堡店1",
                id: 9527,
                Price: 100,
                Fluctuate: "15%",
                TotalPossession: 3500
            },
            {
                name: "汉堡店3",
                id: 9527,
                Price: 100,
                Fluctuate: "15%",
                TotalPossession: 3500
            },
        ];

        var listdata = [
            {
                id: 2,
                name: "22",
                avatarUrl: "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=607947196,2238683854&fm=26&gp=0.jpg",
                listData: list,
                openId: "oGxOa5bd61v9jI_indIdQtI2T5P8",
                // num : 0
            },
            {
                id: 6,
                name: "22",
                avatarUrl: "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=607947196,2238683854&fm=26&gp=0.jpg",
                listData: list,
                openId: "oGxOa5bjKLaCSbkPev09yVze0WSA",
                // num : 1
            },
            {
                id: 3,
                name: "22",
                avatarUrl: "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=607947196,2238683854&fm=26&gp=0.jpg",
                listData: list,
                openId: "oGxOa5bjKLaCSbkPev09yVze0WSA",
                // num : 2
            },
            {
                id: 3,
                name: "22",
                avatarUrl: "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=607947196,2238683854&fm=26&gp=0.jpg",
                listData: list,
                openId: "oGxOa5bjKLaCSbkPev09yVze0WSA",
                // num : 3
            },
            {
                id: 7,
                name: "汪汪333",
                avatarUrl: "https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eohXLEIOV99ic2JosrQDgIgL4cU4ZlmmvkWzGpygkNV9aEJ6nCC2mVf4kYBDHogNOHgXo2wZhv85jA/132?aa=a.jpg",
                listData: list,
                openId: "oGxOa5SQ1ltBWWsVRirUvXUBGRRY",
                // num : 4
            },
            {
                id: 8,
                name: "汪汪",
                avatarUrl: "https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eohXLEIOV99ic2JosrQDgIgL4cU4ZlmmvkWzGpygkNV9aEJ6nCC2mVf4kYBDHogNOHgXo2wZhv85jA/132?aa=a.jpg",
                listData: list,
                openId: "11",
                // num : 4
            },
            {
                id: 9,
                name: "汪汪",
                avatarUrl: "https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eohXLEIOV99ic2JosrQDgIgL4cU4ZlmmvkWzGpygkNV9aEJ6nCC2mVf4kYBDHogNOHgXo2wZhv85jA/132?aa=a.jpg",
                listData: list,
                openId: "11",
                // num : 4
            },
            {
                id: 10,
                name: "汪汪",
                avatarUrl: "https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eohXLEIOV99ic2JosrQDgIgL4cU4ZlmmvkWzGpygkNV9aEJ6nCC2mVf4kYBDHogNOHgXo2wZhv85jA/132?aa=a.jpg",
                listData: list,
                openId: "11",
                // num : 4
            },

        ]

        if (data != null) {
            listdata = [];
            for (let i = 0; i < data.length; i++) {
                let friendInfo = data[i];
                let nickName = friendInfo.nickname;
                let avatarUrl = friendInfo.avatarUrl + "?aa=a.jpg";
                let ScoreValue = friendInfo.KVDataList[0].value;
                var d = {}
                d.id = parseInt(ScoreValue);
                d.name = nickName;
                d.openId = friendInfo.openid;
                d.avatarUrl = avatarUrl;
                d.listData = list;
                // d.num = i;
                // console.log("每条",d);
                listdata.push(d);
                // if (friendInfo.openid == userData.openId) {
                //     userData.httpData.data.avatarUrl = avatarUrl + "?aa=a.jpg";
                //     userData.httpData.data.nickName = nickName;
                //     userData.httpData.data.id = d.id;
                //     // userData.httpData.data.num = d.num;
                //     console.log('1111=', userData.httpData.data.avatarUrl);
                // }
            }
        }
        var lists = this.getSortArr(listdata);

        //获取自己的排名信息
        for (let index = 0; index < lists.length; index++) {
            const element = lists[index];
            if (element.openId == userData.openId) {
                userData.ranking = index + 1;
                userData.httpData.data.avatarUrl = element.avatarUrl;
                userData.httpData.data.nickName = element.name;
                userData.httpData.data.id = element.id;

                // console.log( element.avatarUrl,'==333=', userData.httpData.data.avatarUrl);
                break;
            }
        }
        if (callback != null) {
            callback(lists);
        }
        return lists;
    },
    getSortArr: function (arr) {
        return arr.sort(this.sortNumberfunction);
    },
    sortNumberfunction: function (a, b) {
        return b.id - a.id;
    },
    addMyItem: function () {
        if (userData.httpData.data.avatarUrl == "")
            return;

        let node = cc.instantiate(this.prefab);
        node.parent = this.node;
        node.y -= 340;
        this.nodes.push(node);
        // // getUserInfo will return the nickName, getFriendCloudStorage will return the nickname.
        let nickName = userData.httpData.data.nickName;
        let avatarUrl = userData.httpData.data.avatarUrl;
        let ScoreValue = userData.httpData.data.id;
        // // console.log("ScoreValue="+ScoreValue);
        let userName = node.getChildByName('userName').getComponent(cc.Label);
        let userIcon = node.getChildByName('mask').getChildByName('userIcon').getComponent(cc.Sprite);
        let Scorelabel = node.getChildByName('Score').getComponent(cc.Label);

        node.getChildByName('ranking').getChildByName('RankText').getComponent(cc.Label).string = userData.ranking;
        console.log('1111=', avatarUrl);
        userName.string = nickName;
        Scorelabel.string = ScoreValue;

        cc.loader.load({ url: avatarUrl, type: 'png' }, (err, texture) => {
            if (err) console.error(err);
            // userIcon.spriteFrame = new cc.SpriteFrame(texture);
            this.setsprite(userIcon, new cc.SpriteFrame(texture));
        });

    },


    setsprite(targetSprite, texture) {
        targetSprite.spriteFrame = texture;
    },


    testListView: function (listdata) {
        for (let i = 0; i < listdata.length; i++) {
            let friendInfo = listdata[i];
            this.createtest(friendInfo, i);
        }
        this.setOnClickItem(function (index) {
            // console.log("条目点击",listdata[index],"点了索引了",index);
            UtilsPrefabs
                .init(this.node.parent)
                .addPrefabs(UtilsPrefabs.PrefabsName[5], null, function (node) {
                    this.initcreateUserInfo(listdata[index], node);
                    var PCloseButton = UtilsPrefabs.getNode("PCloseButton", node);
                    UtilsPrefabs.setOff(PCloseButton);
                    UtilsPrefabs.setOn(PCloseButton, function () {
                        UtilsPrefabs.removePrefabs(this.node.parent, node.name);
                    }.bind(this))

                }.bind(this));

        }.bind(this));


    },
    createtest(user, index) {
        let node = this.createPrefab(index);
        // getUserInfo will return the nickName, getFriendCloudStorage will return the nickname.
        let nickName = user.name;
        let avatarUrl = user.avatarUrl;
        let ScoreValue = user.id;
        // console.log("ScoreValue="+ScoreValue);
        let userName = node.getChildByName('userName').getComponent(cc.Label);
        let userIcon = node.getChildByName('mask').getChildByName('userIcon').getComponent(cc.Sprite);
        let Scorelabel = node.getChildByName('Score').getComponent(cc.Label);
        node.__itemID = index;
        if (userName != null) {
            userName.string = nickName;
        }
        if (Scorelabel != null) {
            Scorelabel.string = ScoreValue;
        }
        console.log('avatarUrl=', avatarUrl);
        // console.log(nickName + '\'s info has been getten.');
        cc.loader.load({
            url: avatarUrl, type: 'png'
        }, (err, texture) => {
            if (err) console.error(err);
            userIcon.spriteFrame = new cc.SpriteFrame(texture);
        });

    },

    Transcendfun: function (a, b) {

        this.Transcendnode = UtilsPrefabs.getNode("Transcend", cc.find("Canvas"));
        this.Transcendnode.active = true;
        this.animCtrl = this.Transcendnode.getComponent("cc.Animation");
        if (a != null && b != null) {
            this.setItemDataA(a);
            this.setItemDataB(b);
        }


        if (this.animCtrl != null) {
            this.animCtrl.play('Transcend');
            this.animCtrl.on('finished', this.finished, this);
        }


    },

    getCurrs: function (x, lists) {
        // console.log("近来数据全不全",x,lists);
        this.ranklist.active = true;
        if (x == null && lists == null) {

            this.initData(null, function (list) {

                var listdata = [];
                for (var i = 0; i < list.length; i++) {
                    if (list[i].openId == userData.openId) {

                        // console.log("我 前面",list[i-1]);
                        // console.log("我 ",list[i]);
                        // console.log("我 后面",list[i+1]);
                        if (list[i - 1] != null) {
                            list[i - 1].num = i;

                        }
                        if (list[i] != null) {
                            list[i].num = i + 1;
                        }
                        if (list[i + 1] != null) {
                            list[i + 1].num = i + 2;
                        }
                        listdata.push(list[i - 1]);
                        listdata.push(list[i]);
                        listdata.push(list[i + 1]);
                        this.setleftmidrightRankListData(listdata);
                    }
                }
            }.bind(this))



        } else {
            // console.log("我在统计数组4",lists);
            var listdata = [];
            for (var i = 0; i < lists.length; i++) {
                if (lists[i].openId == userData.openId) {

                    // console.log("我 前面",lists[i-1]);
                    // console.log("我 ",lists[i]);
                    // console.log("我 后面",lists[i+1]);
                    if (lists[i - 1] != null) {
                        lists[i - 1].num = i;

                    }
                    if (lists[i] != null) {
                        lists[i].num = i + 1;
                    }
                    if (lists[i + 1] != null) {
                        lists[i + 1].num = i + 2;
                    }
                    listdata.push(lists[i - 1]);
                    listdata.push(lists[i]);
                    listdata.push(lists[i + 1]);
                    this.setleftmidrightRankListData(listdata);
                }
            }
        }
    },

    curr: function (data) {
        this.info.active = true;

        let layou = UtilsPrefabs.getNode("layou", this.info);
        let ic = layou.children[1];
        let name = layou.children[2];
        let money = layou.children[3];

        name.getComponent(cc.Label).string = data.name;
        money.getComponent(cc.Label).string = data.id;


        cc.loader.load({
            url: data.avatarUrl, type: 'png'
        }, (err, texture) => {
            if (err) console.error(err);
            ic.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture);
        });


        setTimeout(function () {
            this.info.active = false;
        }.bind(this), 4000)

    },


    setleftmidrightRankListData: function (listdata) {
        // console.log("进来的数据是",listdata);
        this.closeRanklist();
        // console.log("我在统计数组5",listdata);
        this.ranklist.active = true;
        for (var i = 0; i < listdata.length; i++) {
            if (listdata[i] != null) {
                var bg = this.ranklist.getChildByName("bg");
                bg.children[i].active = true;


                let num = UtilsPrefabs.getNode("num", bg.children[i]);
                let ic = UtilsPrefabs.getNode("ic", bg.children[i]);
                let name = UtilsPrefabs.getNode("name", bg.children[i]);
                let money = UtilsPrefabs.getNode("money", bg.children[i]);

                num.getComponent(cc.Label).string = listdata[i].num + "名";
                name.getComponent(cc.Label).string = listdata[i].name;
                money.getComponent(cc.Label).string = listdata[i].id;


                cc.loader.load({
                    url: listdata[i].avatarUrl, type: 'png'
                }, (err, texture) => {
                    if (err) console.error(err);
                    ic.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture);
                });

            }
        }

        this.ranklist.getChildByName("sub").on(cc.Node.EventType.TOUCH_END, function (event) {

            this.closeRanklist();
        }.bind(this));

        setTimeout(function () {
            this.closeRanklist();
        }.bind(this), 5000)

    },

    closeRanklist: function () {
        for (var i = 0; i < this.ranklist.getChildByName("bg").children.length; i++) {
            this.ranklist.getChildByName("bg").children[i].active = false;
        }

        this.ranklist.getChildByName("sub").off(cc.Node.EventType.TOUCH_END);
        this.ranklist.active = false;
    },



    setItemDataA: function (a) {
        let nickName = a.name;
        let avatarUrl = a.avatarUrl;
        let ScoreValue = a.id;
        // console.log("ScoreValue="+ScoreValue);i
        this.Transcendnode = UtilsPrefabs.getNode("Transcend", cc.find("Canvas"));
        this.Other = UtilsPrefabs.getNode("i", this.Transcendnode);
        var block = UtilsPrefabs.getNode("block", this.Other);

        let userName = block.getChildByName('userName').getComponent(cc.Label);
        let userIcon = block.getChildByName('mask').children[0].getComponent(cc.Sprite);
        let Scorelabel = block.getChildByName('Score').getComponent(cc.Label);

        userName.string = nickName;
        Scorelabel.string = ScoreValue;
        // console.log(nickName + '\'s info has been getten.');
        cc.loader.load({
            url: avatarUrl, type: 'png'
        }, (err, texture) => {
            if (err) console.error(err);
            userIcon.spriteFrame = new cc.SpriteFrame(texture);
        });
    },
    setItemDataB: function (b) {
        let nickName = b.name;
        let avatarUrl = b.avatarUrl;
        let ScoreValue = b.id;
        // console.log("ScoreValue="+ScoreValue);
        this.Transcendnode = UtilsPrefabs.getNode("Transcend", cc.find("Canvas"));
        var Other = UtilsPrefabs.getNode("Other", this.Transcendnode);
        var block = UtilsPrefabs.getNode("block", Other);

        let userName = block.getChildByName('userName').getComponent(cc.Label);
        let userIcon = block.getChildByName('mask').children[0].getComponent(cc.Sprite);
        let Scorelabel = block.getChildByName('Score').getComponent(cc.Label);

        userName.string = nickName;
        Scorelabel.string = ScoreValue;
        // console.log(nickName + '\'s info has been getten.');
        cc.loader.load({
            url: avatarUrl, type: 'png'
        }, (err, texture) => {
            if (err) console.error(err);
            userIcon.spriteFrame = new cc.SpriteFrame(texture);
        });
    },




    onClickItem: function () {
    },

    setOnClickItem: function (onClickItem) {
        this.onClickItem = onClickItem;
    },


    createUserBlock(user, index) {
        let node = this.createPrefab(index);
        // getUserInfo will return the nickName, getFriendCloudStorage will return the nickname.
        let nickName = user.nickName ? user.nickName : user.nickname;
        let avatarUrl = user.avatarUrl;
        let ScoreValue = (user.KVDataList)[0].value;
        // console.log("ScoreValue="+ScoreValue);
        let userName = node.getChildByName('userName').getComponent(cc.Label);
        let userIcon = node.getChildByName('mask').children[0].getComponent(cc.Sprite);
        let Scorelabel = node.getChildByName('Score').getComponent(cc.Label);

        userName.string = nickName;
        Scorelabel.string = ScoreValue;
        // console.log(nickName + '\'s info has been getten.');
        cc.loader.load({
            url: avatarUrl, type: 'png'
        }, (err, texture) => {
            if (err) console.error(err);
            userIcon.spriteFrame = new cc.SpriteFrame(texture);
        });
    },
    createPrefab(index) {
        let node = cc.instantiate(this.prefab);
        node.parent = this.content;
        this.nodes.push(node);

        switch (index) {
            case 0:
                node.getComponent(cc.Sprite).spriteFrame = this.GoldBG;
                node.getChildByName('ranking').getChildByName('RankIcon').getComponent(cc.Sprite).spriteFrame = this.GoldMedal;
                break;
            case 1:
                node.getChildByName('ranking').getChildByName('RankIcon').getComponent(cc.Sprite).spriteFrame = this.SilverMedal;
                break;
            case 2:
                node.getChildByName('ranking').getChildByName('RankIcon').getComponent(cc.Sprite).spriteFrame = this.BronzeMedal;
                break;
            default:
                node.getChildByName('ranking').getChildByName('RankText').getComponent(cc.Label).string = index + 1;
        }
        return node;
    },
    initcreateUserInfo: function (listdata, node) {
        cc.loader.loadRes(UtilsPrefabs.PrefabsName[6], function (err, texture) {

            this.itemprefab = cc.instantiate(texture);

            for (let i = 0; i < listdata.listData.length; i++) {
                let info = listdata.listData[i];
                var StockSort = UtilsPrefabs.getNode("StockSort", node);
                var ScrollView = UtilsPrefabs.getNode("ScrollView", StockSort);
                var view = UtilsPrefabs.getNode("view", ScrollView);
                var content = UtilsPrefabs.getNode("content", view);
                this.createUserInfo(info, i, content);
            }
        }.bind(this));

    },
    createUserInfo(user, index, nodes) {
        var itemnode = cc.instantiate(this.itemprefab);
        nodes.addChild(itemnode);

        var Layout = UtilsPrefabs.getNode("Layout", itemnode);

        var Name = UtilsPrefabs.getNode("Name", Layout);
        var Code = UtilsPrefabs.getNode("Code", Layout);
        var Price = UtilsPrefabs.getNode("Price", Layout);
        var Fluctuate = UtilsPrefabs.getNode("Fluctuate", Layout);
        var TotalPossession = UtilsPrefabs.getNode("TotalPossession", Layout);

        Name.getComponent(cc.Label).string = user.name;
        Code.getComponent(cc.Label).string = user.id;
        Price.getComponent(cc.Label).string = user.Price;
        Fluctuate.getComponent(cc.Label).string = user.Fluctuate;
        TotalPossession.getComponent(cc.Label).string = user.TotalPossession;

        // console.log("来了吗",user,index,nodes);

    },

});
