cc.Class({
  extends: cc.Component,
  properties: {
    isSwiveling: false,    // 是否回头
    totalTime: 45 * 1000,  // 总时间, bed 
    animationTime: 1 * 1000,   // 转头过程单位时间, bed
    needSwivelCount: 10, // 需要回头的次数
    game: {
      default: null,
      type: cc.Node,
    },
    bigHead: {
      default: null,
      type: cc.Node,
    },
    coming: {
      default: null,
      type: cc.Node,
    }
  },

  onLoad: function() {
    this.startSwivel()
  },

  swivelAnimation: function() {
    var time = this.animationTime / 8 / 1000

    var enableSwivel = cc.callFunc(function() {
      this.isSwiveling = true
    }, this)

    var disableSwivel = cc.callFunc(function() {
      this.isSwiveling = false
    }, this)

    var coming = cc.find("coming", this.node)
    var bigHead = cc.find("big_head", this.node)

    var comingAction = cc.sequence(
      cc.moveTo(time, cc.p(100, 0)),
      cc.delayTime(time),
      cc.moveTo(time, cc.p(-50, 0)),
      cc.delayTime(time)
    )

    var action = cc.sequence(
      cc.delayTime(time * 4),   // for coming time
      cc.moveTo(time, cc.p(100, 0)),
      enableSwivel,
      cc.delayTime(4 * time), 
      cc.moveTo(time, cc.p(0, 0)),
      disableSwivel,
    )
 
    coming.runAction(comingAction)
    bigHead.runAction(action)
  }, 

  update: function(dt) {
    console.log('🐞-checking', this.isSwiveling)
  },

  // 获取转头时间的数组, [0.6, 1.2, 2.3, 3.4, 4.8, 5.2, 6.3]
  getSwivelTimeArray: function(totalTime, count, animationTime) {
    var timeArray = []
    var interval = totalTime / count
    var ratio = animationTime / interval    // 每个时间段前后间隔，避免边界情况
    for (var i = 0; i < count; i++) {
      // var rand = (Math.random() + i) * interval 
      var rand = (Math.random() * (1 - (ratio / 2)) + i) * interval + (animationTime / 2)
      timeArray.push(rand)
    }
    return timeArray
  },

  startSwivel: function() {
    var swivelTimeArray = this.getSwivelTimeArray(this.totalTime, this.needSwivelCount, this.animationTime)
    var lastTime

    var swivelFunc = (timeArray) => {
      const nextTime = timeArray.shift()
      if (nextTime) {
        var intervel = !!lastTime ? (nextTime - lastTime) : nextTime  // 获取下一次的时间间隔
        lastTime = nextTime
        this.swivelAnimation()
        setTimeout(() => {
          swivelFunc(timeArray)
        }, intervel)
      } 
    }

    swivelFunc(swivelTimeArray)
  },

})