<template>
  <el-table-column
    v-bind="column"
    v-on="$listeners"
  >

    <template v-slot:header="scope">
      <bi-render
        v-if="column.headerRender"
        :scope="scope"
        :render="column.headerRender"
        type="header"
      />
      <span v-else>{{ scope.column.label }} </span>
      <BiTableHeaderPopper :prop="column.prop" />
    </template>
    <template #default="scope">
      <component
        :is="column.component"
        v-if="column.component"
        v-bind="getCptBind(scope, column)"
        v-on="column.listeners"
      />

      <template v-else-if="column.children">

        <bi-column
          v-for="col in column.children"
          :key="col.prop"
          :column="col"
          v-on="$listeners"
        />
      </template>

      <bi-render
        v-else
        :scope="scope"
        :render="column.render"
      />
    </template>

  </el-table-column>
</template>

<script>
import BiRender from './render'
import CellForced from './forced'
import BiTableHeaderPopper from '../../TableHeaderPopper'

export default {
  name: 'BiColumn',
  components: {
    BiRender,
    BiTableHeaderPopper
  },
  props: {
    column: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    column: {
      handler: 'renderColumn',
      immediate: true
    }
  },
  mounted() {},
  methods: {
    renderColumn() {
      const { column } = this

      // 多选：selection / 索引：index / 展开的按钮：expand
      if (column.type) {
        column.renderHeader = CellForced[column.type].renderHeader
        column.render = column.render || CellForced[column.type].renderCell
      }
      // 格式化内容
      if (column.formatter) {
        column.render = (h, scope) => {
          return <span>{scope.column.formatter(scope.row, scope.column, scope.row[scope.column.property], scope.$index)}</span>
        }
      }
      // 渲染成text
      if (!column.render) {
        column.render = (h, scope) => {
          return <span>{scope.row[scope.column.property]}</span>
        }
      }

      return column
    },

    getColBind(col) {
      const bind = Object.assign({}, this.$attrs, col)
      delete bind.component
      delete bind.listeners
      delete bind.propsHandler
      return bind
    },

    getCptBind({ row, column }, col) {
      const props = { row, col, column }
      const handler = col.propsHandler
      return (handler && handler(props)) || props
    }
  }
}
</script>
