import { _decorator, Component, Node } from "cc";
import BaseUI from "../../scripts/base/BaseUI";
import { Hall } from "../hall/Hall";
import AB from "../../scripts/base/AB";
import { ScrollView } from "cc";
import { instantiate } from "cc";
import { CommonTabsTitle, OnTabClickListener } from "../common/CommonTabsTitle";
import {
  ManagePlayerItem,
  ManagePlayerItemData,
  ManagePlayerItemType,
} from "./ManagePlayerItem";
import UserM from "../../scripts/api/UserM";
import FamilyM, {
  FamilyInfo,
  FamilyJoinPlayer,
  FamilyMember,
} from "../../scripts/api/FamilyM";
const { ccclass, property } = _decorator;

@ccclass("MemberManager")
export class MemberManager extends BaseUI implements OnTabClickListener {
  static async show(data: FamilyInfo) {
    let page = await Hall.ins.showLayer("prefab/family/MemberManager");
    page.getComponent(MemberManager).init(data);
  }
  private _data: FamilyInfo;
  init(data: FamilyInfo) {
    this._data = data;
    this.onTabClick(MemberManager.TAB_APPROVE);
  }

  private static readonly TAB_MEMBERS = 0;
  private static readonly TAB_APPROVE = 1;

  private _tabs: CommonTabsTitle = null!;
  protected onLoad(): void {
    super.onLoad();

    this._tabs = this.getComponentInChildren(CommonTabsTitle);
    this._tabs.init(["MEMBERS", "APPROVE"], this);
  }

  onTabClick(index: number) {
    this._tabs.setSelect(index);

    let list = [];

    if (index == MemberManager.TAB_APPROVE) {
      this.requestData(ManagePlayerItemType.APPROVE);
    } else if (index == MemberManager.TAB_MEMBERS) {
      this.requestData(ManagePlayerItemType.MEMBERS);
    }
  }

  async requestData(type: ManagePlayerItemType) {
    let r = await AB.ins.loadPrefab("prefab/family/ManagePlayerItem");
    let scrollView = this.FindAs("ScrollView", ScrollView);
    scrollView.content.removeAllChildren();

    let list = [];
    if (type == ManagePlayerItemType.APPROVE) {
      list = await FamilyM.ins.familyRequestList(UserM.ins.getFamilyId());
    } else if (type == ManagePlayerItemType.MEMBERS) {
      list = await FamilyM.ins.familyMemberList(UserM.ins.getFamilyId());
    }

    this.FindNode("NoData").active = !list || list.length == 0;

    for (let i = 0; i < list.length; i++) {
      let item = instantiate(r);
      item.parent = scrollView.content;
      let itemData: any = list[i];
      let data = new ManagePlayerItemData();
      data.type = type;
      data.userId = itemData.userId;
      data.userName = itemData.userName;
      data.reason = itemData.reason;
      data.status = itemData.status;
      data.totalXp = itemData.totalXp;
      data.dailyXp = itemData.dailyXp;
      item.getComponent(ManagePlayerItem).init(type, data, this._data);
    }
  }
}
