<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="station">
          <el-select v-model="code_list" multiple collapse-tags filterable placeholder="请搜索自动站" remote reserve-keyword clearable @change="changeCodeList"  style="width: 200px">
                <el-option
                  v-for="item in platformList"
                  :key="item.as_code"
                  :label="item.as_code +' '+item.as_name"
                  :value="item.as_code"
                />
                <template #prefix>
                  <el-icon class="el-input__icon"><search /></el-icon>
                </template>
          </el-select>
        </el-form-item>

        <el-form-item label="所属基地：" prop="base">
          <el-select v-model="searchParam.base" placeholder="请选择" style="width: 200px">
            <el-option v-for="item in baseOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item><div class="lan-state">台站总数5</div></el-form-item>
        <el-form-item><div class="lv-state">设备正常3</div></el-form-item>
        <el-form-item><div class="hong-state">设备故障2</div></el-form-item>
        <el-form-item><div class="cheng-state">危险天气1{{ info.one }}</div></el-form-item> <!-- 操作1     -->

        <!-- 基本信息 -->
        <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="showNineGrid"
                    inline-prompt
                    active-text="开九宫格"
                    inactive-text="关九宫格"
                />
              </el-form-item>
              <!-- 框选 -->
              <el-form-item>
                <el-switch
                  size="large"
                  v-model="isboxDrawn"
                    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="关闭"
                />
              </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>
      <!-- 右侧功能栏 -->
      <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 v-if="showNineGrid" :style="nineGridStyle" class="box">
        <div class="cell" v-for="(value, index) in dataValues" :key="index">
          {{ value }}
        </div>
      </div>

    </div>
    <!-- 右下角经纬度显示 -->
    <div id="mouse-position" class="mouse-position">经纬度: </div>

    <!-- 地图底部控制栏 -->
    <div class="gis-bottom-box">
      <div class="gis-bottom-item">
        <div class="button-bg" @click="isPlay=!isPlay">
          <img v-if="isPlay" class="button-bg-c" style="margin-left: 3px"  src="../../../assets/images/stop.svg"/>
          <img v-else class="button-bg-c"  src="../../../assets/images/play.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"
          type="date"
          placeholder="请选择时间"
        />
      </div>


      <!-- 动态绑定事件间隔 timeInterval -->
      <div class="gis-bottom-item">
        <el-slider
          @change="chageSlider"
          :min="0"
          :max="1439"
          :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="5秒间隔" :value="5000"></el-option>
          <el-option label="2分钟间隔" :value="120000"></el-option>
          <el-option label="5分钟间隔" :value="300000"></el-option>
          <el-option label="10分钟间隔" :value="600000"></el-option>
          <el-option label="60分钟间隔" :value="3600000"></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, reactive, onMounted,onUnmounted } from "vue";
  import imglogo from '/src/assets/images/logo.svg'
  import 'ol/ol.css';
  import TileLayer from 'ol/layer/Tile';
  import OverviewMap from 'ol/control/OverviewMap';
  import { watch, defineComponent } from "vue";
  import { Vector as VectorLayer } from 'ol/layer'; // 引入矢量图层
  import { Vector as VectorSource } from 'ol/source';
  import { Platform} from "@/api/interface";
  import {getDataItemList,getPlatformList,getRgDataList} from "@/api/modules/allData";
  import { l } from "vite/dist/node/types.d-aGj9QkWt";
  import http from "@/api";
  import {ElementColumnsList, ResPage, ResultData} from "@/api/interface/index";
  import { PORT1 } from "@/api/config/servicePort";
  import '@/assets/map/popup.css'
  import { Tile, Image } from 'ol/layer';
  import { XYZ, TileWMS, ImageWMS } from 'ol/source';
  import LayerVector from 'ol/layer/Vector';
  import SourceVector from 'ol/source/Vector';
  import { Map, View, Feature, Overlay } from 'ol';
  import { fromLonLat, transform } from 'ol/proj';
  import { defaults, FullScreen, ScaleLine, ZoomToExtent, ZoomSlider, MousePosition } from 'ol/control'
  import { Point } from 'ol/geom';
  import { Style, Icon, Text, Fill, Stroke, Circle } from 'ol/style';
  import { createStringXY, format } from 'ol/coordinate';
  import { getCenter } from 'ol/extent';
  import { METERS_PER_UNIT } from 'ol/proj/Units';
  import { labelZoomSize, colorRGBtoHex } from "@/assets/map/maptool";
  import { Draw } from 'ol/interaction';




  // const isStationCode = ref()






// 时间选择器、滑块和时间间隔的控制变量
const value2 = ref(0); // 滑动条的默认值（从0点开始）
const intervalDuration = 5000; // 定义持续时间间隔为1000毫秒 5秒刷新一次
let intervalId: ReturnType<typeof setInterval> | null = null;
const timeInterval = ref(5000); // 默认毫秒时间间隔

// 获取当前时间分钟数（以一天的分钟为单位）
const now = new Date();
const currentMinutes = now.getHours() * 60 + now.getMinutes();
const currentDate = ref(new Date()); // 创建一个响应式变量 currentDate，初始化为当前日期
const updateTime = () =>{
  const fullYear = currentDate.value.getFullYear(); // 获取当前年份
  const month = currentDate.value.getMonth(); //获取当前月份
  const currentHour = currentDate.value.getHours(); // 获取当前小时
  const currentMinute = currentDate.value.getMinutes(); // 获取当前分钟
  const currentSeconds = currentDate.value.getSeconds(); // 获取当前秒钟
}

// 设置默认时间为当前时间
// const selectedTime = ref(new Date(currentDate.value.getFullYear(), currentDate.value.getMonth(), currentDate.getDate(), currentDate.getHours(), currentDate.getMinutes()));

// 初始化滑动条的值为当前分钟数
const value = ref(currentMinutes);

// 处理时间间隔的改变
const handleIntervalChange = (newInterval: number) => {
  timeInterval.value = newInterval;
};


  const showNineGrid = ref(false); // 控制九宫格显示与否
  const dataValues = ref(Array(9).fill(0)); // 替换为实际的数据
  const currentStationIndex = ref(0); // 选择的站点索引


  // 存储站点的经纬度和数据值
  const stations = ref([
    { lat: 34.638163632, lon: 116.426066261, value: 10 },
    { lat: 34.638263632, lon: 116.426166261, value: 20 },
    { lat: 34.638363632, lon: 116.426266261, value: 30 },
    // 继续添加其他站点
  ]);

  // 切换九宫格的显示
  const toggleNineGrid = () => {
    showNineGrid.value = !showNineGrid.value;
  };
  // 计算九宫格样式，以站点的经纬度为基准
  const getNineGridPosition = (stationIndex: number) => {
    const station = stations.value[stationIndex];
    return {
      position: 'absolute',
      top: `${station.lat}px`, // 根据需要转换为实际的像素值
      left: `${station.lon}px`, // 根据需要转换为实际的像素值
      transform: 'translate(-50%, -50%)',
      zIndex: 10,
    };
  };

  // 监视站点数据，更新九宫格的数据值
  watch(stations, (newStations) => {
    dataValues.value = newStations.map(station => station.value);
  });
  // 监视当前站点索引，更新九宫格位置
  watch(currentStationIndex, (newIndex) => {
    if (newIndex < stations.value.length) {
      nineGridStyle.value = getNineGridPosition(newIndex);
    }
  });

  // 初始设置九宫格样式
  const nineGridStyle = ref({
    position: 'absolute',
    top: '100px',
    left: '100px',
    zIndex: 100,
  });




  // 新建VectorSource（矢量信息图层） 来存放台站数据
  const stationSource = new VectorSource();
  const stationLayer = new VectorLayer({
    source: stationSource,
  });

  // 定义状态变量
  const value1 = ref('');
  // const value2 = ref(0); // 设置默认滑块值为0 即0时开始
  const visible = ref(false);
  const visible2 = ref(false);
  const checkList = ref(['Value selected and disabled', 'Value A']);
  const isPlay = ref(true);
  const isEagleEyeOn = ref(true); // 鹰眼开关状态
  const isjGG = ref(false); // 九宫格开关状态 默认关闭
  const isboxDrawn = ref(false); // 框选开关状态 默认关闭  boxDrawn
  const isstationName = ref(false); // 站名开关状态 默认关闭  isstationName
  const isstationCode = ref(true); // 站号开关状态 默认打开  isstationCode
  const isstreet = ref(true); // 街道地图开关状态 默认关闭
  const searchParam = reactive({ base: undefined, station: undefined });
  const baseOptions = ref([{ value: 0, label: '基地1' }, { value: 1, label: '基地2' }]);
  const stationOptions = ref([{ value: 0, label: 'M1986' }, { value: 1, label: 'M1987' }]);


  /**站号开关功能 */
  // 监听站号开关变化
  watch(isstationCode,(newValue) =>{
    if(newValue){
      // 打开站号 -
      showStationCodes(); // 显示站号

    }else{
      hideStationCodes();// 关闭站号
    }
  })

  // 显示站号的函数
function showStationCodes() {
  platformList.value.forEach((station) => {
    const latitude = parseFloat(station.as_lat.replace('N', ''));
    const longitude = parseFloat(station.as_lon.replace('E', ''));

    const feature = new Feature({
      geometry: new Point(fromLonLat([longitude, latitude])),
      name: station.as_name,
      code: station.as_code,
    });

    // 设置带站号的样式
    feature.setStyle(new Style({
      image: new Icon({
        src: imglogo,
        scale: 0.008,
      }),
      text: new Text({
        text: station.as_code, // 仅显示站号
        font: '12px Calibri,sans-serif',
        fill: new Fill({ color: '#000' }),
        stroke: new Stroke({ color: '#fff', width: 2 }),
        offsetY: -20,
        textAlign: 'center',
      })
    }));

    stationSource.addFeature(feature); // 添加特征到数据源
  });
}
// 隐藏站号的函数
function hideStationCodes() {
  stationSource.clear(); // 清除所有站号
}



  /**站名开关功能 */
  // 监听站名开关变化
  watch(isstationName,(newValue) =>{
    if(newValue){
      showStationName();// 打开站号
    }else{
      hideStationName()// 关闭站号
    }
  })
  // 显示站名的函数
function showStationName() {
  platformList.value.forEach((station) => {
    const latitude = parseFloat(station.as_lat.replace('N', ''));
    const longitude = parseFloat(station.as_lon.replace('E', ''));

    const feature = new Feature({
      geometry: new Point(fromLonLat([longitude, latitude])),
      name: station.as_name,
      code: station.as_code,
    });

    // 设置带站号的样式
    feature.setStyle(new Style({
      image: new Icon({
        src: imglogo,
        scale: 0.008,
      }),
      text: new Text({
        text: station.as_name, // 仅显示站名
        font: '12px Calibri,sans-serif',
        fill: new Fill({ color: '#000' }),
        stroke: new Stroke({ color: '#fff', width: 2 }),
        offsetY: -20,
        textAlign: 'center',
      })
    }));

    stationSource.addFeature(feature); // 添加特征到数据源
  });
}
// 隐藏站名的函数
function hideStationName() {
  stationSource.clear(); // 清除所有站名
}


  // 查询自动站列表
  const queryas = ref<Platform>({
    pageSize: 10000,
    pageNum: 1
  })
  const platformList =ref<any>([]); // 平台列表存储从后端获取的自动站数据列表

  // 获取站点列表
  const getPlatforms = async () => {
    try{
      const { data } = await getPlatformList(queryas.value);
      platformList.value = data.list;
      console.log("platformList.value:",+ platformList.value); // 在控制台输出平台列表

      getStations(data.list);
      // console.log("打印data.list的数据：",+data.list)
    }catch(error){
      console.log("获取平台列表失败：",error)
    }
  };

  const pageable = ref<any>({
    data_type: true,
    time_order: 0,
    as_code_list:undefined,
    data_items:[],
    pageNum: 1,
    pageSize: 20,
    total: 0
  });

  // 存放选中要素的数据
  const processTableData = ref<any>([]);
  const getList = async () => {
    try {
      const { data } = await getDataItemList(pageable.value); // 假设此函数调用成功并返回数据
      processTableData.value = data.list || []; //保证processTableData不会为null
      getStations(platformList.value);  //更新getStation更新站点

      return data.list; // 确保返回数据
    } catch (error) {
      console.error("获取数据时出错:", error);
      return null; // 如果出错，返回 null
    }
  };

  // 地图台站信息标注
  const getStations = (stations) => {
    console.log(stations,'getstation2');

    stationSource.clear();  // 清除之前的站点标记
    stations.forEach(station => {
      console.log(processTableData.value,'11');

      if (station.as_lon && station.as_lat) {
      const result = processTableData.value.find(item => item.as_code === station.as_code)
      console.log(result,'......result');

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

        // 打印解析后的经纬度
        console.log('Parsed Latitude:', latitude);
        console.log('Parsed Longitude:', longitude);
        // 基础信息，如站号和站名
        const featureTextParts = [
          `${station.as_code}`,
          // `站名: ${station.as_name}`
        ];

        // 确保 data_list 存在且为数组
        const selectedElementsText = copiedCustomizeColumns.value.map(selectedElem => {
          // 检查result是否存在，并且result[selectedElem.data_id]是否存在
          if (result && result[selectedElem.data_id] !== undefined) {
            const value = result[selectedElem.data_id] || "/";  // 如果值不存在则显示“暂无数据”
            return `${selectedElem.data_name}: ${value}${selectedElem.data_unit || ''}`;
          } else {
            // 如果未找到匹配项
            return `${selectedElem.data_name}: /`;
          }
        }).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,
        });

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

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

      }
    });
  };


// 右侧图标
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 formatTooltip = (value) => `${Math.floor(value / 60).toString().padStart(2, '0')}:${(value % 60).toString().padStart(2, '0')}`;
const handleBack = () => value2.value -= 10;
const handleForward = () => value2.value += 10;

// 启动定时器 时间间隔器
const startInterval = () => {
  if (intervalId) clearInterval(intervalId);
  intervalId = setInterval(() => {
    value2.value += 5; // 按每秒自增1进行示例，可根据需求修改
  }, intervalDuration);
};

// 停止定时器
const stopInterval = () => {
  if (intervalId) clearInterval(intervalId);
  intervalId = null;
};



const handleHideChange = () => { visible.value = false; };
const handleShowChange = () => { visible.value = true; };
const handleShowChange2 = () => { visible2.value = true; };
const handleHideChange2 = () => { visible2.value = false; };

// 图层配置数组
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 }
];

// 操作2
const info=ref<any>({
  1:'222',
  2:'99'
})


// 创建图层的函数
const createWMSLayer = ({ layerName, minZoom, maxZoom, opacity = 1 }) => {
  return new TileLayer({
    source: new TileWMS({
      url: 'http://192.168.127.124:8080/geoserver/wms',
      params: { 'LAYERS': layerName, 'TILED': true, 'FORMAT': 'image/png', 'TRANSPARENT': true, 'ENCODING': 'UTF-8' },
      serverType: 'geoserver'
    }),
    opacity,
    minZoom,
    maxZoom
  });
};

const chageSlider = (row) => {
  if(value2.value>1000){
    value2.value = 500
  }
}

let map:any; // 定义为全局变量
let overviewMapControl: OverviewMap;
// 地图初始化
const initializeMap = () => {

  let view =new View({
      center: fromLonLat([104.1954, 35.8617]),
      zoom: 4,
      projection: 'EPSG:3857'//定义坐标系
    })
  map = new Map({
    target: 'map',
    layers: [
    ...layersConfig.map(createWMSLayer),
      stationLayer  // 初始化时添加 stationLayer
    ],
    view: view
  });


  // 定义鹰眼视图层
  const overviewMapLayer = new TileLayer({
    source: new TileWMS({
      url: 'http://192.168.127.124:8080/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] = toLonLat(map.getCoordinateFromPixel(evt.pixel));
      const [lon, lat] = transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326'); // 转换为标准经纬度
      document.getElementById('mouse-position').innerHTML = `经度: ${lon.toFixed(6)}°,  纬度: ${lat.toFixed(6)}°`;
    });
};

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

// 查询所有人工要素字典表
const elementList =ref<any>([])
const getAllRgDataList = async () => {
  const { data } = await getRgDataList();
  elementList.value = data.list
  console.log("所有人工要素：",elementList.value)
};

// 存放选中要素列表
const copiedCustomizeColumns = ref<any>([]);
// 要素的选中和取消
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);
  }
  console.log("copiedCustomizeColumns.value:", copiedCustomizeColumns.value);

  //根据要素查询数据
  pageable.value.data_items  = copiedCustomizeColumns.value
  getList().then((data) => {
    console.log("getList 返回的数据:", data);
  }).catch((error) => {
    console.error("获取数据时出错:", error);
  });

};

  // 在组件挂载时初始化地图
  onMounted(() => {
    // startInterval(); // 组件中挂载启动时间器
    updateTime(); // 页面加载时更新时间
    // selectedTime.value = new Date(currentDate.value.getFullYear(), currentDate.value.getMonth(), currentDate.getDate(), currentDate.getHours(), currentDate.getMinutes());
    getAllRgDataList(); // 存放人工选择的要素列表
    initializeMap();
    getPlatforms();
  });
  // 在组件卸载时清除定时器
onUnmounted(() => {
  stopInterval();
});

</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 {
  position: absolute;
  top:20px;
  right:20px;
  transform: translate(-50%, -50%);
  width: 90px;
  height: 90px;
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 创建3列 */
  grid-template-rows: repeat(3, 1fr); /* 创建3行 */
  border: 1px solid rgba(0, 0, 0, 0.5); /* 盒子的边框 */
  z-index: 10; /* 确保盒子覆盖在地图上方 */
  box-sizing: border-box; /* 边框宽度包含在宽度和高度内 */
}

.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; /* 防止换行 */
}
/**时间间隔 */


</style>
