<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>{{ $t('Calculation.neutralizationTitle') }}</span>
      </div>
    </template>

    <el-form
      :model="form"
      ref="predictForm"
      label-width="240px"
      label-position="left"
    >
      <el-form-item
        :label="$t('Calculation.initialPH')"
        prop="init_pH"
        :error="errorMessages.init_pH"
        required
      >
        <el-input
          v-model="form.init_pH"
          size="large"
          :placeholder="$t('Calculation.neutralization.initialPHPlaceholder')"
          ref="inputRefs.init_pH"
          @input="handleInput('init_pH', $event, 3, 6)"
        >
        </el-input>
      </el-form-item>

      <el-form-item
        :label="$t('Calculation.targetPH')"
        prop="target_pH"
        :error="errorMessages.target_pH"
        required
      >
        <el-input
          v-model="form.target_pH"
          size="large"
          :placeholder="$t('Calculation.neutralization.targetPHPlaceholder')"
          ref="inputRefs.target_pH"
          @input="handleInput('target_pH', $event, 5, 7)"
        >
        </el-input>
      </el-form-item>

      <el-form-item
        :label="$t('Calculation.exchangeableHydrogen')"
        prop="H"
        :error="errorMessages.H"
        required
      >
        <el-input
          v-model="form.H"
          size="large"
          :placeholder="$t('Calculation.neutralization.exchangeableHydrogenPlaceholder')"
          ref="inputRefs.H"
          @input="handleInput('H', $event, 0, 4)"
        >
        </el-input>
      </el-form-item>

      <el-form-item
        :label="$t('Calculation.exchangeableAluminum')"
        prop="Al"
        :error="errorMessages.Al"
        required
      >
        <el-input
          v-model="form.Al"
          size="large"
          :placeholder="$t('Calculation.neutralization.exchangeableAluminumPlaceholder')"
          ref="inputRefs.Al"
          @input="handleInput('Al', $event, 0, 8)"
        >
        </el-input>
      </el-form-item>

      <el-form-item
        :label="$t('Calculation.soilOrganicMatter')"
        prop="OM"
        :error="errorMessages.OM"
        required
      >
        <el-input
          v-model="form.OM"
          size="large"
          :placeholder="$t('Calculation.neutralization.soilOrganicMatterPlaceholder')"
          ref="inputRefs.OM"
          @input="handleInput('OM', $event, 0, 35)"
        >
        </el-input>
      </el-form-item>

      <el-form-item
        :label="$t('Calculation.nitrate')"
        prop="NO3"
        :error="errorMessages.NO3"
        required
      >
        <el-input
          v-model="form.NO3"
          size="large"
          :placeholder="$t('Calculation.neutralization.nitratePlaceholder')"
          ref="inputRefs.NO3"
          @input="handleInput('NO3', $event, 10, 70)"
        >
        </el-input>
      </el-form-item>

      <el-form-item
        :label="$t('Calculation.ammoniumSalt')"
        prop="NH4"
        :error="errorMessages.NH4"
        required
      >
        <el-input
          v-model="form.NH4"
          size="large"
          :placeholder="$t('Calculation.neutralization.ammoniumSaltPlaceholder')"
          ref="inputRefs.NH4"
          @input="handleInput('NH4', $event, 0, 20)"
        >
        </el-input>
      </el-form-item>

      <el-form-item
        :label="$t('Calculation.cationExchangeCapacity')"
        prop="CEC"
        :error="errorMessages.CEC"
        required
      >
        <el-input
          v-model="form.CEC"
          size="large"
          :placeholder="$t('Calculation.neutralization.cationExchangeCapacityPlaceholder')"
          ref="inputRefs.CEC"
          @input="handleInput('CEC', $event, 0, 15)"
        >
        </el-input>
      </el-form-item>

      <el-button type="primary" @click="onSubmit" class="onSubmit"
        >{{ $t('Calculation.calculateButton') }}</el-button
      >

      <el-dialog
        v-model="dialogVisible"
        @close="onDialogClose"
        :close-on-click-modal="false"
        width="500px"
        align-center
        class="dialog-class"
        :title="$t('Calculation.resultTitle')"
      >
        <span class="dialog-class"
          >{{ $t('Calculation.resultUnit') }} {{ result }}{{ $t('Calculation.quicklime') }}</span
        ><br />
        <template #footer>
          <el-button @click="dialogVisible = false">{{ $t('Calculation.closeButton') }}</el-button>
        </template>
      </el-dialog>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick, onMounted } from "vue";
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { api5000 } from "../../../utils/request";
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

// 根据文档修改表单接口
const form = reactive<{
  init_pH: number | null,
  target_pH: number | null,
  H: number | null,
  Al: number | null,
  OM: number | null,
  NO3: number | null,
  NH4: number | null,
  CEC: number | null,
}>({
  init_pH: null,
  target_pH: null,
  H: null,
  Al: null,
  OM: null,
  NO3: null,
  NH4: null,
  CEC: null,
});

const result = ref<number | null>(null);
const dialogVisible = ref(false);
const predictForm = ref<any>(null);
const errorMessages = reactive({
  init_pH: '',
  target_pH: '',
  H: '',
  Al: '',
  OM: '',
  NO3: '',
  NH4: '',
  CEC: '',
});

// 当前选中模型 - 根据文档修改为 33
const selectedModelId = ref<number>(33);
const selectedModelName = ref<string>("降酸预测模型");

// 使用 ref 来存储输入框元素
const inputRefs = reactive<{
  [key in keyof typeof form]: any;
}>({
  init_pH: ref<HTMLInputElement | null>(null),
  target_pH: ref<HTMLInputElement | null>(null),
  H: ref<HTMLInputElement | null>(null),
  Al: ref<HTMLInputElement | null>(null),
  OM: ref<HTMLInputElement | null>(null),
  NO3: ref<HTMLInputElement | null>(null),
  NH4: ref<HTMLInputElement | null>(null),
  CEC: ref<HTMLInputElement | null>(null),
});

// 限制输入为数字并校验范围
const handleInput = (field: keyof typeof form, event: Event, min: number, max: number) => {
  try {
    const inputElement = inputRefs[field].value;
    if (!inputElement) {
      console.error('未找到输入框元素');
      return;
    }

    // 过滤非数字和小数点字符
    const rawValue = (event.target as HTMLInputElement).value;
    const filteredValue = rawValue.replace(/[^0-9.]/g, '');
    inputElement.value = filteredValue;

    if (filteredValue === '') {
      form[field] = null;
      errorMessages[field] = '';
      return;
    }

    const numValue = parseFloat(filteredValue);
    if (isNaN(numValue) || numValue < min || numValue > max) {
      form[field] = null;
      errorMessages[field] = t('Calculation.validationRange', { min, max });
    } else {
      form[field] = numValue;
      errorMessages[field] = '';
    }
  } catch (error) {
    console.error(`处理输入时出错:`, error);
    errorMessages[field] = t('Calculation.validationError');
  }
};

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

// 获取当前保存的模型
const fetchSelectedModel = async () => {
  try {
    const resp = await api5000.post('/model-selection?model_type=acid_reduction');
    if (resp.data && resp.data.data && resp.data.data.model_id) {
      selectedModelId.value = resp.data.data.model_id;
      selectedModelName.value = resp.data.data.model_name;
    } else {
      selectedModelId.value = 33;
      selectedModelName.value = "降酸预测模型";
      console.warn("未获取到选中模型，使用默认 model_id=33");
    }
  } catch (error) {
    selectedModelId.value = 33;
    selectedModelName.value = "降酸预测模型";
    console.warn("获取当前模型失败，使用默认 model_id=33:", error);
  }
};

// 页面挂载时调用
onMounted(() => {
  fetchSelectedModel();
});

// 计算方法 - 根据文档修改参数
const onSubmit = async () => {
  const inputConfigs = [
    { field: 'init_pH' as keyof typeof form, min: 3, max: 6 },
    { field: 'target_pH' as keyof typeof form, min: 5, max: 7 },
    { field: 'H' as keyof typeof form, min: 0, max: 4 },
    { field: 'Al' as keyof typeof form, min: 0, max: 8 },
    { field: 'OM' as keyof typeof form, min: 0, max: 35 },
    { field: 'NO3' as keyof typeof form, min: 10, max: 70 },
    { field: 'NH4' as keyof typeof form, min: 0, max: 20 },
    { field: 'CEC' as keyof typeof form, min: 0, max: 15 },
  ];

  let isValid = true;
  inputConfigs.forEach((config) => {
    const { field, min, max } = config;
    const value = form[field];
    
    if (value === null) {
      isValid = false;
      errorMessages[field] = t('Calculation.validationRange', { min, max });
      return;
    }

    if (!validateInput(value, min, max)) {
      isValid = false;
      errorMessages[field] = t('Calculation.validationRange', { min, max });
    } else {
      errorMessages[field] = '';
    }
  });

  if (!isValid) {
    ElMessage.error(t('Calculation.validationError'));
    return;
  }

  console.log('开始计算...');
  // 根据文档修改参数结构
  const data = {
    model_id: selectedModelId.value,
    parameters: {
      init_pH: form.init_pH,
      target_pH: form.target_pH,
      H: form.H,
      Al: form.Al,
      OM: form.OM,
      NO3: form.NO3,
      NH4: form.NH4,
      CEC: form.CEC,
    }
  };
  // console.log('提交的数据:', data);
  try {
    const response = await api5000.post('/predict', data, {
      headers: {
        "Content-Type": "application/json",
      },
    });
    console.log('预测结果:', response.data);
    if (response.data && typeof response.data.result === 'number') {
      result.value = parseFloat((response.data.result / 10).toFixed(2));
    } else {
      console.error('未获取到有效的预测结果');
      ElMessage.error(t('Calculation.invalidResult'));
    }
    dialogVisible.value = true;
  } catch (error: unknown) {
    console.error('请求失败:', error);
    if (axios.isAxiosError(error)) {
      if (error.response) {
        ElMessage.error(`${t('Calculation.requestFailed')}${error.response.status}`);
      } else if (error.request) {
        ElMessage.error(t('Calculation.noResponse'));
      } else {
        ElMessage.error(`${t('Calculation.requestError')}${(error as Error).message}`);
      }
    } else {
      ElMessage.error(`${t('Calculation.requestError')}${(error as Error).message}`);
    }
  }
};

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

  Object.keys(form).forEach((key) => {
    const typedKey = key as keyof typeof form;
    form[typedKey] = null;
  });

  Object.keys(errorMessages).forEach((key) => {
    const typedKey = key as keyof typeof errorMessages;
    errorMessages[typedKey] = '';
  });

  nextTick(() => {
    if (predictForm.value) {
      predictForm.value.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 {
  font-size: 25px;
  text-align: center;
  color: #333;
  margin-bottom: 0px;
}

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

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

.model-info {
  text-align: center;
  margin-bottom: 20px;
  font-size: 16px;
  color: #555;
}

.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: 22px;
}

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