<template>
  <el-table :data="tableData" border :height="height" :key="tableKey">
    <template v-for="item in tableHeader">
      <table-column
        v-if="item.children && item.children.length"
        :key="item.id"
        :coloumn-header="item"
        label="desc"
        prop="id"
      ></table-column>
      <el-table-column
        v-else
        :key="item.id"
        :label="item[label]"
        :prop="item[prop]"
        :align="item.align"
        :width="item.width"
        show-overflow-tooltip
      ></el-table-column>
    </template>
  </el-table>
</template>

<script>
import TableColumn from './TableColumn'
import cloneDeep from '@/utils/cloneDeep'
export default {
  props: {
    // 多级表头的数据
    tableHeader: {
      type: Array,
      required: true
    },
    prop: {
      type: String,
      default: 'name'
    },
    label: {
      type: String,
      default: 'desc'
    },
    // 表格的高度
    height: String
  },
  components: {
    TableColumn
  },
  data() {
    return {
      //用于重新渲染el-table
      tableKey: 1,
      tableData: []
    }
  },
  watch: {
    tableHeader: {
      handler: function(newVal, oldVal) {
        this.getTableData(newVal)
        this.tableKey = this.tableKey + 1
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    getTableData(data) {
      this.tableData = []
       let tableData = cloneDeep(data)
      for (let item of tableData) {
        if (item.children) {
         tableData = tableData.concat(item.children)
          delete item.children
        }
      }
      for (let index = 0; index < 3; index++) {
        let dataTemp = {}
        tableData.forEach(item => {
          dataTemp[item.name] = '效果字段' + index
          dataTemp[item.id] = '效果字段' + index
        })
        this.tableData.push(dataTemp)
      }
     
    },
  }
}
</script>

<style lang="scss" scoped></style>
