<template>
  <el-table-column v-bind="nextProps">
    <template slot-scope="scope">
      <slot v-bind="scope" :editable="handeRenderEditable(scope)">
        <template v-if="scope.row[prop] === null || scope.row[prop] === undefined || scope.row[prop] === ''">
          <span class="ui-gird-cell__empty"></span>
        </template>
        <template v-else>
          <span class="ui-gird-cell__main" :title="scope.row[prop]">{{scope.row[prop]}}</span>
        </template>
      </slot>
    </template>
  </el-table-column>
</template>
<script>
import { unique } from './util'
import TableColumn from 'element-ui/lib/table-column'
import 'element-ui/lib/theme-chalk/table-column.css'

export default {
  name: 'UiGridColumn',
  inject: ['UiGrid'],
  components: {
    ElTableColumn: TableColumn
  },
  props: {
    label: String,
    prop: String,
    align: String,
    fixed: String,
    sortable: Boolean,
    editable: {
      type: Boolean,
      default: false
    },
    exportable: {
      type: Boolean,
      default: false
    },
    width: [String, Number],
    minWidth: [String, Number]
  },
  computed: {
    rowKey() {
      return this.UiGrid.rowKey
    },
    editingCell() {
      return this.UiGrid.editingCell
    },
    nextProps() {
      if (this.UiGrid.columnInterceptorMethod) {
        return this.UiGrid.columnInterceptorMethod({
          props: this.$props
        })
      } else {
        return this.$props
      }
    }
  },
  created() {
    this.id = unique()
    this.UiGrid.tableColumns.push({
      id: this.id,
      props: this.nextProps
    })
  },
  methods: {
    handeRenderEditable(scope) {
      if (!this.rowKey || !this.editingCell) {
        return
      }
      return this.editingCell.rowId === scope.row[this.rowKey] && this.editingCell.columnId === scope.column.id
    }
  },
  beforeDestroy() {
    let index = -1
    this.UiGrid.tableColumns.some((v, i) => {
      if (v.id === this.id) {
        index = i
        return true
      }
    })
    this.UiGrid.tableColumns.splice(index, 1)
  }
}
</script>
<style lang="less">
.ui-gird-cell__empty{
  color: #ccc;
}
.ui-grid-column__tips{
  display: inline-block;
  vertical-align: top;
}
.ui-gird-cell__main{
  display: block;
  line-height: 24px;
  padding-top: 6px;
  padding-bottom: 6px;
}
.ui-grid{
  .ui-grid__table {
    .el-table__body-wrapper,
    .el-table__fixed-body-wrapper{
      .el-table__cell{
        padding-top: 6px;
        padding-bottom: 6px;
      }
    }
  }
}
</style>
