<template>
  <view class="ml-fixed-header" :class="{'is-background': background}" :style="styles">
    <view class="ml-fixed-header-warpper">
      <slot></slot>
    </view>
  </view>
</template>

<script>
export default {
  name: 'MlFixedHeader',
  props: {
    background: {
      type: Boolean,
      default: true
    },
    backgroundColor: String
  },
  data () {
    return {
      isActive: true
    }
  },
  provide () {
    return {
      $pageFixedTop: this
    }
  },
  inject: {
    layout: {
      from: '$pageLayout',
      default: null
    },
    tabs: {
      from: 'mlTabs',
      default: null
    }
  },
  computed: {
    styles () {
      const bgSys = this.backgroundColor ? `background:${this.backgroundColor};` : ''
      return `${bgSys}`
    },
    activeTab () {
      if (this.tabs) {
        return this.tabs.value
      }
      return null
    }
  },
  watch: {
    activeTab () {
      this.updateStyle()
    }
  },
  mounted () {
    this.isActive = true
    this.startUpdateStyle()
  },
  beforeDestroy () {
    clearTimeout(this.usTimeout)
    this.isActive = false
    if (this.layout && this.layout.setPaddingTop) {
      this.layout.setPaddingTop('')
    }
  },
  destroyed () {
    this.isActive = false
  },
  methods: {
    startUpdateStyle () {
      if (this.isActive) {
        this.calculateStyle()
        this.usTimeout = setTimeout(() => this.startUpdateStyle(), 1000)
      }
    },
    updateStyle () {
      setTimeout(() => {
        this.calculateStyle()
      }, 100)
    },
    calculateStyle () {
      const query = uni.createSelectorQuery().in(this)
      query.select('.ml-fixed-header-warpper').boundingClientRect((data) => {
        if (data && data.height && this.layout && this.layout.setPaddingTop) {
          this.layout.setPaddingTop(`${data.height}px`)
        }
      }).exec()
    }
  }
}
</script>

<style lang="scss">
.ml-fixed-header {
  position: fixed;
  left: 0;
  top: 0;
  z-index: 33;
  width: $ml-page-full-width;
  box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.1);
  // #ifdef H5
  left: 50%;
  transform: translateX(-50%);
  // #endif
  &.is-background {
    background-color: #ffffff;
  }
  .ml-fixed-header-warpper {
    display: flex;
    flex-direction: column;
  }
}
</style>
