import { _decorator, Button, Component, Label, Node, Size, Sprite, } from 'cc';
import { observer, render } from '../store/decorators';
import Panel from "../../Module/Panel";
import { changeScene, hideWaiting, showWaiting } from '../../Module/UIFast';
import { _asyncThrottle, dateFormatter, strFormat } from '../Utils/Utils';
import { HomeScene } from '../Scenes/HomeScene';
import { sendWebNet, sendWebNetWithToken, WebNetName } from '../Utils/WebNet/WebNet';
import { YXCollectionView, YXFlowLayout, YXIndexPath } from '../../Component/YXList/lib';
import { url } from 'inspector';
import { PropPage } from '../Scenes/PropPage';
const { ccclass, property } = _decorator;

enum TAB {
  PRIZE = "PRIZE",
  TOOL = "TOOL",
}
@observer
@ccclass('MyBagPanel')
export class MyBagPanel extends Panel {
  static bundle: string = "MyBagPanel";
  static skin: string = "MyBagPanel";

  @property(Node) closeBtn: Node = null;

  @property(Node) Prize: Node = null;
  @property(Node) Tool: Node = null;

  @property(Node) prize_yes: Node = null;
  @property(Node) prize_btn: Node = null;
  @property(Node) tool_yes: Node = null;
  @property(Node) tool_btn: Node = null;

  @property(YXCollectionView) Prize_List: YXCollectionView = null;
  @property(YXCollectionView) Tool_List: YXCollectionView = null;


  private _tab: TAB = TAB.PRIZE;
  set tab(tab: TAB) { // 设置tab切换
    this._tab = tab;
    const isPrize = tab == TAB.PRIZE;
    const isTool = tab == TAB.TOOL;

    this.prize_yes.active = isPrize;
    this.tool_yes.active = isTool;

    this.Prize.active = isPrize;
    this.Tool.active = isTool;
  }

  get tab() {
    return this._tab;
  }


  prizeDate: any[] = [];
  toolDate: any[] = [];

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

    this.closeBtn.on(Button.EventType.CLICK, this.clickClose, this);
    this.prize_btn.on(Button.EventType.CLICK, this.clickSheng, this);
    this.tool_btn.on(Button.EventType.CLICK, this.clickSingle, this);
  }


  async start() {
    this.Prize_List.numberOfItems = () => this.prizeDate.length;
    this.Prize_List.onCellDisplay = this.onShengCellDisplay;

    const shengLayout = new YXFlowLayout();
    shengLayout.itemSize = new Size(820, 140);
    this.Prize_List.layout = shengLayout;
    this.Prize_List.reloadData();

    this.Tool_List.numberOfItems = () => this.toolDate.length;
    this.Tool_List.onCellDisplay = this.onSingleCellDisplay;

    const singleLayout = new YXFlowLayout();
    singleLayout.itemSize = new Size(820, 140);
    this.Tool_List.layout = singleLayout;
    this.Tool_List.reloadData();

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

  }

  update(deltaTime: number) {

  }

  clickClose = () => {
    this.hidePanel();
  }

  // 点击省榜 
  clickSheng() {
    this.tab = TAB.PRIZE;
    // this.Prize.getChildByName(`goCheck`).active = true;
  }
  // 个人榜
  clickSingle() {
    this.tab = TAB.TOOL;
  }

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

    this.prizeDate = data.spInfo;
    this.Prize_List.reloadData();

    this.Prize_List.node.active = this.prizeDate.length > 0;
  }

  // 刷新奖品
  async updateSingle() {
    const { success, data = [] } = await sendWebNet(WebNetName.prizeDetail);

    if (!success) return;

    const excludeSp = true;      //排除道具

    let records = []

    for (let item of data) {

      const { extra: { name, icon, type }, id, prizeId, gmtCreate } = item;
      if (excludeSp && type === 1) {
        continue;
      }

      records.push({
        id,
        prizeId,
        name,
        icon,
        gmtCreate,
        data: item,
      });
    }

    this.toolDate = records;
    this.Tool_List.reloadData();

    this.Tool_List.node.active = this.toolDate.length > 0;
  }

  // 给每个cell设置数据
  onShengCellDisplay = (cell: Node, indexPath: YXIndexPath, collectionView: YXCollectionView) => {
    const data = this.prizeDate[indexPath.item];
    this.onCellDisplay(cell, data, TAB.TOOL);
  }
  onSingleCellDisplay = (cell: Node, indexPath: YXIndexPath, collectionView: YXCollectionView) => {
    const data = this.toolDate[indexPath.item];
    this.onCellDisplay(cell, data, TAB.PRIZE);
  }

  onCellDisplay = (cell: Node, data, type) => {
    let { icon = 0, id = "", url = "", gmtCreate = 0, name = "", spId = "", spName = "", spNum = 0, spImg = "", dressingStatus = 0 } = data;

    const isPrize = type == TAB.PRIZE;
    const isTool = type == TAB.TOOL;
    const goCheck = cell.getChildByName("goCheck")
    const goBuy = cell.getChildByName("goBuy")
    const goDress = cell.getChildByName("goDress")
    const Derssed = cell.getChildByName("Derssed")


    goCheck.on(Button.EventType.CLICK, () => this.clickToCheck(url, id)) // 奖品-去查看
    goBuy.on(Button.EventType.CLICK, () => this.clickToBuy()) // 道具-去购买
    goDress.on(Button.EventType.CLICK, () => this.clickToDress()) // 道具-去装扮
    Derssed.on(Button.EventType.CLICK, () => this.clickToDefaultDress()) // 道具-换回默认装扮


    goCheck.active = isPrize;
    goBuy.active = isTool && spId != "sp_skin_snake_year"; // 不是蛇皮肤，去购买
    goDress.active = isTool && spId == "sp_skin_snake_year" && dressingStatus == 0; // 已装扮
    cell.getChildByName(`Derssed`).active = isTool && spId == "sp_skin_snake_year" && dressingStatus == 1; // 未装扮
    cell.getChildByName(`name`).getComponent(Label).string = strFormat(name || spName, 32);
    cell.getChildByName(`time`).getComponent(Label).string = gmtCreate ? dateFormatter(gmtCreate, "yyyy.MM.dd hh:mm") : "剩余数量：" + spNum;
    cell.getChildByName("img").getComponent(Sprite).spriteFrame = icon || spImg;
  }

  clickToCheck = (url, id) => {
    this.hidePanel()
    if (url) {
      window.location.href = url;
    } else {
      window.location.href = `/aaw/projectx/takePrize?projectOrderNo=${id}`;
    }
  }

  clickToBuy = _asyncThrottle(async () => {
    this.hidePanel()
    await changeScene(PropPage)
  })

  // clickToDress = async (spId) => {
  clickToDress = _asyncThrottle(async () => {
    const { success, data } = await sendWebNetWithToken(WebNetName.doDress, { spId: "sp_skin_snake_year" });
    if (!success) return;

    console.log("换上了新皮肤");
    this.hidePanel()
  })

  clickToDefaultDress = _asyncThrottle(async () => {
    const { success, data } = await sendWebNetWithToken(WebNetName.doDress, { spId: "sp_decoration_default" });
    if (!success) return;

    console.log("换回了原皮肤");
    this.hidePanel()
  })
}

