<template>
  <!-- 主弹框：标题显示当前组织名称 -->
  <a-modal
    :title="`${currentOrg.orgName || '组织'} - 设备管理`"
    v-model:visible="visible"
    :maskClosable="false"
    :width="800"
    @cancel="handleCancel"
  >
    <!-- 顶部添加设备按钮 -->
    <div class="flex justify-end mb-4" style="margin: 10px 0;">
      <a-button type="primary" @click="showAddModal = true">
        <plus-outlined />
        添加设备
      </a-button>
    </div>

    <!-- 设备表格 -->
    <a-table
      :columns="columns"
      :data-source="devices"
      row-key="deviceId"
      :pagination="false"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'online'">
          <a-badge :status="record.online ? 'success' : 'error'">
            {{ record.online ? '在线' : '离线' }}
          </a-badge>
        </template>
        <template v-if="column.key === 'action'">
          <a-button size="small" type="link" @click="handleEdit(record)">
            编辑
          </a-button>
          <a-button size="small" type="link" danger @click="handleDelete(record)">
            删除
          </a-button>
        </template>
      </template>
    </a-table>

    <!-- 添加/编辑设备子弹框 -->
    <a-modal
      :title="isEditing ? '编辑设备' : '添加设备'"
      v-model:visible="showAddModal"
      :maskClosable="false"
      @cancel="showAddModal = false"
      @ok="handleFormSubmit"
    >
      <a-form
        :model="formData"
        ref="formRef"
        layout="horizontal"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item
          name="deviceId"
          label="设备ID"
          :rules="[{ required: true, message: '请输入设备ID' }]"
        >
          <a-input
            v-model:value="formData.deviceId"
            placeholder="请输入设备ID"
            :disabled="isEditing"
          />
        </a-form-item>
        <a-form-item
          name="deviceName"
          label="设备名称"
          :rules="[{ required: true, message: '请输入设备名称' }]"
        >
          <a-input
            v-model:value="formData.deviceName"
            placeholder="请输入设备名称"
          />
        </a-form-item>
        <a-form-item
          name="deviceType"
          label="设备类型"
          :rules="[{ required: true, message: '请选择设备类型' }]"
        >
          <a-select
            v-model:value="formData.deviceType"
            placeholder="请选择设备类型"
          >
            <a-select-option value="sensor">传感器</a-select-option>
            <a-select-option value="controller">控制器</a-select-option>
            <a-select-option value="gateway">网关</a-select-option>
            <a-select-option value="camera">摄像头</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          name="deviceManufacturer"
          label="设备供应商"
          :rules="[{ required: true, message: '请选择设备供应商' }]"
        >
          <a-select
            v-model:value="formData.deviceManufacturer"
            placeholder="请选择设备供应商"
          >
            <a-select-option value="vendor1">供应商A</a-select-option>
            <a-select-option value="vendor2">供应商B</a-select-option>
            <a-select-option value="vendor3">供应商C</a-select-option>
            <a-select-option value="vendor4">供应商D</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-modal>
</template>

<script setup>
import { ref, reactive, defineExpose } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

// ✅ 1. 不再定义 props.orgRecord 为可修改对象，而是用内部 ref 存储
const currentOrg = ref({ orgName: '默认组织' }); // 当前管理的组织

// 弹框状态
const visible = ref(false);
const showAddModal = ref(false);
const formRef = ref(null);
const isEditing = ref(false);

// 设备列表（后续可替换为 API 数据）
const devices = ref([
  { deviceId: 'DEV001', deviceName: '温度传感器', deviceType: 'sensor', deviceManufacturer: 'vendor1', online: true },
  { deviceId: 'DEV002', deviceName: '智能控制器', deviceType: 'controller', deviceManufacturer: 'vendor2', online: false },
  { deviceId: 'DEV003', deviceName: '网络网关', deviceType: 'gateway', deviceManufacturer: 'vendor3', online: true },
]);

// 表单数据
const formData = reactive({
  deviceId: '',
  deviceName: '',
  deviceType: '',
  deviceManufacturer: '',
});

// 列配置（保持不变）
const columns = ref([
  { title: '设备ID', dataIndex: 'deviceId', key: 'deviceId', align: 'center' },
  { title: '设备名称', dataIndex: 'deviceName', key: 'deviceName', align: 'center' },
  { 
    title: '设备类型', 
    dataIndex: 'deviceType', 
    key: 'deviceType', 
    align: 'center',
    render: (type) => {
      const typeMap = {
        'sensor': '传感器', 'controller': '控制器', 
        'gateway': '网关', 'camera': '摄像头'
      };
      return typeMap[type] || type;
    }
  },
  { 
    title: '设备供应商', 
    dataIndex: 'deviceManufacturer', 
    key: 'deviceManufacturer', 
    align: 'center',
    render: (vendor) => {
      const vendorMap = {
        'vendor1': '供应商A', 'vendor2': '供应商B',
        'vendor3': '供应商C', 'vendor4': '供应商D'
      };
      return vendorMap[vendor] || vendor;
    }
  },
  { title: '连接状态', dataIndex: 'online', key: 'online', align: 'center' },
  { title: '操作', key: 'action', align: 'center', fixed: 'right', width: 120 }
]);

// ✅ 2. 暴露 open 方法：接收 orgRecord 并保存到 currentOrg
function open(options = {}) {
  const { orgRecord } = options;
  if (orgRecord) {
    currentOrg.value = { ...orgRecord }; // 深拷贝避免引用问题
  } else {
    currentOrg.value = { orgName: '默认组织' };
  }

  // ✅ 未来可在这里调用 API 加载该组织的设备：
  // loadDevicesByOrgId(currentOrg.value.id);

  visible.value = true;
}

// 关闭主弹框
function handleCancel() {
  visible.value = false;
  showAddModal.value = false;
  resetForm();
}

// 提交表单
async function handleFormSubmit() {
  try {
    await formRef.value.validate();
    
    if (isEditing.value) {
      const index = devices.value.findIndex(dev => dev.deviceId === formData.deviceId);
      if (index !== -1) {
        devices.value[index] = { ...formData, online: devices.value[index].online };
        message.success('设备编辑成功');
      }
    } else {
      const isExist = devices.value.some(dev => dev.deviceId === formData.deviceId);
      if (isExist) {
        message.error('设备ID已存在');
        return;
      }
      devices.value.push({ ...formData, online: false });
      message.success('设备添加成功');
    }
    
    showAddModal.value = false;
    resetForm();
  } catch (error) {
    console.log('表单验证失败:', error);
  }
}

// 重置表单
function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  isEditing.value = false;
  formData.deviceId = '';
  formData.deviceName = '';
  formData.deviceType = '';
  formData.deviceManufacturer = '';
}

// 编辑设备
function handleEdit(record) {
  isEditing.value = true;
  formData.deviceId = record.deviceId;
  formData.deviceName = record.deviceName;
  formData.deviceType = record.deviceType;
  formData.deviceManufacturer = record.deviceManufacturer;
  showAddModal.value = true;
}

// 删除设备
function handleDelete(record) {
  devices.value = devices.value.filter(dev => dev.deviceId !== record.deviceId);
  message.success('设备已删除');
}

// ✅ 3. 暴露 open 方法给父组件
defineExpose({
  open,
});
</script>

<style scoped>
.ant-modal-body {
  padding: 20px;
}
</style>