<template>
  <div class="mod-dailyweather__weatherdailydata">
    <el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()">
      <el-form-item>
        <el-select v-model="realDataForm.stationId" multiple filterable remote reserve-keyword clearable placeholder="请输入区站名称" :remote-method="remoteSearchStation" :loading="loading" style="width: 300px">
          <el-option v-for="item in stationOptions" :key="item.stationCode" :label="`${item.stationName}`" :value="item.stationCode" />
        </el-select>
      </el-form-item>

<!--      <el-form-item>-->
<!--        <el-date-picker v-model="realDataForm.observeDate" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" :default-time="[new Date(2000, 1, 1), new Date(2000, 1, 1)]" style="width: 360px" />-->
<!--      </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('dailyweather:weatherdailydata:save')" type="primary" icon="Plus" @click="addOrUpdateHandle()">新增</el-button>
        <el-button v-if="state.hasPermission('dailyweather:weatherdailydata:delete')" type="danger" icon="Delete" @click="state.deleteHandle()">批量删除</el-button>
        <el-button type="success" icon="Upload" @click="importHandle()">批量导入</el-button>
      </el-form-item>

      <el-form-item style="float: right; margin-right: 0">
        <el-popover placement="bottom-end" :width="300" trigger="click">
          <template #reference>
            <el-button icon="Grid">展示列设置</el-button>
          </template>
          <div class="column-setting-container">
            <div v-for="group in columnGroups" :key="group.title" class="column-group">
              <div class="group-title">{{ group.title }}</div>
              <el-checkbox-group v-model="selectedColumns">
                <el-checkbox v-for="col in group.columns" :key="col.prop" :label="col.prop" style="width: 120px">
                  {{ col.label }}
                </el-checkbox>
              </el-checkbox-group>
              <el-divider style="margin: 8px 0" />
            </div>
            <div style="text-align: right">
              <el-button size="small" type="primary" link @click="resetColumns">恢复默认</el-button>
            </div>
          </div>
        </el-popover>
      </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" fixed="left"></el-table-column>

      <template v-for="group in columnGroups">
        <template v-for="item in group.columns">
          <el-table-column v-if="selectedColumns.includes(item.prop)" :key="item.prop" :prop="item.prop" :label="item.label" header-align="center" align="center" min-width="120" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="item.prop === 'observeDate'">
                {{ formatObserveDate(scope.row.observeDate) }}
              </span>

              <span v-else-if="item.prop.endsWith('Time') && item.prop !== 'createTime'">
                <el-tag v-if="isValidTime(scope.row[item.prop])" size="small" effect="plain" type="info">
                  {{ formatWeatherTime(scope.row[item.prop]) }}
                </el-tag>
                <span v-else>--</span>
              </span>

              <span v-else-if="item.prop === 'dayAvgWindDirection' || item.prop === 'maxWindDirection'">
                {{ windDirectionLabelLocal(scope.row[item.prop]) }}
              </span>
              <span v-else>{{ scope.row[item.prop] ?? "--" }}</span>
            </template>
          </el-table-column>
        </template>
      </template>

      <el-table-column label="操作" fixed="right" header-align="center" align="center" width="150">
        <template v-slot="scope">
          <el-button v-if="state.hasPermission('dailyweather:weatherdailydata:update')" type="primary" link @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button v-if="state.hasPermission('dailyweather:weatherdailydata: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" />

    <add-or-update ref="addOrUpdateRef" @refreshDataList="state.getDataList" />
    <import-excel ref="importExcelRef" @refreshDataList="state.getDataList" />
  </div>
</template>

<script lang="ts" setup>
import useView from "@/hooks/useView";
import { reactive, ref, toRefs, watch, onMounted, computed } from "vue";
import AddOrUpdate from "./weatherdailydata-add-or-update.vue";
import ImportExcel from "./weatherdailydata-import.vue";
import baseService from "@/service/baseService";
import { useAppStore } from "@/store";
import { windDirectionCode, windDirectionLabel } from "@/utils/windDirection";

const _store = useAppStore();
function windDirectionLabelLocal(deg: any) {
  return windDirectionLabel(deg as number | null | string, _store.state.dicts);
}

const columnGroups = [
  {
    title: "基础信息",
    columns: [
      { prop: "stationId", label: "区站号", default: true },
      { prop: "stationName", label: "站名", default: true },
      { prop: "observeDate", label: "观测日期", default: true },
      { prop: "createDate", label: "创建时间", default: false },
      { prop: "id", label: "系统编号", default: false }
    ]
  },
  {
    title: "温湿度气压数据",
    columns: [
      { prop: "avgTemp", label: "平均气温", default: true },
      { prop: "maxTemp", label: "最高气温", default: true },
      { prop: "minTemp", label: "最低气温", default: true },
      { prop: "maxTempTime", label: "最高气温时间", default: false },
      { prop: "minTempTime", label: "最低气温时间", default: false },
      { prop: "relativeHumidity", label: "相对湿度", default: true },
      { prop: "atmospheres", label: "气压", default: true }
    ]
  },
  {
    title: "降水/风力数据",
    columns: [
      { prop: "rain2020", label: "20-20降水", default: false },
      { prop: "rain0808", label: "08-08降水", default: false },
      { prop: "dayAvgWindSpeed", label: "日平均风速", default: true },
      { prop: "dayAvgWindDirection", label: "日平均风向", default: true },
      { prop: "maxWindSpeed", label: "最大风速", default: false },
      { prop: "maxWindDirection", label: "最大风向", default: false },
      { prop: "maxWindTime", label: "最大风时间", default: false },
      { prop: "extremeWindSpeed", label: "极大风速", default: false },
      { prop: "extremeWindTime", label: "极大风时间", default: false }
    ]
  }
];

// 智能日期截取
const formatObserveDate = (dateStr: any) => {
  if (!dateStr) return "--";
  const str = String(dateStr);
  const separator = str.includes("T") ? "T" : " ";
  return str.split(separator)[0];
};

// 校验有效时间数字
const isValidTime = (val: any) => {
  return val !== null && val !== undefined && val !== "" && !isNaN(Number(val));
};

// 时刻格式化：712 -> 07:12
const formatWeatherTime = (time: any) => {
  let timeStr = String(time);
  if (timeStr.length === 3) timeStr = "0" + timeStr;
  if (timeStr.length === 4) {
    return `${timeStr.substring(0, 2)}:${timeStr.substring(2, 4)}`;
  }
  return timeStr;
};
interface WeatherStation {
  stationName: string;
  stationCode: string;
}
const loading = ref(false);
const stationOptions = ref<WeatherStation[]>([]);
/** 远程搜索防抖定时器 */
let searchTimer: ReturnType<typeof setTimeout> | null = null;

/**
 * 远程搜索区站（300ms 防抖）
 */
const remoteSearchStation = (keyword: string) => {
  if (searchTimer) clearTimeout(searchTimer);
  searchTimer = setTimeout(async () => {
    loading.value = true;
    try {
      const res = await baseService.get("/station/weatherstation/list");
      if (res.code === 0) {
        stationOptions.value = res.data.filter(
          (item: { stationName: string | string[]; stationCode: string | string[] }) =>
            !keyword || item.stationName.includes(keyword) || item.stationCode.includes(keyword)
        );
      }
    } finally {
      loading.value = false;
    }
  }, 300);
};

// 1. 定义真实的表单数据（保持数组，供 <el-select multiple> 正常绑定）
const realDataForm = reactive({
  stationId: "",
  // observeDate: Date,
  // startTime: "",
  // endTime:""
});

// 2. 使用 computed 动态派生出“用于请求的 dataForm”
// 只要 realDataForm 发生变化，这个 computed 就会自动重新计算
const computedDataForm = computed(() => {
  const params = { ...realDataForm };

  // 核心转换逻辑：如果 stationId 是数组，就 join 成字符串
  if (Array.isArray(params.stationId)) {
    params.stationId = params.stationId.join(",");
  }
  // 处理时间区间：将数组拆分为两个独立字段
  if (Array.isArray(params.observeDate) && params.observeDate.length === 2) {
    params.startTime = params.observeDate[0];
    params.endTime = params.observeDate[1];
  } else {
    params.startTime = "";
    params.endTime = "";
  }

  return params;
});

const view = reactive({
  deleteIsBatch: true,
  getDataListURL: "/dailyweather/weatherdailydata/page",
  getDataListIsPage: true,
  exportURL: "/dailyweather/weatherdailydata/export",
  deleteURL: "/dailyweather/weatherdailydata",
  dataForm: computedDataForm
});
const state = reactive({ ...useView(view), ...toRefs(view) });

const getDefaultColumns = () => {
  const defaultCols: string[] = [];
  columnGroups.forEach((g) => {
    g.columns.forEach((c) => {
      if (c.default) defaultCols.push(c.prop);
    });
  });
  return defaultCols;
};

const selectedColumns = ref<string[]>(getDefaultColumns());

watch(
  selectedColumns,
  (newVal) => {
    localStorage.setItem("weather_column_pref", JSON.stringify(newVal));
  },
  { deep: true }
);

onMounted(() => {
  const cache = localStorage.getItem("weather_column_pref");
  if (cache) {
    selectedColumns.value = JSON.parse(cache);
  }
});

const resetColumns = () => {
  selectedColumns.value = getDefaultColumns();
};

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

const importExcelRef = ref();
const importHandle = () => {
  importExcelRef.value.init();
};
</script>

<style scoped>
.column-setting-container {
  padding: 5px;
}
.group-title {
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 8px;
  color: #409eff;
}
.column-group {
  margin-bottom: 10px;
}
:deep(.el-checkbox) {
  margin-right: 15px;
  margin-bottom: 5px;
}
</style>
