<template>
  <div class="sv-grid" :class="{'has-border': hasBorder}">
    <slot></slot>
  </div>
</template>

<script type="text/ecmascript-6">
  export default {
    name: 'svGrid',
    props: {
      cols: {
        type: Number,
        default: 3
      },
      hasBorder: {
        type: Boolean,
        default: true
      }
    },
    data () {
      return {
      }
    },
    methods: {
      setGridCellStyles () {
        let clientWidth = this.$el.clientWidth
        let $children = this.$children

        let lastRowNumber = $children.length % this.cols === 0 ? $children.length / this.cols : Math.floor($children.length / this.cols) + 1

        let lastRowFirstCellIndex = (lastRowNumber - 1) * this.cols

        let cellWidth = $children.length < this.cols ? clientWidth / $children.length : clientWidth / this.cols
        let cellWidthStr = cellWidth.toString()

        if (window.parseInt(cellWidth) !== window.parseFloat(cellWidth)) {
          cellWidthStr = cellWidthStr.substring(0, cellWidthStr.indexOf('.') + 5)
        }
        $children.forEach((child, index) => {
          child.$el.style.width = `${cellWidthStr}px`
          if ((index + 1) % this.cols === 0) {
            child.$el.style.borderRight = 'none'
            child.$el.style.marginLeft = '-1px'
          }

          if (index >= lastRowFirstCellIndex) {
            child.$el.style.borderBottom = 'none'
          }
        })
      }
    },
    mounted () {
      this.setGridCellStyles()
    }
  }
</script>

<style lang="scss" rel="stylesheet/scss">
  @import "../../styles/base";
  .sv-grid{
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    background: #f2f2f2;
    &.has-border{
      .sv-grid-cell{
        border-bottom: 1px solid #e8e8e8;
        border-right:1px solid #e8e8e8;
      }
    }
    .sv-grid-cell{
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: pxToRem(30 0);
      box-sizing: border-box;
      .cell-icon{
        line-height: 1;
        margin-bottom: pxToRem(20);
        color: #5c6b77;
        font-size: pxToRem(48);
        .sv-icon{
          font-size: pxToRem(48);
        }
      }
      .cell-text{
        color:#333;
        font-size: pxToRem(26);
      }
    }
  }
</style>
