<template>
  <div class="dimension-tree-table">
    <table class="table">
      <tr
        v-for="(tr, trind) in tableTreeList"
        :key="trind"
        :data-names="tr.names"
        :data-ids="tr.ids"
      >
        <td v-for="(td, tdind) in tr.tdList" :key="tdind" :rowspan="td.rowspan">
          <span>{{ td.name }}</span>
        </td>
        <td>
          <slot :trItem="tr">
            default slot name
          </slot>
        </td>
      </tr>
    </table>
  </div>
</template>

<script>
import { deepCopy } from "@/plugins/utils";

export default {
  name: "dimension-tree-table",
  props: {
    data: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      dataList: [],
      dataListNums: [],
      tableTreeList: []
    };
  },
  watch: {
    data: {
      immediate: true,
      handler(val) {
        this.dataList = deepCopy(val);
        this.getDataListNums();
        this.serilizeTableList();
      }
    }
  },
  methods: {
    getDataListNums() {
      this.dataListNums = this.dataList.map(item => item.length);
    },
    getRowSpan(curIndex) {
      const listNums = this.dataListNums.slice(curIndex + 1);
      return listNums.reduce((sum, item) => sum * item, 1);
    },
    getNextList(curIndex) {
      if (curIndex + 1 >= this.dataList.length) return;
      return this.dataList[curIndex + 1];
    },
    serilizeTableList() {
      if (!this.dataList.length) {
        this.tableTreeList = [];
        this.dataListNums = [];
        return;
      }

      let tableList = [];
      const serilize = (parentList, allParentList, curList, curIndex) => {
        const rowspan = this.getRowSpan(curIndex);
        const nextList = this.getNextList(curIndex);
        curList.map((item, index) => {
          const newParentList = index ? [] : deepCopy(parentList);
          const curItem = { ...item, rowspan };
          const newAllParentList = [...deepCopy(allParentList), curItem];
          const curRow = [...newParentList, curItem];
          if (nextList) {
            serilize(curRow, newAllParentList, nextList, curIndex + 1);
          } else {
            tableList.push({ tdList: curRow, allList: newAllParentList });
          }
        });
      };
      serilize([], [], this.getNextList(-1), 0);

      this.tableTreeList = tableList.map(item => {
        return {
          ...item,
          ids: item.allList.map(elem => elem.id).join("_"),
          names: item.allList.map(elem => elem.name).join("_")
        };
      });
      console.log(this.tableTreeList);
    }
  }
};
</script>
