<template>
  <div class="table-box">
    <!-- 顶部查询栏 -->
    <div class="card table-search" style="overflow: hidden; display: flex; justify-content: space-between;">
      <el-form :inline="true" label-width="auto">
        <el-form-item label="所属基地：" prop="base">
          <el-select v-model="pageable.base" placeholder="请选择" style="width: 200px" @change="changeBase">
            <el-option label="全部" value=" " />

            <el-option v-for="item in baseList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- 台站参数 -->
        <el-form-item>
          <el-dropdown placement="bottom" max-height="200">
            <div class="lan-state" style="height: 40px;line-height: 40px;cursor: pointer;">台站总数{{ platformList.length }}
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="item in platformList" :key="item.as_code">{{ item.as_name }}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>
        <!-- 设备正常 -->
        <el-form-item>
          <el-dropdown placement="bottom" max-height="200">
            <div class="lv-state" style="height: 40px;line-height: 40px;cursor: pointer;">设备正常{{ normalPlatforms ?
              normalPlatforms.length : 0 }}</div>

            <template #dropdown>
              <el-dropdown-menu>
                <template v-if="normalPlatforms.length > 0"> <el-dropdown-item v-for="item in normalPlatforms"
                    :key="item.as_code">{{ item.as_name }}</el-dropdown-item>
                </template>
                <el-dropdown-item v-else>暂无数据</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>
        <!-- 设备故障 -->
        <el-form-item>
          <el-dropdown placement="bottom" max-height="200">
            <div class="hong-state" style="height: 40px;line-height: 40px;cursor: pointer;">设备故障{{ errorPlatforms ?
              errorPlatforms.length : 0 }}</div>

            <template #dropdown>
              <el-dropdown-menu>
                <template v-if="errorPlatforms.length > 0"> <el-dropdown-item v-for="item in errorPlatforms"
                    :key="item.as_code">{{ item.as_name }}</el-dropdown-item>
                </template>
                <el-dropdown-item v-else>暂无数据</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>

        <!-- 危险天气 -->
        <el-form-item>
          <el-dropdown placement="bottom" max-height="200">
            <div class="cheng-state" style="height: 40px;line-height: 40px;cursor: pointer;">危险天气{{
              dangetWeatherNum.length }}
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <!-- <el-dropdown-item v-for="item in dangetWeatherNum" :key="item">{{ item }}</el-dropdown-item> -->
                <template v-if="dangetWeatherNum.length > 0">
                  <el-dropdown-item v-for="item in dangetWeatherNum" :key="item">{{ item }}</el-dropdown-item>
                </template>
                <el-dropdown-item v-else>暂无数据</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>

        <!-- 基本功能 -->
        <el-form-item>
          <el-popover v-model="visible" @show="handleShowChange" @hide="handleHideChange" placement="bottom"
            :width="200" trigger="click">
            <el-checkbox-group v-model="checkList">
              <!--鹰眼  -->
              <el-form-item>
                <el-switch size="large" v-model="isEagleEyeOn" inline-prompt active-text="打开鹰眼" inactive-text="关闭鹰眼" />
              </el-form-item>
              <!-- 站名 -->
              <el-form-item>
                <el-switch size="large" v-model="isstationName" inline-prompt active-text="打开站名" inactive-text="关闭站名" />
              </el-form-item>
              <!-- 站号 -->
              <el-form-item>
                <el-switch size="large" v-model="isstationCode" inline-prompt active-text="打开站号" inactive-text="关闭站号" />
              </el-form-item>

              <!-- 街道地图 
              <el-form-item>
                <el-switch size="large" v-model="isstreet" inline-prompt active-text="街道地图" inactive-text="卫星地图"
                  @change="toggleMapLayer" />
              </el-form-item>-->

              <!--无卫星图层 -->
              <el-form-item>
                <el-switch size="large" v-model="isstreet" inline-prompt active-text="街道地图" inactive-text="关闭" />
              </el-form-item>

              <!--九宫格 
              <el-form-item>            
                 <el-switch                  
                 size="large" 
                 v-model="isNineGrid"                 
                 inline-prompt 
                 active-text="打开九宫格" 
                 inactive-text="关闭九宫格"                 
                 />
              </el-form-item> -->


            </el-checkbox-group>
            <template #reference>
              <div :class="visible ? 'hei-state-primary' : 'hei-state'">基本功能</div>
            </template>
          </el-popover>
        </el-form-item>



        <!-- 综合填图 -->
        <!-- <el-form-item>
          <el-popover v-model="visible_zonghe" @show="handleShowChange_jiben" @hide="handleHideChange_jiben" placement="bottom"
            :width="200" trigger="click">
            
            <template #reference>
              <div :class="visible_zonghe ? 'hei-state-primary' : 'hei-state'">综合填图</div>
            </template>

            -- 表格内容 -
              <el-table :data="tableData" style="width: 100%" stripe>
                <el-table-column label="序号" prop="index" width="80"></el-table-column>
                <el-table-column label="数据项" prop="dataItem"></el-table-column>
                <el-table-column label="数值" prop="value"></el-table-column>
                <el-table-column label="单位" prop="unit"></el-table-column>
              </el-table>

          </el-popover>
        </el-form-item> -->

        <!-- <el-form-item>
            <el-popover v-model="visible_zonghe" @show="handleShowChange_jiben" @hide="handleHideChange_jiben" placement="bottom" :width="400" trigger="click">
              <template #reference>
                <div :class="visible_zonghe ? 'hei-state-primary' : 'hei-state'">综合填图</div>
              </template>      
                  
                 
                      <div class="container-tag" style="overflow-y:auto; height:300px;">
                        <template v-for="item in filteredElementList" :key="item.id">
                          <div :class="item.isSelected ? 'item-tag-active' : 'item-tag'" @click="toggleSelection(item)">
                            {{ item.data_name }}
                          </div>
                        </template>
                      </div>
                                 



              
            </el-popover>
        </el-form-item>  -->





      </el-form>

      <!-- 右侧功能栏 -->
      <div class="header-button-ri">
        <el-popover class="tab-pane" :width="600" v-model="visible2" @show="handleShowChange2" @hide="handleHideChange2"
          placement="bottom-start" trigger="click">
          <el-tabs tab-position="right" class="demo-tabs">
            <!-- 气温 -->
            <el-tab-pane>
              <template #label>
                <div class="gis-c">
                  <span>气温</span>
                  <img class="gis-icon" src="../../../assets/images/temperature.svg">
                </div>
              </template>
              <div class="container-tag" style="overflow-y:auto; height:300px ">
                <template v-for="item in elementList" :key="item.id">
                  <div v-if="item.data_type === '温湿度'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                    @click="toggleSelection(item)">{{ item.data_name }}</div>
                </template>
              </div>
            </el-tab-pane>

            <!-- 气压 -->
            <el-tab-pane>
              <template #label>
                <div class="gis-c">
                  <span>气压</span>
                  <img class="gis-icon" src="../../../assets/images/pressure.svg">
                </div>
              </template>
              <div class="container-tag" style="overflow-y:auto; height:300px ">
                <template v-for="item in elementList" :key="item.id">
                  <div v-if="item.data_type === '气压'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                    @click="toggleSelection(item)">{{ item.data_name }}</div>
                </template>
              </div>
            </el-tab-pane>

            <!-- 湿度 -->
            <el-tab-pane>
              <template #label>
                <div class="gis-c">
                  <span>湿度</span>
                  <img class="gis-icon" src="../../../assets/images/humidity.svg">
                </div>
              </template>
              <div class="container-tag" style="overflow-y:auto; height:300px ">
                <template v-for="item in elementList" :key="item.id">
                  <div v-if="item.data_type === '温湿度'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                    @click="toggleSelection(item)">{{ item.data_name }}</div>
                </template>
              </div>
            </el-tab-pane>

            <!-- 风 -->
            <el-tab-pane>
              <template #label>
                <div class="gis-c">
                  <span>风</span>
                  <img class="gis-icon" src="../../../assets/images/wind.svg">
                </div>
              </template>
              <div class="container-tag" style="overflow-y: auto;height: 300px;">
                <template v-for="item in elementList" :key="item.id">
                  <div v-if="item.data_type === '风'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                    @click="toggleSelection(item)">{{ item.data_name }}</div>
                </template>
              </div>
            </el-tab-pane>

            <!-- 降雨 -->
            <el-tab-pane>
              <template #label>
                <div class="gis-c">
                  <span>降雨</span>
                  <img class="gis-icon" src="../../../assets/images/rainfall.svg">
                </div>
              </template>
              <div class="container-tag" style="overflow-y:auto; height:300px ">
                <template v-for="item in elementList" :key="item.id">
                  <div v-if="item.data_type === '降水'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                    @click="toggleSelection(item)">{{ item.data_name }}</div>
                </template>
              </div>

            </el-tab-pane>


            <!-- 云量 -->
            <el-tab-pane>
              <template #label>
                <div class="gis-c">
                  <span>云量</span>
                  <img class="gis-icon" src="../../../assets/images/cloud.svg">
                </div>
              </template>
              <div class="container-tag" style="overflow-y:auto; height:300px ">
                <template v-for="item in elementList" :key="item.id">
                  <div v-if="item.data_type === '云'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                    @click="toggleSelection(item)">{{ item.data_name }}</div>
                </template>
              </div>
            </el-tab-pane>

            <!-- 能见度 -->
            <el-tab-pane>
              <template #label>
                <div class="gis-c">
                  <span>能见度</span>
                  <img class="gis-icon" src="../../../assets/images/visibility.svg">
                </div>
              </template>
              <div class="container-tag" style="overflow-y:auto; height:300px ">
                <template v-for="item in elementList" :key="item.id">
                  <div v-if="item.data_type === '能见度'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                    @click="toggleSelection(item)">{{ item.data_name }}</div>
                </template>
              </div>
            </el-tab-pane>

            <!-- 天气现象 -->
            <el-tab-pane>
              <template #label>
                <div class="gis-c">
                  <span>天气现象</span>
                  <img class="gis-icon" src="../../../assets/images/phenomenon.svg">
                </div>
              </template>
              <div class="container-tag" style="overflow-y:auto; height:300px ">
                <template v-for="item in elementList" :key="item.id">
                  <div v-if="item.data_type === '天气现象'" :class="item.isSelected ? 'item-tag-active' : 'item-tag'"
                    @click="toggleSelection(item)">{{ item.data_name }}</div>
                </template>
              </div>
            </el-tab-pane>
          </el-tabs>
          <template #reference>
            <slot name="toolButton">
              <div style="cursor: pointer">
                <img :class="visible2 ? 'gis-icon-type2' : 'gis-icon-type1'" src="@/assets/images/classify.svg" />
              </div>
            </slot>
          </template>
        </el-popover>
      </div>
    </div>

    <!-- 地图与经纬度显示区域 -->
    <div id="map" class="map" style="width: 100%; height: 100vh;">
      <!-- 九宫格盒子 -->
      <div class="grid-container" v-if="isNineGrid">
        <div v-for="item in 9" :key="item" class="grid-item">
          <!-- -- 放置内容  -->
          {{ item }}
        </div>
      </div>
      <!-- 新增图例 -->
      <div id="map-legend"></div>
    </div>
    <!-- popover弹出框 -->
    <div id="popup" class="ol-popup"></div>

    <!-- <span style="color: ${statusColor} !important;">${autoStationStatus}</span> -->


    <!-- 右下角经纬度显示-->
    <div id="mouse-position" class="mouse-position">经纬度: </div>
    <!-- 地图底部控制栏 -->
    <div class="gis-bottom-box">
      <!-- 播放/暂停按钮 -->
      <div class="gis-bottom-item">
        <div class="button-bg" @click="togglePlay">
          <img v-if="isPlay" class="button-bg-c" style="margin-left: 3px" src="../../../assets/images/play.svg" />
          <img v-else class="button-bg-c" src="../../../assets/images/stop.svg" />
        </div>
        <div style="margin-left: 2px" class="gis-bottom-text">{{ isPlay ? '暂停' : '播放' }}</div>
      </div>

      <!-- 上一个按钮 -->
      <div class="gis-bottom-item" @click="handleBack">
        <div class="button-bg">
          <img class="button-bg-c" src="../../../assets/images/back.svg" />
        </div>
        <div style="margin-left: 2px" class="gis-bottom-text">上一个</div>
      </div>
      <!-- 设置当前日期为默认值 -->
      <div class="gis-bottom-item">
        <el-date-picker style="margin-top: 5px" v-model="value1" :disabled-date="disabledDate" type="date"
          placeholder="请选择时间" />
      </div>
      <!-- 时间滑块 -->
      <div class="gis-bottom-item">
        <el-slider @change="changeSlider" :min="1" :max="1440" :format-tooltip="formatTooltip" v-model="value2"
          style="width: 720px;margin: 0px 0px 0px 10px" />
        <img src="../../../assets/images/scale.svg" style="width: 720px; margin-top: -10px" />
      </div>
      <!-- 下一个按钮 -->
      <div class="gis-bottom-item">
        <div class="button-bg" @click="handleForward">
          <img class="button-bg-c" src="../../../assets/images/forward.svg" />
        </div>
        <div style="margin-left: 2px" class="gis-bottom-text">下一个</div>
      </div>

      <!-- 添加事件下拉框-->
      <div class="gis-bottom-item">
        <el-select v-model="timeInterval" placeholder="选择时间间隔" style="width: 150px;">
          <!-- <el-option label="1分钟间隔" :value="1"></el-option> -->
          <el-option label="2分钟间隔" :value="2"></el-option>
          <!-- <el-option label="5分钟间隔" :value="5"></el-option> -->
          <el-option label="10分钟间隔" :value="10"></el-option>
          <el-option label="30分钟间隔" :value="30"></el-option>
          <el-option label="60分钟间隔" :value="60"></el-option>
        </el-select>
      </div>

      <!-- 当前时间显示 -->
      <div class="gis-bottom-item">
        <div class="gis-bottom-hei-state">当前时间 {{ formatTooltip(value2) }}</div>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, watch, defineComponent, computed, reactive, onBeforeUnmount, onMounted, onUnmounted, onDeactivated, onActivated, } from "vue";
import logoImg from '/src/assets/images/logo.svg'
import onLine from '/src/assets/images/on_line.svg'
import weiZhi from '/src/assets/images/weiZhi.svg'
import weiLianJie from '/src/assets/images/weiLianJie.svg'
import TileLayer from 'ol/layer/Tile';
import OverviewMap from 'ol/control/OverviewMap';
import { Vector as VectorLayer } from 'ol/layer'; // 引入矢量图层
import { Vector as VectorSource } from 'ol/source';
import { Platform } from "@/api/interface";
import { getDataItemList, getAs_status, getPlatformList, getRgDataList, getStaitemList, getTacRecordList } from "@/api/modules/allData";
import { XYZ, TileWMS, ImageWMS } from 'ol/source';
import 'ol/ol.css';
import { Map, View, Feature, Overlay } from 'ol';
import { fromLonLat, transform } from 'ol/proj';
import { Point } from 'ol/geom';
import { Style, Icon, Text, Fill, Stroke, Circle } from 'ol/style';
import { getStamp, groupByType } from '@/utils/dateTime'
import { parseTime } from '@/utils/index';
import { useUserStore } from "@/stores/modules/user";
import { ResPage } from '@/api/interface';
import { State } from "driver.js";
import { Tile as TileLayerOl } from 'ol/layer';
import { Options } from 'ol/source/XYZ'; // 引入 XYZOptions 类型
import { toLonLat } from 'ol/proj.js';
import { toStringHDMS } from 'ol/coordinate.js';







// 存放所有要素的数据
const allElementList = ref([
  { id: 1, data_name: '气温', data_type: '温湿度', isSelected: false },
  { id: 2, data_name: '相对湿度', data_type: '温湿度', isSelected: false },
  { id: 3, data_name: '本站气压', data_type: '气压', isSelected: false },
  { id: 4, data_name: '分钟风速', data_type: '风速', isSelected: false },
  { id: 5, data_name: '2分钟风向', data_type: '风向', isSelected: false },
  { id: 6, data_name: '云底高度', data_type: '气象', isSelected: false },
  { id: 7, data_name: '分钟降水量(翻斗)', data_type: '降水', isSelected: false },
  { id: 8, data_name: '1分钟平均能见度', data_type: '能见度', isSelected: false },
  { id: 9, data_name: '视程障碍现象', data_type: '障碍', isSelected: false },
  { id: 10, data_name: '风速', data_type: '风速', isSelected: false },
  { id: 11, data_name: '降水量', data_type: '降水', isSelected: false },
]);

// 根据要求筛选显示的要素
const filteredElementList = computed(() => {
  return allElementList.value.filter(item =>
    [
      '气温',
      '相对湿度',
      '本站气压',
      '分钟风速',
      '2分钟风向',
      '云底高度',
      '分钟降水量(翻斗)',
      '1分钟平均能见度',
      '视程障碍现象',
    ].includes(item.data_name)
  );
});

// 模拟表格数据
// const tableData = ref([
//   { index: 1, dataItem: '温度', value: '30°C', unit: '°C' },
//   { index: 2, dataItem: '湿度', value: '60%', unit: '%' },
//   { index: 3, dataItem: '风速', value: '5 m/s', unit: 'm/s' },
//   { index: 4, dataItem: '降水量', value: '0 mm', unit: 'mm' },
// ]);


















const createPageable = () => {
  return {
    data_type: false, // 查询模式，默认非实时
    base: '',         // 基础查询分类，默认为空
    time_order: 0,    // 时间排序方式，0: 倒序，1: 正序
    as_code_list: [], // 站点代码列表
    data_items: [],   // 数据项列表
    pageNum: 1,       // 当前页码
    pageSize: 20,     // 每页记录数
    total: 0,         // 总记录数
    // beginTime: undefined, // 开始时间
    // endTime: undefined, // 结束时间

  };
};

// 使用 pageable
const pageable = ref<any>(createPageable());


const userStore = useUserStore();
const platformList = ref<any>(computed(() => userStore.stations)) // platformList可查询自动站基本信息接口
const baseList = ref<any>([])

const selectPlatForms = ref<any>([]) // 选中的站点
const getPlatforms = async () => {
  selectPlatForms.value = platformList.value

  getStations(selectPlatForms.value);
  baseList.value = groupByType(platformList.value)

  pageable.value.base = ' '
  pageable.value.as_code_list = platformList.value.map(item => item.as_code)

};

const changeBase = (e) => {
  if (e === ' ') {
    selectPlatForms.value = platformList.value
    pageable.value.as_code_list = platformList.value.map(item => item.as_code)
    getList()

  } else {
    selectPlatForms.value = platformList.value.filter(item => item.as_base == e)
    const item = baseList.value.find(item => item.value === e);
    pageable.value.as_code_list = item.children
    getList()
    // getArrive()
  }
}


const stateList = ref<any>({ normal: [], warning: [], error: [] }) // 获取设备状态
const errorPlatforms = ref<any>([])   // 获取异常站点
const normalPlatforms = ref<any>([])  // 获取正常站点
const getDeviceStatus = async () => { // 获取设备状态
  errorPlatforms.value = []
  normalPlatforms.value = []

  const { data } = await getStaitemList({
    as_code_list: pageable.value.as_code_list,
    data_items: [
      {
        data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
        data_id: 101,
        data_type: "温湿度",
        data_item: "QI_WEN",
        data_name: "气温",
        data_unit: "℃",
        data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
        data_value: "",
        data_order: 1,
        data_condition: 0
      }
    ],
    data_type: true,
    time_order: 1,
    time_space: 1,
  });
  const state = { normal: [], warning: [], error: [] }

  data?.list?.forEach(item => {
    if (item.sta_list.some(item1 => item1.state === 3)) {
      errorPlatforms.value.push(item)

    }
    if (item.sta_list.some(item1 => item1.state === 0)) {
      normalPlatforms.value.push(item)
    }
    const staList = item.sta_list;
    staList.forEach(sta => {
      if (sta.state === 0) {
        state.normal.push(sta)
      } else if (sta.state === 2) { // 注意：要求中提到了state为2的个数，但原始数据中并没有state为2的例子，这里假设需要统计它  
        state.warning.push(sta);
      } else if (sta.state === 3) {
        state.error.push(sta);
      }

    });

  });

  // 从normalPlatforms中过滤掉在errorPlatforms中存在的元素，返回一个没有在errorPlatforms.value中没有匹配as_code的元素的数组
  normalPlatforms.value = normalPlatforms.value.filter(item1 => {
    return !errorPlatforms.value.find(item2 => item2.as_code === item1.as_code);
  });

  stateList.value = state
};


const wertherColumns = ref<any>({
  tact_state_on: true,
  tact_data_on: false,
  tact_state: 0,
  // tact_state: 0,
  // tact_data: 0,
  pageNum: 1,
  pageSize: 999,

});


const weatherInfoArr = ref()
const dangetWeatherNum = ref<any>([])

const weatherInfo = async () => {  // 获取条件查询危险天气记录表getTacRecordList 
  const { data } = await getTacRecordList({ ...wertherColumns.value, as_code_list: pageable.value.as_code_list });
  dangetWeatherNum.value = [...new Set(data.list?.map(obj => obj.as_name))]
};
watch(() => pageable.value.as_code_list, (newValue, oldValue) => {
  if (newValue) {
    getDeviceStatus();
    weatherInfo()
  }
});

//搜索站号
const selectedData = ref([])
const selectedItems = (data) => {
  if (data.length > 0) {
    pageable.value.as_code_list = data
  } else {
    const allCodes = platformList.value.map(item => item.as_code);
    pageable.value.as_code_list = allCodes
  }
};


//搜索站号
const selectedItems2 = (data) => {
  if (data.length > 0) {
    pageable.value.as_code_list = data
  } else {
    const allCodes = platformList.value.map(item => item.as_code);
    pageable.value.as_code_list = allCodes
  }
};

const isStand = ref(true)
const as_code_list = ref(undefined);
const hot = ref(true);
const points = ref(true);
const singleTime = ref(undefined)
const multiTime = ref(undefined)


// 新建VectorSource（矢量信息图层） 来存放台站数据
const stationSource = new VectorSource();
const stationLayer = new VectorLayer({
  source: stationSource,
});
// 定义状态变量
const value1 = ref<Date | null>(null); // 日期变量，设置为当前日期
const value2 = ref(0);
const maxValue = ref(0); // 滑块最大值默认为当前时间
const visible = ref(false); // 基本功能
const visible2 = ref(false); // 右侧功能
const visible_zonghe = ref(false); // 右侧功能
const checkList = ref(['Value selected and disabled', 'Value A']);
const isPlay = ref(false); // 播放状态
const isEagleEyeOn = ref(true); // 鹰眼开关状态 
const isstationName = ref(false); // 站名开关状态 默认关闭  
const isstationCode = ref(true); // 站号开关状态 默认打开  

const isNineGrid = ref(false)

const content = ref('');
const popoverOverlay = ref<Overlay | null>(null);
// let overlay: Overlay;

/** 底部时间轴 */
const timeInterval = ref(2); // 默认时间间隔为2分钟
const getCurrentTimestamp = (): number => {// 返回当前时间戳
  return new Date().getTime();
};

// 设置最大时间为当前时间戳
let maxTime = getCurrentTimestamp();
const getCurrentMinutes = (): number => { // 返回一天中的分钟数（00:00开始计算）
  const now = new Date();
  return now.getHours() * 60 + now.getMinutes();
};


const timeoutId = ref(null);
// 滑动条更新方法，确保时间不超过当前时间
const changeSlider = (data): void => {


  // 如果计时器存在，则清除计时器
  if (timeoutId.value) {
    clearTimeout(timeoutId.value);
  }

  // 设置新的计时器
  timeoutId.value = setTimeout(() => {
    const currentMinutes = getCurrentMinutes();

    if (value1.value && isToday(value1.value) && value2.value > currentMinutes) {
      value2.value = currentMinutes; // 如果超过当前时间则重设为当前分钟数
    }
    getList(); // 确保选中的要素信息更新
    
  }, 500);
};

// 禁用未来日期
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now() - 8.64e6;
};
let playInterval: number | null = null; // 播放状态
// 获取当前时间在一天中的分钟数（从00:00算起）
const getCurrentMinutesOfDay = () => {
  const now = new Date();
  return now.getHours() * 60 + now.getMinutes() - 1;
};
// 切换播放状态
const togglePlay = () => {
  isPlay.value = !isPlay.value;
  if (isPlay.value) {
    // 开始播放，设置定时器
    playInterval = window.setInterval(() => {
      const currentTime = getCurrentTimestamp(); // 当前时间戳
      maxTime = getCurrentMinutesOfDay(); // 更新最大时间
      if (value2.value < currentTime) {
        value2.value += timeInterval.value;
        getList(); // 获取当前时间点的要素信息
      } else {
        getList(); // 获取当前时间点的要素信息
      }
    }, 5000); // 每10秒滑动一次
  } else {
    // 暂停播放，清除定时器
    if (playInterval !== null) {
      clearInterval(playInterval);
      playInterval = null;
    }
  }
};
// const togglePlay = () => { 
//   // isPlay.value = !isPlay.value;
//   if (isPlay.value) {
//     // 开始播放，设置定时器
//     playInterval = window.setInterval(() => {
//       const currentTime = getCurrentTimestamp(); // 当前时间戳
//       maxTime = getCurrentMinutesOfDay(); // 更新最大时间

//       // 自动更新滑块值并获取要素信息
//       if (value2.value < currentTime) {
//         value2.value += timeInterval.value; // 滑块值前进
//         getList(); // 获取当前时间点的要素信息
//       } else {
//         getList(); // 获取当前时间点的要素信息
//       }
//     }, 5000); // 每5秒滑动一次
//   } else {
//     // 暂停播放，清除定时器
//     console.log("暂停播放");
//     if (playInterval !== null) {
//       clearInterval(playInterval);
//       playInterval = null;
//     }
//   }
// };
// 监听滑块变化
const onSliderChange = (val: number) => {
  // 当滑块手动变化时，暂停播放
  if (isPlay.value) {
    togglePlay(); // 暂停播放
  }

  // 防止滑块超过最大时间，确保它不会超过当前实际时间
  if (val > maxTime) {
    value2.value = maxTime; // 设置为当前时间戳
  } else {
    value2.value = val;
  }
  getList(); // 更新数据
};
// 检查传入的日期是否为今天，精确到年、月、日、时、分、秒
const isToday = (date: Date) => {
  const now = new Date();
  // 获取今天的起始时间（即 00:00:00）
  const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  // 获取今天的结束时间（即 23:59:59.999）
  const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0, -1);
  // 判断传入的日期是否在今天的范围内
  return date >= startOfDay && date <= endOfDay;
};
// 时间格式化函数(12:30)  
const formatTooltip = (val: number) => {
  const hours = Math.floor(val / 60).toString().padStart(2, '0');
  const minutes = (val % 60).toString().padStart(2, '0');
  return `${hours}:${minutes}`; //12:30
};
const timeoutI=ref(null)
// 监听日期选择（value1）和滑块值变化（value2）
watch([value1, value2], ([selectedDate, newValue]) => {
  // 如果计时器存在，则清除计时器
  if (timeoutI.value) {
    clearTimeout(timeoutI.value);
  }

  // 设置新的计时器
  timeoutI.value = setTimeout(() => {
    const selectedMinutesValue = newValue;
  // 如果选中日期是今天，则滑块最大值为当前时间的分钟数，否则为 1440（翌日00:00）
  maxValue.value = isToday(selectedDate!) ? getCurrentMinutesOfDay() : 1440;
  // 如果当前滑块值超过最大值，则将其限制为最大值
  if (value2.value > maxValue.value) {
    value2.value = maxValue.value;
  }
  // 更新 date.value，用于显示选中的日期时间
  date.value = `${parseTime(selectedDate, '{y}-{m}-{d} ')}${formatTooltip(value2.value)}`;

  // 控制数据展示，如果日期是今天且超过当前分钟数，则不展示未来时间的数据
  if (selectedMinutesValue <= maxValue.value) {
    getList(); // 确保当前选择的时间展示对应的要素信息
  }
    
    
  }, 500);//500毫秒防抖
  
});


const date = ref<any>(parseTime(new Date(), '{y}-{m}-{d} {h}{i}'))
// 存放选中要素的数据 
const processTableData = ref<any>([]);
// 停止播放和数据请求的函数
const stopFetchingData = () => {
  if (playInterval !== null) {
    clearInterval(playInterval);
    playInterval = null;
  }
  isPlay.value = false; // 设置为暂停状态
};


const getList = async () => {
  // 当滑块值达到最大时间点 实时展示
  if (value2.value >= maxValue.value) {
    pageable.value.data_type = true; // 实时数据模式  
    pageable.value.begin_time = undefined;
    pageable.value.end_time = undefined;
  } else {
    pageable.value.data_type = false; // 历史数据模式   
  }
  try {
    // 发送 API 请求并解构返回的数据 getDataItemList获取实时数据
    let pagea = {}
    if (value2.value >= maxValue.value) {
      pagea = {
        ...pageable.value,
        begin_time: undefined,
        end_time: undefined,
        time_space: 1 // 时间间隔
      }
    } else {
      pagea = {
        ...pageable.value,
        begin_time: getStamp(date.value),
        end_time: getStamp(date.value),
        time_space: 1 // 时间间隔
      }
    }



    const response = await getDataItemList(pagea);
    const dataList = response.data?.list ?? []; // 使用空值合并操作符保证 dataList 总是为数组
    processTableData.value = dataList; // 存储数据，避免 null 值


    // 更新站点数据，减少重复调用
    getStations(selectPlatForms.value);
    return dataList; // 返回数据列表
  } catch (error) {
    return []; // 如果出错，返回空数组以确保数据类型一致
  }
}





/**站号和站名的开关监听 */
watch([isstationCode, isstationName], ([newIsStationCode, newIsStationName]) => {
  getList()
});




// 更新自动站状态
const stationsStatus = ref<any>([])
const getStations_Status = async () => {
  const { data } = await getAs_status();
  stationsStatus.value = data.list;

}

// 更换站点实时图标
const isLiShi = () => {
  if (value2.value >= maxValue.value) {
    return false
  } else {
    return true
  }
}
// 更换站点图标路径
const getIconPath = (station) => {
  const status = searchData(station.as_code);
  if (status === 0) {
    return weiZhi;
  } else if (status === 1) {
    return onLine;
  } else if (status === 2) {
    return weiLianJie;
  } else {
    return weiZhi; // 默认情况，可以根据实际需求调整
  }
};

// 台站状态筛选
const searchData = (code, suffix = "|LEVEL_MAIN") => {
  const searchKey = `${code}${suffix}`;
  const item = stationsStatus.value.find(item => item.key === searchKey);
  if (!item) {
    return 0;
  }
  return item.as_link;
};
const timeGamp = ref<any>([])




const tabPaneData = ref([
  { label: '气温', icon: '@/assets/images/temperature.svg' },
  { label: '气压', icon: '@/assets/images/pressure.svg' },
  { label: '湿度', icon: '@/assets/images/humidity.svg' },
  { label: '风', icon: '@/assets/images/wind.svg' },
  { label: '降雨', icon: '@/assets/images/rainfall.svg' },
  { label: '云量', icon: '@/assets/images/cloud.svg' },
  { label: '能见度', icon: '@/assets/images/visibility.svg' },
  { label: '天气现象', icon: '@/assets/images/phenomenon.svg' }
]);
const playIcon = ref('@/assets/images/play.svg');
const stopIcon = ref('@/assets/images/stop.svg');
const backIcon = ref('@/assets/images/back.svg');
const forwardIcon = ref('@/assets/images/forward.svg');
// 上一个时间节点
const handleBack = () => {
  if (value2.value > 0) {
    value2.value -= timeInterval.value;
  }
  getList()

};

// 下一个时间节点
const handleForward = () => {
  maxTime = getCurrentMinutesOfDay(); // 更新最大时间
  if (isToday(new Date(parseTime(value1.value, '{y}-{m}-{d} ') + formatTooltip(value2.value)))) {
    if (value2.value < maxTime) {
      value2.value += timeInterval.value;
    }
  } else {
    value2.value += timeInterval.value;
  }
  getList()
};
const handleHideChange = () => { visible.value = false; };
const handleShowChange = () => { visible.value = true; };
const handleShowChange2 = () => { visible2.value = true; };
const handleHideChange2 = () => { visible2.value = false; }; visible_zonghe.value
const handleHideChange_jiben = () => { visible_zonghe.value = false; };
const handleShowChange_jiben = () => { visible_zonghe.value = true; };


// // 图层配置数组
const layersConfig = [
  { layerName: 'basemap:boundary', minZoom: 0, maxZoom: 6, opacity: 1 },
  { layerName: 'basemap:province', minZoom: 1, maxZoom: 6 },
  { layerName: 'basemap:capital', minZoom: 6, maxZoom: 10 },
  { layerName: 'basemap:city', minZoom: 6, maxZoom: 10 },
  { layerName: 'basemap:cityName', minZoom: 6, maxZoom: 10 },
  { layerName: 'basemap:county', minZoom: 10, maxZoom: 15 },
  { layerName: 'basemap:countyName', minZoom: 10, maxZoom: 15 },
  { layerName: 'basemap:provinceName', minZoom: 1, maxZoom: 6 }
];

// 创建 WMS 图层
const createWMSLayer = ({ layerName, minZoom, maxZoom, opacity = 1 }) =>
  new TileLayer({
    source: new TileWMS({
      // url: `${import.meta.env.VITE_API_GIS_URL}/geoserver/wms`,
      url: import.meta.env.VITE_API_GIS_URL as string + '/geoserver/wms',
      params: {
        'LAYERS': layerName,
        'TILED': true,
        'FORMAT': 'image/png',
        'TRANSPARENT': true,
        'ENCODING': 'UTF-8'
      },
      serverType: 'geoserver'
    }),
    opacity,
    minZoom,
    maxZoom
  });

// 创建卫星图层
const createSatelliteLayer = () =>
  new TileLayer({
    source: new XYZ({
      // url: import.meta.env.VITE_API_GIS_URL as string + '/geoserver/wms',
      // url: 'http://192.168.196.204/v1.0/gr?x={x}&y={y}&z={z}&#39;',  //卫星地图
      url: 'http://t1.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=49ea1deec0ffd88ef13a3f69987e9a63',
      wrapX: false
    })
  });

// 全局变量
const isstreet = ref(true); // 街道地图开关状态
let streetLayer: null; // 街道图层
let satelliteLayer = createSatelliteLayer(); // 初始化卫星图层
let map: any; // 地图实例
let overlay: Overlay; // 定义为全局变量
let overviewMapControl: OverviewMap;



// 切换图层的显示与隐藏
const toggleMapLayer = () => {
  if (map) {
    // isstreet.value = !isstreet.value;
    streetLayer.setVisible(isstreet.value);     // 切换街道图层可见性
    satelliteLayer.setVisible(!isstreet.value); // 切换卫星图层可见性

    map.layers = isstreet ? ['street'] : ['satellite'];

    // 确保 stationLayer 始终在最上层
    map.getLayers().remove(stationLayer);
    map.addLayer(stationLayer);
  }
};




// 初始化地图
const initializeMap = () => {
  let view = new View({
    center: fromLonLat([104.1954, 35.8617]),
    zoom: 4
  });

  streetLayer = createWMSLayer(layersConfig[0]); // 街道图层

  map = new Map({
    target: 'map',
    layers: [
      ...layersConfig.map(createWMSLayer), // 添加所有配置图层
      satelliteLayer, // 添加卫星图层
      stationLayer,  // 初始化时添加 stationLayer     
    ],
    view: view
  });




  // 设置卫星图层默认关闭
  satelliteLayer.setVisible(false); // 卫星图层默认隐藏
  streetLayer.setVisible(true); // 街道图层默认显示

  // 定义鹰眼视图层
  const overviewMapLayer = new TileLayer({
    source: new TileWMS({
      url: import.meta.env.VITE_API_GIS_URL as string + '/geoserver/wms',
      params: {
        'LAYERS': 'basemap:province',  // 选择可见的图层为省级
        'TILED': true,
        'FORMAT': 'image/png',
        'TRANSPARENT': true,
        'ENCODING': 'UTF-8'
      },
      serverType: 'geoserver'
    })
  });

  // 初始化 OverviewMap 控件并添加至地图
  overviewMapControl = new OverviewMap({
    collapsed: !isEagleEyeOn.value,
    layers: [overviewMapLayer]
  });
  map.addControl(overviewMapControl);

  // 显示小数点经纬度
  map.on('pointermove', (evt) => {
    const [lon, lat] = transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326'); // 转换为标准经纬度
    document.getElementById('mouse-position')!.innerHTML = `经度: ${lon.toFixed(6)}°,  纬度: ${lat.toFixed(6)}°`;
  });



  // 初始化 Overlay 弹出框
  const popupContainer = document.getElementById('popup');
  overlay = new Overlay({
    element: popupContainer,
    positioning: 'center-center',
    stopEvent: false
  });
  map.addOverlay(overlay);

  // 添加点击事件监听
  map.on('singleclick', (event) => {
    const features = map!.getFeaturesAtPixel(event.pixel); // 获取点击处的要素
    if (features.length > 0) {
      const feature = features[0];

      const coordinates = feature.getGeometry().getCoordinates(); // 获取要素坐标
      // const content = feature.get('name'); // 获取自定义属性，如名称

      // 获取站名和自动站状态
      const stationName = feature.get('name') || '未知站名'; // 获取站名

      const stationCode = feature.get('code') || '未知站名'; // 获取站名    

      const matchedData = platformList.value.find(item => item.as_code === stationCode);
      if (matchedData) {
        console.log('匹配到的数据:', matchedData);
        console.log('matchedData.as_lat', matchedData.as_lat);

      } else {
        console.log('未找到匹配的数据');
      }

      // // 获取返回的经纬度
      const latitude = matchedData.as_lat || '未知纬度';
      const longitude = matchedData.as_lon || '未知经度';

      let autoStationStatus = searchData(feature.get('code')); // 根据code 获取 as_link 状态  
      let statusColor = 'black'; // 默认颜色为黑色


      // 根据状态值设置状态文本和颜色
      if (autoStationStatus == 0) {
        autoStationStatus = '未知';
        statusColor = 'gray';
      } else if (autoStationStatus == 1) {
        autoStationStatus = '在线';
        statusColor = 'green';
      } else if (autoStationStatus == 2) {
        autoStationStatus = '未连接';
        statusColor = 'red';
      }


      // 拼接内容展示
      const content =
        `
      <div style="text-align: left; font-size: 12px;">
        状态:<span style="color: ${statusColor};">${autoStationStatus}</span><br>        
        站号:${stationCode}<br>
        站名:${stationName}<br>
        经纬度:${longitude},${latitude}<br>
        
      </div>
    `;


      // 显示弹出框
      popupContainer.innerHTML = content;
      overlay.setPosition(coordinates);
    } else {
      // 点击空白处隐藏弹出框
      overlay.setPosition(undefined);
    }
  });

};

// 监听 isEagleEyeOn 变化，触发折叠状态
watch(isEagleEyeOn, (newValue) => {
  overviewMapControl.setCollapsed(!newValue);
});
// 鹰眼图层的初始化  
const initializeOverviewMap = () => {
  const overviewMapLayer = new TileLayer({
    source: new TileWMS({
      url: import.meta.env.VITE_API_GIS_URL as string + '/geoserver/wms',
      params: {
        'LAYERS': 'basemap:province',
        'TILED': true,
        'FORMAT': 'image/png',
        'TRANSPARENT': true,
        'ENCODING': 'UTF-8'
      },
      serverType: 'geoserver'
    })
  })
};




// 获取站点列表 地图台站信息标注 
const getStations = (stations) => {
  stationSource.clear(); // 清除之前的站点标记

  // 获取选中的日期和滑块值，并计算时间戳
  const selectedDate = value1.value; // 选中日期
  const minutesOfDay = value2.value; // 滑块值（分钟数）

  // 将日期和分钟数合并为完整时间戳
  const hours = Math.floor(minutesOfDay / 60);
  const minutes = minutesOfDay % 60;
  const timestamp = new Date(
    selectedDate!.getFullYear(),
    selectedDate!.getMonth(),
    selectedDate!.getDate(),
    hours,
    minutes
  );

  // 格式化时间戳为 'yyyy-MM-dd HH:mm:ss'
  const formattedTimestamp = timestamp.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    // second: '2-digit',
    hour12: false,
  });

  // 更新图例
  const selectedElements = copiedCustomizeColumns.value.map((col) => ({
    data_name: col.data_name,
    data_unit: col.data_unit || '',
  }));
  updateLegend(selectedElements, formattedTimestamp); // 传递格式化的时间戳





  // stations.forEach((station) => {
  //   if (station.as_lon && station.as_lat) {
  //     const result = processTableData.value.find(
  //       (item) => item.as_code === station.as_code
  //     );
  //     const latitude = parseFloat(station.as_lat.replace('N', ''));
  //     const longitude = parseFloat(station.as_lon.replace('E', ''));

  //     let featureTextParts: string[] = [];

  //     if (isstationCode.value && isstationName.value) {
  //       // 如果 both station code and name are available
  //       featureTextParts = [`${station.as_code}`, `${station.as_name}`];
  //     } else if (isstationCode.value) {
  //       // 如果只有 station code 可用
  //       featureTextParts = [`${station.as_code}`];
  //     } else if (isstationName.value) {
  //       // 如果只有 station name 可用
  //       featureTextParts = [`${station.as_name}`];
  //     }

  //     console.log(copiedCustomizeColumns.value,'copiedCustomizeColumns.value');

  //     // 只显示选中列的数据，不显示单位，无数据时用“/”代替
  //     const selectedElementsText = copiedCustomizeColumns.value
  //       .map((selectedElem) => {
  //         if (result && result[selectedElem.data_id] !== ' ') {
  //           const value = result[selectedElem.data_id] || '/'; // 如果值不存在则显示“/”
  //           return `${value}`; // 显示名称和数值
  //         } else {
  //           return ' /'; // 如果未找到匹配项，只返回“/”
  //         }
  //       })
  //       .filter((value) => value !== '/')
  //       .join('\n'); // 过滤掉所有“/”，使用换行符分隔每个选中要素

  //     // 组合站点基础信息和选中要素信息
  //     const featureText = `${featureTextParts.join('\n')}\n${selectedElementsText}`;

  //     // 创建站点的特征（Feature）
  //     const feature = new Feature({
  //       geometry: new Point(fromLonLat([longitude, latitude], 'EPSG:3857')),
  //       name: station.as_name,
  //       code: station.as_code,
  //       description: selectedElementsText,
  //     });

  //     // 设置站点图标和文字样式
  //     feature.setStyle(
  //       new Style({
  //         image: new Icon({
  //           src: getIconPath(station), //调用图标方法
  //           scale: 0.008,
  //         }),
  //         text: new Text({
  //           text: featureText, // 显示站号、站名和选中要素信息
  //           font: '15px Calibri,sans-serif',
  //           fill: new Fill({ color: '#000' }),
  //           stroke: new Stroke({ color: '#fff', width: 2 }),
  //           offsetY: -20,
  //           textAlign: 'center',
  //         }),
  //       })
  //     );
  //     // 将站点特征添加到站点源
  //     stationSource.addFeature(feature);
  //   }
  // });

  /* stations.forEach((station) => {
   if (station.as_lon && station.as_lat) {
     const result = processTableData.value.find(
       (item) => item.as_code === station.as_code
     );
 
     const latitude = parseFloat(station.as_lat.replace('N', ''));
     const longitude = parseFloat(station.as_lon.replace('E', ''));
 
     let featureTextParts: string[] = [];
 
     if (isstationCode.value && isstationName.value) {
       // 如果 both station code and name are available
       featureTextParts = [`${station.as_code}`, `${station.as_name}`];
     } else if (isstationCode.value) {
       // 如果只有 station code 可用
       featureTextParts = [`${station.as_code}`];
     } else if (isstationName.value) {
       // 如果只有 station name 可用
       featureTextParts = [`${station.as_name}`];
     }
 
     // 获取当前站点状态
     const status = searchData(station.as_code);
 
     // 只显示选中列的数据，不显示单位，无数据时用“/”代替
     // 当 status === 0 或 status === 2 时，不展示历史数据
     const selectedElementsText = 
       status === 1 // 只有实时状态才展示要素信息
         ? copiedCustomizeColumns.value
             .map((selectedElem) => {
               if (result && result[selectedElem.data_id] !== ' ') {
                 const value = result[selectedElem.data_id] || '/'; // 如果值不存在则显示“/”
                 return `${value}`; // 显示名称和数值
               } else {
                 return ' /'; // 如果未找到匹配项，只返回“/”
               }
             })
             .filter((value) => value !== '/')
             .join('\n') // 过滤掉所有“/”，使用换行符分隔每个选中要素
         : ''; // 非实时状态，清空历史要素信息
 
     // 组合站点基础信息和选中要素信息
     const featureText = `${featureTextParts.join('\n')}${selectedElementsText ? `\n${selectedElementsText}` : ''}`;
 
     // 创建站点的特征（Feature）
     const feature = new Feature({
       geometry: new Point(fromLonLat([longitude, latitude], 'EPSG:3857')),
       name: station.as_name,
       code: station.as_code,
       description: selectedElementsText,
     });
 
     // 设置站点图标和文字样式
     feature.setStyle(
       new Style({
         image: new Icon({
           src: getIconPath(station), // 调用图标方法
           scale: 0.008,
         }),
         text: new Text({
           text: featureText, // 显示站号、站名和选中要素信息
           font: '15px Calibri,sans-serif',
           fill: new Fill({ color: '#000' }),
           stroke: new Stroke({ color: '#fff', width: 2 }),
           offsetY: -20,
           textAlign: 'center',
         }),
       })
     );
 
     // 将站点特征添加到站点源
     stationSource.addFeature(feature);
   }
 });*/


  // 可正常展示气温要素默认展示信息
  stations.forEach((station) => {
    if (station.as_lon && station.as_lat) {
      const result = processTableData.value.find(
        (item) => item.as_code === station.as_code
      );

      const latitude = parseFloat(station.as_lat.replace('N', ''));
      const longitude = parseFloat(station.as_lon.replace('E', ''));

      let featureTextParts: string[] = [];

      if (isstationCode.value && isstationName.value) {
        // 如果 both station code and name are available
        featureTextParts = [`${station.as_code}`, `${station.as_name}`];
      } else if (isstationCode.value) {
        // 如果只有 station code 可用
        featureTextParts = [`${station.as_code}`];
      } else if (isstationName.value) {
        // 如果只有 station name 可用
        featureTextParts = [`${station.as_name}`];
      }

      // 获取当前站点状态
      const status = searchData(station.as_code);

      // 只显示选中列的数据，无数据时用“/”代替
      const selectedElementsText = copiedCustomizeColumns.value
        .map((selectedElem) => {
          // 如果 status 是 0 或 2，用 '/' 代替
          if (status === 0 || status === 2) {
            return ' /'; // 使用 '/' 表示没有实时数据
          } else {
            // 如果是实时状态 (status === 1)，显示实际数据
            if (result && result[selectedElem.data_id] !== ' ') {
              const value = result[selectedElem.data_id] || '/'; // 如果值不存在则显示“/”
              return `${value}`; // 显示名称和数值
            } else {
              return ' /'; // 如果未找到匹配项，则显示 '/'
            }
          }
        })
        .filter((value) => value !== '/')
        .join('\n'); // 过滤掉所有“/”，使用换行符分隔每个选中要素

      // 组合站点基础信息和选中要素信息
      const featureText = `${featureTextParts.join('\n')}${selectedElementsText ? `\n${selectedElementsText}` : ''}`;

      // 创建站点的特征（Feature）
      const feature = new Feature({
        geometry: new Point(fromLonLat([longitude, latitude], 'EPSG:3857')),
        name: station.as_name,
        code: station.as_code,
        description: selectedElementsText,
      });

      // 设置站点图标和文字样式
      feature.setStyle(
        new Style({
          image: new Icon({
            src: getIconPath(station), // 调用图标方法
            scale: 0.008,
          }),
          text: new Text({
            text: featureText, // 显示站号、站名和选中要素信息
            font: '15px Calibri,sans-serif',
            fill: new Fill({ color: '#000' }),
            stroke: new Stroke({ color: '#fff', width: 2 }),
            offsetY: -25,
            textAlign: 'center',
          }),
        })
      );

      // 将站点特征添加到站点源
      stationSource.addFeature(feature);
    }
  });









  /*stations.forEach((station) => {
    if (station.as_lon && station.as_lat) {
      const result = processTableData.value.find(
        (item) => item.as_code === station.as_code
      );
  
      const latitude = parseFloat(station.as_lat.replace('N', ''));
      const longitude = parseFloat(station.as_lon.replace('E', ''));
  
      // 获取当前站点状态
      const status = searchData(station.as_code);
  
      // 生成站点图标和信息
      const featureTextParts: string[] = [];
      if (isstationCode.value && isstationName.value) {
        featureTextParts.push(station.as_code, station.as_name);
      } else if (isstationCode.value) {
        featureTextParts.push(station.as_code);
      } else if (isstationName.value) {
        featureTextParts.push(station.as_name);
      }
  
      // 获取选中要素信息
      const selectedElementsText = copiedCustomizeColumns.value
        .map((selectedElem) => {
          if (status === 0 || status === 2) {
            return ' /'; // 无数据
          } else {
            if (result && result[selectedElem.data_id] !== ' ') {
              const value = result[selectedElem.data_id] || '/';
              return `${value}`;
            } else {
              return ' /';
            }
          }
        })
        .filter((value) => value !== '/')
        .join('\n');
  
      const featureText = `${featureTextParts.join('\n')}${selectedElementsText ? `\n${selectedElementsText}` : ''}`;
  
      // 创建站点的特征（Feature）
      const feature = new Feature({
        geometry: new Point(fromLonLat([longitude, latitude], 'EPSG:3857')),
        name: station.as_name,
        code: station.as_code,
        description: selectedElementsText,
      });
  
      // 设置站点图标和文字样式
      feature.setStyle(
        new Style({
          image: new Icon({
            src: getIconPath(station),
            scale: 0.008,
          }),
          text: new Text({
            text: featureText,
            font: '15px Calibri,sans-serif',
            fill: new Fill({ color: '#000' }),
            stroke: new Stroke({ color: '#fff', width: 2 }),
            offsetY: -20,
            textAlign: 'center',
          }),
        })
      );
  
      // 将站点特征添加到站点源
      stationSource.addFeature(feature);
  
      // 计算站点图标的坐标
      // const map = ...; // 获取地图实例
      const pixel = map.getPixelFromCoordinate(fromLonLat([longitude, latitude], 'EPSG:4326'));
      const x = pixel[0];
      const y = pixel[1];
  
      // 创建九宫格元素并添加到地图容器
      const nineGridBox = document.createElement('div');
      nineGridBox.classList.add('grid-container');
      nineGridBox.style.position = 'absolute';
      nineGridBox.style.left = `${x}px`;
      nineGridBox.style.top = `${y + 30}px`; // 图标下方30px（可调整）
  
      // 填充九宫格内容
      nineGridBox.innerHTML = `
        <div v-for="item in 9" :key="item" class="grid-item">
          ${item}
        </div>
      `;
  
      // 将九宫格盒子添加到地图容器
      document.querySelector('.map-container')?.appendChild(nineGridBox); // 假设 .map-container 是地图容器的类名
    }
  });*/


};



// 设置默认选中的气温要素
const defaultSelectedElement = {
  "data_order": 0,
  "data_item": "QI_WEN",
  "data_unit": "℃",
  "data_value": "",
  "data_condition": 0,
  "data_name": "气温",
  "data_id": 101,
  "data_r_table": "SHI_SHI_LIU_YAO_SU_SHU_JU",
  "data_h_table": "LI_SHI_LIU_YAO_SU_SHU_JU",
  "data_type": "温湿度",
  "isSelected": true
};

// // 默认选中列
const copiedCustomizeColumns = ref<any>([]);



// 更新图例函数
const updateLegend = (
  selectedElements: Array<{ data_name: string; data_unit: string }>,
  timestamp: string
) => {
  const legendContainer = document.getElementById('map-legend');
  if (!legendContainer) return;

  // 清空图例内容
  legendContainer.innerHTML = '';

  if (selectedElements.length === 0) {
    legendContainer.style.display = 'none'; // 隐藏图例
    return;
  }

  legendContainer.style.display = 'flex'; // 显示图例

  // 添加时间
  const timeItem = document.createElement('div');
  timeItem.className = 'legend-item time-item';
  // timeItem.textContent = `当前时间: ${timestamp}`; getCurrentTimestamp
  timeItem.textContent = `当前时间: ${timestamp}`;
  legendContainer.appendChild(timeItem);

  // 添加每个选中要素的名称和单位
  selectedElements.forEach((element) => {
    const item = document.createElement('div');
    item.className = 'legend-item';

    item.textContent = `${element.data_name} (${element.data_unit || '-'})`;
    legendContainer.appendChild(item);
  });
};





// 查询所有人工要素字典表
const elementList = ref<any>([])

// const getAllRgDataList = async () => {
//   const { data } = await getRgDataList();
//   elementList.value = data.list

//   // 如果需要根据选中的要素立即更新数据，强制触发一次数据加载
//   if (copiedCustomizeColumns.value.length > 0) {
//     // 调用 getList() 来加载与选中要素相关的数据
//     getList();
//   }

// };

const getAllRgDataList = async () => {
  const { data } = await getRgDataList();
  elementList.value = data.list;

  // 设置右侧功能框的选中状态
  elementList.value.forEach((item) => {
    // 如果该元素在 copiedCustomizeColumns 中，标记为已选中
    if (copiedCustomizeColumns.value.some(selectedItem => selectedItem.data_id === item.data_id)) {
      item.isSelected = true;
    } else {
      item.isSelected = false;
    }
  });

  // 如果需要根据选中的要素立即更新数据，强制触发一次数据加载
  if (copiedCustomizeColumns.value.length > 0) {
    getList(); // 触发数据查询
  }
};


// 要素的选中和取消  
// const toggleSelection = (item) => {
//   item.isSelected = !item.isSelected;

//   if (item.isSelected) {
//     // 添加选中的要素
//     copiedCustomizeColumns.value.push(item);
//   } else {
//     // 取消选中的要素
//     copiedCustomizeColumns.value = copiedCustomizeColumns.value.filter(column => column.data_id !== item.data_id);
//   }
//   //根据要素查询数据
//   pageable.value.data_items = copiedCustomizeColumns.value
//   getList()
// };
const toggleSelection = (item) => {
  item.isSelected = !item.isSelected;

  if (item.isSelected) {
    // 添加选中的要素
    copiedCustomizeColumns.value.push(item);
  } else {
    // 取消选中的要素
    copiedCustomizeColumns.value = copiedCustomizeColumns.value.filter(
      (column) => column.data_id !== item.data_id
    );
  }

  // 根据要素查询数据
  pageable.value.data_items = copiedCustomizeColumns.value;
  getList();
};


// 在组件挂载时初始化地图 
onMounted(() => {
  getStations_Status()

  if (!isPlay.value) {
    togglePlay(); // 如果默认播放，启动播放定时器
  }
  // 根据要素查询数据
  copiedCustomizeColumns.value = [{
    data_order: 0,
    data_item: "QI_WEN",
    data_unit: "℃",
    data_value: "",
    data_condition: 0,
    data_name: "气温",
    data_id: 101,
    data_r_table: "SHI_SHI_LIU_YAO_SU_SHU_JU",
    data_h_table: "LI_SHI_LIU_YAO_SU_SHU_JU",
    data_type: "温湿度",
    isSelected: true
  }]
  pageable.value.data_items = copiedCustomizeColumns.value;




  getList();
  value1.value = new Date();// 设置日期为当前日期
  const now = new Date();
  const currentMinutes = now.getHours() * 60 + now.getMinutes(); // 计算当前时间的分钟数
  value2.value = currentMinutes; // 将滑块的起始值设置为当前时间
  const minutesSinceMidnight = now.getHours() * 60 + now.getMinutes();
  maxValue.value = minutesSinceMidnight;// 设置滑块的最大值为当前时间的分钟数
  getAllRgDataList(); // 存放人工选择的要素列表  
  initializeMap();
  getPlatforms();

});


// 暴露功能方法
defineExpose({
  toggleMapLayer
});














let intervalId;

onActivated(() => {
  intervalId = setInterval(() => {
    getStations_Status();// 获取站点状态数据
    getList();
  }, 60 * 1000);
});

onDeactivated(() => {
  clearInterval(intervalId);
});
</script>



<style>
.ol-overviewmap {
  right: 0.5em !important;
  bottom: 1.5em !important;
  left: initial !important;
}
</style>

<style scoped>
.map {
  width: 100%;
  /* height: 100vh; */
  height: calc(100vh - 50px);
  /* 使用 calc() 来确保地图占满视口高度，减去上方的固定高度 */
  position: relative;
  overflow: hidden;
}

.box .cell {
  border: 1px solid rgba(0, 0, 0, 0.5);
  /* 单元格的边框，设置为1px以确保一致性 */
  box-sizing: border-box;
  /* 边框宽度包含在宽度和高度内 */
  display: grid;
  justify-content: center;
  align-items: center;
}


.slider-scale {
  width: 720px;
  margin-top: -10px;
}

.gis-bottom-box {
  display: flex;
  align-items: center;
}

/* 经纬度所在位置 */
.mouse-position {
  position: absolute;
  bottom: 0px;
  right: 1px;
  background-color: rgba(255, 255, 255, 0.7);
  padding: 3px;
  border: 1px solid #ccc;
  font-size: 14px;
  z-index: 1000;
}

/**时间轴样式 */
.gis-bottom-hei-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 4px 0px 0px 4px;
  /*上、右、下、左内边距。增加右侧间距*/
  background-color: #fffdfd;
  /* 背景颜色 */
  border-radius: 4px;
  display: inline-block;
  /* 让容器适应内容大小 */
  font-size: 14px;
  /* 调整字体大小，确保时间显示清晰 */
  white-space: nowrap;
  /* 防止换行 */
}


/* .grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  grid-gap: 0px;
  width: 10px; 
  height: 10px;  
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;  
  z-index: 1;
  
}

.nine-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 5px;
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.grid-item {
  width: 33.33%;  
  aspect-ratio: 1;  
  padding: 22px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #000;
} */


/* 状态圆圈初始化为边框为黑色 */
.status-circle {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 2px solid black;
  /* 黑色边框 */
  display: inline-block;
  position: relative;
}





#map-legend {
  position: absolute;
  top: 0px;
  left: 50px;
  background: rgba(77, 162, 255, 0.4);
  padding: 8px 12px;
  border-radius: 7px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  font-size: 14px;
  font-family: Arial, sans-serif;
  z-index: 1000;
  /* 确保图例在地图之上 */
  pointer-events: none;
  /* 避免影响地图交互 */
  max-width: 950px;
  /* 控制图例的最大宽度 */
  display: none;
  /* 默认隐藏 */
  display: flex;
  flex-wrap: wrap;
  /* 支持换行 */
  gap: 10px;
  /* 控制每个要素之间的间距 */
  align-items: center;
  /* 垂直居中对齐 */
}

#map-legend .legend-item {
  white-space: nowrap;
  /* 确保单个内容不换行 */
  background: rgba(0, 0, 0, 0.05);
  border-radius: 3px;
  padding: 2px 8px;
}



.ol-popup {
  background-color: rgba(255, 255, 255, 0.5);
  /* 背景设置透明 */
  border: 1px solid rgba(204, 204, 204, 1);
  /* 边框颜色 */
  color: black;
  /* 保持文字完全不透明 */
  padding: 10px;
  border-radius: 10px;
  /**设置圆角为10 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  position: absolute;
  white-space: nowrap;
  font-size: 14px;
  pointer-events: none;
  transform: translateX(5px) translateY(5px);
  /* 向右偏移 20px，上下偏移 */
  text-align: center;
}










.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 5px;
  width: 100px;
  height: 100px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 5px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}

.grid-item {
  background-color: #f0f0f0;
  text-align: center;
  line-height: 30px;
  border: 1px solid #ddd;
}
</style>
