import i18n from "../../../i18n/i18n";
import { GameViewType } from "../../../main/ViewManage";
import ViewObject from "../../../main/ViewObject";
import { HttpStateType, ReveData } from "../../../util/CHttp";
import GoodItem from "../../common/GoodItem";
import MagicBoxItem from "./MagicBoxItem";
import MagicBoxRewardView from "./MagicBoxRewardView";

/**
 * 魔盒详细说明查看
 */
const {ccclass, property} = cc._decorator;

@ccclass
export default class MagicBoxInfoView extends ViewObject {

    @property(cc.Label)
    mName: cc.Label = null;

    @property(cc.Label)
    mAbout: cc.Label = null;

    @property(cc.Node)
    mContent: cc.Node = null;

    @property(cc.Prefab)
    mGoodItem: cc.Prefab = null;

    @property(cc.Sprite)
    mIcon: cc.Sprite = null;

    @property(cc.Label)
    mCount: cc.Label = null;

    public boxItem:MagicBoxItem

    public init(boxItem:MagicBoxItem){
        this.boxItem = boxItem
        let _magicBox = boxItem._magicBox
        this.mName.string = i18n.t(_magicBox.name)
        this.mAbout.string = i18n.t(_magicBox.about)
        cc.resources.load('icon/magic_box/'+_magicBox.icon,
        cc.SpriteFrame,
        (err, spriteFrame:cc.SpriteFrame) =>{
           if(err){
               cc.error(err);
           }else{
              this.mIcon.spriteFrame = spriteFrame;
           }
        });

        let rewardList = this.main.sManage.getRewardViews(_magicBox.list)

        for (let i = 0; i < rewardList.length && i < 5; i++) {
            const element = rewardList[i];
            let node = cc.instantiate(this.mGoodItem)
            let goodItem:GoodItem = node.getComponent(GoodItem)
            goodItem.initReward(this.main,element)
            node.parent = this.mContent
        }
        this.flush()
    }

    public flush(){
        let _magicBox = this.boxItem._magicBox
        let count = this.main.player.getGoodCount(_magicBox.goodId)
        this.mCount.string = count+'/'+_magicBox.goodCount
    }


    public onclickInfo(){
        this.main.viewManage.loadFunc(GameViewType.moheReward,(viewObject:ViewObject)=>{
            let magicBoxInfo = viewObject as MagicBoxRewardView;
            magicBoxInfo.init(this.boxItem)
            viewObject.show();
        });
    }
    public onclickOpen(){
        let msg = {
            id:this.boxItem._magicBox.id
        }
        this.main.gameHttp.sendJson('magicBox/v1/open',msg,(state,reve:ReveData)=>{
            this.main.stopLoad();
            if(state == HttpStateType.SUCCESS){
                if(reve.retCode == 0){
                    this.boxItem.flush()
                    this.flush()
                    this.main.showReward(reve)
                }else{
                    this.main.showTips(reve.message);
                }
            }else{
                this.main.showTips('网络异常');
            }
        });

    }


}
