<template>
  <div class="pub-table-cla">
    <!-- <el-button-group style="width: 100%;margin-bottom: 10px;">
      <div style="width: 50%;float: left;">
        <slot name="btnsArea" />
      </div>
      <div style="float: right;height: 30px">
        <el-dropdown :hide-on-click="false" style="float: left; margin-right: 10px;margin-bottom: 13px;">
          <el-button type="default" class="pub-button-he">
            显示隐藏列
            <span v-show="hiddenColumnTotal > 0">({{ hiddenColumnTotal }})</span>
            <i class="el-icon-arrow-down el-icon--right" />
          </el-button>
          <el-dropdown-menu slot="dropdown" style="overflow-y: auto;max-height: 70%">
            <el-dropdown-item v-for="head in headers" :key="head.attr.prop">
              <el-switch v-model="head.isShow" :active-text="head.attr.label" @change="headerChange" />
              <span />
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-button-group> -->
    <div class="table-height">
      <div class="table-wrap w-table" :class="{'w-table_moving': dragState.dragging}">
        <el-table
          ref="basicTable"
          :data="tableDatas"
          :stripe="true"
          border
          :height="height"
          row-key="roleId"
          highlight-current-row
          style="width: 100%;"
          :header-cell-class-name="headerCellClassName"
          @selection-change="handleSelectionChange"
        >
          <!-- 多选列 -->
          <el-table-column
            v-if="multable"
            type="selection"
            width="55"
            align="center"
            fixed="left"
          />
          <el-table-column
            v-if="isShowIndex"
            type="index"
            align="center"
            label="序号"
            width="55"
          />
          <template v-for="(item,index) in dragHeaders">
            <el-table-column
              v-if="item.isShow && item.slot"
              :key="index"
              v-bind="item.attr"
              :width="item.attr.width"
              align="center"
              :show-overflow-tooltip="true"
              :column-key="index.toString()"
              :render-header="renderHeader"
            >
              <!--某一列插槽-->
              <template slot-scope="scope">
                <slot :name="item.attr.prop" :row="scope.row" />
              </template>
            </el-table-column>
            <el-table-column
              v-else-if="item.isShow"
              :key="index"
              v-bind="item.attr"
              align="center"
              :show-overflow-tooltip="true"
              :column-key="index.toString()"
              :render-header="renderHeader"
            />
          </template>

          <!-- 操作列 -->
          <template v-if="isShowOperate">
            <el-table-column
              v-if="operationNum == 3"
              label="操作"
              width="160"
              :fixed="isFixed"
            >
              <template slot-scope="scope">
                <!-- 将作用域插槽返回的对象scope继续通过作用域插槽暴露出去 -->
                <slot :row="scope.row" />
              </template>
            </el-table-column>
            <el-table-column
              v-else
              label="操作"
              width="100"
            >
              <template slot-scope="scope">
                <!-- 将作用域插槽返回的对象scope继续通过作用域插槽暴露出去 -->
                <slot :row="scope.row" />
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="pageNo"
        :limit.sync="pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import props from './prop.js'

export default {
  name: 'BasicTable',
  props,
  data() {
    return {
      headers: [],
      dragHeaders: [],
      dragState: {
        start: -1, // 起始元素的 index
        end: -1, // 结束元素的 index
        move: -1, // 移动鼠标时所覆盖的元素 index
        dragging: false, // 是否正在拖动
        direction: undefined // 拖动方向
      }
    }
  },
  computed: {
    // 隐藏列数
    hiddenColumnTotal() {
      return this.headers.filter(h => !h.isShow).length
    }
  },
  watch: {
  },
  created() {
    this.headers = this.tabColumns.map((c) => {
      if (c.isShow === undefined) {
        this.$set(c, 'isShow', true)
      }
      return c
    })
    this.dragHeaders = JSON.parse(localStorage.getItem('DRAG_COLUMN')) || this.headers
  },
  mounted() {
  },
  methods: {
    headerChange() {
      this.dragHeaders = []
      for (let i = 0; i < this.headers.length; i++) {
        if (this.headers[i].isShow) {
          this.dragHeaders.push(this.headers[i])
        }
      }
    },
    headerCellClassName({ column, columnIndex }) {
      if (this.multable === true && this.isShowIndex === true) {
        return (columnIndex - 2 === this.dragState.move ? `darg_active_${this.dragState.direction}` : '')
      } else if (this.multable === true || this.isShowIndex === true) {
        return (columnIndex - 1 === this.dragState.move ? `darg_active_${this.dragState.direction}` : '')
      } else {
        return (columnIndex === this.dragState.move ? `darg_active_${this.dragState.direction}` : '')
      }
    },
    renderHeader(createElement, { column }) {
      return createElement(
        'div', {
          'class': ['thead-cell', { 'draggable-column': true, 'dragging': column.columnKey === this.dragState.move }],
          on: {
            mousedown: ($event) => {
              this.handleMouseDown($event, column)
            },
            mouseup: ($event) => {
              this.handleMouseUp($event, column)
            },
            mousemove: ($event) => {
              this.handleMouseMove($event, column)
            }
          }
        },
        [
          // 添加 <a> 用于显示表头 label
          createElement('a', column.label),
          // 添加一个空标签用于显示拖动动画
          createElement('span', {
            'class': ['virtual']
          })
        ])
    },
    // 按下鼠标开始拖动
    handleMouseDown(e, column) {
      this.dragState.dragging = true
      this.dragState.start = parseInt(column.columnKey)
      // 给拖动时的虚拟容器添加宽高
      const table = document.getElementsByClassName('w-table')[0]
      const virtual = document.getElementsByClassName('virtual')
      for (const item of virtual) {
        item.style.height = table.clientHeight - 1 + 'px'
        item.style.width = item.parentElement.parentElement.clientWidth + 'px'
      }
    },

    // 鼠标放开结束拖动
    handleMouseUp(e, column) {
      this.dragState.end = parseInt(column.columnKey) // 记录起始列
      this.dragColumn(this.dragState)
      // 初始化拖动状态
      this.dragState = {
        start: -1,
        end: -1,
        move: -1,
        dragging: false,
        direction: undefined
      }
      localStorage.setItem('DRAG_COLUMN', JSON.stringify(this.dragHeaders))
    },

    // 拖动中
    handleMouseMove(e, column) {
      if (this.dragState.dragging) {
        const index = parseInt(column.columnKey) // 记录起始列
        if (index - this.dragState.start !== 0) {
          this.dragState.direction = index - this.dragState.start < 0 ? 'left' : 'right' // 判断拖动方向
          this.dragState.move = parseInt(column.columnKey)
        } else {
          this.dragState.direction = undefined
        }
      } else {
        return false
      }
    },

    // 拖动易位
    dragColumn({ start, end, direction }) {
      if (start < 0 || end < 0 || start === end) {
        return
      }
      const tempData = []
      const left = direction === 'left'
      const min = left ? end : start - 1
      const max = left ? start + 1 : end
      for (let i = 0; i < this.dragHeaders.length; i++) {
        if (i === end) {
          tempData.push(this.dragHeaders[start])
        } else if (i > min && i < max) {
          tempData.push(this.dragHeaders[left ? i - 1 : i + 1])
        } else {
          tempData.push(this.dragHeaders[i])
        }
      }
      this.dragHeaders = tempData
    },
    // 选择项改变时候（返回当前选中的行）
    handleSelectionChange(selection) {
      this.$emit('rowSelectionChanged', selection)
    },
    // 刷新列表
    getList() {
      console.log('getList')
    }
  }
}
</script>

<style lang="scss" scoped>
  .btns-area {
    padding-left: 0px;
    text-align: left;
  }
  .table-height{
    height:  calc(100% - 60px)
  }
  .pub-table-cla{
    height:  calc(100% - 42px)
  }
  .pub-button-he{
    height: 30px !important;
  }
  .draggable-column {
  transition: transform 0.3s ease-in-out;
}

.dragging {
  transform: scale(1.1); /* 例如，你可以在拖拽时放大被拖拽的列 */
}
</style>
