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

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(Node) None_list: Node = 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.clickPrize, this);
        this.tool_btn.on(Button.EventType.CLICK, this.clickTool, this);
    }


    async start() {
        const { tab = "" } = this.data;
        if (tab && tab == "TOOL") {
            this.tab = TAB.TOOL;
        }

        this.Prize_List.numberOfItems = () => this.prizeDate.length;
        this.Prize_List.onCellDisplay = this.onPrizeCellDisplay;

        const prizeLayout = new YXFlowLayout();
        prizeLayout.itemSize = new Size(880, 200);
        prizeLayout.verticalSpacing = -30;
        this.Prize_List.layout = prizeLayout;
        this.Prize_List.reloadData();


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

        const toolLayout = new YXFlowLayout();
        toolLayout.itemSize = new Size(280, 368);
        toolLayout.priority = YXFlowLayout.Priority.LEFT;
        toolLayout.verticalSpacing = -20;
        this.Tool_List.layout = toolLayout;
        this.Tool_List.reloadData();

        showWaiting(true);
        await Promise.all([
            this.updateTool(),
            this.updatePrize(),
        ]);
        hideWaiting();

    }

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

    // 点击奖品
    clickPrize() {
        this.tab = TAB.PRIZE;
        // this.Prize.getChildByName(`goCheck`).active = true;
    }

    // 道具
    clickTool() {
        if (!store.checkActTime()) return;

        this.tab = TAB.TOOL;
    }

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

        this.toolDate = data.spInfo;
        this.Tool_List.reloadData();

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

    prizeIdType = {};

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

        const { success: suc, data: d } = await sendWebNet(WebNetName.prizeType);

        if (!success) return;

        if (!suc) return;

        const excludeSp = true;      //排除道具

        let records = [];

        const idType = {};
        d.forEach((item) => {
            this.prizeIdType[item.prizeId] = item.prizeType;
        });

        for (let item of data) {

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

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

        if (records.length == 0) {
            this.None_list.active = true;
        }

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

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

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

    onCellDisplay = (cell: Node, data, type) => {
        let {
            icon = 0,
            id = "",
            url = "",
            gmtCreate = 0,
            name = "",
            spId = "",
            spName = "",
            prizeId = "",
            spNum = 0,
            spImg = "",
            dressingStatus = 0,
            lightFlag = false,
        } = 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, prizeId)); // 奖品-去查看
        goBuy.on(Button.EventType.CLICK, () => this.clickToBuy()); // 道具-去购买
        goDress.on(Button.EventType.CLICK, () => this.clickToDress(cell)); // 道具-去装扮
        Derssed.on(Button.EventType.CLICK, () => this.clickToDefaultDress(cell)); // 道具-换回默认装扮


        goCheck.active = isPrize;
        goBuy.active = isTool && spId != "sp_skin_snake_year"; // 不是蛇皮肤，去购买
        goDress.active = isTool && spId == "sp_skin_snake_year" && dressingStatus == 0; // 已装扮
        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;

        cell.getChildByName("light").active = !!lightFlag;

    };

    clickToCheck = (url, id, prizeId) => {
        console.log(prizeId);
        const prizeType = this.prizeIdType[prizeId];

        // 礼品卡页：/packages/giftCard/cardPurchase/index
        // 优惠券页：/packages/marketing/couponList/index
        if (prizeType == 1 || prizeType == 3) {
            // @ts-ignore
            wx.miniProgram.navigateTo({
                url: "/packages/marketing/couponList/index",
            });
        } else if (prizeType == 2 || prizeType == 4) {
            // @ts-ignore
            wx.miniProgram.navigateTo({
                url: "/packages/giftCard/cardPurchase/index?tabcIndex=1",
            });
        } else {
            if (url) {
                window.location.href = url;
            } else {
                window.location.href = `/aaw/projectx/takePrize?projectOrderNo=${id}`;
            }
        }

    };

    clickToBuy = _asyncThrottle(async () => {
        this.hidePanel();
        await changeScene(PropPage, { isFrom: MyBagPanel, isPop: true });
    });

    // clickToDress = async (spId) => {
    clickToDress = _asyncThrottle(async (cell: Node) => {

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

        cell.getChildByName("goDress").active = false;
        cell.getChildByName("Derssed").active = true;

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

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

        cell.getChildByName("goDress").active = true;
        cell.getChildByName("Derssed").active = false;

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

