import { _decorator, Button, Component, Label, Node, Size, Sprite, } from 'cc';
import { observer, render } from '../store/decorators';
import Scene from '../../Module/Scene';
import { changeScene, hideWaiting, showPanel, showWaiting } from '../../Module/UIFast';
import { _asyncThrottle, strFormat } from '../Utils/Utils';
import { HomeScene } from './HomeScene';
import { 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(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(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[] = [];

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

  shengMyRank = 0;
  singleMyRank = 0;
  friendMyRank = 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();


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

  // 分享按钮
  clickShare = _asyncThrottle(async () => {
    const rankIndex = (this.tab == TAB.SHENG) ? this.shengMyRank : (this.tab == TAB.SINGLE) ? this.singleMyRank : this.friendMyRank;
    const rankName = (this.tab == TAB.SHENG) ? "省份榜" : (this.tab == TAB.SINGLE) ? "个人榜" : "好友榜";
    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_List.reloadData();
    this.onCellDisplay(this.Sheng_MY, data.myRankInfo);
    this.shengMyRank = data.myRankInfo?.index;

    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.rightPirzeImg = data.prizeImg;
    const { awardConfigs = [] } = data;
    if (awardConfigs.length > 0) {
      this.leftPirzeImg.spriteFrame = awardConfigs[0].prizeImage;
      this.leftPirzeName.string = strFormat(awardConfigs[0].prizeName, 12);
      this.leftRank.string = awardConfigs[0].rankRange;
      this.rightPirzeImg.spriteFrame = awardConfigs[1].prizeImage;
      this.rightPirzeName.string = strFormat(awardConfigs[1].prizeName, 12);
      this.rightRank.string = awardConfigs[1].rankRange;
    }

    this.singleDate = data.rankInfos;
    this.Single_List.reloadData();
    this.onCellDisplay(this.Single_MY, data.myRankInfo);
    this.singleMyRank = data.myRankInfo?.index;

    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.onCellDisplay(this.Friend_MY, data.myRankInfo);
    this.friendMyRank = data.myRankInfo?.index;

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

  onCellDisplay = (cell: Node, data) => {
    if (!data) return
    
    let { index = 0, province = "", score = 0, nickname = "" } = data;

    let rankTxt = index;

    if (!index) {
      rankTxt = "-";

    } else {
      if (index > 200) {
        rankTxt = "200+";
      }
    }

    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";
  }

  // 倒计时
  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;
  }
}

