<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.id ? '新增气象站' : '修改气象站'"
    width="720px"
    :close-on-click-modal="false"
  >
    <el-form ref="dataFormRef" :model="dataForm" :rules="rules" label-width="110px">
      <!-- ... 前面经纬度等字段保持不变 ... -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="气象站号" prop="stationCode">
            <el-input v-model="dataForm.stationCode" placeholder="例如 57972"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="站点名称" prop="stationName">
            <el-input v-model="dataForm.stationName"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="测站级别" prop="stationLevel">
            <el-select v-model="dataForm.stationLevel" placeholder="选择级别">
              <el-option v-for="item in stationLevelOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="海拔高度(m)" prop="elevation">
            <el-input-number
              v-model="dataForm.elevation"
              :precision="1"
              :step="1"
              style="width:100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="latitude">
            <el-input-number
              v-model="dataForm.latitude"
              :precision="6"
              :step="0.0001"
              :min="-90"
              :max="90"
              style="width:100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经度" prop="longitude">
            <el-input-number
              v-model="dataForm.longitude"
              :precision="6"
              :step="0.0001"
              :min="-180"
              :max="180"
              style="width:100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider>行政区域</el-divider>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="省份" prop="provinceName">
            <el-select v-model="dataForm.provinceName" placeholder="请选择省" clearable @change="onProvinceChange">
              <el-option
                v-for="item in provinceOptions"
                :key="item.id"
                :label="item.name"
                :value="String(item.id)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="地市" prop="cityName">
            <el-select v-model="dataForm.cityName" placeholder="请选择市" clearable @change="onCityChange">
              <el-option
                v-for="item in cityOptions"
                :key="item.id"
                :label="item.name"
                :value="String(item.id)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="区县" prop="countyName">
            <el-select v-model="dataForm.countyName" placeholder="请选择区" clearable>
              <el-option
                v-for="item in countyOptions"
                :key="item.id"
                :label="item.name"
                :value="String(item.id)"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="乡镇名称">
            <el-input v-model="dataForm.townName" placeholder="具体乡镇"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider>管理部门</el-divider>
      <el-row>
        <el-col :span="24">
          <el-form-item label="选择部门" prop="deptId">
            <el-tree :data="deptList" :props="{ label: 'name', children: 'children' }" node-key="id" ref="deptTreeRef" accordion highlight-current @node-click="onDeptClick" style="max-height: 240px; overflow-y: auto; width: 100%; border: 1px solid var(--border); border-radius: 6px; padding: 8px"></el-tree>
          </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, computed, nextTick } from "vue";
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
import { useAppStore } from "@/store";
import { getDictDataList } from "@/utils/utils";

const store = useAppStore();

// 接收父页面传来的地区数据
const props = defineProps<{
  parentMap: Map<number, any[]>
  deptData: any[]
}>();

const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const deptTreeRef = ref();
const deptList = ref<any[]>([]);

const dataForm = reactive({
  id: "",
  stationCode: "",
  stationName: "",
  stationLevel: "",
  latitude: null,
  longitude: null,
  elevation: null,
  provinceName: "", // 存放省级 ID 字符串
  cityName: "",     // 存放市级 ID 字符串
  countyName: "",    // 存放区级 ID 字符串
  townName: "",
  deptId: ""
});

const rules = {
  stationCode: [{ required: true, message: "请输入气象站号", trigger: "blur" }],
  stationName: [{ required: true, message: "请输入站点名称", trigger: "blur" }],
  stationLevel: [{ required: true, message: "请选择测站级别", trigger: "change" }]
};

// ----------------- 字典数据 ----------------

const stationLevelOptions = computed(() =>
  getDictDataList(store.state.dicts, "station_level").map((item: any) => ({
    label: `${item.dictLabel}（${item.dictValue}）`,
    value: Number(item.dictValue)
  }))
);

// ----------------- 下拉框联动逻辑（O(1) 查找） -----------------

// 省级：parentId = 1
const provinceOptions = computed(() => props.parentMap.get(1) || []);

// 市、区列表：动态变化
const cityOptions = ref<any[]>([]);
const countyOptions = ref<any[]>([]);

// 切换省：清空市/区，加载新市列表
const onProvinceChange = (val: string) => {
  dataForm.cityName = "";
  dataForm.countyName = "";
  cityOptions.value = [];
  countyOptions.value = [];
  if (val) {
    cityOptions.value = props.parentMap.get(Number(val)) || [];
  }
};

// 切换市：清空区，加载新区列表
const onCityChange = (val: string) => {
  dataForm.countyName = "";
  countyOptions.value = [];
  if (val) {
    countyOptions.value = props.parentMap.get(Number(val)) || [];
  }
};

function onDeptClick(data: any) {
  dataForm.deptId = data.id;
}

// ----------------- 弹窗操作 -----------------

const init = (id?: number) => {
  visible.value = true;

  // 重置选项
  cityOptions.value = [];
  countyOptions.value = [];
  // 复用父页面的部门数据，无需重复请求
  deptList.value = props.deptData || [];

  nextTick(() => {
    if (dataFormRef.value) dataFormRef.value.resetFields();
    Object.assign(dataForm, {
      id: "",
      provinceName: "",
      cityName: "",
      countyName: "",
      townName: "",
      deptId: ""
    });
    if (id) {
      getInfo(id);
    }
  });
};

// 编辑回显
const getInfo = async (id: number) => {
  const res = await baseService.get(`/station/weatherstation/${id}`);
  const data = res.data;

  // 1. 基础数据赋值
  Object.assign(dataForm, data);

  // 2. 手动加载省市区联动列表数据源
  if (data.provinceName) {
    cityOptions.value = props.parentMap.get(Number(data.provinceName)) || [];
  }
  if (data.cityName) {
    countyOptions.value = props.parentMap.get(Number(data.cityName)) || [];
  }

  // 3. 回显选择的管理部门
  if (data.deptId) {
    nextTick(() => {
      deptTreeRef.value?.setCurrentKey(data.deptId);
    });
  }
};

// 提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate(valid => {
    if (!valid) return;

    const request = !dataForm.id
      ? baseService.post("/station/weatherstation", dataForm)
      : baseService.put("/station/weatherstation", dataForm);

    request.then(() => {
      ElMessage.success("操作成功");
      visible.value = false;
      emit("refreshDataList");
    });
  });
};

defineExpose({ init });
</script>

