<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>反酸模型</span>
      </div>
    </template>
    <el-form
      :model="form"
      ref="predictForm"
      label-width="240px"
      label-position="left"
    >
      <el-form-item
        label="土壤有机质(g/kg)"
        prop="OM"
        :error="errorMessages.OM"
        required
      >
        <el-input
          v-model="form.OM"
          size="large"
          placeholder="请输入土壤有机质0~30(g/kg)"
          @input="handleInput('OM', $event, 0, 30)"
        >
        </el-input>
      </el-form-item>

      <el-form-item
        label="土壤粘粒(g/kg)"
        prop="CL"
        :error="errorMessages.CL"
        required
      >
        <el-input
          v-model="form.CL"
          size="large"
          placeholder="请输入土壤粘粒50~400(g/kg)"
          @input="handleInput('CL', $event, 50, 400)"
        >
        </el-input>
      </el-form-item>

      <!-- 修改：将pH改为CEC -->
      <el-form-item
        label="阳离子交换量(cmol/kg)"
        prop="CEC"
        :error="errorMessages.CEC"
        required
      >
        <el-input
          v-model="form.CEC"
          size="large"
          placeholder="请输入阳离子交换量0~15(cmol/kg)"
          @input="handleInput('CEC', $event, 0, 15)"
        >
        </el-input>
      </el-form-item>

      <el-form-item
        label="交换性氢(cmol/kg)"
        prop="H_plus"
        :error="errorMessages.H_plus"
        required
      >
        <el-input
          v-model="form.H_plus"
          size="large"
          placeholder="请输入交换性氢0~1(cmol/kg)"
          @input="handleInput('H_plus', $event, 0, 1)"
        >
        </el-input>
      </el-form-item>

      <el-form-item
        label="水解氮(g/kg)"
        prop="N"
        :error="errorMessages.N"
        required
      >
        <el-input
          v-model="form.N"
          size="large"
          placeholder="请输入水解氮0~0.2(g/kg)"
          @input="handleInput('N', $event, 0, 0.2)"
        >
        </el-input>
      </el-form-item>

      <el-form-item
        label="交换性铝(cmol/kg)"
        prop="Al3_plus"
        :error="errorMessages.Al3_plus"
        required
      >
        <el-input
          v-model="form.Al3_plus"
          size="large"
          placeholder="请输入交换性铝0~6(cmol/kg)"
          @input="handleInput('Al3_plus', $event, 0, 6)"
        >
        </el-input>
      </el-form-item>

      <el-button type="primary" @click="onSubmit" class="onSubmit"
        >计算</el-button
      >

      <el-dialog
        v-model="dialogVisible"
        @close="onDialogClose"
        :close-on-click-modal="false"
        width="500px"
        align-center
        title="计算结果"
      >
        <span class="dialog-class">pH值: {{ result }}</span>
        <template #footer>
          <el-button @click="dialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { api5000 } from "../../../utils/request"; // 使用api5000


// 定义表单数据接口
interface Form {
  OM: number | null;
  CL: number | null;
  CEC: number | null; // 修改：将pH改为CEC
  H_plus: number | null;
  N: number | null;
  Al3_plus: number | null;
}

const form = reactive<Form>({
  OM: null,
  CL: null,
  CEC: null, // 修改：将pH改为CEC
  H_plus: null,
  N: null,
  Al3_plus: null,
});

const result = ref<number | null>(null);
const dialogVisible = ref(false);
const predictForm = ref<any>(null);
const errorMessages = reactive<Record<string, string>>({
  OM: "",
  CL: "",
  CEC: "", // 修改：将pH改为CEC
  H_plus: "",
  N: "",
  Al3_plus: "",
});

// 限制输入为数字并校验范围
const handleInput = (
  field: keyof Form,
  event: Event,
  min: number,
  max: number
) => {
  const target = event.target as HTMLInputElement;
  let value = target.value.replace(/[^0-9.]/g, "");
  form[field] = value ? parseFloat(value) : null;

  if (!value) {
    errorMessages[field] = "";
    return;
  }

  const numValue = parseFloat(value);
  if (isNaN(numValue) || numValue < min || numValue > max) {
    errorMessages[field] = `输入值应在 ${min} 到 ${max} 之间且为有效数字`;
  } else {
    errorMessages[field] = "";
  }
};

const validateInput = (value: string, min: number, max: number): boolean => {
  const numValue = parseFloat(value);
  return !isNaN(numValue) && numValue >= min && numValue <= max;
};

// 计算方法
const onSubmit = async () => {
  const inputConfigs = [
    { field: "OM" as keyof Form, min: 0, max: 30 },
    { field: "CL" as keyof Form, min: 50, max: 400 },
    { field: "CEC" as keyof Form, min: 0, max: 15 }, // 修改：将pH改为CEC
    { field: "H_plus" as keyof Form, min: 0, max: 1 },
    { field: "N" as keyof Form, min: 0, max: 0.2 },
    { field: "Al3_plus" as keyof Form, min: 0, max: 6 },
  ];

  let isValid = true;
  for (const config of inputConfigs) {
    const { field, min, max } = config;
    const value = form[field];
    if (value === null || !validateInput(value.toString(), min, max)) {
      isValid = false;
      errorMessages[field] = `输入值应在 ${min} 到 ${max} 之间且为有效数字`;
    } else {
      errorMessages[field] = "";
    }
  }

  if (!isValid) {
    ElMessage.error("输入值不符合要求，请检查输入");
    return;
  }

  console.log("开始计算...");
  const data = {
    model_id: 24,
    parameters: {
      OM: form.OM,
      CL: form.CL,
      CEC: form.CEC, // 修改：将pH改为CEC
      H_plus: form.H_plus,
      N: form.N,
      Al3_plus: form.Al3_plus,
    },
  };

  try {
    const response = await api5000.post('/predict', data, {
      headers: {
        "Content-Type": "application/json",
      },
    });
    
    if (response.data?.result?.length > 0) {
      result.value = parseFloat(response.data.result[0].toFixed(2));
      dialogVisible.value = true;
    } else {
      throw new Error("未获取到有效的预测结果");
    }
    dialogVisible.value = true;
  } catch (error: any) {
    console.error("请求失败详情:", error);
    
    let errorMessage = "请求失败";
    if (error.code === "ECONNABORTED") {
      errorMessage = "请求超时，请稍后再试";
    } else if (error.response) {
      // 服务器有响应但状态码不在2xx范围
      errorMessage = `请求失败，状态码: ${error.response.status}`;
      if (error.response.data?.detail) {
        errorMessage += ` - ${error.response.data.detail}`;
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      errorMessage = "无法连接到服务器，请检查网络连接";
      if (error.message.includes("Network Error")) {
        errorMessage = "网络错误，请检查后端服务是否运行";
      }
    }
    
    ElMessage.error(errorMessage);
  }
};

// 监听弹窗关闭事件，关闭后初始化值
const onDialogClose = () => {
  dialogVisible.value = false;

  // 重置表单
  Object.keys(form).forEach((key) => {
    if (key in form) {
      const typedKey = key as keyof Form;
      form[typedKey] = null;
    }
  });

  // 重置错误消息
  Object.keys(errorMessages).forEach((key) => {
    if (key in errorMessages) {
      const typedKey = key as keyof typeof errorMessages;
      errorMessages[typedKey] = "";
    }
  });

  nextTick(() => {
    if (predictForm.value) {
      (predictForm.value as any).resetFields();
    }
  });
};
</script>

<style scoped>
.box-card {
  max-width: 850px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f0f5ff;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 25px;
}

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

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

.el-input {
  width: 80%;
}

.onSubmit {
  display: block;
  margin: 0 auto;
  background-color: #007bff;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.onSubmit:hover {
  background-color: #0056b3;
}

.dialog-class {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%; /* 确保容器占满对话框内容区域 */
  font-size: 20px;
}

@media (max-width: 576px) {
  .el-form {
    --el-form-label-width: 100px;
  }
}

/* 自定义 tooltip 样式 */
:deep(.el-tooltip__popper.is-light) {
  background-color: white;
  border-color: #dcdfe6;
  color: #606266;
}
</style>