<template>
  <el-dialog v-model="dialogVisible" :title="form.id ? '编辑反应器' : '新增反应器'" width="900px" :close-on-click-modal="false"
    :close-on-press-escape="false" destroy-on-close draggable class="reactor-form-dialog">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="reactor-form">
      <el-tabs v-model="activeTab" class="reactor-tabs">
        <el-tab-pane label="基本信息" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="设备编号" prop="deviceNo">
                <el-input v-model="form.deviceNo" placeholder="请输入设备编号" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="反应器名称" prop="productID">
                <el-input v-model="form.productID" placeholder="请输入反应器名称" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="资产编号" prop="assetNo">
                <el-input v-model="form.assetNo" placeholder="请输入资产编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备型号" prop="model">
                <el-select v-model="form.model" placeholder="请选择设备型号" style="width: 100%" filterable allow-create>
                  <el-option v-for="item in state.deviceModelOptions" :key="item.id" :label="item.name"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="规格" prop="specification">
                <el-input v-model="form.specification" placeholder="请输入规格" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="容量(g)" prop="capacity">
                <el-input-number v-model="form.capacity" :min="0" :step="1" style="width: 100%" placeholder="请输入容量" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房间" prop="roomID">
                <el-select v-model="form.roomID" placeholder="请选择房间" style="width: 100%">
                  <el-option v-for="item in state.roomOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备负责人" prop="principalId">
                <el-select v-model="form.principalId" placeholder="请选择设备负责人" style="width: 100%">
                  <el-option v-for="item in state.principalOptions" :key="item.id" :label="item.name"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="压力单位" prop="pressureUnit">
                <el-select v-model="form.pressureUnit" placeholder="请选择压力单位" class="w100">
                  <el-option v-for="item in state.pressureUnitOptions" :key="item.label" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="设备状态" prop="deviceStatus">
                <el-tag>
                  {{ getDeviceStatusDesc(form.deviceStatus ?? 1) }}
                </el-tag>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="维护标记">
                <el-switch v-model="form.maintenanceFlag" active-text="维护中" inactive-text="正常" />
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="维修完成时间" v-if="form.maintenanceFlag">
                <el-date-picker v-model="form.maintenanceTime" type="date" placeholder="预计完成时间" format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD" style="width: 180px" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="设备配置" name="config">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="反应器地秤" prop="equScaleId">
                <el-select v-model="form.equScaleId" placeholder="请选择反应器地秤" class="w100">
                  <el-option v-for="item in state.equScaleOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="补料地秤" prop="feedingScaleId">
                <el-select v-model="form.feedingScaleId" placeholder="请选择补料地秤" class="w100">
                  <el-option v-for="item in state.feedingScaleOptions" :key="item.id" :label="item.name"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="继电器" prop="relayID">
                <el-select v-model="form.relayID" placeholder="请选择继电器" class="w100">
                  <el-option v-for="item in state.relayOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报警器" prop="equAlarmId">
                <el-select v-model="form.equAlarmId" placeholder="请选择报警器" class="w100">
                  <el-option v-for="item in state.equAlarmOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="警告下限(g)" prop="warningLowerLimit">
                <el-input-number v-model="form.warningLowerLimit" :min="0" :step="1" style="width: 100%"
                  placeholder="请输入警告下限" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="警告上限(g)" prop="warningUpperLimit">
                <el-input-number v-model="form.warningUpperLimit" :min="0" :step="1" style="width: 100%"
                  placeholder="请输入警告上限" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="OPC IP" prop="opcip">
                <el-input v-model="form.opcip" placeholder="请输入OPC IP" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="OPC 端口" prop="opcPort">
                <el-input v-model="form.opcPort" placeholder="请输入OPC 端口" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="需要外置泵" prop="isExternalPump">
                <el-switch v-model="form.isExternalPump" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>

        <el-tab-pane label="泵配置" name="pumpConfig">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="泵1速度" prop="pump1.speed">
                <el-input-number v-model="form.pump1.speed" :min="0" :step="1" style="width: 100%"
                  placeholder="请输入泵1速度" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="泵1配置" prop="pump1.configId">
                <el-select 
                  v-model="form.pump1.configId" 
                  placeholder="请选择泵1配置" 
                  style="width: 100%"
                  filterable
                >
                  <el-option 
                    v-for="item in state.pumpConfigOptions" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="泵2速度" prop="pump2.speed">
                <el-input-number v-model="form.pump2.speed" :min="0" :step="1" style="width: 100%"
                  placeholder="请输入泵2速度" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="泵2配置" prop="pump2.configId">
                <el-select 
                  v-model="form.pump2.configId" 
                  placeholder="请选择泵2配置" 
                  style="width: 100%"
                  filterable
                >
                  <el-option 
                    v-for="item in state.pumpConfigOptions" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="泵3速度" prop="pump3.speed">
                <el-input-number v-model="form.pump3.speed" :min="0" :step="1" style="width: 100%"
                  placeholder="请输入泵3速度" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="泵3配置" prop="pump3.configId">
                <el-select 
                  v-model="form.pump3.configId" 
                  placeholder="请选择泵3配置" 
                  style="width: 100%"
                  filterable
                >
                  <el-option 
                    v-for="item in state.pumpConfigOptions" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="泵4速度" prop="pump4.speed">
                <el-input-number v-model="form.pump4.speed" :min="0" :step="1" style="width: 100%"
                  placeholder="请输入泵4速度" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="泵4配置" prop="pump4.configId">
                <el-select 
                  v-model="form.pump4.configId" 
                  placeholder="请选择泵4配置" 
                  style="width: 100%"
                  filterable
                >
                  <el-option 
                    v-for="item in state.pumpConfigOptions" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="泵5速度" prop="pump5.speed">
                <el-input-number v-model="form.pump5.speed" :min="0" :step="1" style="width: 100%"
                  placeholder="请输入泵5速度" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="泵5配置" prop="pump5.configId">
                <el-select 
                  v-model="form.pump5.configId" 
                  placeholder="请选择泵5配置" 
                  style="width: 100%"
                  filterable
                >
                  <el-option 
                    v-for="item in state.pumpConfigOptions" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="泵6速度" prop="pump6.speed">
                <el-input-number v-model="form.pump6.speed" :min="0" :step="1" style="width: 100%"
                  placeholder="请输入泵6速度" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="泵6配置" prop="pump6.configId">
                <el-select 
                  v-model="form.pump6.configId" 
                  placeholder="请选择泵6配置" 
                  style="width: 100%"
                  filterable
                >
                  <el-option 
                    v-for="item in state.pumpConfigOptions" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="泵7速度" prop="pump7.speed">
                <el-input-number v-model="form.pump7.speed" :min="0" :step="1" style="width: 100%"
                  placeholder="请输入泵7速度" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="泵7配置" prop="pump7.configId">
                <el-select 
                  v-model="form.pump7.configId" 
                  placeholder="请选择泵7配置" 
                  style="width: 100%"
                  filterable
                >
                  <el-option 
                    v-for="item in state.pumpConfigOptions" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="泵8速度" prop="pump8.speed">
                <el-input-number v-model="form.pump8.speed" :min="0" :step="1" style="width: 100%"
                  placeholder="请输入泵8速度" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="泵8配置" prop="pump8.configId">
                <el-select 
                  v-model="form.pump8.configId" 
                  placeholder="请选择泵8配置" 
                  style="width: 100%"
                  filterable
                >
                  <el-option 
                    v-for="item in state.pumpConfigOptions" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="OnCancel" size="default">取 消</el-button>
      <el-button type="primary" :loading="state.sureLoading" @click="submitForm" size="default">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="admin/reactor/form">
import { ref, reactive, onMounted, watch, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ReactorApi } from '../../../../api/admin/ReactorApi'
import { RoomApi } from '/@/api/admin/Room'
import { UserApi } from '/@/api/admin/User'
import { DictApi } from '/@/api/admin/Dict'
import { UspscaleApi } from '/@/api/admin/UspscaleApi'
import { UspRelayApi } from '/@/api/admin/UspRelayApi'
import { AlarmApi } from '/@/api/admin/AlarmApi'
import { UspFeedingConfigApi } from '/@/api/admin/UspFeedingConfigApi'

import {
  DeviceStatusEnum,
  MaintenanceFlagEnum,
  ReactorAddInputAndUpdateInput,
  PumpConfig,
  defaultPumpConfig,
  ReactorTypeEnumItem
} from '/@/api/types/reactorType'
import { toOptionsByValue } from '/@/utils/enum'
import { EnumPressureUnit } from '/@/api/admin/enum-contracts'
import eventBus from '/@/utils/mitt'

const { proxy } = getCurrentInstance() as any

const props = defineProps<{
  title: string
}>()

const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const activeTab = ref('basic')

const form = reactive<ReactorAddInputAndUpdateInput>({
  sort: 0,
  deviceNo: '',
  assetNo: '',
  productID: '',
  model: '',
  specification: '',
  capacity: 0,
  roomID: undefined,
  principalId: undefined,
  deviceStatus: 1,
  maintenanceFlag: undefined,
  maintenanceTime: '',
  pressureUnit: '',
  equScaleId: undefined,
  feedingScaleId: undefined,
  relayID: undefined,
  equAlarmId: undefined,
  warningLowerLimit: 0,
  warningUpperLimit: 0,
  errorCode: '',
  isExternalPump: true,
  opcip: '',
  opcPort: '',
  pump1: { ...defaultPumpConfig },
  pump2: { ...defaultPumpConfig },
  pump3: { ...defaultPumpConfig },
  pump4: { ...defaultPumpConfig },
  pump5: { ...defaultPumpConfig },
  pump6: { ...defaultPumpConfig },
  pump7: { ...defaultPumpConfig },
  pump8: { ...defaultPumpConfig }
})

const state = reactive({
  sureLoading: false,
  roomOptions: [] as Array<{ id: number; name: string }>,
  principalOptions: [] as Array<{ id: number; name: string }>,
  deviceStatusOptions: [] as ReactorTypeEnumItem[],
  deviceModelOptions: [] as Array<{ id: string; name: string }>,
  pressureUnitOptions: toOptionsByValue(EnumPressureUnit),
  equScaleOptions: [] as Array<{ id: number; name: string }>,
  feedingScaleOptions: [] as Array<{ id: number; name: string }>,
  relayOptions: [] as Array<{ id: number; name: string }>,
  equAlarmOptions: [] as Array<{ id: number; name: string }>,
  pumpConfigOptions: [] as Array<{ id: number; name: string }>,
})

const rules = reactive<FormRules>({
  deviceNo: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
  productID: [{ required: true, message: '请输入反应器名称', trigger: 'blur' }],
  model: [{ required: true, message: '请选择设备型号', trigger: 'change' }],
  assetNo: [{ required: true, message: '请输入资产编号', trigger: 'blur' }],
  specification: [{ required: false, message: '请输入规格', trigger: 'blur' }],
  capacity: [{ required: true, message: '请输入容量', trigger: 'blur' }],
  roomID: [{ required: false, message: '请选择房间', trigger: 'change' }],
  principalId: [{ required: false, message: '请选择设备负责人', trigger: 'change' }],
  deviceStatus: [{ required: false, message: '请选择设备状态', trigger: 'change' }],
  pressureUnit: [{ required: true, message: '请选择压力单位', trigger: 'change' }],
  equScaleId: [{ required: true, message: '请选择反应器地秤', trigger: 'change' }],
  feedingScaleId: [{ required: false, message: '请输入补料秤ID', trigger: 'blur' }],
  relayID: [{ required: false, message: '请输入继电器ID', trigger: 'blur' }],
  equAlarmId: [{ required: false, message: '请输入报警器ID', trigger: 'blur' }],
  warningLowerLimit: [{ required: true, message: '请输入警告下限', trigger: 'blur' }],
  warningUpperLimit: [{ required: true, message: '请输入警告上限', trigger: 'blur' }],
  'pump1.speed': [
    { required: true, message: '请输入泵1速度', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵1速度不能小于0', trigger: 'blur' }
  ],
  'pump1.configId': [
    { required: true, message: '请输入泵1配置ID', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵1配置ID不能小于0', trigger: 'blur' }
  ],
  'pump2.speed': [
    { required: true, message: '请输入泵2速度', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵2速度不能小于0', trigger: 'blur' }
  ],
  'pump2.configId': [
    { required: true, message: '请输入泵2配置ID', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵2配置ID不能小于0', trigger: 'blur' }
  ],
  'pump3.speed': [
    { required: true, message: '请输入泵3速度', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵3速度不能小于0', trigger: 'blur' }
  ],
  'pump3.configId': [
    { required: true, message: '请输入泵3配置ID', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵3配置ID不能小于0', trigger: 'blur' }
  ],
  'pump4.speed': [
    { required: true, message: '请输入泵4速度', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵4速度不能小于0', trigger: 'blur' }
  ],
  'pump4.configId': [
    { required: true, message: '请输入泵4配置ID', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵4配置ID不能小于0', trigger: 'blur' }
  ],
  'pump5.speed': [
    { required: true, message: '请输入泵5速度', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵5速度不能小于0', trigger: 'blur' }
  ],
  'pump5.configId': [
    { required: true, message: '请输入泵5配置ID', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵5配置ID不能小于0', trigger: 'blur' }
  ],
  'pump6.speed': [
    { required: true, message: '请输入泵6速度', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵6速度不能小于0', trigger: 'blur' }
  ],
  'pump6.configId': [
    { required: true, message: '请输入泵6配置ID', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵6配置ID不能小于0', trigger: 'blur' }
  ],
  'pump7.speed': [
    { required: true, message: '请输入泵7速度', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵7速度不能小于0', trigger: 'blur' }
  ],
  'pump7.configId': [
    { required: true, message: '请输入泵7配置ID', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵7配置ID不能小于0', trigger: 'blur' }
  ],
  'pump8.speed': [
    { required: true, message: '请输入泵8速度', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵8速度不能小于0', trigger: 'blur' }
  ],
  'pump8.configId': [
    { required: true, message: '请输入泵8配置ID', trigger: 'blur' },
    { type: 'number', min: 0, message: '泵8配置ID不能小于0', trigger: 'blur' }
  ]
})

/** 获取设备状态枚举列表 */
const getDeviceStatusOptions = async () => {
  try {
    const res = await new ReactorApi().getDeviceStatusEnumList()
    state.deviceStatusOptions = res.data ?? []
  } catch (error) {
    console.error('获取设备状态枚举列表失败:', error)
  }
}

/** 获取房间列表 */
const getRoomOptions = async () => {
  try {
    const res = await new RoomApi().getPage({
      currentPage: 1,
      pageSize: 1000,
      filter: {}
    })

    state.roomOptions = res.data?.list?.map((item: any) => ({
      id: item.id,
      name: item.roomName
    })) || []
  } catch (error) {
    console.error('获取房间列表失败:', error)
  }
}

/** 获取负责人列表 */
const getPrincipalOptions = async () => {
  try {
    const res = await new UserApi().getPage({
      currentPage: 1,
      pageSize: 1000,
      filter: {}
    })

    state.principalOptions = res.data?.list?.map((item: any) => ({
      id: item.id,
      name: item.userName
    })) || []
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

const getDeviceModelOptions = async () => {
  try {
    const res = await new DictApi().getList(['ReactorModel'])
    state.deviceModelOptions = res.data?.reactorModel?.map((item: any) => ({
      id: item.value,
      name: item.name
    })) || []
  }
  catch (error) {
    console.error('获取设备型号列表失败:', error)
  }
}

const getEquAlarmOptions = async () => {
  try {
    const res = await new AlarmApi().getPage({
      currentPage: 1,
      pageSize: 1000,
      filter: {}
    })

    state.equAlarmOptions = res.data?.list?.map((item: any) => ({
      id: item.id,
      name: item.deviceNo
    })) || []
  } catch (error) {
    console.error('获取报警器列表失败:', error)
  }
}

const getRelayOptions = async () => {
  try {
    const res = await new UspRelayApi().getPage({
      currentPage: 1,
      pageSize: 1000,
      filter: {}
    })

    state.relayOptions = res.data?.list?.map((item: any) => ({
      id: item.id,
      name: item.deviceNo
    })) || []
  }
  catch (error) {
    console.error('获取继电器列表失败:', error)
  }
}

const getEquScaleOptions = async () => {
  try {
    const res = await new UspscaleApi().getPage({      currentPage: 1,
      pageSize: 1000,
      filter: {}
    })

    state.equScaleOptions = res.data?.list?.filter((item: any) => item.isFeedingScale == false).map((item: any) => ({
      id: item.id,
      name: item.deviceNo
    })) || []

    state.feedingScaleOptions = res.data?.list?.filter((item: any) => item.isFeedingScale == true).map((item: any) => ({
      id: item.id,
      name: item.deviceNo
    })) || []
  }
  catch (error) {
    console.error('获取地秤列表失败:', error)
  }
}

const getPumpConfigOptions = async () => {
  try {
    const res = await new UspFeedingConfigApi().getPage({
      currentPage: 1,
      pageSize: 1000,
      filter: {
      }
    })

    state.pumpConfigOptions = res.data?.list?.map((item: any) => ({
      id: item.id,
      name: item.configName
    })) || []
  }
  catch (error) {
    console.error('获取泵配置列表失败:', error)
  }
}

const getDeviceStatusDesc = (status: DeviceStatusEnum) => {
  return state.deviceStatusOptions.find(item => item.value === status)?.label || ''
}

/** 打开弹窗 */
const open = async (id?: number) => {
  proxy.$modal.loading()

  if (id && id > 0) {
    const res = await new ReactorApi().get({ id }, { loading: true })
    if (res?.success && res.data) {
      const formData = res.data as unknown as ReactorAddInputAndUpdateInput
      Object.assign(form, formData)
    }
  } else {
    Object.assign(form, {
      sort: 0,
      deviceNo: '',
      assetNo: '',
      productID: '',
      model: '',
      specification: '',
      capacity: 0,
      roomID: undefined,
      principalId: undefined,
      deviceStatus: 1,
      maintenanceFlag: undefined,
      maintenanceTime: '',
      pressureUnit: '',
      equScaleId: undefined,
      feedingScaleId: undefined,
      relayID: undefined,
      equAlarmId: undefined,
      warningLowerLimit: 0,
      warningUpperLimit: 0,
      errorCode: '',
      isExternalPump: true,
      opcip: '',
      opcPort: '',
      pump1: { ...defaultPumpConfig },
      pump2: { ...defaultPumpConfig },
      pump3: { ...defaultPumpConfig },
      pump4: { ...defaultPumpConfig },
      pump5: { ...defaultPumpConfig },
      pump6: { ...defaultPumpConfig },
      pump7: { ...defaultPumpConfig },
      pump8: { ...defaultPumpConfig },
    })
  }
  proxy.$modal.closeLoading()
  dialogVisible.value = true

  await Promise.all([
    getDeviceStatusOptions(),
    getRoomOptions(),
    getPrincipalOptions(),
    getDeviceModelOptions(),
    getEquScaleOptions(),
    getRelayOptions(),
    getEquAlarmOptions(),
    getPumpConfigOptions()
  ])
}

/** 取消 */
const OnCancel = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

/** 提交表单 */
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      state.sureLoading = true  // 开始加载
      try {
        const api = new ReactorApi()
        const res = form.id ? await api.update(form) : await api.add(form)
        if (res.success) {
          ElMessage.success(form.id ? '修改成功' : '新增成功')
          dialogVisible.value = false
          eventBus.emit('refreshReactor')
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败，请重试')
      } finally {
        state.sureLoading = false  // 结束加载
      }
    }
    else {
      ElMessage.warning('存在未填写的必填项')
    }
  })
}

// 添加对 maintenanceFlag 的监听
watch(() => form.maintenanceFlag, (newValue) => {
  if (newValue != undefined && newValue == 0) {
    form.maintenanceTime = ''
  }
})

onMounted(() => {
  getDeviceStatusOptions()
  getRoomOptions()
  getPrincipalOptions()
  getDeviceModelOptions()
  getEquScaleOptions()
  getRelayOptions()
  getEquAlarmOptions()
  getPumpConfigOptions()
})

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.reactor-form-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 30px;
  }
}

.reactor-form {
  .el-form-item {
    margin-bottom: 22px;
  }
}

.reactor-tabs {
  :deep(.el-tabs__content) {
    padding: 20px 0;
  }

  :deep(.el-tabs__nav) {
    margin-bottom: 20px;
  }
}

:deep(.el-input-number) {
  width: 100%;

  .el-input__wrapper {
    padding-left: 11px;
    padding-right: 11px;
  }
}

:deep(.el-select) {
  width: 100%;
}

.pump-config-section {
  margin-top: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;

  h3 {
    margin-bottom: 20px;
    font-size: 16px;
    color: #303133;
  }
}
</style>
