<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增数据' : '修改数据'" width="900px" :close-on-click-modal="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" label-width="140px" style="padding-right: 20px">
      <el-row :gutter="24">
        <el-divider content-position="left">基本信息</el-divider>
        <el-col :span="12">
          <el-form-item label="站点ID" prop="stationId">
            <el-select v-if="!manualInput" v-model="dataForm.stationId" filterable placeholder="从列表选择或输入" style="width: 100%" clearable>
              <el-option v-for="s in stationOptions" :key="s.stationCode" :label="`${s.stationCode} ${s.stationName || ''}`" :value="s.stationCode" />
              <template #empty>
                <div style="padding: 8px; text-align: center">
                  <el-button size="small" type="primary" link @click="manualInput = true">未找到？点击手动输入</el-button>
                </div>
              </template>
            </el-select>
            <el-input v-else v-model="dataForm.stationId" placeholder="手动输入区站号">
              <template #suffix>
                <el-button size="small" link @click="manualInput = false">列表选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="观测日期" prop="observeDate">
            <el-date-picker v-model="dataForm.observeDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD 00:00:00" style="width: 100%"></el-date-picker>
          </el-form-item>
        </el-col>

        <el-divider content-position="left">温湿度与气压</el-divider>

        <el-col :span="12">
          <el-form-item label="相对湿度" prop="relativeHumidity" label-width="80px">
            <el-input-number v-model="dataForm.relativeHumidity" :precision="1" :step="0.1" controls-position="right" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="气压" prop="atmospheres" label-width="80px">
            <el-input-number v-model="dataForm.atmospheres" :precision="1" :step="0.1" controls-position="right" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="平均气温" prop="avgTemp" label-width="80px">
            <el-input-number v-model="dataForm.avgTemp" :precision="1" :step="0.1" controls-position="right" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高气温" prop="maxTemp" label-width="80px">
            <el-input-number v-model="dataForm.maxTemp" :precision="1" :step="0.1" controls-position="right" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最低气温" prop="minTemp" label-width="80px">
            <el-input-number v-model="dataForm.minTemp" :precision="1" :step="0.1" controls-position="right" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高气温出现时间" prop="maxTempTime" label-width="125px">
            <el-input v-model="dataForm.maxTempTime" placeholder="HHmm"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最低气温出现时间" prop="minTempTime" label-width="125px">
            <el-input v-model="dataForm.minTempTime" placeholder="HHmm"></el-input>
          </el-form-item>
        </el-col>

        <el-divider content-position="left">降水与风力</el-divider>

        <el-col :span="12">
          <el-form-item label="20-20时降水量" prop="rain2020">
            <el-input-number v-model="dataForm.rain2020" :precision="1" :min="0" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="08-08时降水量" prop="rain0808">
            <el-input-number v-model="dataForm.rain0808" :precision="1" :min="0" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="日平均风速" prop="dayAvgWindSpeed">
            <el-input-number v-model="dataForm.dayAvgWindSpeed" :precision="1" :min="0" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="日平均风向" prop="dayAvgWindDirection">
            <el-input-number v-model="dataForm.dayAvgWindDirection" :precision="1" :min="0" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="最大风速" prop="maxWindSpeed">
            <el-input-number v-model="dataForm.maxWindSpeed" :precision="1" :min="0" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大风速风向" prop="maxWindDirection">
            <el-input-number v-model="dataForm.maxWindDirection" :min="0" :max="360" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="极大风速" prop="extremeWindSpeed">
            <el-input-number v-model="dataForm.extremeWindSpeed" :precision="1" :min="0" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="极大风速风向" prop="extremeWindDirection">
            <el-input-number v-model="dataForm.extremeWindDirection" :precision="1" :min="0" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="极大风速出现时间" prop="extremeWindTime" label-width="125px">
            <el-input v-model="dataForm.extremeWindTime" placeholder="HHmm"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大风速出现时间" prop="maxWindTime" label-width="125px">
            <el-input v-model="dataForm.maxWindTime" placeholder="HHmm"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";

const emit = defineEmits(["refreshDataList"]);
const visible = ref(false);
const dataFormRef = ref();
const stationOptions = ref<any[]>([]);
const manualInput = ref(false);

const dataForm = reactive({
  id: "",
  stationId: "",
  observeDate: "",
  avgTemp: 0,
  maxTemp: 0,
  maxTempTime: "",
  minTemp: 0,
  minTempTime: "",
  rain2020: 0,
  rain0808: 0,
  relativeHumidity: 0,
  atmospheres: 0,
  dayAvgWindSpeed: 0,
  dayAvgWindDirection: 0,
  maxWindSpeed: 0,
  maxWindDirection: 0,
  maxWindTime: "",
  extremeWindSpeed: 0,
  extremeWindDirection: 0,
  extremeWindTime: "",
  createDate: ""
});

// 校验规则优化
const rules = ref({
  stationId: [{ required: true, message: "站点不能为空", trigger: "blur" }],
  observeDate: [{ required: true, message: "观测日期不能为空", trigger: "change" }],
  // 时刻格式简单校验 (HHmm)
  maxTempTime: [{ pattern: /^([01]\d|2[0-3])[0-5]\d$/, message: "格式应为HHmm(如0715)", trigger: "blur" }],
  minTempTime: [{ pattern: /^([01]\d|2[0-3])[0-5]\d$/, message: "格式应为HHmm(如1430)", trigger: "blur" }]
});

function getStationList() {
  return baseService.get("/station/weatherstation/list").then((res) => {
    stationOptions.value = res.data || [];
  });
}

onMounted(() => {
  getStationList();
});

const init = (id?: number) => {
  visible.value = true;
  manualInput.value = false;
  dataForm.id = "";
  Object.assign(dataForm, {
    avgTemp: 0,
    maxTemp: 0,
    minTemp: 0,
    rain2020: 0,
    rain0808: 0,
    maxWindSpeed: 0,
    maxWindDirection: 0,
    extremeWindSpeed: 0
  });

  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    getInfo(id);
  }
};

const getInfo = (id: number) => {
  baseService.get("/dailyweather/weatherdailydata/" + id).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) return false;

    const action = !dataForm.id ? baseService.post : baseService.put;
    action("/dailyweather/weatherdailydata", dataForm).then((res) => {
      ElMessage.success({
        message: "提交成功",
        duration: 800,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({ init });
</script>
