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

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'MlFixedHeader',
  props: {
    background: {
      type: Boolean,
      default: true
    },
    backgroundColor: String
  },
  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 () {
      const tabs: any = this.tabs
      if (tabs) {
        return tabs.value
      }
      return null
    }
  },
  watch: {
    activeTab () {
      this.updateStyle()
    }
  },
  mounted () {
    this.updateStyle()
  },
  beforeDestroy () {
    const layout: any = this.layout
    if (layout && layout.setPaddingTop) {
      layout.setPaddingTop('')
    }
  },
  methods: {
    updateStyle () {
      this.$nextTick(() => {
        this.calculateStyle(20)
        this.calculateStyle(50)
        this.calculateStyle(150)
        this.calculateStyle(300)
        this.calculateStyle(800)
        this.calculateStyle(1500)
        this.calculateStyle(4000)
      })
    },
    calculateStyle (timeout: number) {
      setTimeout(() => {
        const query = uni.createSelectorQuery().in(this)
        query.select('.ml-fixed-header-warpper').boundingClientRect((data: any) => {
          const layout: any = this.layout
          if (data && data.height && layout && layout.setPaddingTop) {
            layout.setPaddingTop(`${data.height}px`)
          }
        }).exec()
      }, timeout || 20)
    }
  }
})
</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>
