<template>
  <div class="mod-station__weatherstation">
    <el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()">
      <el-form-item>
        <el-input v-model="state.dataForm.stationName" placeholder="区站名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="state.dataForm.stationCode" placeholder="区站编号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="state.getDataList()">查询</el-button>
      </el-form-item>

      <el-form-item>
        <el-button v-if="state.hasPermission('station:weatherstation:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button v-if="state.hasPermission('station:weatherstation:delete')" type="danger" @click="state.deleteHandle()">删除</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="state.dataListLoading" :data="state.dataList" border @selection-change="state.dataListSelectionChangeHandle" style="width: 100%">
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="id" label="编号" header-align="center" align="center"></el-table-column>
      <el-table-column prop="stationCode" label="区站号" header-align="center" align="center"></el-table-column>
      <el-table-column prop="stationName" label="站点" header-align="center" align="center"></el-table-column>
      <el-table-column label="归属部门" header-align="center" align="center">
        <template #default="{ row }">{{ deptMap.get(Number(row.deptId)) || "" }}</template>
      </el-table-column>
      <el-table-column prop="stationLevel" label="测站级别" header-align="center" align="center">
        <template v-slot="row">
          {{ state.getDictLabel("station_level", row.row.stationLevel) }}
        </template>
      </el-table-column>
      <el-table-column prop="latitude" label="纬度" header-align="center" align="center"></el-table-column>
      <el-table-column prop="longitude" label="经度" header-align="center" align="center"></el-table-column>
      <el-table-column prop="elevation" label="测站高度(米)" header-align="center" align="center"></el-table-column>
      <!-- 使用 map 转换 id -> 中文 -->
      <el-table-column label="省名" header-align="center" align="center">
        <template #default="{ row }">{{ regionMap.get(Number(row.provinceName))?.name || "" }}</template>
      </el-table-column>
      <el-table-column label="地市名" header-align="center" align="center">
        <template #default="{ row }">{{ regionMap.get(Number(row.cityName))?.name || "" }}</template>
      </el-table-column>
      <el-table-column label="区县名" header-align="center" align="center">
        <template #default="{ row }">{{ regionMap.get(Number(row.countyName))?.name || "" }}</template>
      </el-table-column>
      <el-table-column prop="townName" label="乡镇名" header-align="center" align="center"></el-table-column>
      <el-table-column prop="createDate" label="创建时间" header-align="center" align="center"></el-table-column>

      <el-table-column label="操作" fixed="right" header-align="center" align="center" width="150">
        <template v-slot="scope">
          <el-button v-if="state.hasPermission('station:weatherstation:update')" type="primary" link @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button v-if="state.hasPermission('station:weatherstation:delete')" type="primary" link @click="state.deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination :current-page="state.page" :page-sizes="[10, 20, 50, 100]" :page-size="state.limit" :total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="state.pageSizeChangeHandle" @current-change="state.pageCurrentChangeHandle"> </el-pagination>

    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update ref="addOrUpdateRef" :regions-data="regionsData" :region-map="regionMap" @refreshDataList="state.getDataList"> </add-or-update>
  </div>
</template>

<script lang="ts" setup>
import useView from "@/hooks/useView";
import { reactive, ref, toRefs, onMounted } from "vue";
import AddOrUpdate from "./weatherstation-add-or-update.vue";
import baseService from "@/service/baseService";

// 表格 state
const view = reactive({
  deleteIsBatch: true,
  getDataListURL: "/station/weatherstation/page",
  getDataListIsPage: true,
  exportURL: "/station/weatherstation/export",
  deleteURL: "/station/weatherstation",
  dataForm: {
    id: "",
    stationName: "",
    stationCode: ""
  }
});
const state = reactive({
  ...useView(view),
  ...toRefs(view)
});

// 弹窗 ref
const addOrUpdateRef = ref();
const addOrUpdateHandle = (id?: number) => {
  addOrUpdateRef.value.init(id);
};
// const batchInsert = ref();
// const batchInsert() = >{
//
// }

// ---------------- CSV 数据加载 ----------------
const regionsData = ref<any[]>([]);
const regionMap = reactive(new Map<number, any>());

// ---------------- 部门数据加载 ----------------
const deptMap = reactive(new Map<number, string>());
async function loadDepts() {
  try {
    const res = await baseService.get("/sys/dept/list");
    const flat = (list: any[]) => {
      list.forEach((d) => {
        deptMap.set(Number(d.id), d.name);
        if (d.children) flat(d.children);
      });
    };
    flat(res.data || []);
  } catch {
    // ignore
  }
}

onMounted(async () => {
  loadDepts();
  const res = await fetch("/region.csv");
  const text = await res.text();
  const parseCSV = (csvText: string) => {
    const lines = csvText.split("\n").filter((l) => l.trim());
    const headers = lines[0].split(",");
    return lines.slice(1).map((line) => {
      const cols = line.split(",");
      const obj: any = {};
      headers.forEach((h, i) => (obj[h.trim()] = cols[i].trim()));
      return obj;
    });
  };
  const data = parseCSV(text);
  data.forEach((r) => {
    const id = Number(r.id);
    const parentId = Number(r.parentId);
    const level = Number(r.level);
    const name = r.name;
    regionMap.set(id, { id, parentId, level, name });
    regionsData.value.push({ id, parentId, level, name });
  });
});
</script>
