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,
    },

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

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

    SelectedFrame: 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,

    Normal_EquipmentBtn_Sprite: cc.SpriteFrame,
    Selecteded_EquipmentBtn_Sprite: cc.SpriteFrame,


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

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

    seedPrefab: cc.Prefab,

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

    //商城的图标列表
    mySeedIconList: {
      default: [],
      type: [cc.SpriteFrame],
    },

    seedNodeArry: {
      default: [],
      type: [cc.Node],
      serializable: false,
      visible: false,
    },

    //装备start---
    equipmentList: [],
    equipPrefab: cc.Prefab,
    equipNodeArry: {
      default: [],
      type: [cc.Node],
      serializable: false,
      visible: false,
    },
    equipSpriteFrame: {
      default: [],
      type: [cc.SpriteFrame],
    },
    equipIconList: {
      default: [],
      type: [cc.SpriteFrame],
    },
    buyEquipIndex: -1,
    PayEquipPopView: {
      default: null,
      type: cc.Node,
    },
    //装备end---

    snbAmount: 0,
    playAmount: 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,


    seedsView: {
      default: null,
      type: cc.Node,
    },
    // ExchangeView: {
    //   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,
    },
    PayCNTPopViewCNTLabel: {
      default: null,
      type: cc.Label,
    },
    PayCNTPopViewSNBLabel: {
      default: null,
      type: cc.Label,
    },
    PayCNTPopViewMutureDurLabel: {
      default: null,
      type: cc.Label,
    },

    PopViewSeed: {
      default: null,
      type: cc.Sprite,
    },

    isPlaying: false,
  },
  HiddenAll() {
    if (this.Seed.active) this.Seed.active = false
    if (this.Exchange.active) this.Exchange.active = false
    if (this.EquipmentCotainer.active) this.EquipmentCotainer.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((vaule) => {
      this.myWareHouseSeedList = vaule.data.seed
    })
    //获取种子和果实
    GlobalD.GameData.getMallSeed((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("Sell").active = false;
          _seed.getChildByName("SellOut").active = true;
        } else {
          _seed.getChildByName("Sell").active = true;
          _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.mySeedIconList[0] //this.seedSpriteFrame[0];
            break
          case 'Potato':
            _seedScript.bgSprite.spriteFrame = this.mySeedIconList[1] //this.seedSpriteFrame[1];
            break
          case 'Carrot':
            _seedScript.bgSprite.spriteFrame = this.mySeedIconList[2] //this.seedSpriteFrame[2];
            break
          case 'Broccoli':
            _seedScript.bgSprite.spriteFrame = this.mySeedIconList[3] //this.seedSpriteFrame[3];
            break
          case 'Tomato':
            _seedScript.bgSprite.spriteFrame = this.mySeedIconList[4] //this.seedSpriteFrame[4];
            break
          case 'Squash':
            _seedScript.bgSprite.spriteFrame = this.mySeedIconList[5] //this.seedSpriteFrame[5];
            break
          case 'Eggplant':
            _seedScript.bgSprite.spriteFrame = this.mySeedIconList[6] //this.seedSpriteFrame[6];
            break
          case 'Pepper':
            _seedScript.bgSprite.spriteFrame = this.mySeedIconList[7] //this.seedSpriteFrame[7];
            break
          case 'Lentil':
            _seedScript.bgSprite.spriteFrame = this.mySeedIconList[8] //this.seedSpriteFrame[8];
            break
          default:
            break
        }
        this.mySeedList[i].bgSpriteFrame = _seedScript.bgSprite.spriteFrame;
      }
    })
    //获取装备列表
    GlobalD.GameData.onGetMallEquipmentList((vaule) => {
      this.equipmentList = vaule.data
      console.log('this.equipmentList=', this.equipmentList);
      for (let i = 0; i < this.equipmentList.length; i++) {
        let _equip = cc.instantiate(this.equipPrefab)

        if (this.equipmentList[i].amount < 1) {
          _equip.getChildByName("Sell").active = false;
          _equip.getChildByName("SellOut").active = true;
        } else {
          _equip.getChildByName("Sell").active = true;
          _equip.getChildByName('SellOut').active = false
        }

        this.equipNodeArry.push(_equip)
        _equip.parent = this.EquipmentCotainer;
        let _equipScript = _equip.getComponent('Content_Button')
        _equipScript.Name = this.equipmentList[i].name
        // _equipScript.Price = ''
        // _equipScript.CNT = 0;
        _equipScript.SNB = this.equipmentList[i].priceSnb
        // _equipScript.Mature = this.equipmentList[i].maturity + '天'
        _equipScript.Synopsis = this.equipmentList[i].itemDescribe

        //设置一个生成点
        let _spawnScript = _equip.getComponent('Content_equip')
        _spawnScript.onSetStoreView(this.node);
        _spawnScript.myIndex = i
        _equipScript.NumLabel.string = this.equipmentList[i].amount
        _equipScript.NameLabel.string = this.equipmentList[i].name

        switch (this.equipmentList[i].picture) {
          case 'dog':
            _equipScript.bgSprite.spriteFrame = this.equipIconList[0];
            break
          case 'beatDogStick':
            _equipScript.bgSprite.spriteFrame = this.equipIconList[1];
            break
          default:
            break
        }
        this.equipmentList[i].bgSpriteFrame = _equipScript.bgSprite.spriteFrame;
      }
    })
  },
  //切换建筑的面板
  onSwitchBuildingContent(event, index) {

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

    this.EquipmentBtn.getComponent(cc.Sprite).spriteFrame = this.Normal_EquipmentBtn_Sprite

    this.HiddenAll()
    //面板设置index
    //种子
    if ('0' == index) {
      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.scrollViewNode.active = true
      this.seedBottomLabel.active = true
      this.seedsView.active = true
      this.Exchange.active = false
    }
    //兑换
    else if ('1' == index) {
      this.ExchangeBtn.getComponent(cc.Sprite).spriteFrame =
        this.Selecteded_Exchange_Sprite

      this.scrollViewNode.active = false
      this.seedBottomLabel.active = false
      this.seedsView.active = false
      this.Exchange.active = true
    }
    //装备
    else if ('2' == index) {
      this.EquipmentBtn.getComponent(cc.Sprite).spriteFrame =
        this.Selecteded_EquipmentBtn_Sprite
      this.EquipmentCotainer.active = true;
      this.scrollViewNode.active = true
      this.seedBottomLabel.active = true
      this.seedsView.active = true
      this.Exchange.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() {
    GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "转换CNT通道关闭！", 1);
    return;
    //限制相关人员交易
    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
    this._updatePrice()
  },
  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.playAmount=', this.playAmount)
    console.log(
      'this.playAmount price=',
      this.playAmount * 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.playAmount * 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, //把当前背包的数据传进去
              },
              (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.playAmount=', this.playAmount)
    console.log('priceSnb price=', this.mySeedList[this.buySeedIndex].priceSnb)
    console.log(
      'this.playAmount price=',
      this.playAmount * parseInt(this.mySeedList[this.buySeedIndex].priceSnb)
    )
    console.log(
      '支付价格：' +
      this.playAmount * parseInt(this.mySeedList[this.buySeedIndex].priceSnb)
    )
    let playAmount =
      this.playAmount * 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,
      (flag, value) => {
        // console.log("SNB购买后", value);
        this.isPlaying = false
        if (flag && 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.playAmount = parseInt(text)
    var numberTemp = new RegExp('^[A-Za-z0-9]+$')
    if (numberTemp.test(text)) {
      if (Number(text) >= 1) {
        this.playAmount = Number(text)
      } else {
        this.playAmount = 0
        editbox.string = this.playAmount
      }
    } else {
      this.playAmount = 0
      editbox.string = this.playAmount
      // console.log('playAmount', this.snbAmount)
    }
  },
  // 假设这个回调是给 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)
    }
  },

  _updatePrice() {

    this.PayCNTPopViewNameLabel.string = this.mySeedList[this.buySeedIndex].name;
    this.PayCNTPopViewCNTLabel.string = this.mySeedList[this.buySeedIndex].priceCnt;
    this.PayCNTPopViewSNBLabel.string = this.mySeedList[this.buySeedIndex].priceSnb;
    this.PayCNTPopViewMutureDurLabel.string = this.mySeedList[this.buySeedIndex].maturity;
    this.PopViewSeed.spriteFrame = this.mySeedList[this.buySeedIndex].bgSpriteFrame;
    // switch (this.toggleInputValue) {
    //   case '1':
    //     this.PayCNTPopViewNameLabel.string =
    //       this.mySeedList[this.buySeedIndex].name
    //     this.PayCNTPopViewCNTLabel.string =
    //       this.mySeedList[this.buySeedIndex].priceCnt + ' CNT'
    //     this.PayCNTPopViewMutureDurLabel.string =
    //       this.mySeedList[this.buySeedIndex].maturity
    //     break
    //   case '2':
    //     this.PayCNTPopViewNameLabel.string =
    //       this.mySeedList[this.buySeedIndex].name
    //     this.PayCNTPopViewCNTLabel.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
    }
  },

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

  //购买装备
  onPayEquipPopView(myIndex) {
    this.buyEquipIndex = myIndex
    this.PayEquipPopView.active = true
    this.PayEquipPopView.getComponent("PayEquipPopView").setInfo(this.equipmentList[this.buyEquipIndex]);
  },
  PayEquipSNB() {
    console.log(
      '支付价格：' + this.equipmentList[this.buyEquipIndex].priceSnb
    )
    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.onGetAddEquipment(
      { mallOtherId: this.equipmentList[this.buyEquipIndex].id },
      (flag, value) => {
        console.log("SNB购买后", value);
        this.isPlaying = false
        if (flag && 0 === value.code) {
          let _equip = value.data.equip;
          //todo 装备
          GlobalD.GameData.showToast(
            cc.find('Canvas/UICamera'),
            '购买装备成功',
            1
          )
          //重新获取一下snb,会自动更新到面板
          GlobalD.GameData.onGetUserSnb()

          if (0 === _equip.otherType) {
            GlobalD.Dog = _equip;
            this.ManageUI.getComponent('ManageUI').onSettingDogAlpha(255);
            //刷新狗状态
            let _dogContainerScript = cc.find("Canvas/DogContainer").getComponent("DogContainer")
            _dogContainerScript.onSetSelfDogState(_equip);
          } else if (1 === _equip.otherType) {
            GlobalD.Stick = _equip;
            this.ManageUI.getComponent('ManageUI').onSettingStickAlpha(255);
          }



          //更新日志数据
          cc.find('GameNode/ManageDapp')
            .getComponent('ManageDapp')
            .onUpdateSnbList()
        } else {
          GlobalD.GameData.showToast(cc.find('Canvas/UICamera'), value.msg, 2)
        }
      }
    )
  },

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




})
