<template>
  <div
    :style="style"
    class="mm-collapse">
    <slot></slot>
  </div>
</template>

<script>
import config from "../../managers/config"

config.defaults({
  "Collapse.accordion": false,
})

export default {
  name: "mm-collapse",
  props: {
    accordion: {
      type: Boolean,
      default: () => config.get("Collapse.accordion"),
    },
    value: {
      type: [Array, String, Number],
      default() {
        return []
      },
    },
    sticky: {
      type: Boolean,
      default: false,
    },
    maxHeight: {
      type: Number,
      default: 0,
    },
  },
  provide() {
    return {
      "mm-collapse": this,
    }
  },
  data() {
    return {
      localValue: [].concat(this.value),
      isSupportSticky: false,
    }
  },
  computed: {
    style() {
      return {
        maxHeight: this.maxHeight ? `${this.maxHeight}px` : "auto",
      }
    },
    itemList() {
      return this.$children.filter(item => item.$options.name === "mm-collapse-item")
    },
  },
  watch: {
    value(val) {
      this.localValue = [].concat(val)
    },
    localValue: {
      immediate: true,
      handler() {
        this.$nextTick(_ => {
          this.$children.forEach((child, index) => {
            child.index = index
          })
        })
      },
    },
  },
  mounted() {
    this.isSupportSticky = this.cssSupport("position", "sticky")
    if (!this.isSupportSticky && this.sticky) {
      this.$el.addEventListener("scroll", this.handleScroll, false)
    }
  },
  beforeDestroy() {
    if (!this.isSupportSticky && this.sticky) {
      this.$el.removeEventListener("scroll", this.handleScroll, false)
    }
  },
  methods: {
    setActiveNames(activeNames) {
      activeNames = [].concat(activeNames)

      this.localValue = activeNames
      this.$emit("input", activeNames)
      this.$emit("change", activeNames)
    },
    handleItemClick(item) {
      if (this.accordion) {
        this.setActiveNames(
          (this.localValue[0] || this.localValue[0] === 0) && this.localValue[0] === item.name
            ? ""
            : item.name
        )
      } else {
        let activeNames = this.localValue.slice(0)
        let index = activeNames.indexOf(item.name)

        if (index > -1) {
          activeNames.splice(index, 1)
        } else {
          activeNames.push(item.name)
        }
        this.setActiveNames(activeNames)
      }
    },
    handleScroll({ target: { scrollTop } }) {
      this.itemList.forEach(item => {
        item.updateFixed(scrollTop)
      })
    },
    cssSupport(attr, value) {
      let element = document.createElement("div")

      if (attr in element.style) {
        element.style[attr] = value
        return element.style[attr] === value
      } else {
        return false
      }
    },
  },
}
</script>
