<template>
  <th class="n-th" :class="thClasses" @mouseenter="onMouseEnter" @mouseleave="onMouseLeave">
    <div class="n-th-cell" :class="cellClasses">
      <!-- 自定义 -->
      <n-builder v-if="column.headerBuilder" :name="column.headerBuilder" :column="column"></n-builder>
      <!-- 文本 -->
      <span class="n-th-title" v-else :title="column.title">{{column.title}}</span>
      <!-- 排序 -->
      <template v-if="column.sortable">
        <n-icon v-if="column['_sort'] === 'desc'" class="n-th-sort" active size="16" scene="default" type="sort-descending" @click="onSortClick"></n-icon>
        <n-icon v-else-if="column['_sort'] === 'asc'" class="n-th-sort" active size="16" scene="default" type="sort-ascending" @click="onSortClick"></n-icon>
        <n-icon v-else class="n-th-sort" scene="default" type="sort" size="16" @click="onSortClick"></n-icon>
      </template>
<!--      <n-th-sort v-if="column.sortable" :sort-by="column._sort" @click.native="onSortClick(column)"></n-th-sort>-->
      <n-th-resize class="n-th-hover-visible" v-if="hasResize && !column.frozen" :column="column"
                   @on-resize-start="onResizeStart(index)" @on-resize-end="onResizeEnd"></n-th-resize>
    </div>
  </th>
</template>

<script>
import NBuilder from '@uif/next/lib/components/builder'
import NIcon from '@uif/next/lib/components/icon'
// import NThSort from './th-sort'
import NThResize from './th-resize'
import {getThCellClasses} from '_common/tableUtil'

export default {
  name: 'n-table-th',
  components: {
    NIcon,
    // NThSort,
    NThResize,
    NBuilder
  },
  props: {
    column: {
      type: Object,
      default () {
        return {}
      }
    },
    index: {
      type: Number,
      default: 0
    },
    hasResize: {
      type: Boolean,
      default: false
    },
    // 列表样式（下标）
    classIndex: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {
    }
  },
  computed: {
    hasIcon () {
      return this.column.sortable
    },
    thClasses () {
      return Object.entries(this.classIndex).filter(kv => kv[1] === this.column).map(kv => kv[0])
    },
    cellClasses () {
      return getThCellClasses(this.column)
    }
  },
  methods: {
    // 排序事件
    onSortClick () {
      this.$emit('on-sort', this.column)
    },
    onResizeStart () {
      this.$set(this.classIndex, 'n-table-column-resize', this.column)
    },
    onResizeEnd () {
      this.$delete(this.classIndex, 'n-table-column-resize')
      this.$emit('on-resize-end', this.column)
    },
    onMouseEnter () {
      if (!this.classIndex['n-table-column-resize']) {
        this.$set(this.classIndex, 'n-table-column-hover', this.column)
      }
    },
    onMouseLeave () {
      if (!this.classIndex['n-table-column-resize'] && this.classIndex['n-table-column-hover'] === this.column) {
        this.$set(this.classIndex, 'n-table-column-hover', -1)
      }
    }
  }
}
</script>
