cc.Class({
    extends: cc.Component,

    properties: {

        Seed: {
            default: null,
            type: cc.Node,
        },
        Exchange: {
            default: null,
            type: cc.Node,
        },
        SeedBtn: {
            default: null,
            type: cc.Node,
        },
        ExchangeBtn: {
            default: null,
            type: cc.Node,
        },

        SelectedFrame: cc.Node,

        //Building40: cc.Node,
        ManageUI: cc.Node,
        //四个按钮对应的sprite
        Normal_Seed_Sprite: cc.SpriteFrame,
        Selecteded_Seed_Sprite: cc.SpriteFrame,

        Normal_Exchange_Sprite: cc.SpriteFrame,
        Selecteded_Exchange_Sprite: cc.SpriteFrame,

        //需要切换节点顺序的父节点
        container: cc.Node,

        //商城的列表
        mySeedList: [],

        seedPrefab: cc.Prefab,

        seedSpriteFrame: {
            default: [],
            type: [cc.SpriteFrame]
        },

        seedNodeArry: {
            default: [],
            type: [cc.Node]
        },
        snbAmount: 0,
        cntAmount: 0,
        ExchangePopView: {
            default: null,
            type: cc.Node,
        },
        PayCNTPopView: {
            default: null,
            type: cc.Node,
        },
        PaySNBPopView: {
            default: null,
            type: cc.Node,
        },
        buySeedIndex: -1,

        snbAmountLabel: {
            default: [],
            type: [cc.Label]
        },
        //拿到仓库列表的节点
        buildingView: {
            default: null,
            type: cc.Node,
        },
        myWareHouseSeedList: null,
        //轮询种子列表状态
        AutoGetSeedsData: null,

        bottomLabel: {
            default: null,
            type: cc.Node,
        },
        seedBottomLabel: {
            default: null,
            type: cc.Node,
        },

        scrollViewNode: {
            default: null,
            type: cc.Node,
        },

        //购买种类数值
        toggleInputValue: {
            default: '1',
            visible: false
        },
        PayCNTPopViewNameLabel: {
            default: null,
            type: cc.Label,
        },
        PayCNTPopViewPriceLabel: {
            default: null,
            type: cc.Label,
        },
        PayCNTPopViewMutureDurLabel: {
            default: null,
            type: cc.Label,
        },

        isPlaying: false,
    },
    HiddenAll() {
        if (this.Seed.active)
            this.Seed.active = false;
        if (this.Exchange.active)
            this.Exchange.active = false;
    },
    start() {
        //获取到仓库列表的脚本
        this.buildingViewScript = this.buildingView.getComponent("BuildingView");
        //默认设置第一个节点为 最上面
        this.SeedBtn.setSiblingIndex(10);
        // console.log('SNB=======', GlobalD.GameData.SNB)
        this.snbAmountLabel.string = GlobalD.GameData.SNB;
        //这里也初始化获取一个数据
        GlobalD.GameData.getWarehouseSeedAndFruit((res, vaule) => {
            this.myWareHouseSeedList = vaule.data.seed;
        });
        //获取种子和果实
        GlobalD.GameData.getMallSeed((res, vaule) => {
            //console.log('vaule111111111=', vaule)
            this.mySeedList = vaule.data;

            console.log('this.mySeedList[i]=', this.mySeedList);
            for (let i = 0; i < this.mySeedList.length; i++) {
                //没有种子数量不显示 todo 看看后续需不需要处理删除
                //if (this.mySeedList[i].amount < 1) continue;
                
                let _seed = cc.instantiate(this.seedPrefab);

                //if (this.mySeedList[i].amount < 1)
                if (this.mySeedList[i].amount < 1)
                {
                    //_seed.getChildByName("SellOut").active = true;
                }
                else{
                    _seed.getChildByName("SellOut").active = false;
                }

                // _seed.getChildByName("buy_button").active = true;
                // _seed.getChildByName("Name").active = false;
                // _seed.getChildByName("Name").getChildByName("Num").getComponent(cc.Label).strng = '';//'x'+this.mySeedList[i].amount;

                this.seedNodeArry.push(_seed);
                _seed.parent = this.Seed;
                let _seedScript = _seed.getComponent("Content_Button");
                _seedScript.Name = this.mySeedList[i].name;
                _seedScript.Price = '';
                _seedScript.CNT = this.mySeedList[i].priceCnt;
                _seedScript.SNB = this.mySeedList[i].priceSnb;
                _seedScript.Mature = this.mySeedList[i].maturity + "天";
                _seedScript.Synopsis = this.mySeedList[i].seedDescribe;

                //设置一个生成点
                let _spawnScript = _seed.getComponent("Content_seed");
                _spawnScript.myIndex = i;
                _spawnScript.SpawnPoint = cc.find("Canvas/SpawnParent/SpawnPoint");
                _seedScript.NumLabel.string = this.mySeedList[i].amount;
                _seedScript.NameLabel.string = this.mySeedList[i].name;
                switch (this.mySeedList[i].picture) {
                    case "Cabbage":
                        _seedScript.bgSprite.spriteFrame = this.seedSpriteFrame[0];
                        break;
                    case "Potato":
                        _seedScript.bgSprite.spriteFrame = this.seedSpriteFrame[1];
                        break;
                    case "Carrot":
                        _seedScript.bgSprite.spriteFrame = this.seedSpriteFrame[2];
                        break;
                    case "Broccoli":
                        _seedScript.bgSprite.spriteFrame = this.seedSpriteFrame[3];
                        break;
                    case "Tomato":
                        _seedScript.bgSprite.spriteFrame = this.seedSpriteFrame[4];
                        break;
                    case "Squash":
                        _seedScript.bgSprite.spriteFrame = this.seedSpriteFrame[5];
                        break;
                    case "Eggplant":
                        _seedScript.bgSprite.spriteFrame = this.seedSpriteFrame[6];
                        break;
                    case "Pepper":
                        _seedScript.bgSprite.spriteFrame = this.seedSpriteFrame[7];
                        break;
                    case "Lentil":
                        _seedScript.bgSprite.spriteFrame = this.seedSpriteFrame[8];
                        break;
                    default:
                        break;
                }
            }
        });
    },
    //切换建筑的面板
    onSwitchBuildingContent(event, index) {

        this.SeedBtn.setScale(1);
        this.ExchangeBtn.setScale(1);

        this.SeedBtn.getComponent(cc.Sprite).spriteFrame = this.Normal_Seed_Sprite;
        this.ExchangeBtn.getComponent(cc.Sprite).spriteFrame = this.Normal_Exchange_Sprite;

        this.SeedBtn.setContentSize(100, 54);
        this.ExchangeBtn.setContentSize(100, 54);

        this.SeedBtn.y = -5;
        this.ExchangeBtn.y = -5;

        this.HiddenAll();
        //面板设置index

        //种子
        if ('0' == index) {
            this.SeedBtn.y = -20;
            this.SeedBtn.getComponent(cc.Sprite).spriteFrame = this.Selecteded_Seed_Sprite;
            this.Seed.active = true;
            if (this.seedNodeArry.length != 0) {
                this.SelectedFrame.parent = this.seedNodeArry[0];
            }
            this.SeedBtn.zIndex = 10;
            this.SeedBtn.setContentSize(110, 100);
            this.ExchangeBtn.zIndex = 1;
            // this.ExchangeBtn.setContentSize(86, 88);
            this.bottomLabel.active = false;
            this.scrollViewNode.active = true;
            this.seedBottomLabel.active = true;
        }
        //兑换
        else if ('1' == index) {
            this.ExchangeBtn.y = -20;
            this.ExchangeBtn.getComponent(cc.Sprite).spriteFrame = this.Selecteded_Exchange_Sprite;
            this.Exchange.active = true;

            this.ExchangeBtn.zIndex = 10;
            this.ExchangeBtn.setContentSize(110, 100);
            this.SeedBtn.zIndex = 1;
            // this.SeedBtn.setContentSize(86, 88);

            this.bottomLabel.active = true;
            this.scrollViewNode.active = false;
            this.seedBottomLabel.active = false;
        }
    },
    switch: function () {
        var children = this.container.children;
        var length = children.length;
        if (length > 1) {
            var src = Math.floor(Math.random() * length);
            var node = children[src];
            var dst = src === length - 1 ? 0 : src + 1;
            node.setSiblingIndex(dst);
        }
    },
    OpentSNBExchangeToCNT() {
        //限制相关人员交易
        if (1 === GlobalD.UserInfo.limitTran) {
            GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "转换CNT通道关闭，请联系相关管理人员！", 1);
            return;
        }
        //更新数据
        this.snbAmountLabel.string = GlobalD.GameData.SNB;
        this.ExchangePopView.active = true;
    },
    SNBExchangeToCNT() {
        //限制相关人员交易
        if (1 === GlobalD.UserInfo.limitTran) {
            GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "转换CNT通道关闭，请联系相关管理人员！", 1);
            return;
        }
        if (0 === Number(this.snbAmount) || 0 != Number(this.snbAmount) % 5) {
            GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "请输入5的倍数兑换！", 1);
            return;
        }
        console.log("发起兑换："+Number(this.snbAmount));
        GlobalD.GameData.onSnbToCnt(Number(this.snbAmount), (data) => {
            //更新数据
            this.snbAmountLabel.string = GlobalD.GameData.SNB;
            this.ExchangePopView.active = false;
            console.log('data=', data)
            // console.log('res=', res)
        });
    },
    onPayCNTPopView(myIndex) {
        this.buySeedIndex = myIndex;
        this.PayCNTPopView.active = true;
        // console.log('this.mySeedList[this.buySeedIndex] =',this.mySeedList[this.buySeedIndex])
        // this.PayCNTPopView.getChildByName("BG").getChildByName("BG1_sprite_splash").getChildByName("NameLabel").getChildByName("label").getComponent(cc.Label).string = this.mySeedList[this.buySeedIndex].name;
        // this.PayCNTPopView.getChildByName("BG").getChildByName("BG1_sprite_splash").getChildByName("PriceLabel").getChildByName("label").getComponent(cc.Label).string = this.mySeedList[this.buySeedIndex].priceCnt + ' CNT';
        // this.PayCNTPopView.getChildByName("BG").getChildByName("BG1_sprite_splash").getChildByName("MutureDurLabel").getChildByName("label").getComponent(cc.Label).string = this.mySeedList[this.buySeedIndex].maturity;
        this._updatePrice();
        // this.PayCNTPopViewNameLabel.string = this.mySeedList[this.buySeedIndex].name;
        // this.PayCNTPopViewPriceLabel.string = this.mySeedList[this.buySeedIndex].priceCnt + ' CNT';
        // this.PayCNTPopViewMutureDurLabel.string = this.mySeedList[this.buySeedIndex].maturity;

    },
    onPaySNBPopView(myIndex) {
        this.buySeedIndex = myIndex;
        this.PaySNBPopView.active = true;
        // console.log('this.mySeedList[this.buySeedIndex] =',this.mySeedList[this.buySeedIndex])
        this.PaySNBPopView.getChildByName("BG").getChildByName("BG1_sprite_splash").getChildByName("NameLabel").getChildByName("label").getComponent(cc.Label).string = this.mySeedList[this.buySeedIndex].name;
        this.PaySNBPopView.getChildByName("BG").getChildByName("BG1_sprite_splash").getChildByName("PriceLabel").getChildByName("label").getComponent(cc.Label).string = this.mySeedList[this.buySeedIndex].priceCnt + ' SNB';
        this.PaySNBPopView.getChildByName("BG").getChildByName("BG1_sprite_splash").getChildByName("MutureDurLabel").getChildByName("label").getComponent(cc.Label).string = this.mySeedList[this.buySeedIndex].maturity;

    },
    PayCNT() {
        console.log('this.cntAmount=', this.cntAmount)
        console.log('this.cntAmount price=', this.cntAmount * parseInt(this.mySeedList[this.buySeedIndex].priceCnt))

        //购买种子也要使用轮询

        let currentAmount = 0;

        for (let i = 0; i < this.myWareHouseSeedList.length; i++) {
            if (this.myWareHouseSeedList[i].id == this.mySeedList[this.buySeedIndex].id) {
                currentAmount = this.myWareHouseSeedList[i].amount;
            }
        }
        //当前背包的数量
        console.log("currentAmount:", {
            seedId: this.mySeedList[this.buySeedIndex].id,
            currentAmount: currentAmount //把当前背包的数据传进去
        });
        let playAmount = this.cntAmount * parseInt(this.mySeedList[this.buySeedIndex].priceCnt);
        if (0 === playAmount) {
            GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "请输入购买数量", 1);
            return;
        }
        // if (this.isPlaying) {
        //     GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "购买过快！", 1);
        //     return;
        // }
        // this.isPlaying = true;
        // GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "区块确认中,请耐心等待！", 120);
        GlobalD.GameData.payCNT(playAmount, 4, this.mySeedList[this.buySeedIndex].id + "", (data) => {
            const [err, tx] = data;
            // this.isPlaying = false;
            if (err === null) {
                // TODO 成功, 支付为链上操作，需要提供回调接口给这边服务端确认交易成功后修改购买订单结果
                console.log(tx) // 交易hash，唯一标识符
                //todo 种子
                if (this.AutoGetSeedsData) {
                    this.unschedule(this.AutoGetSeedsData);
                    this.AutoGetSeedsData = null;
                }
                this.AutoGetSeedsData = () => {
                    // getSeedCount ++;
                    GlobalD.GameData.onGetSeedState(
                        {
                            seedId: this.mySeedList[this.buySeedIndex].id,
                            currentAmount: currentAmount //把当前背包的数据传进去
                        },
                        (res, value) => {
                            console.log("轮询种子:" + JSON.stringify(value));
                            if (0 === value.code) {
                                this.unschedule(this.AutoGetSeedsData);
                                console.log("轮询种子购买成功");
                                GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "种子购买成功！", 1);

                                // this.PayCNTPopView.active = false;

                                //直接重新初始化一下列表，
                                this.buildingViewScript.onUpdateList();
                            }
                        });
                };
                this.schedule(this.AutoGetSeedsData, 5);
            } else {
                console.log(err)
                GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), err, 2);
            }

        });
    },
    PaySNB() {
        console.log('this.snbAmount=', this.cntAmount)
        console.log('priceSnb price=', this.mySeedList[this.buySeedIndex].priceSnb)
        console.log('this.snbAmount price=', this.cntAmount * parseInt(this.mySeedList[this.buySeedIndex].priceSnb))
        console.log("支付价格：" + this.cntAmount * parseInt(this.mySeedList[this.buySeedIndex].priceSnb));
        let playAmount = this.cntAmount * parseInt(this.mySeedList[this.buySeedIndex].priceSnb);
        if (0 === playAmount) {
            GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "请输入购买数量", 1);
            return;
        }

        if (this.isPlaying) {
            GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "购买过快！", 1);
            return;
        }
        GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "支付处理中...", 10);

        this.isPlaying = true;
        GlobalD.GameData.onBuySeedsWithSNB(playAmount, this.mySeedList[this.buySeedIndex].id, (res, value) => {
            // console.log("SNB购买后", value);
            this.isPlaying = false;
            if (0 === value.code) {
                //todo 种子
                GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "种子购买成功！", 1);
                // this.PayCNTPopView.active = false;

                //重新获取一下snb,会自动更新到面板
                GlobalD.GameData.onGetUserSnb();

                //直接重新初始化一下列表，
                this.buildingViewScript.onUpdateList();

                //更新日志数据
                cc.find("GameNode/ManageDapp").getComponent("ManageDapp").onUpdateSnbList();
            } else {
                GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), value.msg, 2);
            }
        });
    },
    onTextChanged1: function (text, editbox, customEventData) {
        // 这里的 text 表示 修改完后的 EditBox 的文本内容
        // 这里 editbox 是一个 cc.EditBox 对象
        // 这里的 customEventData 参数就等于你之前设置的 "foobar"
        this.cntAmount = parseInt(text);
    },
    // 假设这个回调是给 textChanged 事件的
    onTextChanged2: function (text, editbox, customEventData) {
        // 这里的 text 表示 修改完后的 EditBox 的文本内容
        // 这里 editbox 是一个 cc.EditBox 对象
        // 这里的 customEventData 参数就等于你之前设置的 "foobar"
        // this.snbAmount = parseInt(text);
        var numberTemp = new RegExp("^[A-Za-z0-9]+$");
        if (numberTemp.test(text)) {
            if (Number(text) >= 1) {
                this.snbAmount = Number(text);
            } else {
                this.snbAmount = 0;
                editbox.string = this.snbAmount;
            }
        } else {
            this.snbAmount = 0;
            editbox.string = this.snbAmount;
            console.log("请输入5的倍数", this.snbAmount);
        }
    },

    onToggleInput(value, evnentData) {
        this.toggleInputValue = evnentData;
        this._updatePrice();
    },

    _updatePrice() {
        switch (this.toggleInputValue) {
            case "1":
                // this.totalPriceValue = 700 * this.inputInviteValue;
                // this.totalPriceLabel.string = this.totalPriceValue + "CNT";
                this.PayCNTPopViewNameLabel.string = this.mySeedList[this.buySeedIndex].name;
                this.PayCNTPopViewPriceLabel.string = this.mySeedList[this.buySeedIndex].priceCnt + ' CNT';
                this.PayCNTPopViewMutureDurLabel.string = this.mySeedList[this.buySeedIndex].maturity;
                break;
            case "2":
                // this.totalPriceValue = 2500 * this.inputInviteValue;
                // this.totalPriceLabel.string = this.totalPriceValue + "CNT";
                this.PayCNTPopViewNameLabel.string = this.mySeedList[this.buySeedIndex].name;
                this.PayCNTPopViewPriceLabel.string = this.mySeedList[this.buySeedIndex].priceSnb + ' SNB';
                this.PayCNTPopViewMutureDurLabel.string = this.mySeedList[this.buySeedIndex].maturity;
                break;
            default:
                console.error("this.toggleInputValue 不是1 2 3！", this.toggleInputValue);
                break;
        }

    },
    //根据状态吊起不同支付
    onSwitchPlayType() {
        switch (this.toggleInputValue) {
            case "1"://cnt 支付
                this.PayCNT();
                break;
            case "2": //snb 支付
                this.PaySNB();
                break;
            default:
                console.error("状态吊起错误", this.toggleInputValue);
                GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "请先选择支付方式", 1);
                break;
        }
    },

    onDestory(){
        if (this.AutoGetSeedsData) {
            this.unschedule(this.AutoGetSeedsData);
            this.AutoGetSeedsData = null;
        }
    }

});
