const ListViewAdapter = require('./ListViewAdpater');
cc.Class({
    extends: cc.Component,

    properties: {
        scrollView: cc.ScrollView,
        content: cc.Node,
        prefabRankItem: cc.Prefab,


        // prefabGameOverRank: cc.Prefab,
        // gameOverRankLayout: cc.Node,
        current: 0,
        users: [],
        spacing: 0,
        loadingLabel: cc.Label,
    },

    onLoad() {
        console.log('onLoad------------------------------------------------------------');

        this.listAdapter = new ListViewAdapter(this.scrollView);
    },

    start() {
        this.removeChild();
        if (window.wx != undefined) {
            window.wx.onMessage(data => {
                console.log("接收主域发来消息：", data)
                if (data.messageType == 0) {//移除排行榜
                    this.removeChild();
                } else if (data.messageType == 1) {//获取好友排行榜
                    this.fetchFriendData(data.key1);
                } else if (data.messageType == 3) {//提交得分
                    this.submitScore(data.key1, data.stars);
                } else if (data.messageType == 4) {//获取好友排行榜横向排列展示模式
                    this.gameOverRank(data.key1);
                } else if (data.messageType == 5) {//获取群排行榜
                    this.fetchGroupFriendData(data.key1, data.shareTicket);
                } else if (data.messageType == 6) {
                    this.previousPage();
                } else if (data.messageType == 7) {
                    this.nextPage();
                }
            });
        } else {
            this.fetchFriendData(1000);
        }
    },


    // 开放数据域 KVData 以key/value形式保存
    // 以下为本项目value格式，转为string之后才能提交
    //  {
    //        
    //     "wxgame": {//wxgame 字段是微信要求保留的字段，这样才能在微信小游戏中心显示好友排行榜（其实目前看来这个功能不是十分重要）
    //           "score":16, // 好友星星数量，即等级展示
    //           "update_time": 1513080573   //数据提交的时间戳
    //     },
    //     "gender":0,   //0代表女性，1代表男性
    //     "jobName":"国际巨星" //好友的艺人头衔
    //   }

    submitScore(key1, score, gender, jobName) { //提交得分
        if (window.wx != undefined) {
            window.wx.getUserCloudStorage({
                // 以key/value形式存储
                keyList: [key1],
                success: function (getres) {
                    if (getres.KVDataList.length != 0) {
                        let preScore = JSON.parse(getres.KVDataList[0].value).wxgame.score;
                        if (preScore > score) {
                            return;
                        }
                    }
                    // 对用户托管数据进行写数据操作

                    let myValue = {
                        wxgame: {
                            score: score,
                            update_time: Date.parse(new Date()) / 1000
                        },
                        gender: gender,
                        jobName: jobName
                    }

                    let valueString = JSON.stringify(myValue);

                    window.wx.setUserCloudStorage({
                        KVDataList: [{ key: key1, value: valueString }],
                        success: function (res) {
                            console.log('setUserCloudStorage', 'success', res)
                        },
                        fail: function (res) {
                            console.log('setUserCloudStorage', 'fail')
                        },
                        complete: function (res) {
                        }
                    });
                },
                fail: function (res) {
                    console.log('getUserCloudStorage', 'fail')
                },
                complete: function (res) {

                }
            });
        } else {
            cc.log("提交得分:" + key1 + " : " + score)
        }
    },

    removeChild() {
        this.content.removeAllChildren();
    },

    fetchFriendData(key1) {
        this.loadingLabel.node.active = true;
        this.loadingLabel.node.string = '加载中...';
        this.current = 0;
        if (window.wx != undefined) {
            wx.getUserInfo({
                openIdList: ['selfOpenId'],
                success: (userRes) => {
                    console.log('success', userRes.data)
                    let userData = userRes.data[0];
                    //取出所有好友数据
                    wx.getFriendCloudStorage({
                        keyList: [key1],
                        success: res => {
                            console.log("wx.getFriendCloudStorage success", res);
                            let data = res.data;
                            data.sort((a, b) => {
                                if (a.KVDataList.length == 0 && b.KVDataList.length == 0) {
                                    return 0;
                                }
                                if (a.KVDataList.length == 0) {
                                    return 1;
                                }
                                if (b.KVDataList.length == 0) {
                                    return -1;
                                }
                                let b_score = JSON.parse(b.KVDataList[0].value).wxgame.score;
                                let a_score = JSON.parse(a.KVDataList[0].value).wxgame.score;
                                return b_score - a_score;
                            });

                            this.users = data;

                            this.listAdapter.updateItems(this.users, this.prefabRankItem, 'WechatFriendListItem');
                            this.loadingLabel.node.active = false;
                        },
                        fail: res => {
                            console.log("wx.getFriendCloudStorage fail", res);
                            this.loadingLabel.string = "数据加载失败，请检测网络，谢谢。";
                        },
                    });
                },
                fail: (res) => {
                    this.loadingLabel.string = "数据加载失败，请检测网络，谢谢。";
                }
            });
        }
    },

    previousPage() {
        if (this.current > 0) {
            let start = this.current - 5;
            this.current = start;
            this.notifyData();
        } else {
            // wx.showToast({
            //     title:'已经是第一页了～'
            // }) 
        }
    },

    nextPage() {
        let start = this.current + 5;
        if (start >= this.users.length) {
            if (this.hasMore) {
                this.getTotalRank();
            } else {
                // wx.showToast({
                //     title:'没有下一页了～'
                // })
            }
        } else {
            this.current = start;
            this.notifyData();
        }
    },

    fetchGroupFriendData(key1, shareTicket) {
        this.removeChild();
        if (window.wx != undefined) {
            wx.getUserInfo({
                openIdList: ['selfOpenId'],
                success: (userRes) => {
                    console.log('success', userRes.data)
                    let userData = userRes.data[0];
                    //取出所有好友数据
                    wx.getGroupCloudStorage({
                        shareTicket: shareTicket,
                        keyList: [key1],
                        success: res => {
                            console.log("wx.getGroupCloudStorage success", res);
                            this.loadingLabel.active = false;
                            let data = res.data;
                            data.sort((a, b) => {
                                if (a.KVDataList.length == 0 && b.KVDataList.length == 0) {
                                    return 0;
                                }
                                if (a.KVDataList.length == 0) {
                                    return 1;
                                }
                                if (b.KVDataList.length == 0) {
                                    return -1;
                                }
                                return b.KVDataList[0].value - a.KVDataList[0].value;
                            });
                            for (let i = 0; i < data.length; i++) {
                                var playerInfo = data[i];
                                var item = cc.instantiate(this.prefabRankItem);
                                item.getComponent('RankItem').init(i, playerInfo);
                                item.getComponent('RankItem').isSelf = false;
                                this.content.addChild(item);
                                if (data[i].avatarUrl == userData.avatarUrl) {
                                    let userItem = cc.instantiate(this.prefabRankItem);
                                    userItem.getComponent('RankItem').isSelf = true;
                                    userItem.getComponent('RankItem').init(i, playerInfo);
                                    userItem.y = -354;
                                    this.node.addChild(userItem, 1, 1000);
                                }
                            }
                        },
                        fail: res => {
                            console.log("wx.getFriendCloudStorage fail", res);
                            this.loadingLabel.string = "数据加载失败，请检测网络，谢谢。";
                        },
                    });
                },
                fail: (res) => {
                    this.loadingLabel.string = "数据加载失败，请检测网络，谢谢。";
                }
            });
        }
    },

    gameOverRank(key1) {
        this.removeChild();
        this.gameOverRankLayout.active = true;
        if (window.wx != undefined) {
            wx.getUserInfo({
                openIdList: ['selfOpenId'],
                success: (userRes) => {
                    cc.log('success', userRes.data)
                    let userData = userRes.data[0];
                    //取出所有好友数据
                    wx.getFriendCloudStorage({
                        keyList: [key1],
                        success: res => {
                            cc.log("wx.getFriendCloudStorage success", res);
                            this.loadingLabel.active = false;
                            let data = res.data;
                            data.sort((a, b) => {
                                if (a.KVDataList.length == 0 && b.KVDataList.length == 0) {
                                    return 0;
                                }
                                if (a.KVDataList.length == 0) {
                                    return 1;
                                }
                                if (b.KVDataList.length == 0) {
                                    return -1;
                                }
                                return b.KVDataList[0].value - a.KVDataList[0].value;
                            });
                            for (let i = 0; i < data.length; i++) {
                                if (data[i].avatarUrl == userData.avatarUrl) {
                                    if ((i - 1) >= 0) {
                                        if ((i + 1) >= data.length && (i - 2) >= 0) {
                                            let userItem = cc.instantiate(this.prefabGameOverRank);
                                            userItem.getComponent('GameOverRank').init(i - 2, data[i - 2]);
                                            this.gameOverRankLayout.addChild(userItem);
                                        }
                                        let userItem = cc.instantiate(this.prefabGameOverRank);
                                        userItem.getComponent('GameOverRank').init(i - 1, data[i - 1]);
                                        this.gameOverRankLayout.addChild(userItem);
                                    } else {
                                        if ((i + 2) >= data.length) {
                                            let node = new cc.Node();
                                            node.width = 200;
                                            this.gameOverRankLayout.addChild(node);
                                        }
                                    }
                                    let userItem = cc.instantiate(this.prefabGameOverRank);
                                    userItem.getComponent('GameOverRank').init(i, data[i], true);
                                    this.gameOverRankLayout.addChild(userItem);
                                    if ((i + 1) < data.length) {
                                        let userItem = cc.instantiate(this.prefabGameOverRank);
                                        userItem.getComponent('GameOverRank').init(i + 1, data[i + 1]);
                                        this.gameOverRankLayout.addChild(userItem);
                                        if ((i - 1) < 0 && (i + 2) < data.length) {
                                            let userItem = cc.instantiate(this.prefabGameOverRank);
                                            userItem.getComponent('GameOverRank').init(i + 2, data[i + 2]);
                                            this.gameOverRankLayout.addChild(userItem);
                                        }
                                    }
                                }
                            }
                        },
                        fail: res => {
                            console.log("wx.getFriendCloudStorage fail", res);
                            this.loadingLabel.string = "数据加载失败，请检测网络，谢谢。";
                        },
                    });
                },
                fail: (res) => {
                    this.loadingLabel.string = "数据加载失败，请检测网络，谢谢。";
                }
            });
        }
    },
});
