import Main from "../../../main/Main";
import { AudioMgr, GameViewType } from "../../../main/ViewManage";
import ViewObject from "../../../main/ViewObject";
import FqPay, { UM_EVENT_ID } from "../../../pay/FqPay";
import { HttpStateType, ReveData } from "../../../util/CHttp";
import { __BuyCoinData, __BuyPandoraData, __BuyPowerData, __PayData } from "../../data/sdata/SManage";
import PayShopItem from "../../pay/PayShopItem";
import TopMenu from "../TopMenu";
import ExchangeAmethystView from "./ExchangeAmethystView";
import ShopCoinItem from "./ShopCoinItem";
import ShopPandoraItem from "./ShopPandoraItem";
import ShopPowerItem from "./ShopPowerItem";

interface ShopData {
    marketMoneyData: Array<__BuyCoinData>,
    marketPowerData: Array<__BuyPowerData>,

    playerMarketMoney: Map<string, number>,
    playerMarketPower: Map<string, number>,
}

interface PandoraData {
    playerPandora: {
        count: number
        data: Map<string, number>
    }
    pandoraData: Array<__BuyPandoraData>
}

enum BuyType {
    marketMoney = "marketMoney",    // 金币
    marketPower = "marketPower",    // 体力
    pandora = "pandora",            // 潘多拉
}

const { ccclass, property } = cc._decorator;

@ccclass
export default class ShopView extends ViewObject {

    @property(cc.Node)
    insetContent: cc.Node = null;

    @property(cc.Node)
    content: cc.Node = null;

    @property(cc.Prefab)
    payItem: cc.Prefab = null;

    @property(cc.Prefab)
    powerItem: cc.Prefab = null;

    @property(cc.Prefab)
    coinItem: cc.Prefab = null;

    @property(cc.Prefab)
    pandoraItem: cc.Prefab = null;

    @property(cc.Node)
    amethystNode: cc.Node = null;

    @property(cc.Node)
    diamondNode: cc.Node = null;

    @property(cc.Node)
    powerTips: cc.Node = null;

    private curInsetNode: cc.Node = null;
    private curInsetNum: number = 104;     // 默认插页104

    shopData: ShopData = null;
    pandoraData: PandoraData = null;

    shopPandoraItem: ShopPandoraItem = null;
    pandorId: number = 0;
    pandoraDrawCount: number = 1;   // 抽奖次数
    needAmethyst: number = 0;       // 需要紫水晶数量

    _isClick: boolean = false;    // 防止连续点击

    itemList: Map<string | number, Array<cc.Node>> = new Map;

    public httpEvent(reveData: ReveData) {
        let data = reveData.data;
        if (data["_pack"] != undefined) {
            this.refreshAmethyst();
        }
    }

    init(index: number = 104) {
        this.main.topNode.getComponent(TopMenu).forbidBtn(false);
        this.curInsetNum = index;
        this.curInsetNode = this.insetContent.getChildByName(index + "");
        this.powerTips.active = Number(index) == 102;
        this.changeStatus(this.curInsetNode, true);
        this.changeLayout(this.curInsetNum);
        this.refreshAmethyst();
        this.refreshDiamond();

        this.getPandoraData(() => {
            if (index == 104) {
                this.pandoraView();
            }
        });
        this.getShopData(() => {
            if (index == 102) {
                this.powerView();
            } else if (index == 103) {
                this.coinView();
            }
        });
        if (index == 101) {
            this.payView();
        }
    }


    getShopData(callBack: Function) {
        let msg = {};
        this.main.gameHttp.sendJson('marketMoney/v1/data', msg, (state, reve: ReveData) => {
            this.main.stopLoad();
            if (state == HttpStateType.SUCCESS) {
                if (reve.retCode == 0) {
                    console.log("==reve=getShopData===", reve)
                    this.shopData = reve.data;
                    callBack && callBack();
                } else {
                    this.main.showTips(reve.message);
                }
            } else {
                this.main.showTips('网络异常');
            }
        });
    }

    getPandoraData(callBack: Function) {
        let msg = {};
        this.main.gameHttp.sendJson('pandora/v1/data', msg, (state, reve: ReveData) => {
            this.main.stopLoad();
            if (state == HttpStateType.SUCCESS) {
                if (reve.retCode == 0) {
                    console.log("==reve=getPandoraData===", reve)
                    this.pandoraData = reve.data;
                    callBack && callBack();
                } else {
                    this.main.showTips(reve.message);
                }
            } else {
                this.main.showTips('网络异常');
            }
        });
    }

    /**
     * 
     * @param type 
     * @param shopId 
     */
    buy(type: string, shopId: number, callBack: Function) {
        let msg = {
            id: shopId
        };

        this.main.gameHttp.sendJson(`${type}/v1/buy`, msg, (state, reve: ReveData) => {
            this.main.stopLoad();
            if (state == HttpStateType.SUCCESS) {
                if (reve.retCode == 0) {
                    console.log("==reve==buy==", reve)
                    this.main.playerEffectByPath(AudioMgr.gift);
                    this.main.showReward(reve);
                    callBack && callBack();
                } else {
                    if (type == BuyType.pandora && reve.retCode == 600501) {
                        this.showExchangeAmethystView();
                    } else {
                        this.main.showTips(reve.message);
                    }
                }
            } else {
                this.main.showTips('网络异常');
            }
            this._isClick = false;
        });
    }

    playVideo(callback: (result: number) => void, id: number) {
        let eventId1 = "";
        let eventId2 = "";
        if (this.curInsetNum == 102) {
            eventId1 = UM_EVENT_ID.ad_power_0;
            eventId2 = UM_EVENT_ID.ad_power_1;
        } else if (this.curInsetNum == 103) {
            eventId1 = UM_EVENT_ID.ad_money_0;
            eventId2 = UM_EVENT_ID.ad_money_1;
        } else if (this.curInsetNum == 104) {
            if (id == 1001) {
                eventId1 = UM_EVENT_ID.ad_pdl_t_0;
                eventId2 = UM_EVENT_ID.ad_pdl_t_1;
            } else if (id == 1002) {
                eventId1 = UM_EVENT_ID.ad_pdl_m_0;
                eventId2 = UM_EVENT_ID.ad_pdl_m_1;
            }
        }
        let fqPay: FqPay = new FqPay(this.main);
        fqPay.adVideo(callback, eventId1, eventId2);
    }


    // 切换插页的时候做隐藏处理
    showList(lastIndex: number, curIndex: number) {
        if (this.itemList[lastIndex] && this.itemList[lastIndex].length) {
            this.itemList[lastIndex].forEach((element: cc.Node) => {
                element.active = false;
            });
        }

        if (this.itemList[curIndex] && this.itemList[curIndex].length) {
            this.itemList[curIndex].forEach((element: cc.Node) => {
                element.active = true;
            });
        }
    }

    isCreatorItem(curIndex: number) {
        let b = true;
        if (this.itemList[curIndex]) {
            b = false;
        }
        return b
    }


    payView() {
        if (!this.isCreatorItem(101)) return
        let _payDatas = this.main.sManage.payDatas
        for (let i = 0; i < _payDatas.length; i++) {
            const element = _payDatas[i];
            if (element.type == 1) {
                let node = cc.instantiate(this.payItem)
                node.parent = this.content;
                if (!this.itemList[101]) {
                    this.itemList[101] = [];
                }
                this.itemList[101].push(node);
                let payItem = node.getComponent(PayShopItem)
                payItem.init(element, this.main)
                payItem.setCallback((item: PayShopItem) => {
                    let fqPay: FqPay = new FqPay(this.main)
                    fqPay.pay(item._payData, () => {
                        this.refreshDiamond();
                        this.itemList[101].forEach((element: cc.Node) => {
                            element.getComponent(PayShopItem).showFirstGave();
                        });
                    })
                })
            }
        }
    }

    powerView() {
        if (!this.isCreatorItem(102)) return
        this.shopData.marketPowerData.forEach((data, index) => {
            let node = cc.instantiate(this.powerItem)
            node.parent = this.content;
            if (!this.itemList[102]) {
                this.itemList[102] = [];
            }
            this.itemList[102].push(node);
            let powerItem = node.getComponent(ShopPowerItem);
            powerItem.lbtime.active = index == 0;
            powerItem.init(data, this.shopData.playerMarketPower);
            powerItem.setCallback((item: ShopPowerItem) => {
                console.log("===buy power===")
                if (item.shopId == item.videoId) {
                    if (item.videoMap[item.shopId]) {
                        this.playVideo(result => {
                            if (result == 1) {
                                this.buy(BuyType.marketPower, item.shopId, () => {
                                    item.refresh(item.shopId);
                                });
                            } else {
                                this.main.showTips("广告还未准备好");
                            }
                        }, item.shopId)
                    } else {
                        this.main.showTips("今日广告次数已用完");
                    }
                } else {
                    if (this._isClick) {
                        this.main.showTips("当前操作过于频繁！");
                        return
                    }
                    this._isClick = true;
                    this.buy(BuyType.marketPower, item.shopId, () => {
                        this.refreshDiamond();
                    });
                }
            })
        })
    }

    coinView() {
        if (!this.isCreatorItem(103)) return
        this.shopData.marketMoneyData.forEach((data, index) => {
            let node = cc.instantiate(this.coinItem)
            node.parent = this.content;
            if (!this.itemList[103]) {
                this.itemList[103] = [];
            }
            this.itemList[103].push(node);
            let coinItem = node.getComponent(ShopCoinItem);
            coinItem.lbtime.active = index == 0;
            coinItem.init(data, this.shopData.playerMarketMoney);
            coinItem.setCallback((item: ShopCoinItem) => {
                console.log("====buy coin======", item.shopId)
                if (item.shopId == item.videoId) {
                    if (item.videoMap[item.shopId]) {
                        this.playVideo(result => {
                            if (result == 1) {
                                this.buy(BuyType.marketMoney, item.shopId, () => {
                                    item.refresh(item.shopId);
                                });
                            } else {
                                this.main.showTips("广告还未准备好");
                            }
                        }, item.shopId)
                    } else {
                        this.main.showTips("今日广告次数已用完");
                    }
                } else {
                    if (this._isClick) {
                        this.main.showTips("当前操作过于频繁！");
                        return
                    }
                    this._isClick = true;
                    this.buy(BuyType.marketMoney, item.shopId, () => {
                        this.refreshDiamond();
                    });
                }
            })
        });
    }

    // 潘多拉魔盒
    pandoraView() {
        if (!this.isCreatorItem(104)) return
        this.pandoraData.pandoraData.forEach(data => {
            let node = cc.instantiate(this.pandoraItem)
            node.parent = this.content;
            if (!this.itemList[104]) {
                this.itemList[104] = [];
            }
            this.itemList[104].push(node);
            let pandoraItem = node.getComponent(ShopPandoraItem);
            pandoraItem.init(data, this.pandoraData.playerPandora);
            pandoraItem.setCallback((item: ShopPandoraItem) => {
                console.log("====buy pandora======")
                this.pandoraDrawCount = item.pandoraDrawCount;
                this.needAmethyst = item.needAmethyst;
                this.pandorId = item.shopId;
                this.shopPandoraItem = item;
                if (!item.videoMap[item.shopId]) {
                    if (this._isClick) {
                        this.main.showTips("当前操作过于频繁！");
                        return
                    }
                    this._isClick = true;
                    this.buy(BuyType.pandora, item.shopId, () => {
                        item.refreshDraw(item.shopId);
                        this.refreshAmethyst();
                    });
                } else {
                    this.playVideo(result => {
                        if (result == 1) {
                            this.buy(BuyType.pandora, item.shopId, () => {
                                item.refreshDraw(item.shopId);
                                item.refresh(item.shopId);
                            });
                        } else {
                            this.main.showTips("广告还未准备好");
                        }
                    }, item.shopId)
                }
            })
        })
    }

    // // 紫水晶
    // amethystView() {
    //     this.content.removeAllChildren();
    //     for (let i = 0; i < 2; i++) {
    //         let node = cc.instantiate(this.amethystItem)
    //         node.parent = this.content
    //         let amethystItem = node.getComponent(ShopAmethystItem);
    //         amethystItem.setCallback((item: ShopAmethystItem) => {
    //             console.log("====buy amethyst======")
    //         })
    //     }
    // }

    changeStatus(target: cc.Node, click: boolean) {
        if (click) {
            target.getChildByName("liang").active = true;
            target.getChildByName("an").active = false;
        } else {
            target.getChildByName("liang").active = false;
            target.getChildByName("an").active = true;
        }
    }

    changeLayout(index: number) {
        let layout = this.content.getComponent(cc.Layout);
        if (index == 101) {
            layout.paddingLeft = 10;
            layout.paddingTop = 0;
        } else if (index == 104 || index == 102 || index == 103) {
            layout.paddingLeft = 30;
            layout.paddingTop = 80;
        }
    }

    refreshAmethyst() {
        let num = this.main.player.getGoodCount(1009);
        this.amethystNode.getChildByName("lbamethyst").getComponent(cc.Label).string = ` ${num}`;
    }

    refreshDiamond() {
        let num = this.main.player.role.gold;
        this.diamondNode.getChildByName("lbdiamond").getComponent(cc.Label).string = ` ${num}`;
    }

    showExchangeAmethystView() {
        this.main.viewManage.loadFunc(GameViewType.exchangeAmethyst, (viewObject: ViewObject) => {
            let view = viewObject as ExchangeAmethystView;
            view.show();
            view.init(this.pandoraDrawCount, this.needAmethyst, () => {
                this.buy(BuyType.pandora, this.pandorId, () => {
                    this.shopPandoraItem.refreshDraw(this.pandorId);
                    this.refreshAmethyst();
                    this.refreshDiamond();
                });
            });
        });
    }

    onClickInset(eventTouch: cc.Event.EventTouch, data: string) {
        if (this.curInsetNum == Number(data)) return
        this.changeStatus(this.curInsetNode, false);
        this.changeStatus(eventTouch.target, true);
        this.changeLayout(Number(data));
        this.curInsetNode = eventTouch.target;
        let lastIndex = this.curInsetNum;
        this.showList(lastIndex, Number(data));
        this.curInsetNum = Number(data);
        this.powerTips.active = Number(data) == 102;
        // this.amethystNode.active = Number(data) == 104;
        if (Number(data) == 101) {
            this.payView();
        } else if (Number(data) == 102) {
            this.powerView();
        } else if (Number(data) == 103) {
            this.coinView();
        } else if (Number(data) == 104) {
            this.pandoraView();
        }
        // console.log("onClickInset", arguments);
    }


    onClose() {
        this.main.topNode.getComponent(TopMenu).forbidBtn(true);
        this.exitDistroy();
    }
    // update (dt) {}
}
