<template>
  <table class="uif-t-header">
    <u-colgroup :columns="columns"></u-colgroup>
    <thead>
    <tr>
      <template v-for="(column, index) in columns">
        <th class="uif-t-header-th" :class="{resize: resize === index}" :key="index">
          <header-cell :index="index" :column="column" :value="selectionValue" :indeterminate="indeterminate"
                       @sort="handleSort(index, $event)" @selection="handleSelection"></header-cell>
          <header-resize v-if="hasResize && !column.frozen" :index="index" :column="column"
                         @change="changeResize" @columns-resize="handleColumnsResize"></header-resize>
        </th>
      </template>
    </tr>
    </thead>
  </table>
</template>

<script>
import HeaderCell from './cell'
import HeaderResize from './resize'
import UColgroup from '../colgroup'
import {some} from '@uif/hq/lib/utils/array'
export default {
  components: {
    HeaderCell,
    HeaderResize,
    UColgroup
  },
  props: {
    columns: {
      type: Array,
      default () {
        return []
      }
    },
    dataList: {
      type: Array,
      default () {
        return []
      }
    },
    hasResize: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      resize: -1
    }
  },
  computed: {
    hasSelection () {
      return some(this.columns, data => data.type === 'selection')
    },
    selectionValue () {
      return this.hasSelection && this.dataList.length > 0 && !some(this.dataList, data => !data['_isChecked'])
    },
    indeterminate () {
      return !this.selectionValue && some(this.dataList, data => data['_isChecked'])
    }
  },
  watch: {},
  created () {
  },
  methods: {
    handleSort (idx, type) {
      this.columns.forEach((column, index) => {
        if (index === idx) {
          this.$set(column, '_sort', type)
        } else if (column['_sort']) {
          this.$set(column, '_sort', null)
        }
      })
      this.$emit('sort', this.columns[idx], type)
    },
    handleSelection () {
      const value = some(this.dataList, data => !data['_isChecked'])
      this.dataList.forEach(data => {
        if (data['_isChecked'] !== value) {
          this.$set(data, '_isChecked', value)
        }
      })
      this.$emit('selection', value, this.dataList)
    },
    changeResize (index) {
      this.resize = index
    },
    handleColumnsResize () {
      this.$emit('columns-resize')
    }
  }
}
</script>
