import { _decorator, Button, Component, Label, Node, Size, Sprite, } from 'cc';
import { observer, render } from '../store/decorators';
import { _asyncThrottle, dateFormatter, strFormat } from '../Utils/Utils';
import { getProjectId, LOG_TYPE, sendLog, sendWebNet, WebNetName } from '../Utils/WebNet/WebNet';
import { SpriteFrame } from 'cc';
import { assetManager } from 'cc';
import { MainGame } from './MainGame/MainGame';
import { miniGoUrl } from '../AppTool';
import Scene from "db://assets/core/Module/Scene";
import { changeScene, hideWaiting, showToast, showWaiting } from "db://assets/core/Module/UIFast";
import { YXCollectionView, YXFlowLayout, YXIndexPath } from "db://assets/core/Component/YXList/lib";
import { HomeScene } from "db://assets/Scripts/Scenes/HomeScene";
const { ccclass, property } = _decorator;

@observer
@ccclass('PrizeScene')
export class PrizeScene extends Scene {
  static bundle: string = "PrizeScene";
  static skin: string = "PrizeScene";


  @property(Node) backBtn: Node = null;
  @property(YXCollectionView) Prize_List: YXCollectionView = null;

  PrizeListData: any[] = [];

  onLoad() {
    this.backBtn.on(Button.EventType.CLICK, this.clickBackHome, this);
  }

  onDestroy() {
  }

  currentPrizeLevel = 0
  async start() {
    // 排行榜的展示
    this.Prize_List.numberOfItems = () => this.PrizeListData.length;
    this.Prize_List.onCellDisplay = this.onPrizeListCellDisplay;

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

    showWaiting(true);

    await this.updatePrizeInfo();

    hideWaiting();
  }

  update(deltaTime: number) {

  }

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

  // rank榜单信息
  async updatePrizeInfo() {
    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 && (item.prizeId?.indexOf("sp_red") == -1) && item?.prizeId != "sp_compose_1") {
        continue;
      }

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

    // if (records.length == 0) {
    //     this.None_list.active = true;
    // }
    // this.Prize_List.node.active = this.PrizeListData.length > 0;

    this.PrizeListData = records;
    this.Prize_List.reloadData();

  }

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


  onPrizeCellDisplay = (cell: Node, data, index) => { // tab栏item的展示
    let {
      id = "",
      url = "",
      name = "",
      icon = "",
      gmtCreate = "",
    } = data;

    const goCheck = cell.getChildByName("item_btn");
    cell.getChildByName("item_name").getComponent(Label).string = strFormat(name, 12);
    cell.getChildByName("item_date").getComponent(Label).string = dateFormatter(gmtCreate, "yyyy-MM-dd hh:mm:ss");
    cell.getChildByPath("img_bg/img").getComponent(Sprite).spriteFrame = icon
    goCheck.on(Button.EventType.CLICK, () => this.clickToCheck(url, data)); // 奖品-去查看

  }

  clickToCheck = async (url, item) => {
    console.info("奖品跳转", item);
    const { prizeId, id } = item;
    console.info("id11111", prizeId);
    if ((prizeId.indexOf("sp_red") != -1) || prizeId == "sp_compose_1") {
      miniGoUrl("/pagesNews/user/userRed")
      return;
    }
    if (prizeId.indexOf("sp_exclusive_coupon") != -1) {
      miniGoUrl("/pagesNews/user/coupon")
      return;
    }
    if (item.data.extra.refType === "virtual") {
      const { data } = await sendWebNet(WebNetName.queryPrizeDetail, {
        recordId: id,
        projectId: getProjectId(),
      });
      console.info(data);
      if (data?.orderNo) {
        // 线上正式用这个
        //
        // @ts-ignore
        wx.miniProgram.reLaunch({
          url:
            "/pages/index/index?orderNo=" +
            id +
            "&activityId=" +
            data?.activityId +
            "&uid=" +
            data?.uid +
            "&activityUrl=" +
            encodeURIComponent(location.origin + "/projectx/" + getProjectId() + "/index.html?jumpFlag=1"),
        });
      } else {
        showToast("请稍后再试～");
      }
    } else if (item.data.extra.refType !== "virtual") {
      location.href = `/aaw/projectx/takePrize?projectOrderNo=${id}`;
    }


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

  };
}
