<template>
  <el-dialog
    :model-value="modelValue"
    title="新增除尘器"
    width="460px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @update:model-value="$emit('update:modelValue', $event)"
  >
    <div class="add-dust-form">
      <div class="form-item">
        <div class="selector-wrap">
          <el-select v-model="formData.dustType" placeholder="除尘器选择" style="width: 238px">
            <el-option
              v-for="item in dustTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button type="primary" size="default" @click="selectDustType">选择</el-button>
        </div>
      </div>

      <div class="form-content">
        <el-form ref="formRef" :model="formData" label-width="100px" :rules="rules">
          <el-form-item label="除尘器名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入" />
          </el-form-item>
          
          <el-form-item label="除尘器编号" prop="code">
            <el-input v-model="formData.code" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="所属工序" prop="process">
            <el-select v-model="formData.process" placeholder="工序选择">
              <el-option
                v-for="item in processOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="仓室数量" prop="chamberCount">
            <el-input v-model.number="formData.chamberCount" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="电磁阀数量" prop="valveCount">
            <el-input v-model.number="formData.valveCount" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="合理压差范围" prop="pressureRange">
            <div class="range-input">
              <el-input v-model.number="formData.pressureMin" placeholder="请输入" />
              <span class="separator">～</span>
              <el-input v-model.number="formData.pressureMax" placeholder="请输入" />
            </div>
          </el-form-item>

          <el-form-item label="服务器IP" prop="serverIp">
            <el-input v-model="formData.serverIp" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </div>

      <div class="form-footer">

        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue';

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:modelValue', 'save']);

const formRef = ref(null);

const dustTypeOptions = [
  { value: 1, label: '除尘器类型1' },
  { value: 2, label: '除尘器类型2' },
  { value: 3, label: '除尘器类型3' }
];

const processOptions = [
  { value: 1, label: '转炉' },
  { value: 2, label: '炼铁' }
];

const formData = reactive({
  dustType: '',
  name: '',
  code: '',
  process: '',
  chamberCount: null,
  valveCount: null,
  pressureMin: null,
  pressureMax: null,
  serverIp: ''
});

const rules = {
  name: [{ required: true, message: '请输入除尘器名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入除尘器编号', trigger: 'blur' }],
  process: [{ required: true, message: '请选择所属工序', trigger: 'change' }],
  chamberCount: [
    { required: true, message: '请输入仓室数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '仓室数量必须大于0', trigger: 'blur' }
  ],
  valveCount: [
    { required: true, message: '请输入电磁阀数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '电磁阀数量必须大于0', trigger: 'blur' }
  ],
  pressureMin: [
    { required: true, message: '请输入最小压差', trigger: 'blur' },
    { type: 'number', message: '必须为数字', trigger: 'blur' }
  ],
  pressureMax: [
    { required: true, message: '请输入最大压差', trigger: 'blur' },
    { type: 'number', message: '必须为数字', trigger: 'blur' }
  ],
  serverIp: [
    { required: true, message: '请输入服务器IP', trigger: 'blur' },
    { pattern: /^(\d{1,3}\.){3}\d{1,3}$/, message: 'IP地址格式不正确', trigger: 'blur' }
  ]
};

const selectDustType = () => {
  // 这里可以根据选择的除尘器类型预填充表单数据
  // 如果有预设模板数据，可以在这里设置
  console.log('Selected dust type:', formData.dustType);
};

const submitForm = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      // 组装压差范围
      const pressureRange = `${formData.pressureMin}～${formData.pressureMax}`;
      
      // 准备提交的数据
      const submitData = {
        dustType: formData.dustType,
        deviceName: formData.name,
        deviceNo: formData.code,
        process: formData.process,
        healthScore: formData.chamberCount, // 仓室数量保存在healthScore
        health2Score: formData.valveCount, // 电磁阀数量保存在health2Score
        lastAlarmTime: pressureRange, // 合理压差范围保存在lastAlarmTime字段
        serverIp: formData.serverIp,
        // 生成默认的状态矩阵
        status: generateDefaultStatus(formData.chamberCount)
      };
      
      // 发送数据到父组件处理保存逻辑
      emit('save', submitData);
      emit('update:modelValue', false);
    } else {
      console.error('Form validation failed');
      return false;
    }
  });
};

const cancel = () => {
  // 重置表单状态和数据
  formRef.value.resetFields();
  formData.dustType = '';
  formData.name = '';
  formData.code = '';
  formData.process = '';
  formData.chamberCount = null;
  formData.valveCount = null;
  emit('update:modelValue', false);
};

// 生成默认的状态矩阵
const generateDefaultStatus = (totalChambers) => {
  // 默认状态：正常（status=1），每排最多5个仓室
  const rows = Math.ceil(totalChambers / 5);
  const result = [];
  
  let chamberIndex = 1;
  for (let rowIndex = 0; rowIndex < rows; rowIndex++) {
    const row = [];
    const chambersInRow = Math.min(5, totalChambers - rowIndex * 5);
    
    for (let i = 0; i < chambersInRow; i++) {
      row.push({
        index: chamberIndex++,
        status: 1, // 正常状态
        count: 1  // 默认阀门数量
      });
    }
    
    result.push(row);
  }
  
  return result;
};
</script>

<style lang="scss" scoped>
.add-dust-form {
  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding: 0 0 0 50px;
    box-sizing: border-box;
    
    .number-badge {
      width: 24px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      background-color: #f8cd4e;
      color: #000;
      border-radius: 4px;
      font-weight: bold;
      margin-right: 10px;
    }
    
    .selector-wrap {
      display: flex;
      align-items: center;
      gap: 10px;
      flex: 1;
    }
  }
  
  .form-content {
    padding: 0 30px;
    
    .range-input {
      display: flex;
      align-items: center;
      
      .separator {
        margin: 0 5px;
        color: #606266;
      }
    }
  }
  
  .form-footer {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    
    .el-button {
      width: 120px;
    }
  }
}

:deep(.el-form-item__label) {
  font-size: 14px;
  color: #606266;
}

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

:deep(.el-select) {
  width: 100%;
}
</style> 