<template>
  <!-- 主弹框：标题显示当前组织名称 -->
  <a-modal
    :title="`${orgRecord.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"
        :rules="formRules"
        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, defineProps, defineEmits, defineExpose } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message, Form } from 'ant-design-vue';

// 1. 定义props：接收父组件传递的组织信息
const props = defineProps({
  orgRecord: {
    type: Object,
    default: () => ({ orgName: '默认组织' }), // 默认值防止空值报错
    required: false
  }
})

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

// 2. 设备表格列配置（优化显示文本）
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 }
]);

// 设备数据（后续可替换为接口请求：根据orgRecord.id获取该组织的设备）
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 formRules = reactive({
  deviceId: [{ required: true, message: '请输入设备ID' }],
  deviceName: [{ required: true, message: '请输入设备名称' }],
  deviceType: [{ required: true, message: '请选择设备类型' }],
  deviceManufacturer: [{ required: true, message: '请选择设备供应商' }],
});

// 3. 暴露给父组件的方法：打开弹框（可接收参数）
function open(options = {}) {
  const { orgRecord } = options;
  if (orgRecord) {
    // 更新当前组织信息（父组件传递的组织数据）
    props.orgRecord = orgRecord; 
  }
  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 {
      // 添加设备：检查ID唯一性
      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('设备已删除');
}

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

<style scoped>
/* 可选：调整弹框内边距 */
.ant-modal-body {
  padding: 20px;
}
</style>