<template>
  <el-dialog :model-value="modelValue" :title="editData ? '编辑除尘器' : '新增除尘器'" width="500px" :close-on-click-modal="false"
    :close-on-press-escape="false" @update:model-value="cancel">
    <div class="add-dust-form all-select-btn">
      <div class="form-item">
        <div class="selector-wrap">
          <el-select v-model="formData.dustType" placeholder="除尘器选择" style="width: 238px" filterable remote
            :remote-method="handleSearch" :loading="loading">
            <el-option v-for="item in dustTypeOptions" :key="item.deviceNo" :label="item.deviceName"
              :value="item.deviceNo" />
          </el-select>
          <el-button type="deafault" size="default" class="search-btn-balck-theme" @click="selectDustType">选择</el-button>
        </div>
      </div>

      <div class="form-content">
        <el-form ref="formRef" :model="formData" label-width="120px" :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.productionLineId" :label="item.productionLineName"
                :value="item.productionLineId" />
            </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="合理压差范围" required>
            <div class="range-input">
              <el-form-item prop="pressureMin" class="coordinate-item">
                <el-input v-model.number="formData.pressureMin" placeholder="请输入" />
              </el-form-item>
              <span class="separator">～</span>
              <el-form-item prop="pressureMax" class="coordinate-item">
                <el-input v-model.number="formData.pressureMax" placeholder="请输入" />
              </el-form-item>
            </div>
          </el-form-item>

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

          <el-form-item label="二维图坐标" required>
            <div class="coordinate-inputs">
              <el-form-item prop="coordinateX" class="coordinate-item">
                <el-input v-model.number="formData.coordinateX" placeholder="X坐标">
                  <template #prefix>X:</template>
                </el-input>
              </el-form-item>
              <el-form-item prop="coordinateY" class="coordinate-item">
                <el-input v-model.number="formData.coordinateY" placeholder="Y坐标">
                  <template #prefix>Y:</template>
                </el-input>
              </el-form-item>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <div class="form-footer">

        <el-button @click="cancel" class="cancel-btn-balck-theme">取消</el-button>
        <el-button type="default" class="search-btn-balck-theme" @click="submitForm">确认</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { getVisDusterList, getProductionLine } from "@/request/api/dustOverview";
import { getToken } from "@/utils/auth";
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: null
  }
});

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

const formRef = ref(null);

const dustTypeOptions = ref([]);
const allDustOptions = ref([]);
const processOptions = ref([]);

const lastSearchQuery = ref('');

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



const rules = {
  name: [{ required: true, message: '请输入除尘器名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入除尘器编号', trigger: 'blur' }],
  process: [{ required: true, message: '请选择所属工序', trigger: 'blur' }],
  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', min: 0, message: '最小压差不能小于0', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && formData.pressureMax && value >= formData.pressureMax) {
          callback(new Error('必须小于最大压差'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  pressureMax: [
    { required: true, message: '请输入最大压差', trigger: 'blur' },
    { type: 'number', min: 0, message: '最大压差不能小于0', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && formData.pressureMin && value <= formData.pressureMin) {
          callback(new Error('必须大于最小压差'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  serverIp: [
    { required: true, message: '请输入服务器IP', trigger: 'blur' },
    { pattern: /^(\d{1,3}\.){3}\d{1,3}$/, message: 'IP地址格式不正确', trigger: 'blur' }
  ],
  coordinateX: [
    { required: true, message: '请输入X坐标', trigger: 'blur' },
    { type: 'number', message: 'X坐标必须为数字', trigger: 'blur' }
  ],
  coordinateY: [
    { required: true, message: '请输入Y坐标', trigger: 'blur' },
    { type: 'number', message: 'Y坐标必须为数字', trigger: 'blur' }
  ]
};

const loading = ref(false);

const initDustOptions = () => {
  loading.value = true;
  getVisDusterList().then(res => {
    dustTypeOptions.value = res.data;
    allDustOptions.value = res.data;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

const handleSearch = (query) => {
  if (query === lastSearchQuery.value) {
    return;
  }
  lastSearchQuery.value = query;

  if (!query) {
    dustTypeOptions.value = allDustOptions.value;
    return;
  }

  loading.value = true;
  const params = {
    deviceName: query
  };
  getVisDusterList(params).then(res => {
    dustTypeOptions.value = res.data;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

const productionLine = () => {
  getProductionLine({
    branchFactoryId: getToken("dataBranchFactoryId")
  }).then(res => {
    processOptions.value = res.data;
  })
}

onMounted(() => {
  productionLine();
  initDustOptions();
});

const selectDustType = () => {
  const item = dustTypeOptions.value.find(item => item.deviceNo === formData.dustType);
  formData.name = item.deviceName;
  formData.code = item.deviceNo;
  formData.process = item.productionLineId;
  // 校验表单
  formRef.value.validate((valid) => {
  });
};
const submitForm = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      // 准备提交的数据
      const submitData = {
        deviceNo: formData.code,
        deviceName: formData.name,
        productionLineId: formData.process,
        compartNum: formData.chamberCount,
        valveNum: formData.valveCount,
        serviceIp: formData.serverIp,
        pressureDiffLow: formData.pressureMin,
        pressureDiffHigh: formData.pressureMax,
        x: formData.coordinateX,
        y: formData.coordinateY,
      };

      // 如果是编辑模式，添加id
      if (props.editData) {
        submitData.id = props.editData.id;
      }
      // 发送数据到父组件处理保存逻辑
      emit('save', submitData);
      // emit('update:modelValue', false);
    } else {
      return false;
    }
  });
};
const resetForm = () => {
  // 重置表单状态和数据
  formData.dustType = '';
  formData.name = '';
  formData.code = '';
  formData.process = '';
  formData.chamberCount = null;
  formData.valveCount = null;
  formData.pressureMin = null;
  formData.pressureMax = null;
  formData.serverIp = '';
  formData.coordinateX = null;
  formData.coordinateY = null;
}

const cancel = () => {
  resetForm();
  formRef.value.resetFields();
  emit('cancel', {});
};

// 监听editData变化，初始化表单数据
watch(() => props.editData, (newVal) => {
  if (newVal) {
    formData.name = newVal.deviceName;
    formData.code = newVal.deviceNo;
    formData.process = newVal.productionLineId;
    formData.chamberCount = Number(newVal.compartNum);
    formData.valveCount = Number(newVal.valveNum);
    formData.pressureMin = Number(newVal.pressureDiffLow);
    formData.pressureMax = Number(newVal.pressureDiffHigh);
    formData.serverIp = newVal.serviceIp;
    formData.coordinateX = Number(newVal.x);
    formData.coordinateY = Number(newVal.y);
  } else {
    resetForm();
  }
}, { immediate: true });

watch(() => props.modelValue, (newVal) => {
  if (newVal === false) {
    resetForm();
  }
}, { immediate: true });

</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: 30px;
    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%;
}

.coordinate-inputs {
  display: flex;
  gap: 10px;

  .coordinate-item {
    flex: 1;
    margin-bottom: 0;

    :deep(.el-input__prefix) {
      color: #606266;
    }
  }
}
</style>