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 { TipsData, TipsLayer } from "../layer/TipsLayer";
import { Vec2 } from "cc";
import { HelpImage, HelpType } from "../layer/HelpImage";

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();

    this.initStaticGrades();
  }

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

  async refresh() {
    let data = await this.init();
    this.initTitles();

    let grade = data.rankInfo.badgeId;
    if (grade <= 0) {
      grade = 8;
    }

    console.error("grade", grade);

    this.initRankPeoples(grade);
    // grade = 3;
    this.refreshMyGradeInGradeList(grade);
  }

  private refreshMyGradeInGradeList(grade: number) {
    let s = this.FindAs("GradeItemScrollView", ScrollView);
    let self = this;
    setTimeout(() => {
      s.scrollToOffset(new Vec2(100 * (8 - grade), 0), 0.1);
      self.refreshGradeSelected(grade);
    }, 1000);
  }

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

    this.setText("lbl_rank_add_tips", desc);

    this.setText(
      "lbl_grade_detail_grade_name",
      ConfigM.ins.getGrade(grade)?.name || "ROOKIE"
    );
  }

  private _type: number = PageRank.RankTypeSeason;

  async initRankPeoples(grade: number) {
    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.refreshGradeSelected(data.id);
    this.initRankPeoples(data.id);
  }
  async initStaticGrades() {
    let s = this.FindAs("GradeItemScrollView", ScrollView);
    s.content.removeAllChildren();
    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);
    }
  }
  async init(): Promise<RankDto> {
    this.FindNode("pog_info").active = this._type == PageRank.RankTypeSeason;

    let data: RankDto = await RankM.ins.rankData(this._type);
    this.ui(data);
    return data;
  }
  async ui(data: RankDto) {
    this.setText("lbl_total_pog", "" + Utils.formatNumber(data.seasonPog, 2));
    this.setText(
      "lbl_today_send",
      "" + Utils.formatNumber(data.dailyGrantPog, 0)
    );
    this.setText("lbl_remain_pog", "" + Utils.formatNumber(data.remainPog, 2));
    // 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":
        HelpImage.show(HelpType.Rank);
        break;
      case "btn_utility":
        let content = `Check out POG Economy & Leaderboard Mechanics from Litepaper: `;
        let data = TipsLayer.build(content);
        data.link = `https://telgather.gitbook.io/telgather-litepaper/telgather-economy/pog-economy-and-leaderboard-mechanics`;
        data.show();
        break;
    }
  }
}
