<template>
  <div class="top-right-btn" :style="style">
    <el-row>
      <el-tooltip class="item" effect="dark" content="列配置" placement="top" v-if="columns">
        <el-popover placement="bottom-end" width="260" trigger="click" v-model="open">
          <div class="column-panel">
            <!-- 搜索 -->
            <el-input v-model="keyword" size="mini" placeholder="搜索字段" clearable class="search-input" />

            <!-- 操作区 -->
            <div class="panel-actions">
              <el-checkbox :value="checkAll" :indeterminate="isIndeterminate" @change="onCheckAll"> 全选 </el-checkbox>
              <el-link type="primary" :underline="false" @click="resetColumns"> 恢复默认 </el-link>
            </div>

            <!-- 可拖拽列表 -->
            <div class="list-wrapper">
              <draggable
                v-model="innerColumns"
                :options="{ handle: '.drag-handle', animation: 150 }"
                ghost-class="ghost"
              >
                <transition-group name="flip-list" tag="div">
                  <div v-for="item in innerColumns" :key="item.key" class="column-item" v-show="matchKeyword(item)">
                    <el-checkbox v-model="item.visible">
                      {{ item.label }}
                    </el-checkbox>
                    <span class="drag-handle">
                      <img src="@/assets/images/icon-drag.png" style="width: 10px; height: 15px" alt="" />
                    </span>
                  </div>
                </transition-group>
              </draggable>
            </div>

            <!-- 底部按钮 -->
            <div class="panel-footer">
              <el-button size="mini" type="primary" style="width: 100%" @click="applyChange"> 确 定 </el-button>
            </div>
          </div>

          <!-- 触发按钮 -->
          <svg-icon slot="reference" icon-class="menu" class="menu-icon" />
        </el-popover>
      </el-tooltip>

      <el-tooltip class="item" effect="dark" content="列表全屏" placement="top" style="margin: 5px 0 0 10px">
        <svg-icon icon-class="full-screen" @click="toggleFullscreen" />
      </el-tooltip>
    </el-row>
  </div>
</template>

<script>
import draggable from 'vuedraggable'

export default {
  name: 'RightToolbarElementDraggable',
  components: { draggable },
  props: {
    columns: {
      type: Array,
      required: true,
    },
    gutter: {
      type: Number,
      default: 10,
    },
  },
  data() {
    return {
      open: false,
      keyword: '',
      innerColumns: [],
      backupColumns: [],
    }
  },
  computed: {
    style() {
      const ret = {}
      if (this.gutter) ret.marginRight = `${this.gutter / 2}px`
      return ret
    },
    checkAll() {
      return this.innerColumns.length ? this.innerColumns.every((c) => c.visible) : false
    },
    isIndeterminate() {
      const visCount = this.innerColumns.filter((c) => c.visible).length
      return visCount > 0 && visCount < this.innerColumns.length
    },
  },
  watch: {
    columns: {
      immediate: true,
      deep: true,
      handler(val) {
        // 复用你原来 transfer 逻辑的“本地副本”思想
        this.innerColumns = val.map((c) => ({ ...c }))
        this.backupColumns = val.map((c) => ({ ...c }))
      },
    },
  },
  methods: {
    matchKeyword(item) {
      if (!this.keyword) return true
      const k = this.keyword.toLowerCase()
      return (item.label || '').toLowerCase().includes(k)
    },
    onCheckAll(val) {
      this.innerColumns.forEach((c) => (c.visible = val))
    },
    resetColumns() {
      // 恢复为“初始 columns”快照
      this.innerColumns = this.backupColumns.map((c) => ({ ...c }))
    },
    applyChange() {
      // === 关键：完全复用你原来 dataChange 的思想 ===
      // 把 innerColumns 的 visible / 顺序，同步回 this.columns
      this.innerColumns.forEach((col, idx) => {
        const target = this.columns.find((c) => c.key === col.key)
        if (target) {
          target.visible = col.visible
        }
      })

      // 同步顺序：直接用 splice 重排原数组（保证引用不变）
      const newOrder = this.innerColumns.map((c) => c.key)
      const ordered = newOrder.map((k) => this.columns.find((c) => c.key === k)).filter(Boolean)

      this.columns.splice(0, this.columns.length, ...ordered)

      this.open = false
    },
    toggleFullscreen() {
      let tableEl = document.querySelector('.el-table')
      if (!tableEl) {
        const tables = Array.from(document.querySelectorAll('.el-table'))
        tableEl = tables.find((t) => t.offsetParent !== null)
      }
      if (!tableEl) {
        this.$message.warning('未找到表格区域')
        return
      }

      let pagerEl = document.querySelector('.pagination-container')
      if (!pagerEl) {
        const pagers = Array.from(document.querySelectorAll('.pagination-container'))
        pagerEl = pagers.find((p) => p.offsetParent !== null)
      }

      let fullscreenEl = tableEl.parentElement
      if (pagerEl) {
        while (fullscreenEl && (!fullscreenEl.contains(tableEl) || !fullscreenEl.contains(pagerEl))) {
          fullscreenEl = fullscreenEl.parentElement
        }
      }
      if (!fullscreenEl) fullscreenEl = tableEl

      const doc = document

      if (!fullscreenEl.__fsBound) {
        fullscreenEl.__oldBg = fullscreenEl.style.background
        fullscreenEl.__oldMinHeight = fullscreenEl.style.minHeight
        fullscreenEl.__fsBound = true
      }

      if (!doc.fullscreenElement) {
        fullscreenEl.style.background = '#fff'
        fullscreenEl.style.minHeight = '100vh'

        const onFsChange = () => {
          if (!document.fullscreenElement) {
            fullscreenEl.style.background = fullscreenEl.__oldBg || ''
            fullscreenEl.style.minHeight = fullscreenEl.__oldMinHeight || ''

            this.$nextTick(() => {
              const tableVm = tableEl.__vue__ || document.querySelector('.el-table')?.__vue__
              tableVm?.doLayout()
            })

            document.removeEventListener('fullscreenchange', onFsChange)
          }
        }

        document.addEventListener('fullscreenchange', onFsChange)
        fullscreenEl.requestFullscreen && fullscreenEl.requestFullscreen()
      } else {
        doc.exitFullscreen && doc.exitFullscreen()
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.top-right-btn {
  display: flex;
  align-items: center;
}

.menu-icon {
  cursor: pointer;
  font-size: 16px;
}

.column-panel {
  padding: 8px;
  max-height: 400px;
  display: flex;
  flex-direction: column;
}

.list-wrapper {
  flex: 1;
  overflow-y: auto;
}

.search-input {
  margin-bottom: 8px;
}

.panel-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.column-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4px 0;
}

.drag-handle {
  cursor: grab;
  margin-right: 8px;
  color: #999;
  user-select: none;
}

.ghost {
  opacity: 0.4;
}

.panel-footer {
  margin-top: 8px;
}
</style>
