<template>
    <table
        :style="{
            width: bodyWidth
        }"
        cellspacing="0"
        cellpadding="0"
        border="0">
        <colgroup>
            <col v-for="column in columns"
                 :key="column.id"
                 :name="column.id">
            <col v-if="hasGutter"
                 name="gutter">
        </colgroup>
        <tbody :class="{ 'has-gutter': hasGutter }">
            <tr v-for="(row, rowIndex) in data"
                :key="rowIndex">
                <td
                    v-for="(column, cellIndex) in columns"
                    :key="column.id"
                    v-bind="setColumn(column,cellIndex)"
                    v-show="setColumn(column,cellIndex).rowSpan&&setColumn(column,cellIndex).colSpan"
                    :class="getRowClasses(column, cellIndex)">
                    <render-cell :row="row"
                                 :column="setColumn(column,cellIndex)"
                                 :cellIndex="cellIndex"
                                 :cell="$parent.$scopedSlots[column.property]" />
                </td>
                <th v-if="hasGutter"
                    class="gutter" />
            </tr>
        </tbody>
    </table>
</template>

<script>
import Table from 'element-ui/lib/table';
import RenderCell from './render-cell';
import LayoutObserver from './layout-observer';

export default {
    components: {
        RenderCell
    },
    props: {
        extend: {
            type: Object,
            default: () => ({})
        },
        data: {
            type: Array,
            default: () => ([])
        },
        fixed: {
            type: String,
            default: ''
        }
    },
    destroyed() {
        this.tableLayout.removeObserver(this);
    },
    methods: {
        init() {
            this.tableLayout.addObserver(this);
            this.onColumnsChange(this.tableLayout);
        },
        ...LayoutObserver.methods,
        ...Table.components.TableFooter.methods,
        /**
       * 
       */
        setColumn(column, index) {
            let current = '';
            const cfg = this.extend[index];
            if (cfg) {
                current = JSON.parse(JSON.stringify(column));
                Object.assign(current, cfg);
            }
            return current || column;
        }
    },
    computed: {
        table() {
            return this.$parent.table;
        },
        columns() {
            const columns = (this.table && this.table.store.states.columns) || [];
            return columns;
        },
        tableLayout() {
            return (this.table && this.table.layout) || {};
        },
        hasGutter() {
            return !this.fixed && this.tableLayout.gutterWidth;
        },
        bodyWidth() {
            return this.table && `${this.table.layout.bodyWidth}px`;
        }
    }
};
</script>
