<!--
 * @Author: ChenChanghua
 * @Date: 2021-09-22 13:47:23
 * @LastEditors: ChenChanghua
 * @LastEditTime: 2022-02-11 17:55:55
 * @Description: file content
-->
<script>
import GridItem from "./GridItem.vue";

export default {
  props: {
    data: Object,
    height: {
      type: Number,
      required: true,
    },
    width: {
      type: Number,
      required: true,
    },
    measures: {
      type: Function,
      required: true,
    },
  },
  components: {
    GridItem,
  },
  created() {
    this.configWidth = this.width;
    this.configHeight = this.height;

    // 通过measure函数，计算item信息
    let measure_result = this.measures();
    let current_line_x = 0;
    let current_line_y = 0;
    for (let idx = 0; idx < this.data.length; idx++) {
      if (current_line_x + measure_result.width > this.configWidth) {
        // new line
        current_line_x = 0;
        current_line_y += measure_result.height;
      }

      this.itemData.push(
        Object.freeze({
          id: idx,
          xPos: current_line_x,
          yPos: current_line_y,
          data: this.data[idx],
        })
      );

      // next item x
      current_line_x += measure_result.width;
    }
  },
  setup() {
    return {
      configWidth: 0,
      configHeight: 0,
      itemData: [],
    };
  },
  mounted() {},
  updated() {},
};
</script>

<template>
  <div
    :style="{ width: configWidth, height: configHeight, overflow: 'hidden' }"
  >
    <grid-item
      v-for="(item, index) in itemData"
      :key="item.id"
      :index="index"
      :data="item"
    >
      <template v-slot:renderItem="slotProps">
        <slot name="renderItem" v-bind="slotProps"></slot>
      </template>
    </grid-item>
  </div>
</template>
