<script>
import VueGridLayout from 'vue-grid-layout'
import { unique } from '@huntianning/components/src/utils/string'

export default {
  name: 'UiMasonryItem',
  components: {
    GridItem: VueGridLayout.GridItem
  },
  inject: ['UiMasonry'],
  props: {
    id: {
      type: String
    },
    x: {
      type: Number,
      default: 0,
      required: true
    },
    y: {
      type: Number,
      default: 0,
      required: true
    },
    w: {
      type: Number,
      default: 1,
      required: true
    },
    h: {
      type: Number,
      default: 1,
      required: true
    },
    minW: {
      type: Number,
      default: 1
    },
    minH: {
      type: Number,
      default: 1
    },
    maxW: {
      type: Number,
      default: Infinity
    },
    maxH: {
      type: Number,
      default: Infinity
    }
  },
  data() {
    return {
      ready: false,
      info: {
        count: 0
      }
    }
  },
  computed: {
    uid() {
      return this.id || unique()
    },
    margin() {
      return this.UiMasonry.margin
    },
    item() {
      return {
        i: this.uid,
        w: this.w,
        h: this.h,
        x: this.x,
        y: this.y
      }
    }
  },
  created() {
    this.UiMasonry.addItem(this.item, {
      minW: this.minW,
      minH: this.minH,
      maxW: this.maxW,
      maxH: this.maxH
    }, {
      info: this.info
    }, {
      functional: true,
      render: () => {
        if (!this.ready) {
          return null
        }
        if (!this.$scopedSlots.default) {
          return null
        }
        return this.$scopedSlots.default()
      }
    })
  },
  mounted() {
    this._timer = setTimeout(() => {
      this.ready = true
    })
  },
  updated() {
    this.info.count++
  },
  beforeDestroy() {
    this.UiMasonry.removeItem(this.uid)
    clearTimeout(this._timer)
  },
  render() {
    return null
  }
}
</script>
