import { _decorator, Component, Node, Event } from "cc";

import { game } from "cc";
import { instantiate } from "cc";

import { Vec3 } from "cc";
import { Sprite } from "cc";
import BaseUI from "../../scripts/base/BaseUI";
import UIUtils from "../../scripts/base/UIUtils";
import { Hall } from "../hall/Hall";
import { WheelDialog } from "../play/WheelDialog";
import UserM, {
  GameInfo,
  GameTaskInfo,
  GiftItemInfo,
  GoodInfo,
} from "../../scripts/api/UserM";
import Utils from "../../scripts/utils/Utils";
import ConfigM, { ConfigGame } from "../../scripts/api/ConfigM";
import AB from "../../scripts/base/AB";
import GameM, { GameSpinResult } from "../../scripts/api/GameM";
import { GameTaskItem, GameTaskItemCallback } from "../play/GameTaskItem";
import TgM from "../../scripts/mgr/TgM";
import { Tips } from "../../scripts/mgr/Tips";
import { TipsData, TipsLayer } from "./TipsLayer";
import { GoodsId } from "../../scripts/api/GoodsId";
import ItemsM from "../../scripts/mgr/ItemsM";
import { RewardLayer } from "./RewardLayer";
import { PlayGamePassReward } from "../play/PlayGamePassReward";
const { ccclass, property } = _decorator;

@ccclass("GameDetailLayer")
export class GameDetailLayer extends BaseUI implements GameTaskItemCallback {
  private claiming: boolean = false;
  onClaim(taskId: number, refreshTimes: number, node: Node): void {
    if (this.claiming) {
      return;
    }
    this.claiming = true;
    let self = this;
    let a = instantiate(node);
    a.parent = node;
    a.setPosition(0, 0, 0);
    UIUtils.moveToNewParent(this.FindNode("icon_spin_slot"), a);
    UIUtils.AnimBezierMoveAndScale(a, new Vec3(0, 0, 0), 1.2, 0.8, () => {
      self.claiming = false;
      a.destroy();
      self.onClaimSpinCount(refreshTimes);
    });
  }
  onClaimSpinCount(refreshTimes: number) {
    this.data.currentSpin = refreshTimes;
    this.refreshSpinTimes();
    UIUtils.AnimScaleShake(this.FindNode("lbl_game_spin_times"), 2, 0.6, false);
  }
  static async show(gameId: number) {
    let layer = await Hall.ins.showLayer("prefab/layer/GameDetailLayer");
    layer.getComponent(GameDetailLayer).init(gameId);
  }

  protected onLoad(): void {
    super.onLoad();
    // this.FindNode("game_pass_pvz_node").active = false;
  }

  // private spinTimes: number = 0;

  private data: GameInfo;
  async init(gameId: number) {
    let data = await GameM.ins.getGameDetailInfo(gameId);
    if (!data) {
      return;
    }
    this.data = data;

    if (data.gameId == 2) {
      this.FindNode("btn_play").active = false;
    }

    this.refreshGamePassReward();

    if (data.gameUser != null) {
      this.setText("lbl_link_user_name", data.gameUser.userName);
    }

    let c = ConfigM.ins.getGame(data.gameId);
    this.showButtons(c);

    this.setText("lbl_name", c.gameName);
    console.log("item.remainPog", data.remainPog);
    if (data.seasonPog > 0) {
      this.setText(
        "lbl_remain_info",
        Utils.formatNumber(data.remainPog, 2) +
          "/" +
          Utils.formatNumber(data.seasonPog, 0)
      );
      this.setText(
        "lbl_my_reward_pog",
        Utils.formatNumber(data.myRewardPog, 0)
      );
    } else {
      this.setText("lbl_remain_info", "Coming soon");
      this.setText(
        "lbl_my_reward_pog",
        Utils.formatNumber(data.myRewardPog, 0)
      );
    }

    this.setIcon(data.gameId);

    this.initTask(data.taskList);

    this.refreshSpinTimes();
  }
  async refreshGamePassReward() {
    let giftList = this.data?.giftList;
    let game_pass_node = this.FindNode("game_pass_reward_layout");
    game_pass_node.removeAllChildren();
    if (!giftList || giftList.length == 0) {
      return;
    }
    let prefab = await AB.ins.loadPrefab("prefab/play/PlayGamePassReward");
    for (let i = 0; i < giftList.length; i++) {
      let gift: GiftItemInfo = giftList[i];
      let item = instantiate(prefab);
      item.parent = game_pass_node;
      item
        .getComponent(PlayGamePassReward)
        .init(
          this.data.gameId,
          gift,
          this.onClaimGamePassGiftSuccess.bind(this)
        );
    }
  }
  private onClaimGamePassGiftSuccess(gift: GiftItemInfo) {
    Tips.show("Claimed successfully");
    this.init(this.data.gameId);
  }

  showButtons(c: ConfigGame) {
    this.FindNode("btn_start_game_web").active = c.webLink && c.webLink != "";
    this.FindNode("btn_start_game_tg").active = c.tgLink && c.tgLink != "";
    this.FindNode("btn_start_game_line").active =
      c.lineLink && c.lineLink != "";
  }
  async initTask(taskList: GameTaskInfo[]) {
    if (!taskList || taskList.length == 0) {
      this.FindNode("NoData").active = true;
      return;
    }
    this.FindNode("NoData").active = false;
    let prefab = await AB.ins.loadPrefab("prefab/play/GameTaskItem");
    let normal_task_layout = this.FindNode("task_layout_normal");

    let normalTaskList = taskList.filter((item) => item.taskType == 1);

    for (let i = 0; i < normalTaskList.length; i++) {
      let normalTask = normalTaskList[i];
      let item = instantiate(prefab);
      item.parent = normal_task_layout;
      item.getComponent(GameTaskItem).init(this.data.gameId, normalTask, this);
    }

    let seasonTaskList = taskList.filter((item) => item.taskType == 2);
    if (seasonTaskList.length == 0) {
      this.FindNode("lbl_title_task_season").active = false;
      return;
    }
    let season_task_layout = this.FindNode("task_layout_season");

    for (let i = 0; i < seasonTaskList.length; i++) {
      let seasonTask = seasonTaskList[i];
      let item = instantiate(prefab);
      item.parent = season_task_layout;
      item.getComponent(GameTaskItem).init(this.data.gameId, seasonTask, this);
    }
  }
  async setIcon(gameId: number) {
    let path = "texture/play/icon_" + gameId;
    let spriteFrame = await AB.ins.loadSpriteFrame(path);
    this.FindAs("icon_game", Sprite).spriteFrame = spriteFrame;
  }

  protected simpleOnBtnClick(name: string): void {
    let c = ConfigM.ins.getGame(this.data.gameId);
    switch (name) {
      case "btn_start_spin":
        this.startSpin();
        break;
      case "btn_start_spin_10":
        this.spin10times();
        break;

      case "btn_start_game_web":
        ConfigM.ins.openLink(c.webLink);
        break;
      case "btn_start_game_tg":
        ConfigM.ins.openLink(c.tgLink);
        break;
      case "btn_start_game_line":
        ConfigM.ins.openLink(c.lineLink);
        break;
    }
  }
  async choose10times() {
    return new Promise((resolve) => {
      let tips = Utils.setI18nLabel("Play.TipsChoose10Times");

      let d = new TipsData(tips);
      d.onCancel = () => {
        resolve(false);
      };
      d.onConfirm = () => {
        resolve(true);
      };
      d.forceConfirm = false;
      d.show();
    });
  }

  async startSpin() {
    if (!this.data) {
      Tips.show("Please wait for the game data to load");
      return;
    }
    if (!this.data.gameId) {
      Tips.show("Game id not found");
      return;
    }

    if (this.data.currentSpin <= 0) {
      return;
    }

    // if (this.data.currentSpin >= 10) {
    //   let ok = await this.choose10times();
    //   if (ok) {
    //     this.spin10times();
    //     return;
    //   }
    // }

    WheelDialog.show(this.data.gameId);

    this.data.currentSpin--;
    this.refreshSpinTimes();
  }
  async spin10times() {
    if (this.data.currentSpin < 10) {
      return;
    }

    let loadingNode = this.FindNode("requesting_10_times");
    loadingNode.active = true;
    let onceTimes = 10;

    this.data.currentSpin -= onceTimes;
    this.refreshSpinTimes();

    let critCount = UserM.ins.getGoodsCount(GoodsId.POG_CRITICAL_CARD);
    let rewards = [];
    for (let index = 0; index < onceTimes; index++) {
      let spinResult: GameSpinResult = await GameM.ins.gameSpin(
        this.data.gameId
      );
      if (!spinResult) {
        continue;
      }
      let pog = spinResult.totalPog;

      if (critCount > 0) {
        critCount--;
        let critResult = await GameM.ins.getCritReward(
          this.data.gameId,
          spinResult.spinId
        );
        if (!critResult) {
          continue;
        }
        pog += critResult.critPog;
      }

      let g = new GoodInfo();
      g.count = pog;

      if (pog > 0) {
        g.id = GoodsId.POG;
      } else {
        g.id = GoodsId.AIR;
      }

      rewards.push(g);
    }

    RewardLayer.show(rewards);

    await UserM.ins.refreshInfo();
    loadingNode.active = false;
  }

  refreshSpinTimes() {
    this.setText("lbl_game_spin_times", "x" + this.data.currentSpin + "");
    this.FindAs("btn_start_spin", Sprite).grayscale =
      this.data.currentSpin <= 0;

    this.FindAs("btn_start_spin_10", Sprite).grayscale =
      this.data.currentSpin < 10;
  }
}
