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

import { Tips } from "../../scripts/mgr/Tips";
import { CommonTabsTitle, OnTabClickListener } from "../common/CommonTabsTitle";
import RankM, { RankDto } from "../../scripts/api/RankM";
import Utils from "../../scripts/utils/Utils";
import UserM from "../../scripts/api/UserM";
import { ScrollView } from "cc";
import AB from "../../scripts/base/AB";
import ConfigM, { Config, ConfigGrade } from "../../scripts/api/ConfigM";
import { instantiate } from "cc";
import { GradeItem } from "../item/GradeItem";
import { Prefab } from "cc";
import { RankPlayerItem } from "../item/RankPlayerItem";
import { HelpLayer } from "../layer/HelpLayer";
import { HelpRank } from "../layer/HelpRank";
import { TipsData, TipsLayer } from "../layer/TipsLayer";
const { ccclass, property } = _decorator;

@ccclass("PageRank")
export class PageRank extends BaseUI implements OnTabClickListener {
  public static readonly RankTypeSeason = 0;
  public static readonly RankTypeTotal = 1;

  private tabs: CommonTabsTitle;

  private rank_people_layout: Node;

  protected onLoad(): void {
    super.onLoad();
    this.tabs = this.FindAs("CommonTabsTitle", CommonTabsTitle);
    this.rank_people_layout = this.FindNode("rank_people_layout");

    // 获取内部的水平ScrollView
    let gradeScrollView = this.FindAs("GradeItemScrollView", ScrollView);

    // 最简单的方式：设置内部ScrollView不取消内部事件，让外部ScrollView可以正常响应垂直滑动
    if (gradeScrollView) {
      gradeScrollView.cancelInnerEvents = false;
    }

    let tab_titles = [
      Utils.setI18nLabel("Rank.Season"),
      Utils.setI18nLabel("Rank.Total"),
    ];
    this.tabs.init(tab_titles, this);

    this.refresh();
  }

  async refresh() {
    if (this._grade <= 0) {
      this._grade = UserM.ins.getGrade();
    }

    this.init();
    this.initGrades();
    this.initTitles();

    this.initRankPeoples(this._grade);
  }

  private refreshGradeSelected() {
    this.getComponentsInChildren(GradeItem).forEach((item) => {
      item.setSelected(item && item.data.id == this._grade);
    });
    let Allocation = ConfigM.ins.getGradeAllocation(this._grade);
    let PogBooster = ConfigM.ins.getGrade(this._grade).addition;
    let desc = `${Allocation}% TOG Allocation + ${PogBooster}% POG Booster from Badge NFT`;

    this.setText("lbl_rank_add_tips", desc);
  }

  private _type: number = PageRank.RankTypeSeason;
  private _grade: number = 0;

  async initRankPeoples(grade: number) {
    this.refreshGradeSelected();
    let tpl = await AB.ins.loadPrefab("prefab/item/RankPlayerItem");
    let data = await RankM.ins.rankPeoples(this._type, grade);
    this.rank_people_layout.removeAllChildren();

    if (!data || !data.rankList || data.rankList.length <= 0) {
      return;
    }
    for (let i = 0; i < data.rankList.length; i++) {
      let item = instantiate(tpl);
      item.getComponent(RankPlayerItem).init(data.rankList[i]);
      this.rank_people_layout.addChild(item);
    }
  }
  initTitles() {
    this.setText(
      "lbl_t_current_season",
      Utils.setI18nLabel("Rank.CurrentSeason")
    );
    this.setText("lbl_t_season_desc", Utils.setI18nLabel("Rank.TotalPogTip"));
    this.setText("lbl_t_sent", Utils.setI18nLabel("Rank.TodaySend"));
    this.setText("lbl_t_remaining", Utils.setI18nLabel("Rank.TodayRemaining"));

    this.setText("lbl_rank_my_tips", Utils.setI18nLabel("Rank.MyRankTip"));
    this.setText(
      "lbl_online_time_tips",
      Utils.setI18nLabel("Rank.WeekTimeTip")
    );

    this.setText(
      "lbl_t_grade_title",
      Utils.setI18nLabel("Rank.AllTankSegmentTitle")
    );
  }

  onGradeClick(data: ConfigGrade) {
    this._grade = data.id;
    this.initRankPeoples(this._grade);
  }
  async initGrades() {
    let s = this.FindAs("GradeItemScrollView", ScrollView);
    let p = await AB.ins.loadPrefab("prefab/item/GradeItem");
    let grades = ConfigM.ins.Grades();
    for (let i = 0; i < grades.length; i++) {
      let item = instantiate(p);
      item
        .getComponent(GradeItem)
        .init(grades[i], this.onGradeClick.bind(this));
      s.content.addChild(item);
      if (grades[i].id == this._grade) {
        item.getComponent(GradeItem).setSelected(true);
      }
    }
  }
  async init() {
    this.FindNode("pog_info").active = this._type == PageRank.RankTypeSeason;

    let data: RankDto = await RankM.ins.rankData(this._type);
    this.ui(data);
  }
  async ui(data: RankDto) {
    this.setText("lbl_total_pog", "" + Utils.formatNumber(data.seasonPog, 0));
    this.setText(
      "lbl_today_send",
      "" + Utils.formatNumber(data.dailyGrantPog, 0)
    );
    this.setText("lbl_remain_pog", "" + Utils.formatNumber(data.remainPog, 0));
    // let gradeAddValue = ConfigM.ins.getGradeAddValue(data.rankInfo.rank);
    let grade = data.rankInfo.badgeId;

    let gradeConfig = ConfigM.ins.getGrade(grade);
    if (gradeConfig != null) {
      this.setText(
        "lbl_rank_my",
        gradeConfig.name +
          " #" +
          data.rankInfo.rank +
          " +" +
          gradeConfig.addition +
          "%"
      );
    } else {
      this.setText("lbl_rank_my", "ROOKIE #" + data.rankInfo.rank);
    }

    this.setText("lbl_online_time", Utils.getTimeStrByS(data.onlineTime));

    this.setText("lbl_season_time", UserM.ins.getSeasonEndTimeText());
  }

  public onTabClick(index: number) {
    // this._type = index;
    // this.init();
    Tips.show("ComingSoon");
    this.tabs.setSelect(this._type);
  }

  protected simpleOnBtnClick(name: string): void {
    switch (name) {
      case "btn_rank_tips":
        HelpRank.show();
        break;
      case "btn_utility":
        let data = new TipsData();
        data.title = "";
        data.content = `Check out POG Economy & Leaderboard Mechanics from Litepaper: `;
        data.forceConfirm = true;
        data.link = `https://telgather.gitbook.io/telgather-litepaper/telgather-economy/pog-economy-and-leaderboard-mechanics`;

        TipsLayer.show(data);
        break;
    }
  }
}
