<template>
  <el-table
    :key="tableKey"
    :data="tableData"
    :header-cell-style="{
      background: '#409eff',
      color: '#fff',
      fontWeight: 'bold',
      fontSize: '14px',
    }"
    border
    class="api-edit-table"
    stripe
    v-bind="$attrs"
  >
    <el-table-column
      v-for="row of rows"
      :key="row"
      :label="row"
      :prop="row"
      fixed
    ></el-table-column>
    <table-column
      v-for="s of columns"
      :key="s.key"
      :data="s"
      :prefix="s.key"
    ></table-column>
  </el-table>
</template>
<script>
import tableColumn from "./tableColumn.vue";
export default {
  components: { tableColumn },
  props: ["chartData", "rowParamList", "columnParamList", "indexParamList"],
  data() {
    return {
      tableData: [],
      columns: [],
      rows: [],
      tableKey: "some",
    };
  },
  mounted() {
    this.flush();
  },
  methods: {
    flush() {
      let { rowParamList, columnParamList, indexParamList, chartData } = this;
      let renameList = rowParamList
        .concat(columnParamList)
        .concat(indexParamList);
      chartData = chartData.map((i) =>
        renameList.reduce(
          (r, j) => ({ ...r, [j.columnComments]: i[j.columnName] }),
          {}
        )
      );
      rowParamList = rowParamList.map((i) => i.columnComments);
      columnParamList = columnParamList.map((i) => i.columnComments);
      indexParamList = indexParamList.map((i) => i.columnComments);
      let mergeData = chartData.reduce(
        (r, item) => {
          let nowColumn = [...columnParamList];
          let prefix = "";
          let childs = r.columns;
          while (nowColumn.length) {
            let columnKey = nowColumn.shift();
            prefix += item[columnKey] + "--";
            let leaf = childs.find((j) => j.key == item[columnKey]);
            if (!leaf) {
              leaf = { key: item[columnKey], children: [] };
              childs.push(leaf);
            }
            childs = leaf.children;
          }
          let valueObject = r.data.find((d) => {
            for (let rowKey of rowParamList) {
              if (d[rowKey] != item[rowKey]) return false;
            }
            return true;
          });
          if (!valueObject) {
            valueObject = rowParamList.reduce(
              (re, ro) => ({ ...re, [ro]: item[ro] }),
              {}
            );
            r.data.push(valueObject);
          }
          indexParamList.forEach((t) => {
            if (!childs.find((c) => c.key == t)) {
              childs.push({ key: t });
            }
            valueObject[prefix + t] = item[t];
          });
          return r;
        },
        { columns: [], data: [] }
      );
      this.rows = rowParamList;
      this.columns = mergeData.columns;
      this.tableData = mergeData.data;
      this.tableKey = Math.random() * 10000;
    },
  },
};
</script>
<style lang="scss">
.api-edit-table {
  overflow-x: scroll;
  height: 100%;
}
</style>
