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


cc.Class({
    extends: cc.Component,

    properties: {

        bgSprite: cc.Sprite,

        headSprite: cc.Sprite,
        nickLabel: cc.Label,
        starCountLabel: cc.Label,
        genderIcon: cc.Sprite,

        _itemId: 0,

        titleLabel: cc.Label,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this.titleLabel.node.opacity = 0;
    },

    /**
     * gender  [int]
     * head    [string]
     * nick    [string]
     * stars   [int]
     * uid     [int]
     * */
    updateItem(userInfo, itemId) {

        this._itemId = itemId;

        this.user = userInfo;
        //昵称
        this.nickLabel.string = userInfo.nickname;
        //头像
        this.createImageFromUrl(userInfo.avatarUrl, (spriteFrame) => {
            this.headSprite.spriteFrame = spriteFrame;
        }, () => {

        });

        let value = JSON.parse(userInfo.KVDataList[0].value);

        // 性别
        let genderPath = value.gender == 0 ? './icon_female' : './icon_male';
        cc.loader.loadRes(genderPath, cc.SpriteFrame, (err, spriteFrame) => {
            this.genderIcon.spriteFrame = spriteFrame;
        });

        //艺人头衔
        this.titleLabel.string = value.jobName;

        //星星数量
        this.starCountLabel.string = value.wxgame.score;
    },

    start() {

    },

    createImageFromUrl(avatarUrl, success, fail) {

        var index = avatarUrl.indexOf('https:');
        var httpIndex = avatarUrl.indexOf('http:');
        if (index === 0 || httpIndex === 0) {
            //以'https:'开头

        } else {
            avatarUrl = 'https:' + avatarUrl;
        }
        if (window.wx != undefined) {
            try {
                let image = wx.createImage();
                image.onload = () => {
                    try {
                        let texture = new cc.Texture2D();
                        texture.initWithElement(image);
                        texture.handleLoadedTexture();
                        success(new cc.SpriteFrame(texture))
                    } catch (e) {
                        cc.log(e);
                        fail();
                    }
                };
                image.src = avatarUrl;
            } catch (e) {
                cc.log(e);
                fail();
            }
        } else {
            cc.loader.load({
                url: avatarUrl, type: 'jpg'
            }, (err, texture) => {
                if (err === undefined || err === null) {
                    success(new cc.SpriteFrame(texture));
                } else {
                    fail();
                }
            });
        }
    }

    // update (dt) {},
});
