import { _decorator, Component, Event, Node } from "cc";
import BaseUI from "../../scripts/base/BaseUI";
import { ScrollView } from "cc";
import UserM, { GoodInfo } from "../../scripts/api/UserM";
import { instantiate } from "cc";
import { RewardItem } from "../item/RewardItem";
import { OnItemClick } from "../item/RewardItem";
import { RewardLayer } from "../layer/RewardLayer";
import { Tips } from "../../scripts/mgr/Tips";
import ConfigM, { Config } from "../../scripts/api/ConfigM";

import ItemsM from "../../scripts/mgr/ItemsM";
import ShopM from "../../scripts/api/ShopM";
import EV, { EV_TYPE } from "../../scripts/mgr/EV";
import { CommonTabsTitle } from "../common/CommonTabsTitle";
const { ccclass, property } = _decorator;

@ccclass("PageStorage")
export class PageStorage extends BaseUI {
  protected onLoad(): void {
    super.onLoad();

    this.getComponentInChildren(CommonTabsTitle).init(["STORAGE"], this.onTabClick.bind(this));

    
    EV.ins.on(
      EV_TYPE.USER_GOOD_REFRESH,
      this.onUserGoodRefresh.bind(this),
      this
    );
  }

  onUserGoodRefresh() {
    this.init();
  }

  onItemClick(item: GoodInfo): void {
    //  RewardLayer.mock()

    if (!ConfigM.ins.GoodIsBox(item.id)) {
      Tips.show("" + ConfigM.ins.getGoodName(item.id));
      return;
    }

    this.openBox(item);
  }

  private async openBox(item: GoodInfo) {
    let num = 1;
    if (item.count >= 10) {
      num = 10;
    }  

    let result = await ShopM.ins.openBox(item.id, num);
    if (result) {
      ItemsM.ins.itemChange(result.changeList, result.goodList);
      // this.init();
    }
  }

  public onShow(): void {
    this.init();
  }

  onTabClick(index: number) {
    this.init();
  }

  async init() {
    let self = this;
    let tpl = this.FindNode("RewardItem");

    tpl.active = false;
    let scrollView = this.FindAs("ScrollView", ScrollView);
    scrollView.content.removeAllChildren();
    let list = await UserM.ins.getDisPlayGoods();

    if (list.length == 0) {
      this.FindNode("NoData").active = true;
      return;
    }

    this.FindNode("NoData").active = false;

    for (let i = 0; i < list.length; i++) {
      let item = instantiate(tpl);
      item.active = true;
      item.parent = scrollView.content;
      item
        .getComponent(RewardItem)
        .init(0, list[i], self.onItemClick.bind(self));
    }
  }
}
