<template>
  <div>
    <!-- 表格 -->
    <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <!-- 勾选框列 -->
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <!-- 其他列 -->
      <el-table-column
          label="日期"
          prop="date">
      </el-table-column>
      <el-table-column
          label="姓名"
          prop="name">
      </el-table-column>
      <el-table-column
          label="地址"
          prop="address">
      </el-table-column>
    </el-table>

    <!-- 显示选中行数据的按钮 -->
    <el-button @click="showDialog">编辑选中行</el-button>

    <!-- 弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="编辑选中行">
      <el-form :model="formData">
        <el-form-item label="日期">
          <el-input v-model="formData.date"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="formData.address"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveChanges">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessageBox } from 'element-plus';

// 表格数据
const tableData = ref([
  {
    date: '2016-05-03',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-02',
    name: 'John',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-04',
    name: 'Jane',
    address: 'No. 189, Grove St, Los Angeles',
  },
]);

const selectedRows = ref([]);
const dialogVisible = ref(false);
const formData = ref({
  date: '',
  name: '',
  address: '',
});

// 处理选中项变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 显示弹窗
const showDialog = () => {
  if (selectedRows.value.length !== 1) {
    ElMessageBox.alert('请选中一行进行编辑', '提示', {
      confirmButtonText: '确定',
    });
    return;
  }

  // 设置表单数据为选中行的数据
  formData.value = { ...selectedRows.value[0] };
  dialogVisible.value = true;
};

// 保存更改
const saveChanges = () => {
  // 将更改保存到原始数据
  const index = tableData.value.findIndex(row => row.date === formData.value.date);
  if (index !== -1) {
    tableData.value[index] = { ...formData.value };
  }

  dialogVisible.value = false;
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
