<template>
  <td class="n-td" @click="onCellClick" @mouseenter="onMouseEnter" @mouseleave="onMouseLeave">
    <div class="n-td-cell" :class="classes" :style="styles">
      <!-- 自定义 -->
      <n-builder v-if="column.builder" :name="column.builder" :data="data" :column="column" :index="index"></n-builder>
      <!-- 文本 -->
      <span class="n-td-text" :title="cellText" v-else>{{cellText}}</span>
    </div>
  </td>
</template>

<script>
import NBuilder from '@uif/next/lib/components/builder'
import {isFunction} from '@uif/next/lib/utils/tools'
import { getTdCellClasses } from '_common/tableUtil'

export default {
  name: 'n-table-td',
  components: {
    NBuilder
  },
  props: {
    column: {
      type: Object,
      default () {
        return {}
      }
    },
    data: {
      type: Object,
      default () {
        return {}
      }
    },
    index: {
      type: Number,
      default: 0
    },
    // 列表样式（下标）
    classIndex: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {
    }
  },
  computed: {
    cellText () {
      const {key, getText} = this.column
      return isFunction(getText) ? getText(this.data, this.index) : this.data[key]
    },
    styles () {
      return this.data._height ? {height: this.data._height + 'px'} : null
    },
    classes () {
      return getTdCellClasses(this.column, this.data, this.index)
    }
  },
  methods: {
    onCellClick (event) {
      if (this.column.stop) {
        event.stopPropagation()
      }
      this.$emit('on-cell-click', event, this.data, this.index, this.column)
    },
    onMouseEnter () {
      this.$set(this.classIndex, 'n-table-column-hover', this.column)
    },
    onMouseLeave () {
      if (this.classIndex['n-table-column-hover'] === this.column) {
        this.$set(this.classIndex, 'n-table-column-hover', -1)
      }
    }
  }
}
</script>
