const StarApi = require('../net/StarApi');

cc.Class({
    extends: cc.Component,

    properties: {
        //
        starItemPrefab: cc.Prefab,

        starLayout: cc.Layout,

        //
        progressBar: cc.ProgressBar,
        countLabel: cc.Label,
        // percentLabel: cc.Label,
        percentRichText: cc.RichText,

        //
        descNode: cc.Node,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        GameEvent.on('show_star_desc', this, (starInfo) => {
            this.showDescView(starInfo);
        });
    },

    onDestroy() {
        GameEvent.off('show_star_desc', this);
    },

    start () {
        this.getAllStars().then((respondData) => {
            console.log(respondData);
            this.configData(respondData);
        }).catch((code) => {
            console.log(code);
        });
    },

    /// 网络请求
    getAllStars() {
        return new Promise((resolve, reject) => {
            // 获取目标用户的建筑
            StarApi.getAllStars((respondData) => {
                resolve(respondData);
            }, (code) => {
                reject(code);
            });
        })
    },

    configData(respondData) {
        this.respondData = respondData;

        if (respondData.userStars.length > 0) {
            var isUnlockedCount = 0;
            for (let i = 0; i < respondData.userStars.length; ++i) {
                let star = respondData.userStars[i];
                let item = cc.instantiate(this.starItemPrefab);
                item = item.getComponent('StarHandbookItem');
                item.configData(star);
                this.starLayout.node.addChild(item.node);
                if (star.starCount > 0) {
                    isUnlockedCount++;
                }
            }

            let totalCount = respondData.userStars.length;
            this.countLabel.string = `${isUnlockedCount}/${totalCount} 已收集的明星`;
            let percent = (isUnlockedCount/totalCount * 100).toFixed(2);
            // this.percentLabel.string = `${percent}%`;
            this.percentRichText.string = `<b><outline color=#3d2e1d width=2><color=#FFD800 >${percent}%</color></outline></b>`;
        }
    },

    closeView() {
        this.node.destroy();
    },

    //显示描述信息
    showDescView(starInfo) {
        this.descNode.active = true;

        this.descNode.getComponent('StarHandbookDesc').configData(starInfo);
    },

    closeDescView() {
        this.descNode.active = false;
    },

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