import { _decorator, Button, Component, Label, Node, Size, Sprite, } from 'cc';
import { observer, render } from '../store/decorators';
import Scene from '../../Module/Scene';
import { backScene, changeScene, hideWaiting, showPanel, showWaiting } from "../../Module/UIFast";
import { _asyncThrottle, strFormat } from '../Utils/Utils';
import { HomeScene } from './HomeScene';
import { LOG_TYPE, sendLog, sendWebNet, WebNetName } from '../Utils/WebNet/WebNet';
import { YXCollectionView, YXFlowLayout, YXIndexPath } from '../../Component/YXList/lib';
import RankPosterPanel from '../Panels/RankPosterPanel';
const { ccclass, property } = _decorator;

enum TAB {
  SHENG = "SHENG", // 省榜
  SINGLE = "SINGLE", // 个人榜
  FRIEND = "FRIEND", // 好友榜
}
@observer
@ccclass('RankScence')
export class RankScence extends Scene {
  static bundle: string = "RankScene";
  static skin: string = "RankScene";


  @property(Node) backBtn: Node = null;
  @property(Node) shareBtn: Node = null;

  @property(Node) Sheng: Node = null;
  @property(Node) Single: Node = null;
  @property(Node) Friend: Node = null;

  @property(Node) sheng_yes: Node = null;
  @property(Node) sheng_no: Node = null;
  @property(Node) single_yes: Node = null;
  @property(Node) single_no: Node = null;
  @property(Node) friend_yes: Node = null;
  @property(Node) friend_no: Node = null;

  @property(YXCollectionView) Sheng_List: YXCollectionView = null;
  @property(YXCollectionView) Single_List: YXCollectionView = null;
  @property(YXCollectionView) Friend_List: YXCollectionView = null;
  @property(Node) Sheng_MY: Node = null;
  @property(Node) Single_MY: Node = null;
  @property(Node) Friend_MY: Node = null;
  @property(Node) Sheng_List_None: Node = null;
  @property(Node) Single_List_None: Node = null;
  @property(Node) Friend_List_None: Node = null;
  @property(Label) Sheng_title: Label = null;

  // @property(Sprite) leftPirzeImg: Sprite = null;
  // @property(Label) leftPirzeName: Label = null;
  // @property(Label) leftRank: Label = null;
  // @property(Sprite) rightPirzeImg: Sprite = null;
  // @property(Label) rightPirzeName: Label = null;
  // @property(Label) rightRank: Label = null;
  @property(YXCollectionView) Prize_List: YXCollectionView = null;

  @property(Label) hour: Label = null;
  @property(Label) second: Label = null;
  @property(Label) minute: Label = null;


  private _tab: TAB = TAB.SINGLE;
  set tab(tab: TAB) { // 设置tab切换
    this._tab = tab;
    const isSheng = tab == TAB.SHENG;
    const isSingle = tab == TAB.SINGLE;
    const isFriend = tab == TAB.FRIEND;

    this.sheng_yes.active = isSheng;
    this.sheng_no.active = !isSheng;
    this.single_yes.active = isSingle;
    this.single_no.active = !isSingle;
    this.friend_yes.active = isFriend;
    this.friend_no.active = !isFriend;
    // this.listBg.setScale(isDaily ? 1 : -1, 1, 1);

    this.Sheng.active = isSheng;
    this.Single.active = isSingle;
    this.Friend.active = isFriend;
  }

  get tab() {
    return this._tab;
  }


  shengDate: any[] = [];
  singleDate: any[] = [];
  friendDate: any[] = [];
  PrizeDate: any[] = [];

  opTime = 0;
  lastTime = 0;
  currentTime = 0;
  isCountingDown = true;

  shengMyRank = {
    index: 0,
    score: 0
  };
  singleMyRank = {
    index: 0,
    score: 0
  };
  friendMyRank = {
    index: 0,
    score: 0
  };

  onLoad() {
    this.tab = TAB.SINGLE;

    this.backBtn.on(Button.EventType.CLICK, this.clickBackHome, this);
    this.shareBtn.on(Button.EventType.CLICK, this.clickShare, this);
    this.sheng_no.on(Button.EventType.CLICK, this.clickSheng, this);
    this.single_no.on(Button.EventType.CLICK, this.clickSingle, this);
    this.friend_no.on(Button.EventType.CLICK, this.clickFriend, this);
  }

  onDestroy() {
    this.isCountingDown = false;
  }

  async start() {
    // 省榜
    this.Sheng_List.numberOfItems = () => this.shengDate.length;
    this.Sheng_List.onCellDisplay = this.onShengCellDisplay;

    const shengLayout = new YXFlowLayout();
    shengLayout.itemSize = new Size(800, 50);
    this.Sheng_List.layout = shengLayout;
    this.Sheng_List.reloadData();

    // 个人榜
    this.Single_List.numberOfItems = () => this.singleDate.length;
    this.Single_List.onCellDisplay = this.onSingleCellDisplay;

    const singleLayout = new YXFlowLayout();
    singleLayout.itemSize = new Size(607, 47);
    this.Single_List.layout = singleLayout;
    this.Single_List.reloadData();

    // 好友榜
    this.Friend_List.numberOfItems = () => this.friendDate.length;
    this.Friend_List.onCellDisplay = this.onFriendellDisplay;

    const friendLayout = new YXFlowLayout();
    friendLayout.itemSize = new Size(800, 50);
    this.Friend_List.layout = friendLayout;
    this.Friend_List.reloadData();

    // 奖品
    this.Prize_List.numberOfItems = () => this.PrizeDate.length;
    this.Prize_List.onCellDisplay = this.onPrizeListCellDisplay;

    const PrizeLayout = new YXFlowLayout();
    PrizeLayout.itemSize = new Size(220, 300);
    this.Prize_List.layout = PrizeLayout;
    this.Prize_List.reloadData();

    showWaiting(true);
    await Promise.all([
      this.updateSheng(),
      this.updateSingle(),
      this.updateFriend(),
    ]);
    hideWaiting();

    this.schedule(this.updateCountdown, 1);
  }

  update(deltaTime: number) {

  }

  // 返回首页
  clickBackHome = _asyncThrottle(async () => {
    // await changeScene(HomeScene);
      await backScene();
  });

  // 分享按钮
  clickShare = _asyncThrottle(async () => {
    const rankLog = (this.tab == TAB.SHENG) ? 13 : (this.tab == TAB.SINGLE) ? 14 : 15;
    sendLog(LOG_TYPE.CLICK, rankLog)

    let rankIndex
    let rankName

    if (this.tab == TAB.SHENG) {
      rankName = "省份榜"
      rankIndex = this.shengMyRank.index > 200 ? "200+" : this.shengMyRank.index
      if (!this.shengMyRank.score && (!this.shengMyRank?.index || this.shengMyRank?.index == -1)) {
        rankIndex = "暂无排名"
      }
      if (this.shengMyRank?.score && (!this.shengMyRank?.index || this.shengMyRank?.index == -1)) {
        rankIndex = "200+"
      }
    }
    if (this.tab == TAB.SINGLE) {
      rankName = "个人榜"
      rankIndex = this.singleMyRank.index > 200 ? "200+" : this.singleMyRank.index

      if (!this.singleMyRank.score && (this.singleMyRank?.index || this.singleMyRank?.index != -1)) {
        rankIndex = "暂无排名"
      }
      if (this.singleMyRank?.score && (!this.singleMyRank?.index || this.singleMyRank?.index == -1)) {
        rankIndex = "200+"
      }
    }
    if (this.tab == TAB.FRIEND) {
      rankName = "好友榜"
      rankIndex = this.friendMyRank.index > 1000 ? "1000+" : this.friendMyRank.index
      if (!this.friendMyRank.score && (!this.friendMyRank?.index || this.friendMyRank?.index == -1)) {
        rankIndex = "暂无排名"
      }
      if (this.friendMyRank?.score && (!this.friendMyRank?.index || this.friendMyRank?.index == -1)) {
        rankIndex = "1000+"
      }
    }
    showPanel(RankPosterPanel, { rankName: rankName, rankIndex: rankIndex })
  });


  // 点击省榜 
  clickSheng() {
    this.tab = TAB.SHENG;
  }
  // 个人榜
  clickSingle() {
    this.tab = TAB.SINGLE;
  }
  // 好友榜
  clickFriend() {
    this.tab = TAB.FRIEND;
  }


  /******  数据 ******/
  // 刷新省榜
  async updateSheng() {
    const { success, data } = await sendWebNet(WebNetName.shengRank);
    if (!success) return;

    this.shengDate = data.rankInfos;

    this.Sheng_title.string = `超过${data.provinceEntryScore}长度的玩家数`;
    this.Sheng_List.reloadData();
    this.onMyCellDisplay(this.Sheng_MY, data.myRankInfo, "SHENG");
    this.shengMyRank = data.myRankInfo

    this.Sheng_List.node.active = this.shengDate.length > 0;
    this.Sheng_List_None.active = this.shengDate.length <= 0; // 如果没有数据隐藏
  }

  // 刷新个人榜
  async updateSingle() {
    const { success, data } = await sendWebNet(WebNetName.singleRank);
    if (!success) return;

    this.singleDate = data.rankInfos;
    this.Single_List.reloadData();
    this.PrizeDate = data.awardConfigs;
    this.Prize_List.reloadData();
    this.onMyCellDisplay(this.Single_MY, data.myRankInfo, "SINGLE");
    this.singleMyRank = data.myRankInfo

    this.Single_List.node.active = this.singleDate.length > 0;
    this.Single_List_None.active = this.singleDate.length <= 0; // 如果没有数据隐藏

    this.opTime = data.endTime;
  }

  // 刷新好友榜
  async updateFriend() {
    const { success, data } = await sendWebNet(WebNetName.friendRank);
    if (!success) return;

    this.friendDate = data.rankInfos;
    this.Friend_List.reloadData();
    this.onMyCellDisplay(this.Friend_MY, data.myRankInfo, "FRIEND");
    this.friendMyRank = data.myRankInfo

    this.Friend_List.node.active = this.friendDate.length > 0;
    this.Friend_List_None.active = this.friendDate.length <= 0;
  }

  // 给每个cell设置数据
  onShengCellDisplay = (cell: Node, indexPath: YXIndexPath, collectionView: YXCollectionView) => {
    const data = this.shengDate[indexPath.item];
    this.onCellDisplay(cell, data);
  }
  onSingleCellDisplay = (cell: Node, indexPath: YXIndexPath, collectionView: YXCollectionView) => {
    const data = this.singleDate[indexPath.item];
    this.onCellDisplay(cell, data);
  }
  onFriendellDisplay = (cell: Node, indexPath: YXIndexPath, collectionView: YXCollectionView) => {
    const data = this.friendDate[indexPath.item];
    this.onCellDisplay(cell, data);
  }

  onPrizeListCellDisplay = (cell: Node, indexPath: YXIndexPath, collectionView: YXCollectionView) => {
    const data = this.PrizeDate[indexPath.item];
    this.onPrizeCellDisplay(cell, data);
  }

  onCellDisplay = (cell: Node, data) => {
    if (!data) return

    let { index = 0, province = "", score = 0, nickname = "" } = data;

    let rankTxt = index;

    if (!score && (!index || index == -1)) {
      rankTxt = "-";
    }

    if (score && (!index || index == -1)) {
      if (this.tab != TAB.FRIEND) {
        rankTxt = "200+";
      }
      if (this.tab == TAB.FRIEND) {
        rankTxt = "1000+";
      }
    }

    if (this.tab != TAB.FRIEND && index > 200) {
      rankTxt = "200+";
    }
    if (this.tab == TAB.FRIEND && index > 1000) {
      rankTxt = "1000+";
    }

    cell.getChildByName(`rank`).getComponent(Label).string = rankTxt;
    cell.getChildByName(`sheng`).getComponent(Label).string = province || strFormat(`${nickname || "微信用户"}`, 12);
    // cell.getChildByName(`length`).getComponent(Label).string = (score > 99999999 ? "99999999+" : score) || "0";
    cell.getChildByName(`length`).getComponent(Label).string = (this.formatNumberWithUnit(score)) || "0";
  }

  onMyCellDisplay = (cell: Node, data, tab) => {
    if (!data) return

    let { index = 0, province = "", score = 0, nickname = "" } = data;

    let rankTxt = index;

    if (!score && (!index || index == -1)) {
      rankTxt = "-";
    }

    if (score && (!index || index == -1)) {
      if (tab == TAB.FRIEND) {
        rankTxt = "1000+";
      }
      if (tab != TAB.FRIEND) {
        rankTxt = "200+";
      }
    }

    if (tab != TAB.FRIEND && index > 200) {
      rankTxt = "200+";
    }
    if (tab == TAB.FRIEND && index > 1000) {
      rankTxt = "1000+";
    }

    cell.getChildByName(`rank`).getComponent(Label).string = rankTxt;
    cell.getChildByName(`sheng`).getComponent(Label).string = province || strFormat(`${nickname || "微信用户"}`, 12) + "(我)";
    // cell.getChildByName(`length`).getComponent(Label).string = (score > 99999999 ? "99999999+" : score) || "0";
    cell.getChildByName(`length`).getComponent(Label).string = (this.formatNumberWithUnit(score)) || "0";
  }

  formatNumberWithUnit = (num) => {
    if (num < 10000) {
        return num; // 如果小于一万，直接返回原数
    } else if (num < 100000000) {
        // 大于一万小于一亿，转为以万为单位
        const numInWan = num / 10000;
        // 使用slice截取小数点后三位，不四舍五入
        const formattedNum = (numInWan + '').slice(0, numInWan.toString().includes('.') ? numInWan.toString().indexOf('.') + 4 : numInWan.toString().length);
        return formattedNum + '万';
    } else {
        // 大于等于一亿，转为以亿为单位
        const numInYi = num / 100000000;
        // 使用slice截取小数点后三位，不四舍五入
        const formattedNum = (numInYi + '').slice(0, numInYi.toString().includes('.') ? numInYi.toString().indexOf('.') + 4 : numInYi.toString().length);
        return formattedNum + '亿';
    }
}

  

  onPrizeCellDisplay = (cell: Node, data) => {
    if (!data) return

    let { prizeImage = 0, prizeName = "", rankRange = 0, sendCount = 0 } = data;
    console.log("data", data);

    cell.getChildByName(`PirzeImg`).getComponent(Sprite).spriteFrame = prizeImage;
    cell.getChildByName(`PrizeName`).getComponent(Label).string = sendCount + "个" +strFormat(prizeName, 12)
    cell.getChildByName(`Rank`).getComponent(Label).string = `第${rankRange}名`;
    cell.getChildByName(`prizeNum`).getComponent(Label).string = "x" + sendCount;
  }

  // 倒计时
  getCurrentTimestamp() {
    return +new Date();
  }

  updateCountdown() {
    if (!this.isCountingDown) return;
    const currentTime = this.getCurrentTimestamp();
    this.lastTime = this.opTime - currentTime;


    if (this.lastTime <= 0) {
      this.setCountdownTime(0, 0, 0);
      this.isCountingDown = false;
      this.unschedule(this.updateCountdown);
      return;
    } else {
      const hours = Math.floor(this.lastTime / (1000 * 60 * 60));
      const minutes = Math.floor((this.lastTime % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((this.lastTime % (1000 * 60)) / 1000);

      // 更新倒计时显示
      this.setCountdownTime(hours, minutes, seconds);
    }
  }

  // 设置倒计时显示
  setCountdownTime(hours, minutes, seconds) {
    this.hour.string = hours > 9 ? hours.toString() : '0' + hours;
    this.minute.string = minutes > 9 ? minutes.toString() : '0' + minutes;
    this.second.string = seconds > 9 ? seconds.toString() : '0' + seconds;
  }
}

