import {
  _decorator,
  Component,
  Node,
  tween,
  Vec3,
  Color,
  UIOpacity,
  RichText,
} from "cc";
import BaseUI from "../../scripts/base/BaseUI";
import UserM, { GoodInfo } from "../../scripts/api/UserM";
import Utils from "../../scripts/utils/Utils";
import { Label } from "cc";
import { Event } from "cc";
import { Tips } from "../../scripts/mgr/Tips";
import { GemRechargeLayer } from "../layer/GemRechargeLayer";
import { Hall } from "./Hall";
import { RewardLayer } from "../layer/RewardLayer";
import { GoodsId } from "../../scripts/api/GoodsId";
import ItemsM from "../../scripts/mgr/ItemsM";
import EV, { EV_TYPE } from "../../scripts/mgr/EV";
import { PageShop } from "./PageShop";
import { GamePassItem } from "../item/GamePassItem";
import RankM, { RankDto } from "../../scripts/api/RankM";
import { PageRank } from "./PageRank";
import ConfigM from "../../scripts/api/ConfigM";
import { Sprite } from "cc";
import AB from "../../scripts/base/AB";
import { SpriteFrame } from "cc";
import FamilyM from "../../scripts/api/FamilyM";
import { TipsData, TipsLayer } from "../layer/TipsLayer";
import { InputNameLayer } from "../family/InputNameLayer";

const { ccclass, property } = _decorator;

@ccclass("HallTitleBar")
export class HallTitleBar extends BaseUI {
  private t: Label;

  private _pog: number;
  private _gem: number;

  onLoad() {
    super.onLoad();

    this.setText("lbl_title_player_name", UserM.ins.getUserName());

    this._pog = UserM.ins.getGoodsCount(GoodsId.POG);
    this._gem = UserM.ins.getGoodsCount(GoodsId.GEM);
    let self = this;
    setInterval(() => {
      self.setText(
        "lbl_hall_title_season_time",
        UserM.ins.getSeasonEndTimeText()
      );
    }, 1000);

    ItemsM.ins.on(GoodsId.POG, this.onPogChange, this);
    ItemsM.ins.on(GoodsId.GEM, this.onGemChange, this);

    this.refreshUI();

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

  onUserGoodRefresh(goodList: GoodInfo[]) {
    this._pog = UserM.ins.getGoodsCount(GoodsId.POG);
    this._gem = UserM.ins.getGoodsCount(GoodsId.GEM);
    this.refreshUI();
  }

  onPogChange(count: number) {
    this._pog += count;
    if (this._pog < 0) {
      this._pog = 0;
    }
    this.refreshUI();
  }
  onGemChange(count: number) {
    this._gem += count;
    if (this._gem < 0) {
      this._gem = 0;
    }
    this.refreshUI();
  }

  refreshUI() {
    this.setText(
      "lbl_hall_title_season_time",
      UserM.ins.getSeasonEndTimeText()
    );
    this.setText("lbl_pog", UserM.ins.getPogDisplay());
    this.setText("lbl_gem", Utils.formatNumber(this._gem, 1));

    let gamePassCount = UserM.ins.getGamePassCount();
    this.FindNode("lbl_game_pass_count").active = gamePassCount > 0;
    if (gamePassCount > 0) {
      this.setText("lbl_game_pass_count", "x" + gamePassCount);
    }

    this.setFamilyInfo();

    this.setGradeIcon();
  }
  async setFamilyInfo() {
    if (UserM.ins.data.familyId != null && UserM.ins.data.familyId != "") {
      let family = await FamilyM.ins.getFamilyInfo(UserM.ins.data.familyId);
      if (UserM.ins.data.userId == family?.ownerDto?.ownerId) {
        this.setText("lbl_title_player_family_name", "👑" + family.familyName);
      } else {
        this.setText("lbl_title_player_family_name", "👤" + family.familyName);
      }
    } else {
      this.setText("lbl_title_player_family_name", "");
    }
  }
  async setGradeIcon() {
    let data: RankDto = await RankM.ins.rankData(PageRank.RankTypeSeason);
    let grade = data.rankInfo.badgeId;
    // grade=3
    if (grade <= 0 || grade > 7) {
      return;
    }

    let a = await AB.ins.loadSpriteFrame("texture/common/grade" + grade + "");
    let f = a as SpriteFrame;
    this.FindAs("icon_my_grade", Sprite).spriteFrame = f;
  }

  protected async simpleOnBtnClick(name: string): Promise<void> {
    switch (name) {
      case "btn_name_layout":
        this.changeNickName();
        break;
      case "btn_gem":
        GemRechargeLayer.show();
        break;
      case "btn_title_game_pass":
        // Tips.show("Game Pass");
        Hall.ins.switchPage(Hall.PageShop);
        // RewardLayer.mock();
        break;
      
      case "btn_game_pass":
        let page = await Hall.ins.switchPage(Hall.PageShop);
        if (!page) {
          return;
        }
        let shop = page.getComponent(PageShop);
        shop.switchTab(PageShop.TAB_GAME_PASS);
        if (UserM.ins.getGamePassCount() <= 0) {
          return;
        }

        setTimeout(() => {
          let ts = page.node.getComponentsInChildren(GamePassItem);
          for (let i = 0; i < ts.length; i++) {
            if (ts[i].node.parent.name == "content") {
              ts[i].showAnim(this.FindNode(name));
              break;
            }
          }
        }, 500);

        break;
    }
  }
  async changeNickName() {
    
    let tips=Utils.setI18nLabel("Common.AlterNameConfirm");

    let ok = await TipsLayer.showConfirm("", tips);
    if (!ok) {
      return;
    }

   if(UserM.ins.getGoodsCount(GoodsId.GEM)<30){
    Tips.show(Utils.setI18nLabel("Common.NoGem"));
    return;
   }

    let name = await InputNameLayer.show(10);
    if (!name || name == "") {
      return;
    }
    let result = await UserM.ins.alterName(name);
    if (result) {
      this.setText("lbl_title_player_name", name);
    }
    // this.setText("lbl_title_player_name", name);
  }
}
