<template>
  <el-popover
    ref="popover"
    placement="bottom"
    width="300"
    trigger="click"
  >
    <el-input v-model="searchKey" class="mb5" @keyup.enter.native="handleFilterSearch" />
    <el-table
      ref="filterTable"
      :data="filteredList"
      size="mini"
      :max-height="400"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column prop="column" label="数据" show-overflow-tooltip />
    </el-table>

    <div class="text-right mt10">
      <el-button size="mini" @click="filterCancel">重置</el-button>
      <el-button type="primary" size="mini" @click="filterConfirm">确认</el-button>
    </div>

    <span slot="reference">{{ label }}</span>
  </el-popover>
</template>

<script>
export default {
  props: {
    // 展示的列表数据
    data: {
      type: Array,
      default: () => []
    },
    // 字段值
    prop: {
      type: String,
      default: ''
    },
    // 标签
    label: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      currentRows: [],
      // 未筛选的列表
      originalList: [],
      searchKey: null
    }
  },
  computed: {
    // 设置默认全选
    list() {
      return this.data.reduce((acc, cur) => {
        const prop = cur[this.prop]
        const has = acc.some(i => i.column === prop)
        if (!has) {
          acc.push({ column: prop })
        }
        return acc
      }, [])
    },
    // 过滤
    // 新增计算属性 filteredList，用于存储过滤后的数据
    filteredList() {
      if (!this.searchKey || this.searchKey.trim() === '') {
        return this.list
      }
      return this.list.filter(item =>
        item.column && item.column.toString().toLowerCase().includes(this.searchKey.toLowerCase())
      )
    }
  },
  methods: {
    filterConfirm() {
      // 查询所有的选中的
      // 抛出选中的数据
      this.$emit('selectData', this.currentRows, this.prop)
      this.$refs.popover.showPopper = false
    },
    handleFilterSearch() {
      this.searchKey = this.searchKey.trim()
    },
    handleSelectionChange(val) {
      this.currentRows = val
    },
    filterCancel() {
      this.$refs.filterTable.clearSelection()
      this.$emit('selectData', this.currentRows, this.prop)
      this.$refs.popover.showPopper = false
    }
  }
}
</script>

<style>

</style>
