<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>

      <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 axios from "axios";
import { useRouter } from "vue-router";
import request from "../../utils/request";

// 定义表单数据接口
interface Form {
  OM: number | null;
  CL: number | null;
  CEC: number | null;
  H_plus: number | null;
  N: number | null;
  Al3_plus: number | null;
  delta_ph: number | null;
}

const form = reactive<Form>({
  OM: null,
  CL: null,
  CEC: null,
  H_plus: null,
  N: null,
  Al3_plus: null,
  delta_ph: null,
});

const router = useRouter();
const result = ref<number | null>(null);
const dialogVisible = ref(false);
const predictForm = ref<any>(null);
const errorMessages = reactive<Record<string, string>>({
  OM: "",
  CL: "",
  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 },
    { 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]; // 现在 TypeScript 明白 field 是 keyof Form 类型
    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: 25,
    parameters: {
      organic_matter: form.OM,
      chloride: form.CL,
      cec: form.CEC,
      h_concentration: form.H_plus,
      n: form.N,
      al_concentration: form.Al3_plus,
    },
  };

  try {
    const response = await request.post("/predict", data, {
      headers: {
        "Content-Type": "application/json",
      },
    });
    console.log("预测结果:", response.data);
    if (
      response.data &&
      response.data.result &&
      response.data.result.length > 0
    ) {
      result.value = parseFloat(response.data.result[0].toFixed(2));
    } else {
      console.error("未获取到有效的预测结果");
      ElMessage.error("未获取到有效的预测结果");
    }
    dialogVisible.value = true;
  } catch (error: any) {
    console.error("请求失败:", error);
    if (error.response) {
      ElMessage.error(`请求失败，状态码: ${error.response.status}`);
    } else if (error.request) {
      ElMessage.error("请求发送成功，但没有收到响应");
    } else {
      ElMessage.error("请求过程中发生错误: " + error.message);
    }
  }
};

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

  // 使用类型断言确保 key 是 keyof Form 类型
  Object.keys(form).forEach((key) => {
    if (key in form) {
      const typedKey = key as keyof Form;
      form[typedKey] = null;
    }
  });

  // 同样地处理 errorMessages
  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>