<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="800px"
    append-to-body
    @close="handleClose"
  >
    <!-- 搜索区域 -->
    <div class="search-box">
      <el-form :inline="true" :model="queryParams" @submit.native.prevent>
        <el-form-item>
          <el-input
            v-model="queryParams.title"
            placeholder="请输入名称"
            clearable
            @keyup.enter.native="handleQuery"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading" fit highlight-current-row border stripe
      :data="tableData"
      row-key="id"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      ref="table"
    >
      <el-table-column
        type="selection"
        :reserve-selection="true"
        width="55"
      />

      <el-table-column
        v-for="column in dataColumns"
        :key="column.field"
        :prop="column.field"
        :label="column.label"
        :width="column.width"
        :formatter="column.formatter"
        show-overflow-tooltip
      />
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'DataSelector',
  props: {
    // 弹窗标题
    title: {
      type: String,
      default: '选择数据'
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 表格列配置
    dataColumns: {
      type: Array,
      required: true
    },
    // 获取数据的方法
    fetchData: {
      type: Function,
      required: true
    },
    // 已选中的数据
    selected: {
      type: [Array, Object],
      default: () => (this.multiple ? [] : null)
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: ''
      },
      // 表格数据
      tableData: [],
      // 总条数
      total: 0,
      // 选中的数据
      selectedData: []
    }
  },
  watch: {
    selected: {
      immediate: true,
      handler(val) {
        if (val) {
          this.selectedData = this.multiple ? [...val] : [val];
        }
      }
    }
  },
  methods: {
    // 显示弹窗
    show() {
      this.dialogVisible = true
      this.getList()
      // 下一个 tick 等待表格渲染完成后设置选中状态
      this.$nextTick(() => {
        if (this.selectedData.length > 0) {
          this.selectedData.forEach(row => {
            this.$refs.table.toggleRowSelection(row, true)
          })
        }
      })
    },
    // 获取数据列表
    async getList() {
      this.loading = true
      try {
        const { data, total } = await this.fetchData(this.queryParams)
        this.tableData = data.map(item => ({
          ...item,
          id: item.id || item.userId || item.deptId
        }))
        this.total = total
      } catch (error) {
        console.error('获取数据失败:', error)
      } finally {
        this.loading = false
      }
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        title: ''
      }
      this.getList()
    },
    // 多选改变
    handleSelectionChange(selection) {
      if (!this.multiple && selection.length > 1) {
        // 单选模式下，只保留最后选中的一项
        const lastSelected = selection[selection.length - 1]
        this.$refs.table.clearSelection()
        this.$refs.table.toggleRowSelection(lastSelected, true)
        this.selectedData = [lastSelected]
      } else {
        this.selectedData = selection
      }
    },
    // 单击行
    handleRowClick(row) {
      if (!this.multiple) {
        this.$refs.table.clearSelection()
        this.$refs.table.toggleRowSelection(row, true)
      }
    },
    // 确认选择
    handleConfirm() {
      this.$emit('confirm', this.multiple ? this.selectedData : this.selectedData[0])
      this.handleClose()
    },
    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false
      this.selectedData = []
      this.resetQuery()
      this.$refs.table.clearSelection()
    }
  }
}
</script>

<style lang="scss" scoped>
.search-box {
  margin-bottom: 5px;
  .el-input {
    width: 300px;
  }
}
</style> 