<template>
  <div class="editable-table-container">
    <el-table :data="tableData" border style="width: 100%" :show-header="true" @cell-click="handleCellClick">
      <el-table-column v-for="(column, index) in columns" :key="index" :prop="column.prop" :label="column.label"
        :width="column.width">
        <template #default="scope">
          <template
            v-if="editingCell.rowIndex === scope.$index && editingCell.columnIndex === index && column.editComponent">
            <!-- 编辑状态 -->
            <component :is="column.editComponent || 'el-input'" v-model="scope.row[column.prop]"
              v-bind="column.editProps || {}" @change="handleEditChange(scope.row, column.prop)" @blur="handleEditBlur"
              @keyup.enter="handleEditBlur" ref="editComponentRef">
              <!-- 动态插槽 -->
              <template v-if="column.editSlots?.component">
                <component v-for="(comp, compIndex) in column.editSlots.props" :is="column.editSlots?.component"
                  :key="compIndex" v-bind="column.editSlots.props?.[compIndex] || {}" />
              </template>
            </component>
          </template>
          <template v-else>
            <!-- 显示状态 -->
            <el-tooltip effect="dark" :content="formatCellValue(scope.row[column.prop], column) " placement="top">
              <span>{{ formatCellValue(scope.row[column.prop], column) }}</span>
            </el-tooltip>

          </template>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column v-if="showActionColumn" label="操作" :width="actionWidth">
        <template #default="scope">
          <div v-for="(item,index) in actionButtons" style="display: inline-block;">
            <el-button v-if="!(item.hide&&item.hide(scope.$index, scope.row))" style="margin-right: 10px;" size="small" :type="item.type" :key="index" link @click="item.click(scope.$index, scope.row)">{{ item.name }}</el-button>
          </div>
          <el-button  size="small" v-if="showDeleteButton" type="danger" link @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row class="table-actions" v-if="showActionBar">
      <el-col :span="24" class="operations">
        <el-button plain type="primary" @click="handleAddRow">新增行</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, watch, nextTick, onMounted } from 'vue'

const props = defineProps({
  // 表格数据
  data: {
    type: Array,
    required: true,
    default: () => []
  },
  // 列配置
  columns: {
    type: Array,
    required: true,
    default: () => []
  },
  // 是否显示操作列
  showActionColumn: {
    type: Boolean,
    default: true
  },
  showDeleteButton: {
    type: Boolean,
    default: true
  },
  // 是否显示顶部操作栏
  showActionBar: {
    type: Boolean,
    default: true
  },
  // 是否启用单元格点击编辑
  cellClickEdit: {
    type: Boolean,
    default: true
  },
  // 新增行的默认数据
  defaultNewRow: {
    type: Object,
    default: null
  },
  //操作按钮配置
  actionButtons: {
    type: Array,
    default: () => []
  },
  actionWidth: {
    type: Number,
    default: 180
  }
})

const emit = defineEmits(['change', 'del', 'add', "ready", "blur"])

const tableData = ref([...props.data])
const editingCell = ref({
  rowIndex: -1,
  columnIndex: -1
})
const oldValue = ref(null)
const editComponentRef = ref(null)

// 监听props.data变化
watch(() => props.data, (newVal) => {
  tableData.value = [...newVal]
}, { deep: true })

// 格式化单元格显示值
const formatCellValue = (value, column) => {
  if (column.formatter) {
    return column.formatter(value)
  }

  // 处理select类型的显示值
  if (column.editComponent === 'el-select' && column.editSlots?.props) {
    const options = column.editSlots.props || []
    const option = options.find(opt => opt.value === value)
    return option ? option.label : value
  }

  return value
}

// 单元格点击事件
const handleCellClick = (row, column, cell, event) => {
  if (!props.cellClickEdit) return

  const columnIndex = props.columns.findIndex(col => col.prop === column.property)
  if (columnIndex === -1 || column.property === undefined) return

  startEditing(row, columnIndex)
}

// 开始编辑
const startEditing = (row, columnIndex) => {
  const rowIndex = tableData.value.findIndex(item => item === row)
  if (rowIndex === -1) return

  editingCell.value = {
    rowIndex,
    columnIndex
  }

  // 保存旧值
  const prop = props.columns[columnIndex].prop
  oldValue.value = row[prop]

  // 下一个tick聚焦输入框
  nextTick(() => {
    console.log(editComponentRef.value[0])
    if (editComponentRef.value && editComponentRef.value[0].focus) {
      editComponentRef.value[0].focus()
    }
  })
}


// 删除按钮点击事件
const handleDelete = (index, row) => {
  emit('del', row, index)
  tableData.value.splice(index, 1)
}

// 新增行
const handleAddRow = () => {
  const newRow = props.defaultNewRow || createDefaultRow()
  tableData.value.push(newRow)

  // 自动进入编辑状态
  nextTick(() => {
    startEditing(newRow, 0)
  })

  emit('add', newRow)
}

// 创建默认行数据
const createDefaultRow = () => {
  const row = {}
  props.columns.forEach(column => {
    if (column.prop) {
      row[column.prop] = column.defaultValue !== undefined
        ? column.defaultValue
        : (column.editComponent === 'el-input-number' ? 0 : '')
    }
  })
  return row
}

// 编辑完成事件
const handleEditBlur = () => {
  const { rowIndex, columnIndex } = editingCell.value
  if (rowIndex === -1 || columnIndex === -1) return

  const row = tableData.value[rowIndex]
  const prop = props.columns[columnIndex].prop

  // 触发change事件
  emit('blur', row, prop, oldValue.value, row[prop])

  // 重置编辑状态
  editingCell.value = {
    rowIndex: -1,
    columnIndex: -1
  }
  oldValue.value = null
}

onMounted(() => {
  emit('ready')
})

// 编辑内容变化事件
const handleEditChange = (row, prop) => {
  emit('change', row, prop, oldValue.value, row[prop])
}

// 暴露方法给父组件
defineExpose({
  getTableData: () => tableData.value,
  setTableData: (data) => {
    tableData.value = [...data]
  },
  addRow: handleAddRow
})
</script>

<style scoped>
:deep(.el-table th.el-table__cell) {
  background-color: #f5f5f5;
}

:deep(.el-table thead) {
  color: inherit;
}

.editable-table-container {
  width: 100%;
  margin: 20px 0;
}

.table-actions {
  margin-bottom: 15px;
}

.operations {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background: #f5f5f5;
  margin-top: 10px;
  padding: 10px;
}
</style>
