import { _decorator, Component, Node } from "cc";
import BaseUI from "../../scripts/base/BaseUI";
import { ScrollView } from "cc";

import EV, { EV_TYPE } from "../../scripts/mgr/EV";
import UserM from "../../scripts/api/UserM";
import AB from "../../scripts/base/AB";
import { instantiate } from "cc";
import { FamilyPageHas } from "../family/FamilyPageHas";
import { Vec2 } from "cc";

const { ccclass, property } = _decorator;

@ccclass("PageFamily")
export class PageFamily extends BaseUI {
  private _scrollView: ScrollView;
  onLoad(): void {
    super.onLoad();
   
    this._scrollView = this.FindAs("ScrollView", ScrollView);
    EV.ins.on(
      EV_TYPE.FAMILY_STATUS_UPDATE,
      this.onFamilyStatusUpdate.bind(this),
      this
    );
    EV.ins.on(
      EV_TYPE.FAMILY_SEARCH_RESULT,
      this.onFamilySearchResult.bind(this),
      this
    );
  }

  protected onDestroy(): void {
    EV.ins.off(
      EV_TYPE.FAMILY_STATUS_UPDATE,
      this.onFamilyStatusUpdate.bind(this),
      this
    );
    EV.ins.off( 
      EV_TYPE.FAMILY_SEARCH_RESULT,
      this.onFamilySearchResult.bind(this),
      this
    );
  }

  private onFamilySearchResult() {
    setTimeout(() => {
      this._scrollView.scrollToOffset(new Vec2(0, 500), 0.3);
    }, 300);
  }

  private onFamilyStatusUpdate() {
    this.refresh();
  }

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

  async refresh() {
    console.error("refresh", new Date().getTime());
    let familyId = UserM.ins.getFamilyId();
    let hasFamily = familyId != null && familyId.length > 0;
    // this.FindNode("FamilyPageHas").active = hasFamily;
    // this.FindNode("FamilyPageNo").active = !hasFamily;

    this._scrollView.content.removeAllChildren();
    let path = hasFamily
      ? "prefab/family/FamilyPageHas"
      : "prefab/family/FamilyPageNo";
    let showPagePrefab = await AB.ins.loadPrefab(path);
    let page = instantiate(showPagePrefab);
    this._scrollView.content.addChild(page);
    if (hasFamily) {
      page.getComponent(FamilyPageHas).onShow();
    }
  }
}
