// const constants = require('Constants');
// var reGameStates = require('GameStates');
var AConfig = require('../Config')
cc.Class({
  extends: cc.Component,

  properties: {
    //左上角按钮列表
    LeftMenu: cc.Node,
    //编辑建筑物时候的ui显示
    EditorialBuildings: cc.Node,
    //记录编辑按钮的父对象
    _thisEditBuildingsParent: cc.Node,
    _Cancellation: cc.Button,
    _Comfirmation: cc.Button,
    _buildTarget: cc.Node,
    //显示建筑的详细信息
    //建筑面板
    BuildingInfoView: cc.Node,
    //ui Mask 对应的touch
    UITouch: {
      default: null,
      type: cc.Node,
    },
    //设置面板
    SettingInfoView: cc.Node,
    //建筑面板
    //建筑物列表.后面根据数据动态添加content的内容。
    //todo..
    BuildView: cc.Node,
    StoreView: cc.Node,
    BuildContent_Button: { default: null, type: cc.Button, visible: false },
    BuildContent_OldButton: { default: null, type: cc.Button, visible: false },
    BuildContent_Normal_Sprite: cc.SpriteFrame,
    BuildContent_Pressed_Sprite: cc.SpriteFrame,
    ButtonSelectedFrame: cc.Node,
    //建筑版面的介绍模板
    BuildContent_Name: cc.Label,
    BuildContent_Price: cc.Label,
    BuildContent_Mature: cc.Label,
    BuildContent_Synopsis: cc.Label,
    //人才面板
    PersonnelView: cc.Node,
    //股票面板
    StockView: cc.Node,
    //幸运转盘
    LuckView: cc.Node,
    // 底部的菜单栏
    BottomView: cc.Node,

    // 其他农场用户的界面节点
    OtherFarmerMask: cc.Node,

    Evn: cc.Node,
    Seed: cc.Node,
    EveryDaySignView: cc.Node,

    //提示面板
    TipView: cc.Node,
    //提示面板预制
    TipViewPrefab: cc.Prefab,
    ShowRewards: cc.Node,
    BuildingFrameArray: {
      default: [],
      type: [cc.Node],
      serializable: true,
    },
    Goldenlabel: cc.Node,
    Diamondlabel: cc.Node,
    CNTlabel: cc.Node,
    SNBlabel: cc.Node,
    Strengthlabel: cc.Node,
    Luckylabel: cc.Node,

    //显示的库存总量，人才界面
    cropContent: cc.Label,
    woodContent: cc.Label,
    mineContent: cc.Label,

    //钻石兑换金币
    DiamondGapView: cc.Node,
    DiamondNowlabel: cc.Label,
    ExchangeBtn: cc.Button,
    //钻石足够获得种子
    DiamondSeedsView: cc.Node,
    LightRotate: cc.Node,
    DiamondSeeds_SureBtn: cc.Button,

    inviteNode: cc.Node,

    listUserInfoNode: cc.Node,

    //商店面的介绍模板
    mallContent_Name: cc.Label,
    mallContent_Price: cc.Label,
    mallContent_SNBPrice: cc.Label,
    mallContent_Mature: cc.Label,
    mallContent_Synopsis: cc.Label,

    //偷取成功生成一个提示
    StealViewSuccessPrefab: cc.Prefab,

    //场景开始时候，打开的黑色遮罩
    surroundingBlack: cc.Node,

    dogButtonNode: cc.Node,
    stickButtonNode: cc.Node
  },
  onLoad() {
    cc.game.setFrameRate(30)
    cc.director.preloadScene('Login', function () { }.bind(this))
    if (this.EditorialBuildings) {
      this._thisEditBuildingsParent = this.EditorialBuildings.parent
      this._Cancellation = this.EditorialBuildings.getChildByName(
        'Cancellation'
      ).getComponent(cc.Button)
      this._Comfirmation = this.EditorialBuildings.getChildByName(
        'Confirmation'
      ).getComponent(cc.Button)
    }
    task.managerUi = this
    var data1 = {
      name: 'Whoareyou',
      openId: userData.openId,
    }
    UtilsWX.postMessage(data1)
    UtilsWX.shareMenu()
    UtilsWX.initWXSubContextView(cc.find('Canvas/UICamera/wx'))
    UtilsWX.openWXSubContextView(false)
  },

  isGame: function () {
    this.times = 0
    cc.game.on(
      cc.game.EVENT_HIDE,
      function () {
        console.log('游戏进入后台', this.getTime())
        if (UtilsWX.shareTag == 0) {
          // this.onHideGame();//处理游戏切到后台时的事件
          this.times = this.getTime()
          task.onLoad()
          // this.onShowGame();//处理游戏切回前台时的事件
          cc.director.loadScene(
            'Login',
            function () {
              task.showPointerNode = null
            }.bind(this)
          )
        }
      },
      this
    )

    cc.game.on(
      cc.game.EVENT_SHOW,
      function () {
        console.log('重新返回游戏', this.getTime())

        // if (this.getTime()-this.times>=30000) {

        if (UtilsWX.shareTag == 0) {
        }
        UtilsWX.setShareTag(0)

        // }
      },
      this
    )
  },

  getTime: function () {
    return new Date().getTime()
  },

  // InitTask(BFirstLoadGame) {
  //     // todo 新手教学 初始化
  //     console.log("初始化真的假的", BFirstLoadGame);
  //     if (!BFirstLoadGame) {
  //         //首次初始化
  //         task.onLoad();
  //         //创建员工
  //         cc.find('GameNode/ManageWorker').getComponent('ManageWorker').onRecruit();
  //         cc.find('GameNode/ManageWorker').getComponent('ManageWorker').onRecruit();

  //     } else {
  //         task._init();
  //         task.addSeneceTaskIcon();
  //         task.onLoadno();
  //     }
  //     this.Init();
  // },

  start() {
    /*
          其中第一个参数为捕捉的时间名，在官方文档中给出了几个选择,我们主要列举下触碰时间
        cc.Node.EventType.TOUCH_START 当手按下时触发
        cc.Node.EventType.TOUCH_END 当手抬起时候
        cc.Node.EventType.TOUCH_MOVE 当手按下滑动时
        cc.Node.EventType.TOUCH_CANCEL 当手按下滑动后 抬起时
        */
    if (this._Cancellation)
      this._Cancellation.node.on(
        cc.Node.EventType.TOUCH_END,
        this.onCancellationEditor,
        this
      )
    if (this._Comfirmation)
      this._Comfirmation.node.on(
        cc.Node.EventType.TOUCH_END,
        this.onConfirmationEditor,
        this
      )
  },
  Init() {
    this._setLockBuildingColor()

    let BuildingStateArray = GlobalD.GameData.GetBuildingLockStateArray()
    for (let i = 0; i < BuildingStateArray.length; i++) {
      if (BuildingStateArray[i] == 1) {
        if (this.BuildingFrameArray[i]) this.OpenBuildingUILock(i, false)
      }
      if (this.BuildingFrameArray[i])
        this.BuildingFrameArray[i]
          .getChildByName('Lock')
          .getChildByName('PriceBG')
          .getChildByName('label')
          .getComponent(cc.Label).string = this.FormatMoney(
            AConfig.BuildingUnlockMoneyArray[i]
          )
    }

    // *********** todo *************
    //初始化，面板信息
    //运营费用数组
    let _runningCostArray = AConfig.RunningCostArray
    for (let i = 0; i < _runningCostArray.length; i++) {
      if (this.BuildingFrameArray[i]) {
        let _contentButton =
          this.BuildingFrameArray[i].getComponent('Content_Button')
        _contentButton.Price = AConfig.RunningCostArray[i] //运营费用
        //设置新的钻石价格
        let _DiamondNumArray = GlobalD.GameData.GetDiamondNumArray()
        _contentButton.DiamondPrice = _DiamondNumArray[i] //钻石费用
      }
    }

    //如果用户未租赁过土地且未用钻石兑换过种子，则显示
    GlobalD.GameData.getPlayerExchangeState((res, value) => {
      //warn 这里需要增加对结果的判断
      if (0 === value.code) {
        //没有兑换过和没有租赁过
        if (!value.data.isExchange && !value.data.isLeased) {
          this.DiamondGapViewShow()
        }
      }
    })

    //显示背景
    this.surroundingBlack.active = true;
  },
  _setLockBuildingColor() {
    let BuildingStateArray = GlobalD.GameData.GetBuildingLockStateArray()

    for (let index = 0; index < BuildingStateArray.length; index++) {
      if (this.BuildingFrameArray[index] && BuildingStateArray[index] == 0) {
        this.BuildingFrameArray[index].color = new cc.Color(150, 150, 150, 150)
        this.BuildingFrameArray[index].getChildByName(
          'New Sprite(Splash)'
        ).color = new cc.Color(0, 0, 0, 255)
        this.BuildingFrameArray[index].getChildByName('Name').active = false
      }
    }
  },
  OpenBuildingUILock(Index, BLock) {
    let Lock = (this.BuildingFrameArray[Index].getChildByName('Lock').active =
      BLock)

    let BuildingStateArray = GlobalD.GameData.GetBuildingLockStateArray()
    if (!BLock && BuildingStateArray[Index] == 0) {
      BuildingStateArray[Index] = 1
      this.BuildingFrameArray[Index].color = new cc.Color(255, 255, 255, 255)
      this.BuildingFrameArray[Index].getChildByName(
        'New Sprite(Splash)'
      ).color = new cc.Color(255, 255, 255, 255)
      this.BuildingFrameArray[Index].getChildByName('Name').active = true
      GlobalD.GameData.SetBuildingLockStateArray(BuildingStateArray)
    }
  },
  OnUnLockBuilding(event, CustomEventData, callback) {
    cc.loader.loadRes(
      'prefab/UnlockBuiding',
      function (err, texture) {
        this.UnlockBuildingDialogView = cc.instantiate(texture)
        this.BuildView.addChild(this.UnlockBuildingDialogView)

        {
          //CloseBtn
          let close = this.UnlockBuildingDialogView.getChildByName('close')
          let clickEventHandler = new cc.Component.EventHandler()
          clickEventHandler.target = this.node
          clickEventHandler.component = 'ManageUI'
          clickEventHandler.handler = 'onClickCloseInUnlockBuilding'
          let button = close.getComponent(cc.Button)
          button.clickEvents.push(clickEventHandler)
        }
        {
          //NoBtn
          let NoBTN = this.UnlockBuildingDialogView.getChildByName('NoBTN')
          let clickEventHandler = new cc.Component.EventHandler()
          clickEventHandler.target = this.node
          clickEventHandler.component = 'ManageUI'
          clickEventHandler.handler = 'onClickNoBTNInUnlockBuilding'
          let button = NoBTN.getComponent(cc.Button)
          button.clickEvents.push(clickEventHandler)
        }
        {
          //YesBtn
          let YesBTN = this.UnlockBuildingDialogView.getChildByName('YesBTN')
          let clickEventHandler = new cc.Component.EventHandler()
          clickEventHandler.target = this.node
          clickEventHandler.component = 'ManageUI'
          clickEventHandler.handler = 'onClickYesBTNInUnlockBuilding'
          clickEventHandler.customEventData = CustomEventData
          let button = YesBTN.getComponent(cc.Button)
          button.clickEvents.push(clickEventHandler)
        }

        //Close
        if (callback != null) {
          callback(this.UnlockBuildingDialogView)
        }
      }.bind(this)
    )
  },
  onClickCloseInUnlockBuilding(event) {
    this.UnlockBuildingDialogView.destroy()
  },
  onClickNoBTNInUnlockBuilding(event) {
    this.UnlockBuildingDialogView.destroy()
  },
  onClickYesBTNInUnlockBuilding(event, CustomEventData) {
    this.UnlockBuildingDialogView.destroy()

    let Index = parseInt(CustomEventData)
    let CostCoin = AConfig.BuildingUnlockMoneyArray[Index]
    if (
      GlobalD.GameData.GetDiamond() > CostCoin ||
      GlobalD.GameData.GetDiamond() == CostCoin
    ) {
      GlobalD.GameData.PlusDiamond(-CostCoin)
      this.OpenBuildingUILock(Index, false)

      cc.loader.loadRes(
        'prefab/show',
        function (err, texture) {
          this.ShowRewardsView = cc.instantiate(texture)
          this.BuildView.addChild(this.ShowRewardsView)
          let Rewards =
            this.ShowRewardsView.getChildByName('GivePrize').getChildByName(
              'Rewards'
            )
          Rewards.getComponent(cc.Sprite).spriteFrame = this.BuildingFrameArray[
            Index
          ].getChildByName('New Sprite(Splash)').getComponent(
            cc.Sprite
          ).spriteFrame

          var Sunshine =
            this.ShowRewardsView.getChildByName('GivePrize').getChildByName(
              'Sunshine'
            )
          var GivePrize = this.ShowRewardsView.getChildByName('GivePrize')
          Sunshine.scaleX = 0
          Sunshine.scaleY = 0
          GivePrize.scaleX = 0
          GivePrize.scaleY = 0
          Sunshine.stopAllActions()
          GivePrize.stopAllActions()
          this.scheduleOnce(function () {
            var sc2 = cc.scaleTo(0.5, 0.8, 0.8)
            Sunshine.runAction(sc2)
            var sc3 = cc.scaleTo(0.5, 1.3, 1.3)
            GivePrize.runAction(sc3)

            var repeat = cc.repeatForever(cc.rotateBy(5.0, 360))
            Sunshine.runAction(repeat)
          }, 0.1)

          //CloseBtn
          let close = this.ShowRewardsView.getChildByName('close')
          let clickEventHandler = new cc.Component.EventHandler()
          clickEventHandler.target = this.node
          clickEventHandler.component = 'ManageUI'
          clickEventHandler.handler = 'OnShowRewardsViewClose'
          let button = close.getComponent(cc.Button)
          button.clickEvents.push(clickEventHandler)
        }.bind(this)
      )

      return
    }
    //No Enough Diamond
    cc.loader.loadRes(
      'prefab/ShowNoMoney',
      function (err, texture) {
        this.ShowNoMoneyView = cc.instantiate(texture)
        this.BuildView.addChild(this.ShowNoMoneyView)
        let DetailLabel = this.ShowNoMoneyView.getChildByName('DetailLabel')
        DetailLabel.getComponent(cc.Label).string = '钻石不够！'

        this.scheduleOnce(
          function () {
            this.ShowNoMoneyView.destroy()
          }.bind(this),
          1
        )
      }.bind(this)
    )
  },
  OnShowRewardsViewClose(event, CustomEventData) {
    this.ShowRewardsView.destroy()
  },

  //弹出购买提示
  onPurchaseTips(_contentButton) {
    // cc.log('是否用钻石购买建筑', _contentButton.node.name);

    if (this.TipViewPrefab) {
      let _TipView
      _TipView = cc.instantiate(this.TipViewPrefab)
      _TipView.parent = this.TipView
      _TipView.setPosition(cc.v2(0, 0))
      _TipView
        .getComponent('TipView')
        .onShowTip({ ContentButton: _contentButton, TipViewNode: this.TipView })
      // cc.log(_TipView.name);
    }
  },
  //点击了建造列表里面的按钮时候改变样式
  onSetButtonState(Data, Synopsis) {
    cc.Component.EventHandler.emitEvents(Data.Target.clickEvents)
  },
  onSetButtonInfoState(Data, Synopsis) {
    if (Synopsis) {
      this.onSetButtonInfo(Synopsis.Name, Synopsis.Price, Synopsis.Mature, Synopsis.Synopsis)
    }
  },
  //设置介绍信息
  onSetButtonInfo(_Name, _Price, _Mature, _Synopsis) {
    this.BuildContent_Name.string = _Name
    this.BuildContent_Mature.string = _Mature
    this.BuildContent_Price.string = "x" + _Price
    this.BuildContent_Synopsis.string = _Synopsis.replace(/\n|\r/g, '')
  },

  /**
   * 设置商城信息
   * @param {}} Data
   * @param {*} Synopsis
   */
  onSetMallInfoState(Data, Synopsis) {
    if (Synopsis) {
      this.onSetMallInfo(
        Synopsis.Name,
        Synopsis.Mature,
        Synopsis.CNT,
        Synopsis.SNB,
        Synopsis.Synopsis
      )
    }
  },
  //设置介绍信息
  onSetMallInfo(_Name, _mature, _CNT, _SNB, _Synopsis) {
    this.mallContent_Name.string = _Name
    this.mallContent_Price.string = _CNT
    this.mallContent_SNBPrice.string = _SNB;
    this.mallContent_Mature.string = _mature
    this.mallContent_Synopsis.string = _Synopsis.replace(/\n|\r/g, '')
  },
  //编辑对应的建筑
  onEditorialBuildings(mUI_buildTarget) {
    if (!this.EditorialBuildings) {
      cc.warn('EditorialBuildings is Null!')
      return
    }
    this.EditorialBuildings.active = true
    //重置上一个编辑建筑的状态
    if (this._buildTarget && this._buildTarget.getComponent('buildingsTouch')) {
      this._buildTarget.getComponent('buildingsTouch').onCancelEdit()
    }
    this._buildTarget = mUI_buildTarget
    this.EditorialBuildings.parent = mUI_buildTarget
    this.EditorialBuildings.setPosition(cc.v2(0, 0))
  },
  //取消编辑
  onCancellationEditor() {
    //获取建筑物上的组件
    let buildTouch = this._buildTarget.getComponent('buildingsTouch')
    let isTaskNext = buildTouch.onTaskBuild()
    if (!isTaskNext) return
    if (task.isMushBuildState) {
      cc.loader.loadRes(
        'resUI/ShowNotEnoughMoney',
        function (err, texture) {
          var prefab = cc.instantiate(texture)
          prefab.getComponent('ShowNotEnoughMoney').Text("请点击'√'号")
          this._buildTarget.addChild(prefab)
        }.bind(this)
      )
      return
    }
    // if (buildTouch) {
    buildTouch.onCancelEdit()
    // }

    this.EditorialBuildings.active = false
    this.EditorialBuildings.parent = this._thisEditBuildingsParent
    this.EditorialBuildings.setPosition(cc.v2(10000, 100))
    this._buildTarget = null
  },
  //确定编辑(创建建筑物 对号)
  onConfirmationEditor() {
    //获取建筑物上的组件
    let buildTouch = this._buildTarget.getComponent('buildingsTouch')
    let isTaskNext = buildTouch.onTaskBuild()
    if (!isTaskNext) return
    // if (buildTouch) {
    buildTouch.onFinishEdit()
    // }

    this.EditorialBuildings.active = false
    this.EditorialBuildings.parent = this._thisEditBuildingsParent
    this.EditorialBuildings.setPosition(cc.v2(10000, 100))

    this._buildTarget = null
  },

  //如果相等的话返回true
  verctor3IsEqual(vector1, vector2) {
    let isEqual = false
    let out = new cc.Vec3()
    out.x = vector2.x - vector1.x
    out.y = vector2.y - vector1.y
    out.z = vector2.z - vector1.z
    if (out.x == 0 && out.y == 0 && out.z == 0) {
      isEqual = true
    }
    return isEqual
  },
  //收起全部菜单
  onHideMenu() {
    // if (this.BuildView) {
    //     this.BuildView.active = false;
    // }
    //音效设置界面
    if (this.SettingInfoView.active)
      this.onSetTouchStatus(this.SettingInfoView, false)
    //建造界面
    // if (this.BuildView.active) this.onSetTouchStatus(this.BuildView, false)
    //人才界面
    // if (this.PersonnelView.active)
    //   this.onSetTouchStatus(this.PersonnelView, false)
    //股票界面
    // if (this.StockView.active) this.onSetTouchStatus(this.StockView, false)
    //转盘界面
    // if (this.LuckView.active) this.onSetTouchStatus(this.LuckView, false)
    //商城界面
    if (this.StoreView.active) this.onSetTouchStatus(this.StoreView, false)
  },

  //底部菜单栏
  onBottomMenuView(isActive) {
    if (this.BottomView) {
      this.BottomView.active = isActive
    }

    // cc.log('不能显示面板信息：');
    GlobalD.GameControl._isBuildingCanEdit = !isActive
  },

  //农场界面相关菜单
  onOtherFarmerView(isActive) {
    if (this.OtherFarmerMask) {
      this.OtherFarmerMask.active = isActive
    }
  },
  //开启信息显示
  onShowBuildingInfo(buildingInfo) {
    this.BuildingInfoView.active = true
    if (!this._buildingInfoViewScript)
      this._buildingInfoViewScript =
        this.BuildingInfoView.getComponent('buildingInfoView')

    //显示房屋信息
    this._buildingInfoViewScript.onSetBuildingInfoView(buildingInfo)
  },
  //关闭信息显示
  onCloseBuildingInfo() {
    this.BuildingInfoView.active = false
  },
  //进入编辑模式，
  onEnterEditing() { },
  onSetTouchStatus(target, isActive) {
    target.active = isActive
    if (this.UITouch) {
      this.UITouch.active = isActive
    }
  },

  /**
   * 绑定邀请
   */
  onInvite_Open() {
    this.inviteNode.getComponent('inviteInfo').onOpenInviteInfo()
  },

  onListUserInfo_Open() {
    this.listUserInfoNode.getComponent('userListInfo').onOpen()
  },

  onListUserInfo_Close() {
    this.listUserInfoNode.getComponent('userListInfo').onClose()
  },

  //点击钻石兑换
  onButtonEvent_Exchange() {
    this.DiamondGapView.active = true
    // this.onSetTouchStatus(this.DiamondGapView, true)
    //判断钻石数量是否大于等于3万个
    if (GlobalD.GameData.GetDiamond() < 30000) {
      this.ExchangeBtn.interactable = false
      // GlobalD.GameData.showToast(
      //   cc.find('Canvas/UICamera'),
      //   '钻石数量不够，累积到30000个钻石即可免费兑换一包辣椒种子。',
      //   2
      // )
      return
    } else {
      this.ExchangeBtn.interactable = true
    }
  },
  //点击取消钻石兑换
  onButtonEvent_ExchangeCancel() {
    this.DiamondGapView.active = false
  },

  //点击确认钻石兑换辣椒种子
  onButtonEvent_ExchangeChili() {
    let diamonAmount = 30000
    //调用兑换接口
    GlobalD.GameData.exchangeSeed(diamonAmount, (value) => {
      return
      //兑换成功
      if (0 === value.code) {
        var BuildingView = cc
          .find('Canvas/UICamera/BuildingContainer/BuildingView')
          .getComponent('BuildingView')
        BuildingView.onUpdateList()

        this.DiamondGapView.active = false
        this.DiamondSeedsView.active = true

        //光芒旋转
        var rotate = cc.repeatForever(cc.rotateBy(2, -100, 0))
        this.LightRotate.runAction(rotate)
      } else {
        //兑换失败
        GlobalD.GameData.showToast(cc.find('Canvas/UICamera'), value.msg, 2)
      }
    })
  },

  //点击钻石兑换的确认按钮
  onButtonEvent_DiamondSure() {
    this.DiamondSeedsView.active = false
    //停止光芒旋转
    this.LightRotate.stopAllActions()
  },

  //音效设置界面
  onButtonEvent_Setting_OPen() {
    this.onHideMenu()
    this.onSetTouchStatus(this.SettingInfoView, true)
  },
  onButtonEvent_Setting_Close() {
    this.onSetTouchStatus(this.SettingInfoView, false)
  },
  //建造界面
  onButtonEvent_Building_OPen() {
    this.onHideMenu()
    this.onSetTouchStatus(this.BuildView, true)
    this.BuildView.getComponent('BuildingView').onSwitchBuildingContent(
      null, //this.Evn.getComponent(cc.Button)
      4
    )
  },
  //商城界面
  onButtonEvent_Store_OPen() {
    this.onHideMenu()
    this.onSetTouchStatus(this.StoreView, true)
    this.StoreView.getComponent('StoreView').onSwitchBuildingContent(
      this.Seed.getComponent(cc.Button),
      0
    )
  },
  novice: function () {
    var BuildingView = cc.find('Canvas/UICamera/BuildingContainer/BuildingView')
    task.removeTaskNode(task.taskCursorName[2]) //左上
    task.addTaskTips(
      BuildingView,
      task.taskPrefab[1],
      -180,
      180,
      task.taskCursorName[2],
      function (nodePrefabs) {
        //手指
        this.nodePrefabs = nodePrefabs
      }.bind(this)
    )
  },
  novice1: function () {
    var BuildingView = cc.find('Canvas/UICamera/BuildingContainer/BuildingView')
    task.addTaskTips(
      BuildingView,
      task.novice[1],
      0,
      50,
      task.taskCursorName[3],
      function (node) {
        UtilsPrefabs.setOn(
          node.getChildByName('SureBtn'),
          function () {
            UtilsPrefabs.setOff(node.getChildByName('SureBtn'))

            var mt = cc.moveTo(1, 110, 180) //右上

            var finished = cc.callFunc(
              function () {
                task.removeTaskNode(task.taskCursorName[3])
                this.novice2()
              }.bind(this)
            )
            var sequence = cc.sequence(mt, finished)
            this.nodePrefabs.runAction(sequence)

            task.isShowTaskNode(task.taskCursorName[3], false)
          }.bind(this)
        )
      }.bind(this)
    )
  },
  novice2: function () {
    var BuildingView = cc.find('Canvas/UICamera/BuildingContainer/BuildingView')
    task.addTaskTips(
      BuildingView,
      task.novice[2],
      0,
      50,
      task.taskCursorName[3],
      function (node) {
        UtilsPrefabs.setOn(
          node.getChildByName('SureBtn'),
          function () {
            UtilsPrefabs.setOff(node.getChildByName('SureBtn'))

            var mt = cc.moveTo(1, -200, 0) //

            var finished = cc.callFunc(
              function () {
                task.removeTaskNode(task.taskCursorName[3])
                this.novice3()
              }.bind(this)
            )
            var sequence = cc.sequence(mt, finished)
            this.nodePrefabs.runAction(sequence)

            task.isShowTaskNode(task.taskCursorName[3], false)
          }.bind(this)
        )
      }.bind(this)
    )
  },
  novice3: function () {
    var BuildingView = cc.find('Canvas/UICamera/BuildingContainer/BuildingView')
    task.addTaskTips(
      BuildingView,
      task.novice[3],
      0,
      -150,
      task.taskCursorName[3],
      function (node) {
        UtilsPrefabs.setOn(
          node.getChildByName('SureBtn'),
          function () {
            task.removeTaskNode(task.taskCursorName[3])
          }.bind(this)
        )
      }.bind(this)
    )
  },

  //外面管理的手指
  novicepersonnel: function () {
    task.removeTaskNode(task.taskCursorName[2]) //左上
    task.addTaskTips(
      task.personnelview,
      task.taskPrefab[1],
      0,
      0,
      task.taskCursorName[2],
      function (nodePrefabs) {
        //手指
        this.nodePrefabs = nodePrefabs
      }.bind(this)
    )
  },
  //外面的 建筑手指
  noviceBuilding: function () {
    //建造农舍指引
    task.showTiledTile(0, 0, 0, 23, 25)
  },
  novice4: function () {
    var BuildingView = cc.find('Canvas/UICamera/BuildingContainer/BuildingView')
    task.addTaskTips(
      BuildingView,
      task.novice[4],
      0,
      -200,
      task.taskCursorName[3],
      function (node) {
        UtilsPrefabs.setOn(
          node.getChildByName('SureBtn'),
          function () {
            task.removeTaskNode(task.taskCursorName[3])
          }.bind(this)
        )
      }.bind(this)
    )
  },
  //关闭 建造框
  onButtonEvent_Building_Close() {
    // cc.log(this.BuildView);
    this.onSetTouchStatus(this.BuildView, false)
  },
  //关闭 商城框
  onButtonEvent_Store_Close() {
    this.onSetTouchStatus(this.StoreView, false)
  },
  //人才界面
  onButtonEvent_Personnel_OPen() {
    this.onHideMenu()
    this.onSetTouchStatus(this.PersonnelView, true)
  },
  onButtonEvent_Personnel_Close() {
    this.onSetTouchStatus(this.PersonnelView, false)
  },
  //股票界面
  onButtonEvent_Stock_OPen() {
    this.onHideMenu()
    this.onSetTouchStatus(this.StockView, true)
    // console.log("所有建筑物数据", GlobalD.game.buildingsTiledMapUnit);
    UtilsWX.lookRankList(true)
    this.showFriend()
  },
  //限制
  returnDialog: function (cursor) {
    var num = 0
    // console.log("要创建什么提示呢数字", cursor);
    switch (cursor) {
      case 1:
        num = 0
        break
      case 4:
        num = 1
        break
      case 6:
        num = 2
        break
    }
    console.log('要创建什么提示呢', task.returnPrefab[num])
    var Canvas = cc.find('Canvas/UICamera')
    task.addTaskTips(
      Canvas,
      task.returnPrefab[num],
      0,
      0,
      task.taskCursorName[4],
      function (nodePrefabs) {
        UtilsPrefabs.setOn(
          nodePrefabs.getChildByName('SureBtn'),
          function () {
            task.removeTaskNode(task.taskCursorName[4])
          }.bind(this)
        )
      }.bind(this)
    )
  },

  showFriend: function () {
    // var data1 = {
    //     name: "Whoareyou",
    //     openId : userData.openId
    // }
    // UtilsWX.postMessage(data1);
    var data = {
      name: 'showFriend',
    }
    UtilsWX.postMessage(data)
  },

  onButtonEvent_Stock_Close() {
    this.onSetTouchStatus(this.StockView, false)
    var data = {
      name: 'hideFriend',
    }
    UtilsWX.postMessage(data)
    setTimeout(
      function () {
        UtilsWX.lookRankList(false)
      }.bind(this),
      200
    )
  },
  //转盘界面
  onButtonEvent_Luck_OPen() {
    this.onHideMenu()
    this.onSetTouchStatus(this.LuckView, true)
    if (this.nodePrefabsLuck != null) {
      task.removeNode(this.nodePrefabsLuck)
    }
  },
  isTask: function (obj) {
    var Canvas = cc.find('Canvas/UICamera')
    UtilsPrefabs.init(Canvas).addPrefabs(
      UtilsPrefabs.sharePrefab[1],
      null,
      function (node) {
        var gosharebtn = UtilsPrefabs.getNode('gosharebtn', node)

        var close = UtilsPrefabs.getNode('close', node)
        UtilsPrefabs.setOn(
          close,
          function () {
            UtilsPrefabs.removePrefabs(Canvas, node.name)
            if (task.TaskIconCountClick == 5) {
              if (obj.currentTarget.name == 'GetGift') {
                task.addTaskIconCountClick()
                task.removeTaskNodes()
              }
            }
          }.bind(this)
        )

        UtilsPrefabs.setOn(
          gosharebtn,
          function () {
            // console.log("点击分享按钮");

            UtilsWX.sharebtn(
              function () {
                UtilsPrefabs.setOff(gosharebtn)
                GlobalD.GameData.PlusGolden(GlobalD.GameData.shareGive[0])
                GlobalD.GameData.PlusDiamond(GlobalD.GameData.shareGive[1])
                if (task.TaskIconCountClick == 5) {
                  if (obj.currentTarget.name == 'GetGift') {
                    task.addTaskIconCountClick()
                    task.removeTaskNodes()
                  }
                }
              }.bind(this)
            )
            UtilsPrefabs.removePrefabs(Canvas, node.name)
          }.bind(this)
        )
      }.bind(this)
    )
  },
  isTask4: function () {
    if (task.TaskIconCountClick == 4) {
      task.addTaskIconCountClick()
      task.removeTaskNodes()
    }
  },
  onButtonEvent_Luck_Close(obj) {
    // console.log("现在是谁点的", obj);
    let Wheel = this.LuckView.getChildByName('Wheel').getComponent('Wheel')
    Wheel.node.active = true
    Wheel.ShowRewards.active = false

    this.onSetTouchStatus(this.LuckView, false)

    if (obj.target.name == 'GetGift') {
      this.isTask(obj)
    }
  },
  onButtonEvent_EveryDay_OPen() {
    this.onHideMenu()
    this.onSetTouchStatus(this.EveryDaySignView, true)
    //打开每日签到 外面的按钮
    if (task.TaskIconCountClick == 4) {
      var EveryDaySign = cc.find(
        'Canvas/UICamera/OverTheMask/EveryDaySignContainer/EveryDaySignView'
      )
      // var Canvas = cc.find("Canvas/UICamera");
      // task.removeTaskNodes();

      task.removeTaskNode(task.taskCursorName[4])
      task.addTaskTips(
        EveryDaySign,
        task.taskPrefab[1],
        20,
        -470,
        task.taskCursorName[4],
        function (nodePrefabs) { }.bind(this)
      )
    }
  },
  onButtonEvent_EveryDay_Close() {
    this.onSetTouchStatus(this.EveryDaySignView, false)
  },
  onShowRewards: function (Index) {
    let ManageBuildingScript = this.node.getComponent('ManageBuildings')
    console.log('走了吗', Index)

    let GivePrize = this.ShowRewards.getChildByName('GivePrize')
    let Rewards = GivePrize.getChildByName('Rewards')

    Rewards.getComponent(cc.Sprite).spriteFrame = this.BuildingFrameArray[
      Index
    ].getChildByName('New Sprite(Splash)').getComponent(cc.Sprite).spriteFrame

    //开始播放
    var Sunshine =
      this.ShowRewards.getChildByName('GivePrize').getChildByName('Sunshine')
    Sunshine.scaleX = 0
    Sunshine.scaleY = 0
    GivePrize.scaleX = 0
    GivePrize.scaleY = 0
    Sunshine.stopAllActions()
    GivePrize.stopAllActions()
    this.scheduleOnce(function () {
      this.ShowRewards.opacity = 255
      this.ShowRewards.active = true
      var sc2 = cc.scaleTo(1, 0.5, 0.5)
      Sunshine.runAction(sc2)
      var sc3 = cc.scaleTo(1, 1, 1)
      GivePrize.runAction(sc3)

      var repeat = cc.repeatForever(cc.rotateBy(5.0, 360))
      Sunshine.runAction(repeat)
    }, 0.1)
  },
  onCloseShowRewards: function () {
    this.ShowRewards.active = false
  },

  DiamondGapViewShow: function () {
    this.DiamondGapView.active = true
  },
  GoldenChangeCallBack: function (Num, LastMoney, CurrentMoney) {
    let Scale = 30
    let Index = -1
    // if(Num>10*Scale)
    // {
    //     Index = 7;//伐木场
    // }
    // if(Num>30*Scale)
    // {
    //     Index = 8;//矿坑
    // }

    // if(Num>70*Scale)
    // {
    //     // Index = 9;//加工厂
    // }

    // if(Num>350*Scale && Num<450*Scale)
    // {
    //     Index = 4;//单元楼
    // }
    if (Num > 4000 && Num < 4500) {
      Index = 4 //单元楼
    }
    // else if(Num>450*Scale && Num<550*Scale)
    // {
    //     Index = 11;//鲜花店
    // }
    else if (Num > 4500 && Num < 5500) {
      Index = 11 //鲜花店
    } else if (Num > 550 * Scale && Num < 650 * Scale) {
      Index = 12 //甜品店
    }
    if (Num > 650 * Scale && Num < 750 * Scale) {
      Index = 7 //伐木场
    } else if (Num > 750 * Scale && Num < 950 * Scale) {
      Index = 13 //汉堡店
    }
    // else if(Num>850*Scale)
    // {
    //     Index = 0;//公路
    // }
    else if (Num > 950 * Scale && Num < 1050 * Scale) {
      Index = 14 //咖啡店
    } else if (Num > 1050 * Scale && Num < 1150 * Scale) {
      Index = 5 //别墅
    } else if (Num > 1150 * Scale && Num < 1250 * Scale) {
      Index = 15 //洋装店
    }
    if (Num > 1250 * Scale && Num < 1350 * Scale) {
      Index = 8 //矿坑
    } else if (Num > 1350 * Scale) {
      Index = 16 //酒吧
    }
    // else if(Num>250*Scale)
    // {
    //     Index = 4;//单元楼
    // }
    // else if(Num>600*Scale)
    // {
    //     Index = 5;//别墅
    // }

    var BuildingStateArray = GlobalD.GameData.GetBuildingStateArray()
    if (Index == 0) {
      if (BuildingStateArray[Index] != 1) {
        BuildingStateArray[0] = 1 //公路
        BuildingStateArray[1] = 1 //路铲
        BuildingStateArray[2] = 1 //拆迁

        let Building0 =
          this.node.getComponent('ManageBuildings').BuildingArray[0]
        let Building1 =
          this.node.getComponent('ManageBuildings').BuildingArray[1]
        let Building2 =
          this.node.getComponent('ManageBuildings').BuildingArray[2]
        Building0.active = true
        Building1.active = true
        Building2.active = true

        GlobalD.GameData.SetBuildingStateArray(BuildingStateArray)
        this.onShowRewards(Index)
      }
    } else {
      if (BuildingStateArray[Index] != 1 && Index != -1) {
        cc.log('Index=' + Index)
        BuildingStateArray[Index] = 1
        let Building =
          this.node.getComponent('ManageBuildings').BuildingArray[Index]
        Building.active = true

        GlobalD.GameData.SetBuildingStateArray(BuildingStateArray)
        this.onShowRewards(Index)
      }
    }

    let Diff = CurrentMoney - LastMoney
    let InitMoneyNum = LastMoney
    let AnimTimes = 0
    let Times = 3
    this.schedule(
      function () {
        if (Diff > 0) {
          InitMoneyNum += parseInt((CurrentMoney - LastMoney) / Times)
        } else {
          InitMoneyNum -= parseInt((CurrentMoney - LastMoney) / Times)
        }

        let result = this.FormatMoney(InitMoneyNum)
        if (AnimTimes == Times - 1) {
          this.Goldenlabel.getComponent(cc.Label).string =
            this.FormatMoney(CurrentMoney)
          return
        }
        this.Goldenlabel.getComponent(cc.Label).string = result
        AnimTimes++
      },
      0.05,
      Times
    )
  },
  DiamondChangeCallBack: function (Num, LastMoney, CurrentMoney) {
    let Diff = CurrentMoney - LastMoney
    let InitMoneyNum = LastMoney
    let AnimTimes = 0
    let Times = 3
    this.schedule(
      function () {
        if (Diff > 0) {
          InitMoneyNum += parseInt((CurrentMoney - LastMoney) / Times)
        } else {
          InitMoneyNum -= parseInt((CurrentMoney - LastMoney) / Times)
        }

        let result = this.FormatMoney(InitMoneyNum)
        if (AnimTimes == Times - 1) {
          // this.DiamondNowlabel.string = result + '/30000'
          this.Diamondlabel.getComponent(cc.Label).string =
            this.FormatMoney(CurrentMoney)

          return
        }
        // this.DiamondNowlabel.string = result + '/30000'
        this.Diamondlabel.getComponent(cc.Label).string = result
        AnimTimes++
      },
      0.05,
      Times
    )
  },

  CNTChangeCallBack: function (Num) {
    this.CNTlabel.getComponent(cc.Label).string = this.formatPrice(Num)
  },
  SNBChangeCallBack: function (Num) {
    this.SNBlabel.getComponent(cc.Label).string = this.formatPrice(Num);
  },
  formatPrice(price) {
    return String(price).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  },
  FormatMoney(s, n) {
    n = n > 0 && n <= 20 ? n : 2
    s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(n) + ''
    var l = s.split('.')[0].split('').reverse(),
      r = s.split('.')[1]
    let t = ''
    for (let i = 0; i < l.length; i++) {
      t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? ',' : '')
    }
    return t.split('').reverse().join('') //+ "." + r;
  },



  /**
   * 偷取果实
   */
  onStealAllFruit() {
    //todo 偷取之前本地判断下体力值
    if (GlobalD.PlayerAttribute.currentStrength <= 0) {
      GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "体力不足，无法收取作物！", 1);
      return;
    }

    GlobalD.GameData.onStealAllFruit({ otherUserId: GlobalD.OtherUserInfo.userId }, (value) => {
      console.log(value);

      if (0 === value.code) {
        if (0 !== value.data.stealSum) {
          // if (this.StealViewSuccessPrefab) {
          //   let _TipView = cc.instantiate(this.StealViewSuccessPrefab)
          //   _TipView.parent = this.TipView
          //   _TipView.setPosition(cc.v2(0, 0))
          //   _TipView
          //     .getComponent('StealViewSuccess')
          //     .setInfo({ amount: value.data.stealSum });
          // }
          this.onInitStealViewSuccessPrefab(value.data);

          let BuildingView = cc.find('Canvas/UICamera/BuildingContainer/BuildingView').getComponent('BuildingView');
          BuildingView.onUpdateList();

          //偷取成功后，关闭对应土地的提示图标
          let _landBuildingsInfo = cc.find("Canvas/MyMapNode").children;
          let _stealList = value.data.steals;
          for (let j = 0; j < _stealList.length; j++) {
            for (let i = _landBuildingsInfo.length - 1; i >= 0; i--) {
              let resetLandInfo = _landBuildingsInfo[i];
              if (resetLandInfo.name == "Labour_205_Holy_Farmland") {
                let leaseFarmlandInfoScript = resetLandInfo.getComponent("LeaseFarmlandInfo");
                if (leaseFarmlandInfoScript.leaseLandInfo && leaseFarmlandInfoScript.leaseLandInfo.configLandId == _stealList[j].landId) {
                  leaseFarmlandInfoScript.onHideStealHarvest();
                }
              }

            }
          }
        } else {
          GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "未偷取到果实！", 1);
        }
      } else {
        GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), value.msg, 1);
      }

    });
  },

  /**
   * 生成一个提示面板
   * @param {偷取对象} stealObj 
   */
  onInitStealViewSuccessPrefab(stealObj) {
    if (this.StealViewSuccessPrefab) {
      let _TipView = cc.instantiate(this.StealViewSuccessPrefab)
      _TipView.parent = this.TipView
      _TipView.setPosition(cc.v2(0, 0))
      _TipView
        .getComponent('StealViewSuccess')
        .setSingleStealInfo(stealObj);
    }
  },
  //体力值
  StrengthChangeCallBack: function (Num) {
    this.Strengthlabel.getComponent(cc.Label).string = Num
  },
  //幸运值
  LuckyChangeCallBack: function (Num) {
    this.Luckylabel.getComponent(cc.Label).string = Num
  },

  //小狗和木棒
  onSettingDogAlpha(opacity) {
    this.dogButtonNode.opacity = opacity;
  },
  onSettingStickAlpha(opacity) {
    this.stickButtonNode.opacity = opacity;
  },

  onDetectDog() {
    if (GlobalD.Dog) {
      if (GlobalD.Dog.remainingConsumption > 0) {
        GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "已经拥有小狗。", 1);
      } else {
        GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "需要点击狗盆购买狗粮。", 1);
      }
    } else {
      GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "尚未拥有小狗。", 1);
    }
  },
  onDetectStick() {
    if (GlobalD.Stick) {
      GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "已经装备打狗棒。", 1);
    } else {
      GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "尚未购买打狗棒。", 1);
    }
  }
})
