<template>
  <div>
    <el-button type="primary" @click="handleAdd">新增设备</el-button>
    <el-table :data="data" style="width: 100%">
      <el-table-column prop="name" label="设备名" width="180" />
      <el-table-column prop="address" label="设备地址" width="180" />
      <el-table-column prop="threshold" label="报警阈值" width="180" />
      <el-table-column prop="password" label="二次密码" width="180" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-space size="middle">
            <el-button type="primary" @click="modifyData(scope.row)">修改密码</el-button>
            <el-button type="danger" @click="deleteDevice(scope.row)">删除设备</el-button>
          </el-space>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-model="isOpen"
      :title="isAdding ? '新增设备' : '修改设备'"
      width="30%"
      :destroy-on-close="true"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        label-width="120px"
        @finish="onCreate"
        @finish-failed="onFinishFailed"
      >
        <el-form-item label="设备名" prop="name" :rules="[{ required: true, message: '请输入设备名' }]">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="设备地址" prop="address" :rules="[{ required: true, message: '请输入设备地址' }]">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="报警阈值" prop="threshold" :rules="[{ required: true, message: '请输入报警阈值' }]">
          <el-input-number v-model="form.threshold" :min="0" />
        </el-form-item>
        <el-form-item label="二次密码" prop="password" :rules="[{ required: true, message: '请输入二次密码' }]">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { ElButton, ElTable, ElTableColumn, ElSpace, ElDialog, ElForm, ElFormItem, ElInput, ElInputNumber, ElMessage } from 'element-plus';

const data = ref([
  {
    address: "长沙",
    key: "1",
    name: "G12555",
    password: "******",
    threshold: 0
  }
]);

const isAdding = ref(false); // 新增状态
const currentRecord = ref(null); // 当前操作的记录
const isOpen = ref(false);
const formRef = ref(null);
const form = ref({
  name: '',
  address: '',
  threshold: 0,
  password: ''
});

watch(() => currentRecord.value, (newVal) => {
  if (newVal) {
    form.value.name = newVal.name;
    form.value.address = newVal.address;
    form.value.threshold = newVal.threshold;
    form.value.password = newVal.password;
  }
});

const modifyData = (record) => {
  currentRecord.value = record;
  isAdding.value = false;
  isOpen.value = true;
};

const handleAdd = () => {
  isAdding.value = true; // 设置为新增状态
  currentRecord.value = null; // 清空记录
  isOpen.value = true;
};

const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo);
  // 处理表单验证失败的情况
};

const deleteDevice = (record) => {
  const index = data.value.findIndex(item => item.key === record.key);
  if (index !== -1) {
    data.value.splice(index, 1);
    ElMessage.success('设备删除成功');
  }
};

const handleClose = () => {
  isOpen.value = false;
  form.value = {
    name: '',
    address: '',
    threshold: 0,
    password: ''
  };
};

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (isAdding.value) {
        addDevice({ ...form.value, key: String(data.value.length + 1) }); // 新增设备
      } else {
        updateDevice({ ...form.value, key: currentRecord.value.key }); // 更新设备
      }
      handleClose();
    } else {
      console.log('error submit!!');
      return false;
    }
  });
};

const addDevice = (device) => {
  device.key = String(data.value.length + 1); // 假设key是唯一的标识符
  data.value.push(device);
  ElMessage.success('设备新增成功');
};

const updateDevice = (device) => {
  const index = data.value.findIndex(item => item.key === device.key);
  if (index !== -1) {
    data.value[index] = { ...data.value[index], ...device };
    ElMessage.success('设备修改成功');
  }
};
</script>
