import { _decorator, Component, Node } from "cc";
import BaseUI from "../../scripts/base/BaseUI";
import { Hall } from "../hall/Hall";
import RechargeM, { RechargeHistoryItem } from "../../scripts/api/RechargeM";
import { ScrollView } from "cc";
import { instantiate } from "cc";
import { HistoryItem } from "./HistoryItem";
const { ccclass, property } = _decorator;

@ccclass("HistoryRecharge")
export class HistoryRecharge extends BaseUI {
  static async show() {
    let layer = await Hall.ins.showLayer("prefab/layer/HistoryRecharge");
    layer.getComponent(HistoryRecharge).init();
  }

  private tpl: Node;
  private scrollView: ScrollView;
  async init() {
    this._page = 0;
    this.requestData();
  }

  protected onLoad(): void {
    super.onLoad();
    this.tpl = this.FindNode("HistoryItem");
    this.scrollView = this.FindAs("ScrollView", ScrollView);

    this.FindNode("btn_more").active = false;
    this.FindNode("NoData").active = false;
    this.tpl.active = false;
  }
  private _page: number = 1;

  async requestData() {
    this._page++;

    let list: RechargeHistoryItem[] = await RechargeM.ins.getHistoryRecharge(
      this._page
    );

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

    for (let i = 0; i < list.length; i++) {
      let newItem = instantiate(this.tpl);
      newItem.active = true;
      let data = list[i];
      let desc = data.productDesc;
      let valueString = data.amount + " " + data.currency;
      let time = data.createTime;
      newItem.parent = this.scrollView.content;

      newItem.getComponent(HistoryItem).init(desc, valueString, time);
    }

    let more = this.FindNode("btn_more");

    more.setSiblingIndex(this.scrollView.content.children.length - 1);

    more.active = list.length > 0;
  }

  protected simpleOnBtnClick(name: string): void {
    switch (name) {
      case "btn_more":
        this.requestData();
        break;
    }
  }
}
