import { _decorator, Button, Label, Node, randomRangeInt, Sprite, Color, Size } from 'cc';
import Scene from "db://assets/Module/Scene";
import { YXCollectionView, YXFlowLayout, YXIndexPath } from "db://assets/Component/YXList/lib";
import { sendWebNet, WebNetName } from "db://assets/Scripts/Utils/WebNet/WebNet";
import { changeScene } from "db://assets/Module/UIFast";
import { HomeScene } from "db://assets/Scripts/Scenes/HomeScene";
import { PrizeItem } from "./PrizeItem";

const {ccclass, property} = _decorator;

@ccclass('PrizeScene')
export class PrizeScene extends Scene {

    static skin: string = "PrizeScene";
    static group: string[] = ["PrizeScene"];


    @property(Node)
    backBtn: Node = null;

    @property(YXCollectionView)
    collectionView: YXCollectionView = null

    prizeData: any[] = []

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

    async start() {
        this.collectionView.numberOfItems = () => this.prizeData.length;
        this.collectionView.onCellDisplay = this.onCellDisplay;

        const layout = new YXFlowLayout();
        layout.itemSize = new Size(676, 132);
        layout.verticalSpacing = 16;
        this.collectionView.layout = layout;
        this.collectionView.reloadData();

        this.updateRecords();

    }

    async updateRecords() {
        const {success, data} = await sendWebNet(WebNetName.records);
        if (!success) return;

        this.prizeData = data;
        this.collectionView.reloadData();

    }

    clickBtn() {
        changeScene(HomeScene);
    }

    onCellDisplay = (cell: Node, indexPath: YXIndexPath, collectionView: YXCollectionView) => {

        const ts = cell.getComponent(PrizeItem);
        ts.data = this.prizeData[indexPath.item];

        const {extra} = this.prizeData[indexPath.item];
        const {name, icon} = extra;
        cell.getChildByName(`img`).getComponent(Sprite).spriteFrame = icon;
        cell.getChildByName(`name`).getComponent(Label).string = name;
    }

}

