<template>
  <div :style="configStyle"
       class="vuc-datatable-header-config"
       ref="headerConfig"
       v-click-outside:pointerdown="handleOutsideClick"
       @contextmenu.prevent="handleContextMenu">
    <Row v-if="showDrag">
      <draggable :key="`${_uid}`"
                 class="drag-arear"
                 v-model="columns"
                 :style="dragStyle"
                 :options="{group: {name: 'layout', put: true}, draggable: '.vuc-header-column',handle:'.vuc-header-drag-icon', forceFallback: true, sort: true, animation: 50}"
                 @end="handleEnd">
        <template v-for="(el,index) in columns">
          <Col :class="[el.fixed?'vuc-header-column-fixed':`vuc-header-column`]"
               v-if="!['index', 'selection', 'tools'].includes(el.type)  && el.title && el.title.trim() !== ''"
               :span="colspan"
               :key="`${_uid}_${index}`">

          <header-config-item :key="`${_uid}_${index}`"
                              :element="el"
                              @on-set-visibled="val=>setVisibled(el,val)"
                              @on-set-locked="val=>setLocked(el,val)">

          </header-config-item>
          </Col>

        </template>
      </draggable>
    </Row>
    <div style="padding-top:10px;padding-left:8px;">

      <Checkbox @on-change="setColumnAutoWidth"
                :value="showAutoColumnChecked">根据内容调整列宽自适应</Checkbox>
      <Checkbox @on-change="setColumnCheck"
                v-if="showSelectAll"
                :value="columnCheckValue">全选</Checkbox>
    </div>
  </div>
</template>

<script>
import HeaderConfigItem from './header-config-item.vue'
// import $ from 'zepto'
import draggable from 'vuedraggable'
export default {
  name: 'VucDatatableHeaderConfig',
  components: { HeaderConfigItem, draggable },
  props: {
    // 表格字段
    customs: {
      type: Array,
      default: () => []
    },
    autoColumnWidth: {
      type: Boolean,
      default: false
    },
    columnCheckValue: {
      type: Boolean,
      default: true
    },
    showSelectAll: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      showDrag: true,
      columns: this.customs.filter(el => !['index', 'selection', 'tools'].includes(el.type) && el.title && el.title.trim() !== '')
    }
  },
  computed: {
    colspan () {
      const cfgCols = this.customs.filter(el => !['index', 'selection', 'tools'].includes(el.type) && el.title && el.title.trim() !== '')
      let cols = 12
      if (cfgCols.length > 24) {
        cols = 6
      } else if (cfgCols.length > 16) {
        cols = 8
      }

      return cols
    },
    configStyle () {
      const { rows, cols } = this.getListCount()
      return `height:${rows * 35 + 30}px;width:${cols * 196}px;`
    },
    dragStyle () {
      const cfgCols = this.customs.filter(el => !['index', 'selection', 'tools'].includes(el.type) && el.title && el.title.trim() !== '')
      let cols = 2
      if (cfgCols.length > 24) {
        cols = 4
      } else if (cfgCols.length > 16) {
        cols = 3
      }
      return `column-count:${cols};-webkit-column-count:${cols};-moz-column-count:${cols};`
    },
    showAutoColumnChecked () {
      return this.autoColumnWidth
    }
  },
  watch: {
    // customs: {
    //   deep: true,
    //   handler () {
    //     this.columns = this.customs.filter(el => !['index', 'selection', 'tools'].includes(el.type) && el.title && el.title.trim() !== '')
    //   }
    // }
  },
  methods: {
    updateVisibleCols () {
      this.columns = this.customs.filter(el => !['index', 'selection', 'tools'].includes(el.type) && el.title && el.title.trim() !== '')
    },
    handleContextMenu (event) {
      event.stopPropagation()
      return false
    },
    getListCount () {
      let cols = 2
      const cfgCols = this.customs.filter(el => !['index', 'selection', 'tools'].includes(el.type) && el.title && el.title.trim() !== '')
      const len = cfgCols.length
      if (len > 24) {
        cols = 4
      } else if (len > 16) {
        cols = 3
      }
      const rows = Math.ceil(len / cols)
      return { rows, cols }
    },
    getColItems (index) {
      const { rows } = this.getListCount()
      const cfgCols = this.customs.filter(el => !['index', 'selection', 'tools'].includes(el.type) && el.title && el.title.trim() !== '')
      return cfgCols.splice(index * rows, rows)
    },
    initConfig () {

    },
    handleOutsideClick (event) {
      /*       if ($(event.target).closest('.vuc-datatable-header-config').length === 0) {
              this.$emit('handleOutsideClick')
            } */
    },
    setVisibled (el, val) {
      el.visible = val
      this.$emit('handleVisibleColumn', { column: el, val, columns: this.columns })
      if (!val) {
        this.showSelectAll = false
        setTimeout(() => {
          this.columnCheckValue = false
          this.showSelectAll = true
        }, 50)
      } else {
        if (this.columns.length > 0) {
          let obj = this.columns.find(f => !f.visible)
          if (!obj) {
            this.columnCheckValue = true
          }
        }
      }
    },
    setLocked (el, val) {
      this.$emit('handleLockedColumn', { column: el, val, columns: this.columns })
    },
    handleEnd () {
      setTimeout(() => {
        for (let i = 0, len = this.columns.length; i < len; i++) {
          // this.columns[i].__index = i
          // this.$set(this.columns, i, this.columns[i])
          const idx = this.customs.findIndex(col => col.field === this.columns[i].field)
          this.customs[idx].__index = i
        }
        this.$emit('refreshColumns', this.customs)
      }, 10)
    },
    setColumnAutoWidth (checked) {
      this.$emit('setColumnAutoWidth', checked)
    },
    setColumnCheck (checked) {
      this.showDrag = false
      setTimeout(() => {
        this.columns.forEach(item => {
          this.setVisibled(item, checked)
        })
        this.$emit('refreshColumns', this.customs)
        this.showDrag = true
      }, 50)
    }
  },
  mounted () {
    if (this.columns.length > 0) {
      let obj = this.columns.find(f => !f.visible)
      if (obj) {
        this.columnCheckValue = false
      } else {
        this.columnCheckValue = true
      }
    }
    // console.log(JSON.parse(JSON.stringify(this.columns)), JSON.parse(JSON.stringify(this.customs)), '表头信息')
  }
}
</script>

<style lang="less" scoped>
@import './vuc-datatable-header-config.less';
</style>
