<template>
  <div class="flexbox-item" :style="style" @click="onClick">
    <slot></slot>
  </div>
</template>
<script>
const prefixList = ['-moz-box-', '-webkit-box-', '']

export default {
  name: 'FlexboxItem',
  props: {
    span: [Number, String],
    order: [Number, String],
    grow: [Number, String]
  },
  methods: {
    buildWidth(width) {
      if (typeof width === 'number') {
        if (width < 1) {
          return width
        } else {
          return width / 12
        }
      } else if (typeof width === 'string') {
        return width.replace('px', '') / this.bodyWidth
      }
    },
    onClick(e) {
      this.$emit('click', e)
    }
  },
  computed: {
    style() {
      let styles = {}

      if (!!this.$parent && !!this.$parent.orient) {
        let marginName = this.$parent.orient === 'horizontal' ? 'marginLeft' : 'marginTop'
        styles[marginName] = `${this.$parent.gutter}px`
      }

      if (this.span) {
        for (let i = 0; i < prefixList.length; i++) {
          styles[prefixList[i] + 'flex'] = `0 0 ${this.buildWidth(this.span) * 100}%`
        }
      }
      if (typeof this.order !== 'undefined') {
        styles.order = this.order
      }
      if (typeof this.grow !== 'undefined') {
        styles['flex-grow'] = this.grow
        styles['min-width'] = 'inherit'
        styles['width'] = 'inherit'
      }
      return styles
    }
  },
  data() {
    return {
      bodyWidth: document.documentElement.offsetWidth
    }
  }
}
</script>
