Component({
  properties: {
    title: {
      type: String
    },
    color: {
      type: String,
      value: '#000000'
    },
    background: {
      type: String,
      value: 'rgba(0,0,0,0)'
    },
    home: {
      type: Boolean,
      value: false
    },
    homePath: {
      type: String,
      value: '/pages/map/map'
    },
    placeholder: {
      type: Boolean,
      value: true
    },
    autoFixed: {
      type: Boolean,
      value: true
    },
    autoFixedDistance: {
      type: Number,
      value: 4
    },
    autoFixedStyle: {
      type: String
    },
  },
  data: {
    fixed: false,
    showBack: false,
    height: 56,
    barHeight: 32
  },
  lifetimes: {
    ready() {
      const NAVIGATION_HEIGHT_CACHE = `NAVIGATION_HEIGHT`
      const NAVIGATION_BAR_HEIGHT_CACHE = `NAVIGATION_BAR_HEIGHT`
      const pages = getCurrentPages()
      let height = wx.getStorageSync(NAVIGATION_HEIGHT_CACHE) || 0
      let barHeight = wx.getStorageSync(NAVIGATION_BAR_HEIGHT_CACHE) || 0
      if (!height || !barHeight) {
        const menuButtonRect = wx.getMenuButtonBoundingClientRect()
        height = menuButtonRect.bottom
        barHeight = height - menuButtonRect.top
        wx.setStorageSync(NAVIGATION_HEIGHT_CACHE, height)
        wx.setStorageSync(NAVIGATION_BAR_HEIGHT_CACHE, barHeight)
      }
      this.setData({
        showBack: pages.length > 1,
        height,
        barHeight
      })
      this.triggerEvent('ready', {
        navigationBarHeight: height + 6,
        statusBarHeight: height - barHeight
      })
    },
    attached() {
      if (this.data.autoFixed) {
        this._createIntersectionObserver()
      }
    }
  },
  methods: {
    back() {
      wx.navigateBack()
    },
    backHome() {
      wx.reLaunch({
        url: this.data.homePath
      })
    },
    _createIntersectionObserver() {
      wx.nextTick(() => {
        const observer = wx.createIntersectionObserver(this, { initialRatio: 1, observeAll: false })
        observer.relativeToViewport().observe('.navigation-observer', () => {
          const fixed = !this.data.fixed
          this.setData({
            fixed
          })
          this.triggerEvent('fixed', {
            status: fixed
          })
        })
      })
    }
  }
})