<template>
  <div
    class="mm-tfooter"
    :class="tfooterClass">
    <div
      ref="tfooter"
      class="mm-tfooter-wrapper"
      :style="wrapperStyle"
      @scroll="tfooterProps.scrollHandler">
      <mm-footer
        ref="tfooterInner"  
        v-bind="tfooterProps"
        :columns="columns"></mm-footer>
    </div>
    <mm-tfixed
      v-if="leftColumns.length"
      :store="store"
      position="left">
      <mm-footer
        v-bind="tfooterProps"
        :columns="leftColumns"
        fixed="left"></mm-footer>
    </mm-tfixed>
    <mm-tfixed
      v-if="rightColumns.length"
      :store="store"
      position="right">
      <div :style="helperStyle">
        <mm-footer
          v-bind="tfooterProps"
          :columns="rightColumns"
          fixed="right"></mm-footer>
      </div>
    </mm-tfixed>
  </div>
</template>

<script>
import Tfixed from "./tfixed"
import Footer from "./footer.js"

export default {
  components: {
    "mm-tfixed": Tfixed,
    "mm-footer": Footer,
  },
  props: {
    tfooterProps: Object,
    leftColumns: Array,
    rightColumns: Array,
    columns: Array,
    store: Object,
  },
  computed: {
    tfooterClass() {
      return {
        "mm-tfooter--scrolled": this.scrolled,
      }
    },
    wrapperStyle() {
      const { canScrollX, canScrollY, scrollBarWidth } = this.store.layout
      return {
        marginRight: !canScrollY ? `-${scrollBarWidth}px` : 0,
        marginBottom: !canScrollX ? `-${scrollBarWidth}px` : 0,
      }
    },
    // For align with tbody
    helperStyle() {
      const { canScrollY, scrollBarWidth } = this.store.layout
      return {
        overflow: "scroll",
        marginBottom: `-${scrollBarWidth}px`,
        marginRight: canScrollY ? 0 : `-${scrollBarWidth}px`,
      }
    },
    bodyHeight() {
      return this.store.layout.rowHeightList.reduce((total, item) => total + item, 0)
    },
    scrolled() {
      const { canScrollY, scrollY } = this.store.layout
      const { tbody } = this.store.refs
      if (!tbody) {
        return false
      }

      return canScrollY ? (scrollY + tbody.offsetHeight) < this.bodyHeight : false
    },
  },
  mounted() {
    this.store.setRef("tfooter", this.$refs.tfooter)
    this.store.setRef("tfooterInner", this.$refs.tfooterInner)
  },
}
</script>
