import { _decorator, Component, Node, Animation } from "cc";
import BaseUI from "../../scripts/base/BaseUI";
import { MemberManager } from "./MemberManager";
import { InputNameLayer } from "./InputNameLayer";
import EV, { EV_TYPE } from "../../scripts/mgr/EV";
import AB from "../../scripts/base/AB";
import { instantiate } from "cc";
import { RankPlayerDto } from "../../scripts/api/RankM";
import { RankPlayerItem } from "../item/RankPlayerItem";
import { FamilyMemberItem } from "./FamilyMemberItem";
import PayM from "../../scripts/mgr/PayM";
import { Label } from "cc";
import ShareM from "../../scripts/mgr/ShareM";
import { Tips } from "../../scripts/mgr/Tips";
import FamilyM, { FamilyInfo, FamilyMember } from "../../scripts/api/FamilyM";
import UserM from "../../scripts/api/UserM";
import Utils from "../../scripts/utils/Utils";
import { TipsData, TipsLayer } from "../layer/TipsLayer";
import { GoodsId } from "../../scripts/api/GoodsId";
import { HelpImage, HelpType } from "../layer/HelpImage";
const { ccclass, property } = _decorator;

@ccclass("FamilyPageHas")
export class FamilyPageHas extends BaseUI {
  private _data: FamilyInfo;

  async editFamilyNotice() {
    let notice = await InputNameLayer.show(100);
    if (notice == null) {
      return;
    }
    let familyId = UserM.ins.getFamilyId();
    if (familyId == null || familyId.length == 0) {
      return;
    }
    let result = await FamilyM.ins.editFamilyNotice(familyId, notice);
    if (!result) {
      return;
    }

    Tips.show("Success");

    this.setText("lbl_my_family_notice", notice);
  }

  onShow() {
    this.staticUI();
    this.familyInfo();
    setTimeout(() => {
      this.showMembers();
    }, 1000);
  }
  staticUI() {
    this.setText(
      "lbl_family_tips_member",
      Utils.setI18nLabel("Family.FamilyMemberBenefits")
    );
    this.setText(
      "lbl_family_tips_owner",
      Utils.setI18nLabel("Family.FamilyOwnerBenefits")
    );
  }

  private icon_family_pog_owner: Node;
  private icon_family_pog_owner_anim: Node;
  private icon_family_box: Node;
  private icon_family_box_anim: Node;

  protected onLoad(): void {
    super.onLoad();
    this.FindNode("owner_manage_node").active = false;
    this.FindNode("lbl_new_approve_node").active = false;

    this.icon_family_pog_owner = this.FindNode("icon_family_pog_owner");
    this.icon_family_pog_owner_anim = this.FindNode(
      "icon_family_pog_owner_anim"
    );
    this.icon_family_box = this.FindNode("icon_family_box");
    this.icon_family_box_anim = this.FindNode("icon_family_box_anim");

    EV.ins.on(EV_TYPE.FAMILY_DATA_UPDATE, this.familyInfo.bind(this), this);
    EV.ins.on(EV_TYPE.FAMILY_MEMBER_UPDATE, this.showMembers.bind(this), this);
    EV.ins.on(EV_TYPE.FAMILY_MEMBER_UPDATE, this.ownerUI.bind(this), this);
  }

  protected onDestroy(): void {
    EV.ins.off(EV_TYPE.FAMILY_DATA_UPDATE, this.familyInfo.bind(this), this);
    EV.ins.off(EV_TYPE.FAMILY_MEMBER_UPDATE, this.showMembers.bind(this), this);
    EV.ins.off(EV_TYPE.FAMILY_MEMBER_UPDATE, this.ownerUI.bind(this), this);
  }

  async familyUI() {
    let result = this._data;
    this.setText(
      "lbl_family_pog",
      Utils.formatNumber(Number(result.dailyPog), 1)
    );

    this.setText(
      "lbl_family_exp",
      Utils.formatNumber(Number(result.xp), 0) + "/100"
    );

    this.setText(
      "lbl_family_game_pass_count",
      Utils.formatNumber(Number(result.seasonPassGame), 0)
    );

    this.setText(
      "lbl_people_count",
      `${result.memberSize}/${result.totalSize}`
    );

    this.setText("lbl_my_family_name", result.familyName);
    this.setText("lbl_my_family_owner_name", result.ownerDto?.ownerName);
    this.setText("lbl_my_family_notice", result.notice);

    this.setText(
      "lbl_family_reward_box_count",
      "x" + Utils.formatNumber(Number(result.boxCount), 0)
    );

    let showBoxAnim = result.boxCount > 0;
    // showBoxAnim = true;
    this.icon_family_box.active = !showBoxAnim;
    this.icon_family_box_anim.active = showBoxAnim;

    if (result.ownerDto?.owner) {
      this.FindNode("owner_manage_node").active = true;
      this.ownerUI();
    } else {
      this.FindNode("owner_manage_node").active = false;
    }
  }
  ownerUI() {
    if (this._data.ownerDto == null) {
      return;
    }
    this.setText(
      "lbl_owner_reward_pog",
      "x" + Utils.formatNumber(Number(this._data.ownerDto?.rewardPog), 1)
    );

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

    let showPogAnim = this._data.ownerDto.rewardPog > 0;
    // showPogAnim = true;
    this.icon_family_pog_owner.active = !showPogAnim;
    this.icon_family_pog_owner_anim.active = showPogAnim;

    this.showNewApproveCount();
  }
  async familyInfo() {
    let self = this;
    let familyId = UserM.ins.getFamilyId();
    if (familyId == null || familyId.length == 0) {
      return;
    }
    let result: FamilyInfo = await FamilyM.ins.getFamilyInfo(familyId);
    if (!result) {
      return;
    }
    this._data = result;

    this.familyUI();
  }
  async showNewApproveCount() {
    let result = await FamilyM.ins.familyRequestList(this._data.familyId);

    let newApproveCount = 0;
    if (result != null) {
      newApproveCount = result.length;
    }

    this.FindNode("lbl_new_approve_node").active = newApproveCount > 0;
    if (newApproveCount > 0) {
      this.setText("lbl_new_approve_count", `${newApproveCount}`);
    }
  }
  async showMembers() {
    let familyId = UserM.ins.getFamilyId();
    if (familyId == null || familyId.length == 0) {
      return;
    }
    let members_layout = this.FindNode("members_layout");
    let p = await AB.ins.loadPrefab("prefab/family/FamilyMemberItem");
    members_layout.removeAllChildren();
    let list: FamilyMember[] = await FamilyM.ins.familyMemberList(familyId);
    if (list == null || list.length == 0) {
      return;
    }
    for (let index = 0; index < list.length; index++) {
      let item = instantiate(p);
      item.active = true;
      item.parent = members_layout;
      let playerData = list[index];
      item.getComponent(FamilyMemberItem).init(playerData);
    }

    let familySize = list.length;
    this.setText("lbl_people_count", `${familySize}/${this._data.totalSize}`);
  }

  protected simpleOnBtnClick(name: string): void {
    let self = this;
    switch (name) {
      case "btn_leave_family":
        this.leaveFamily();
        break;
      case "btn_edit_family_notice":
        this.editFamilyNotice();
        break;
      case "btn_approve":
        MemberManager.show(this._data);
        break;
      case "btn_share_family":
        this.shareFamily();
        break;
      case "btn_family_reward_box":
        this.openFamilyRewardBox();
        break;
      case "btn_family_reward_owner_pog":
        this.openFamilyRewardOwnerPog();
        break;

      case "btn_upgrade_family":
        this.upgradeFamily();
        break;
      case "btn_box_family_box":
        HelpImage.show(HelpType.FamilyBox);
        break;
    }
  }
  async leaveFamily() {
    if (this._data.ownerDto != null) {
      TipsLayer.showConfirm(
        "",
        Utils.setI18nLabel("Family.LeaveFamilyOwnerConfirm")
      );
      return;
    }

    let ok = await TipsLayer.showConfirm("", Utils.setI18nLabel("Family.LeaveFamilyConfirm"));
    if (!ok) {
      return;
    }

    let result = await FamilyM.ins.leaveFamily();
    if (result) {
      Tips.show(Utils.setI18nLabel("Family.LeaveFamilySuccess"));
      await UserM.ins.refreshInfo();
    }
  }
  async upgradeFamily() {
    let costDiamond = 10;

    if (UserM.ins.getGoodsCount(GoodsId.GEM) < costDiamond) {
      Tips.show("Not enough diamond");
      return;
    }

    let upgradeCost = `${costDiamond} Diamond`;

    let dialogResult = await TipsLayer.showConfirm(
      "",
      Utils.setI18nLabel("Family.UpgradeFamilyConfirm", "" + upgradeCost)
    );
    if (!dialogResult) {
      return;
    }

    let result = await FamilyM.ins.upgradeFamily(this._data.familyId);
    if (result) {
      TipsLayer.showConfirm(
        "",
        Utils.setI18nLabel("Family.UpgradeFamilySuccess")
      );
      EV.ins.emit(EV_TYPE.FAMILY_DATA_UPDATE);
      await UserM.ins.refreshInfo();
    }
  }
  async openFamilyRewardOwnerPog() {
    if (this._data.ownerDto == null) {
      return;
    }
    if (this._data.ownerDto.owner == false) {
      return;
    }
    if (this._data.ownerDto.rewardPog <= 0) {
      Tips.show("No reward");
      return;
    }

    let result = await FamilyM.ins.claimFamilyRewardOwnerPog(
      this._data.familyId
    );
    if (result) {
      this._data.ownerDto.rewardStatus = 0;
      this._data.ownerDto.rewardPog = 0;
      this.familyUI();
    }
  }
  async openFamilyRewardBox() {
    let num = this._data.boxCount;
    if (num <= 0) {
      Tips.show("No reward");
      return;
    }
    if (num > 10) {
      num = 10;
    }
    let result = await FamilyM.ins.claimFamilyRewardMemberBox(
      this._data.familyId,
      num
    );
    if (result) {
      console.warn("result", result);
      this._data.boxCount = this._data.boxCount - num;
      this.familyUI();
    }
  }
  shareFamily() {
    Tips.show("Sharing...");
    let familyName = this.FindAs("lbl_my_family_name", Label).string;
    let familyOwner = this.FindAs("lbl_my_family_owner_name", Label).string;
    ShareM.ins.shareFamily(familyName, familyOwner);
  }
}
