<template>
  <div class="map-index">
    <!-- 苏州河 -->
    <div ref="scrollContainer" v-if="route.params.id=='28'" style="border: 2px solid #409EFF;background-color: rgba(127, 161, 215, 0.5);border-radius: 50px 50px 50px 50px;
    align-items: center;display: flex;position: absolute;z-index: 100;bottom: 1%;left: 1%;width:50vw;height: 10vh;overflow-x:auto;overflow-y: hidden;">
      <svg-icon icon-class="start1" v-if="!isStart" @click="reStart"
                style="margin-left: 10%;width: 30px;height:30px;cursor: pointer;"/>
      <svg-icon icon-class="pause1" v-if="isStart" @click="pause"
                style="margin-left: 10%;width: 30px;height:30px;cursor: pointer;"/>
      <el-slider @change="pauseIn" :format-tooltip="formatTooltip" v-model="activities1" :max="dateLength"
                 :marks="marks" style="width: 80%;margin-left: 1%;"/>

    </div>
    <div v-if="route.params.id=='28'"
         style="background-color: white;position: absolute;z-index: 100;top: 1%;left: 1%;width: 20vw;height: 45vh;overflow:auto;">
      <div class="biz-data-card-header">方案列表</div>
      <el-table
          :data="tableDataFangan"
          style="width: 98%;margin-left: 1%;margin-top: 1%;height: 40vh;"
          :cell-style="{ padding:'5px' }"
          :header-cell-style="{fontSize: '14px',height: heightAll*0.01+'px',}"
          :row-style="{ fontSize: '17px',textAlign:'center'}"
          border>
        <el-table-column type="index" label="序号" width="80">
          <template #default="{ $index }">
            <div style="text-align: center;">
              {{ $index + 1 }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称">
          <template #default="scope">
            <span style="cursor: pointer;color:#409EFF" @click="getZ(scope.row)">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="route.params.id=='28'"
         style="background-color: white;position: absolute;z-index: 100;top: 1%;right: 1%;width: 30vw;height: 85vh;overflow:auto;">
      <div class="biz-data-card-header">水位信息</div>
      <el-table
          :data="tableData"
          style="width: 98%;margin-left: 1%;margin-top: 1%;height: 80vh;"
          :cell-style="{ padding:'5px' }"
          :header-cell-style="{fontSize: '14px',height: heightAll*0.01+'px',}"
          :row-style="{ fontSize: '17px',textAlign:'center'}"
          border>
        <el-table-column type="index" label="序号" width="80">
          <template #default="{ $index }">
            <div style="text-align: center;">
              {{ $index + 1 }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="站名" width="200">
        </el-table-column>
        <el-table-column prop="z" label="水位" width=""/>
        <el-table-column prop="time" label="时间" width="210"/>
      </el-table>
    </div>
    <div id="tooltip" ref="tooltipRef" class="tooltip"></div>
    <!-- 温带风暴潮 -->
    <div ref="scrollContainer" v-if="route.params.id=='20'" style="border: 2px solid #409EFF;background-color: rgba(127, 161, 215, 0.5);border-radius: 50px 50px 50px 50px;
    align-items: center;display: flex;position: absolute;z-index: 100;bottom: 1%;left: 1%;width:50vw;height: 10vh;overflow-x:auto;overflow-y: hidden;">
      <svg-icon icon-class="start1" v-if="!isStart" @click="reStartWen"
                style="margin-left: 10%;width: 30px;height:30px;cursor: pointer;"/>
      <svg-icon icon-class="pause1" v-if="isStart" @click="pauseInWen"
                style="margin-left: 10%;width: 30px;height:30px;cursor: pointer;"/>
      <el-slider @change="pauseIn" :format-tooltip="formatTooltip" v-model="activities1" :max="dateLength"
                 :marks="marks" style="width: 80%;margin-left: 1%;"/>
    </div>
    <div v-if="route.params.id=='20'"
         style="background-color: white;position: absolute;z-index: 100;top: 1%;left: 1%;width: 20vw;height: 45vh;overflow:auto;">
      <div class="biz-data-card-header">方案列表</div>
      <el-table
          :data="tableDataFangan"
          style="width: 98%;margin-left: 1%;margin-top: 1%;height: 40vh;"
          :cell-style="{ padding:'5px' }"
          :header-cell-style="{fontSize: '14px',height: heightAll*0.01+'px',}"
          :row-style="{ fontSize: '17px',textAlign:'center'}"
          border>
        <el-table-column type="index" label="序号" width="80">
          <template #default="{ $index }">
            <div style="text-align: center;">
              {{ $index + 1 }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称">
          <template #default="scope">
            <span style="cursor: pointer;color:#409EFF" @click="getZ(scope.row)">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="route.params.id=='20'"
         style="background-color: white;position: absolute;z-index: 100;top: 1%;right: 1%;width: 30vw;height: 85vh;overflow:auto;">
      <div class="biz-data-card-header">风暴潮信息</div>
      <el-table
          :data="tableData"
          style="width: 98%;margin-left: 1%;margin-top: 1%;height: 80vh;"
          :cell-style="{ padding:'5px' }"
          :header-cell-style="{fontSize: '14px',height: heightAll*0.01+'px',}"
          :row-style="{ fontSize: '17px',textAlign:'center'}"
          border>
        <el-table-column type="index" label="序号" width="80">
          <template #default="{ $index }">
            <div style="text-align: center;">
              {{ $index + 1 }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="stnm" label="站名" width="150">
        </el-table-column>
        <el-table-column prop="gfsZ" label="水位" width=""/>
        <el-table-column prop="gfsAddz" label="增水" width=""/>
        <el-table-column prop="gfsAddz" label="风速" width=""/>
        <el-table-column prop="gfsWnddir" label="风向" width=""/>
      </el-table>
    </div>
    <!-- 排水 -->
    <div v-if="route.params.id=='30'"
         style="background-color: white;position: absolute;z-index: 100;top: 1%;left: 1%;width: 20vw;height: 45vh;overflow:auto;">
      <div class="biz-data-card-header">方案列表</div>
      <el-table
          :data="tableDataShanghaifeng"
          style="width: 98%;margin-left: 1%;margin-top: 1%;height: 40vh;"
          :cell-style="{ padding:'5px' }"
          :header-cell-style="{fontSize: '14px',height: heightAll*0.01+'px',}"
          :row-style="{ fontSize: '17px',textAlign:'center'}"
          border>
        <el-table-column type="index" label="序号" width="80">
          <template #default="{ $index }">
            <div style="text-align: center;">
              {{ $index + 1 }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="planName" label="名称">
          <template #default="scope">
            <span style="cursor: pointer;color:#409EFF" @click="getZ(scope.row)">{{ scope.row.planName }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 测试 -->
    <div v-if="route.params.id=='42'"
         style="background-color: white;position: absolute;z-index: 100;top: 1%;left: 1%;width: 30vw;height: 45vh;overflow:auto;">
      <div class="biz-data-card-header">方案列表</div>
      <el-table
          :data="tableDataShanghaifeng"
          style="width: 98%;margin-left: 1%;margin-top: 1%;height: 40vh;"
          :cell-style="{ padding:'5px' }"
          :header-cell-style="{fontSize: '14px',height: heightAll*0.01+'px',}"
          :row-style="{ fontSize: '17px',textAlign:'center'}"
          border>
        <el-table-column type="index" label="序号" width="80">
          <template #default="{ $index }">
            <div style="text-align: center;">
              {{ $index + 1 }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="planName" label="名称" width="150">
          <template #default="scope">
            <span style="cursor: pointer;color:#409EFF" @click="getGeo(scope.row)">{{ scope.row.dataName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="产生时间" width="200">
        </el-table-column>
        <el-table-column prop="timeLength" label="存放时长（天）">
        </el-table-column>
      </el-table>
    </div>
    <el-dialog @close="clearFromLev" :title="titleFengbao" v-model="dialogVisibleFengbao" width="50%" destroy-on-close>
      <div>
        <div style="font-size: 20px;margin-left: 2%;">水位</div>
        <div id="shuiwei" style="width: 100%;height: 18vh;margin-top: 0%;"></div>
      </div>
      <div>
        <div style="font-size: 20px;margin-left: 2%;margin-top:1% ;">增水</div>
        <div id="zengshui" style="width: 100%;height: 18vh;margin-top: 1%;"></div>
      </div>
      <div>
        <div style="font-size: 20px;margin-left: 2%;margin-top:1%">风速</div>
        <div id="fengsu" style="width: 100%;height: 18vh;margin-top: 1%;"></div>
      </div>
      <div>
        <div style="font-size: 20px;margin-left: 2%;margin-top:1%">风向</div>
        <div id="fengxiang" style="width: 100%;height:18vh;margin-top: 1%;"></div>
      </div>
    </el-dialog>
    <el-dialog @close="clearFromLev" title="" v-model="dialogVisibleSuzhou" width="30%" destroy-on-close>
      <el-descriptions
          class="margin-top"
          :title="titleSuzhou"
          :column="1"
          :size="size"
          border
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              站码
            </div>
          </template>
          {{ suzhou.stationId }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              水位
            </div>
          </template>
          {{ suzhou.waterLevel }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              时间
            </div>
          </template>
          {{ suzhou.tm }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <div id="mapChart"></div>
  </div>
</template>
<script setup>
import 'ol/css';
import {defaults as defaultControls} from 'ol/control';
import {
  getForecastlist,
  getStromdatade,
  getStromdataList,
  getStromlist,
  getMdAppFlowDataList,
  getAppData
} from "@/api/standardization/bizDataShowConfig.js";
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import Overlay from 'ol/Overlay';
import {XYZ} from 'ol/source';
import Point from 'ol/geom/Point';
import * as echarts from 'echarts';
import {createDynamicStyle} from "@/views/map/utils/styleParser.js";
import {loadSource} from "../hooks/dataSourceManager.js";
import bus from "@/utils/bus.js";
import {getPopupContentByTemplate, loadPopupChartByTemplate} from "@/views/map/hooks/popupContent.js";
import {isArray} from "@/utils/validate.js";
import {getCenter} from "ol/extent.js";
import jsonDatak5 from "./kaixuan5.json";
import 'ol/ol.css';
import VectorSource from 'ol/source/Vector';
import Feature from 'ol/Feature';
import {Fill, RegularShape, Stroke, Style, Text} from 'ol/style';
import GeoJSON from 'ol/format/GeoJSON';
import suzhouJson from "./suzhou.json";
import {useRoute} from "vue-router";
import suzhouPoint from "./suzhouPoints.json";
import {ref} from 'vue';
import fangan from "./fangan.json";
import test1 from "./test1.json";
import test2 from "./test2.json";
import test3 from "./test3.json";
const dialogVisibleFengbao = ref(false)
const titleFengbao = ref('')
const tableDataFangan = ref([])
const fanganId = ref(null)
const scrollContainer = ref(null);
const scrollAmount = 0;
const widthAll = ref(window.innerWidth)
const dialogVisibleSuzhou = ref(false)
const route = useRoute();
const suzhou = ref({})
const props = defineProps({
  config: Object,
});
const mapChart = ref(null);
// 存储弹窗的引用
const popupOverlays = ref([]);
const activities = ref([])
const activities1 = ref()
const dateLength = ref(0)
const marks = ref({})
const isStart = ref(true)
const tooltipRef = ref(null);
let currentFeature = null
let overlay = null
const tableDataShanghaifeng = ref([])
const geoJSONLayer = ref(null)
onMounted(async () => {
  console.log(route.params.id)
  initMap();
  if (route.params.id === '30') {
    getForecastlist({appId: route.params.id}).then(res => {
      tableDataShanghaifeng.value = res.rows
    })
    polygonLayer.value = createPolygonLayer(jsonDatak5)
    mapChart.value.addLayer(polygonLayer.value);
    overlay = new Overlay({
      element: tooltipRef.value,
      positioning: 'bottom-center',
      offset: [0, -10],
      stopEvent: false,
    });
    mapChart.value.addOverlay(overlay);
    mapChart.value.getView().setZoom(18)
    mapChart.value.getView().setCenter([121.41335460526926, 31.205820744558153]);
    mapChart.value.on('pointermove', (e) => {
      if (e.dragging) {
        return; // 如果正在拖拽地图，则不处理[2,7](@ref)
      }

      const pixel = mapChart.value.getEventPixel(e.originalEvent);
      const feature = mapChart.value.forEachFeatureAtPixel(pixel, (feature) => feature);

      if (feature) {
        // 鼠标在要素上[7](@ref)
        if (feature !== currentFeature) {
          currentFeature = feature;
          console.log(feature.values_)
          // 获取要素属性信息
          const featureCode = feature.values_.element_no;
          const featureDep = feature.values_.DEPTH2D

          // 更新工具提示内容[2](@ref)
          tooltipRef.value.innerHTML = `
          <div class="tooltip-header">编号:${featureCode}</div>
          <div class="tooltip-content">水深: ${featureDep}</div>
        `;

          // 设置工具提示位置并显示[7](@ref)
          overlay.setPosition(e.coordinate);
          tooltipRef.value.style.display = 'block';

          // 更改鼠标指针样式为手型[3,5](@ref)
          mapChart.value.getTargetElement().style.cursor = 'pointer';
        }
      } else {
        // 鼠标不在要素上
        tooltipRef.value.style.display = 'none';
        currentFeature = null;
        mapChart.value.getTargetElement().style.cursor = ''; // 恢复默认指针[3](@ref)
      }
    });
  }
  if (route.params.id === '42') {
    getMdAppFlowDataList({appId: route.params.id}).then(res => {
      tableDataShanghaifeng.value = res.data
      getGeo(tableDataShanghaifeng.value[0])
    })
  }
  if (route.params.id === '28') {
    tableDataFangan.value = fangan.data.records
    const keys = Object.keys(suzhouJson.data.outPutQUZ)
    dateLength.value = keys.length - 1
    keys.forEach(item => {
      var par = {
        content: '',
        timestamp: item,
        size: 'large',
        type: 'primary',
      }
      activities.value.push(par)
    })
    var parTime = uniformSample(activities.value)
    console.log(activities.value)
    var a = Math.round((dateLength.value - 1) * 1 / 3)
    var b = Math.round((dateLength.value - 1) * 2 / 3)
    var c = dateLength.value
    marks.value = {
      0: {
        style: {
          color: '#1989FA',
        },
        label: parTime[0].timestamp.slice(5),
      },
    }
    marks.value[a] = {
      style: {
        color: '#1989FA',
      },
      label: parTime[1].timestamp.slice(5),
    }
    marks.value[b] = {
      style: {
        color: '#1989FA',
      },
      label: parTime[2].timestamp.slice(5),
    }
    marks.value[c] = {
      style: {
        color: '#1989FA',
      },
      label: parTime[3].timestamp.slice(5),
    }
    console.log(activities)
    suzhouJson.data.inputParam = JSON.parse(suzhouJson.data.inputParam)
    console.log(suzhouJson.data)
    timerId = setInterval(changeMap, 1000)
    console.log(suzhouPoint)
    pointLayer.value = createPointlayer(suzhouPoint)
    mapChart.value.addLayer(pointLayer.value);
    mapChart.value.on('click', (event) => {
      const feature = mapChart.value.forEachFeatureAtPixel(
          event.pixel,
          (feature) => feature
      );

      if (feature) {
        pause()
        const properties = feature.getProperties();
        dialogVisibleSuzhou.value = true
        titleSuzhou.value = properties.name
        console.log('要素属性:', properties);
        suzhou.value = properties
        suzhou.value.tm = activities.value[count.value - 1].timestamp
        const title = feature.get('title');
        const id = feature.get('id');
        console.log('标题:', title, 'ID:', id);

        // 获取几何信息
        const geometry = feature.getGeometry();
        const coordinates = geometry.getCoordinates();
        console.log('几何坐标:', coordinates);
      } else {
        console.log('未点击到任何要素');
      }
    })
    if (props.config) {
      // toCenter(props.config.center, props.config.zoom);
      await loadLayers(props.config.layers);
    }
  }
  if (route.params.id === '20') {
    tableDataFangan.value = fangan.data.records
    wendai()
  }
});
const titleSuzhou = ref('')
const count = ref(0)
const tableData = ref()

function getZ(row) {
  console.log(row.id)
}
function setGeoJSONLayer(json){
  var parData = []
  json.features.forEach(item => {
    var par = {
      type: 'Feature',
      geometry: item.geometry,
      properties: item.properties,
    }
    parData.push(par)
  });
  const polygonGeoJSON = {
    "type": "FeatureCollection",
    "features": parData
  };
  // 创建矢量数据源并加载GeoJSON多边形数据[3,4](@ref)
  const vectorSource = new VectorSource({
    features: new GeoJSON().readFeatures(polygonGeoJSON, {
      dataProjection: 'EPSG:4326',
      featureProjection: 'EPSG:4326'
    })
  });

    // 3. 创建矢量图层
    const styleFunction = function (feature) {
      const properties = feature.getProperties();
      if (properties.hvalue >= 50) {
        return new Style({
          fill: new Fill({
            color: 'rgba(248, 152, 152, 0.5)'
          }),
          stroke: new Stroke({
            color: '#ff0000',
            width: 2
          })
        });
      } else if (properties.hvalue < 50 && properties.hvalue >= 40) {
        return new Style({
          fill: new Fill({
            color: 'rgba(255, 0, 0, 0.5)'
          }),
          stroke: new Stroke({
            color: '#ff0000',
            width: 2
          })
        });
      } else if (properties.hvalue < 40 && properties.hvalue >= 30) {
        return new Style({
          fill: new Fill({
            color: 'rgba(51, 126, 204, 0.5)'
          }),
          stroke: new Stroke({
            color: '#ff0000',
            width: 2
          })
        });
      } else if (properties.hvalue < 30 && properties.hvalue >= 20) {
        return new Style({
          fill: new Fill({
            color: 'rgba(121, 187, 255, 0.5)'
          }),
          stroke: new Stroke({
            color: '#ff0000',
            width: 2
          })
        });
      } else if (properties.hvalue < 10 && properties.hvalue >= 1) {
        return new Style({
          fill: new Fill({
            color: 'rgba(149, 212, 117, 0.5)'
          }),
          stroke: new Stroke({
            color: '#ff0000',
            width: 2
          })
        });
      }
      // 默认样式
      return new Style({
        fill: new Fill({
          color: 'rgba(179, 225, 157, 0.5)'  // 半透明蓝色填充
        }),
        stroke: new Stroke({
          color: '#0066ff',  // 蓝色边框
          width: 2           // 边框宽度
        })
      });
    };
    const geoJSONLayer = new VectorLayer({
      source: vectorSource,
      style: styleFunction // 应用样式
    });
    return geoJSONLayer
}
function initChart(x, y, mdName, id, color, danwei) {
  var chartDom = document.getElementById(id);
  var myChart = echarts.init(chartDom);
  var option;
  option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '15%',
      top: '18%',
      containLabel: true
    },
    xAxis: {
      splitLine: {show: false},
      // type: 'category',
      data: x
    },
    yAxis: {
      type: 'value',
      show: true,
      splitLine: {show: false},
      name: danwei,
      axisTick: {
        show: true // 确保显示刻度线
      },
      axisLine: {
        show: true, // 确保显示轴线
        lineStyle: {
          color: '#333', // 可以设置轴线的颜色，例如与文字颜色一致
          // width: 1 // 可以设置轴线宽度，可选
        }
      },
    },
    series: [
      {
        name: mdName,
        type: 'line',
        color: color,
        data: y,
        smooth: true
      },
    ]
  };
  option && myChart.setOption(option);
}

function formatTooltip(val) {
  if (activities.value && activities.value[val]) {
    return activities.value[val].timestamp.slice(5);
  }
  // 数据未就绪时返回默认提示
  return 'Loading...';
}

const tableJason = ref([])

async function wendai() {
  await getStromlist().then(res => {
    var dataJson = res.data
    const vectorSource = new VectorSource();
    dataJson.forEach(station => {
      const feature = new Feature({
        geometry: new Point([station.lgtd, station.lttd]),
        stcd: station.stcd,
        stnm: station.stnm,
      });

      // 设置样式（根据水位值动态设置颜色）
      const style = new Style({
        image: new RegularShape({
          points: 3, // 三角形
          radius: 8, // 大小
          fill: new Fill({
            color: '#FF5722' // 红色填充
          }),
          stroke: new Stroke({
            color: '#fff', // 白色边框
            width: 2
          }),
          angle: Math.PI // 旋转180度，使三角形倒置[1,4](@ref)
        }),
        text: new Text({
          text: station.stnm,
          offsetY: 20,
          font: '12px Microsoft YaHei, sans-serif',
          fill: new Fill({
            color: '#333'
          }),
          stroke: new Stroke({
            color: '#fff',
            width: 1
          }),
          backgroundFill: new Fill({
            color: 'transparent'
          }),
          padding: [2, 4, 2, 4]
        })
      });
      feature.setStyle(style);
      vectorSource.addFeature(feature);
    });
    const vectorLayer = new VectorLayer({
      source: vectorSource,
      properties: {
        name: 'weidaiLayers',
        type: 'vector'
      }
    });
    mapChart.value.addLayer(vectorLayer)
    mapChart.value.on('click', (event) => {
      const feature = mapChart.value.forEachFeatureAtPixel(
          event.pixel,
          (feature) => feature
      );

      if (feature) {
        const properties = feature.getProperties();
        dialogVisibleFengbao.value = true
        titleFengbao.value = properties.stnm + '(站码:' + properties.stcd + ')'
        getStromdatade({stcd: properties.stcd}).then(res => {
          var x = []
          var ygfsZ = []
          var ygfsAddz = []
          var ygfsWndv = []
          var ygfsWnddir = []
          res.data.forEach(item => {
            var parTm = item.tm.slice(5)
            x.push(parTm.slice(0, 5) + '\n' + parTm.slice(-8, -3))
            ygfsZ.push(item.gfsZ)
            ygfsAddz.push(item.gfsAddz)
            ygfsWndv.push(item.gfsWndv)
            ygfsWnddir.push(item.gfsWnddir)
          })
          initChart(x, ygfsZ, properties.stnm, 'shuiwei', '#409EFF', '单位：m')
          initChart(x, ygfsAddz, properties.stnm, 'zengshui', '#67C23A', '单位：m')
          initChart(x, ygfsWndv, properties.stnm, 'fengsu', '#E6A23C', '单位：m/s')
          initChart(x, ygfsWnddir, properties.stnm, 'fengxiang', '#F56C6C', '单位：°')
        })
        console.log('要素属性:', properties);

        // 获取特定属性
        const title = feature.get('title');
        const id = feature.get('id');
        console.log('标题:', title, 'ID:', id);

        // 获取几何信息
        const geometry = feature.getGeometry();
        const coordinates = geometry.getCoordinates();
        console.log('几何坐标:', coordinates);
      } else {
        console.log('未点击到任何要素');
      }
    })
  })
  await getStromdataList().then(res => {
    tableJason.value = res.data
    const keys = Object.keys(res.data)
    dateLength.value = keys.length
    console.log(keys, dateLength.value)
    keys.forEach(item => {
      var par = {
        content: '',
        timestamp: item,
        size: 'large',
        type: 'primary',
      }
      activities.value.push(par)
    })
    var parTime = uniformSample(activities.value)
    console.log(activities.value)
    var a = Math.round((dateLength.value - 1) * 1 / 3)
    var b = Math.round((dateLength.value - 1) * 2 / 3)
    var c = dateLength.value - 1
    marks.value = {
      0: {
        style: {
          color: '#1989FA',
        },
        label: parTime[0].timestamp.slice(5),
      },
    }
    marks.value[a] = {
      style: {
        color: '#1989FA',
      },
      label: parTime[1].timestamp.slice(5),
    }
    marks.value[b] = {
      style: {
        color: '#1989FA',
      },
      label: parTime[2].timestamp.slice(5),
    }
    marks.value[c] = {
      style: {
        color: '#1989FA',
      },
      label: parTime[3].timestamp.slice(5),
    }
  })
  dateLength.value = dateLength.value - 1
  timerId = setInterval(changeWen, 1000)
}
function getGeo(row){
  getAppData({dataId:row.dataId}).then(res=>{
    mapChart.value.removeLayer(geoJSONLayer.value)
    geoJSONLayer.value = setGeoJSONLayer(res.data)
    mapChart.value.addLayer(geoJSONLayer.value);
  })
}
function changeWen() {
  if (tableJason.value) {
    tableData.value = []
    var valuesArray = Object.values(tableJason.value)
    tableData.value = valuesArray[count.value]
    activities1.value = count.value
    count.value++
    if (count.value > dateLength.value) {
      count.value = 0
    }
  }
}

function pause() {
  clearInterval(timerId);
  timerId = null
  isStart.value = false
}

function reStart() {
  timerId = setInterval(changeMap, 1000)
  isStart.value = true
}

function reStartWen() {
  timerId = setInterval(changeWen, 1000)
  isStart.value = true
}

function uniformSample(arr) {
  const n = arr.length;
  if (n === 0) return [];
  if (n <= 4) {
    return arr.slice();
  }

  // 计算三个等分点的索引
  const index0 = 0; // 首元素
  const index1 = Math.round((n - 1) * 1 / 3); // 第一个等分点
  const index2 = Math.round((n - 1) * 2 / 3); // 第二个等分点
  const index3 = n - 1; // 尾元素
  return [
    arr[index0],
    arr[index1],
    arr[index2],
    arr[index3]
  ];
}

function pauseIn() {
  pause()
  count.value = activities1.value
  changeMap()
}

function pauseInWen() {
  pause()
  count.value = activities1.value
  changeWen()
}

function changeMap() {
  tableData.value = []
  const keys1 = Object.keys(suzhouJson.data.outPutQUZ)
  if (count.value >= keys1.length) {
    console.log(count.value, keys1.length)
    count.value = 0
  }
  activities1.value = count.value
  mapChart.value.removeLayer(pointLayer.value)
  const keys = Object.keys(suzhouJson.data.outPutQUZ)
  tableData.value = suzhouJson.data.outPutQUZ[keys[count.value]]
  for (var i = 0; i < suzhouPoint.length; i++) {
    for (var i1 = 0; i1 < suzhouJson.data.outPutQUZ[keys[count.value]].length; i1++) {
      if (suzhouPoint[i].STATIONNAME === suzhouJson.data.outPutQUZ[keys[count.value]][i1].name) {
        suzhouPoint[i].ZZ = suzhouJson.data.outPutQUZ[keys[count.value]][i1].z
      }
    }
  }
  pointLayer.value = createPointlayer(suzhouPoint)
  mapChart.value.addLayer(pointLayer.value);
  // if(count.value%10===0&&count.value!==0){ 
  //   scrollContainer.value.scrollLeft += scrollAmount + widthAll.value;
  // }

  count.value++
}

function createPolygonLayer(jsonData) {
  var parData = []
  if (Array.isArray(jsonData)) {
    jsonData.forEach(item => {
      var par = {
        type: 'Feature',
        geometry: JSON.parse(item.geometry),
        properties: JSON.parse(item.properties),
      }
      parData.push(par)
    });
    const polygonGeoJSON = {
      "type": "FeatureCollection",
      "features": parData
    };
    // 创建矢量数据源并加载GeoJSON多边形数据[3,4](@ref)
    const vectorSource = new VectorSource({
      features: new GeoJSON().readFeatures(polygonGeoJSON, {
        dataProjection: 'EPSG:4326',
        featureProjection: 'EPSG:4326'
      })
    });
    // 创建多边形要素样式[6,7](@ref)
    const styleFunction = function (feature) {
      const properties = feature.getProperties();
      if (properties.DEPTH2D >= 1) {
        return new Style({
          fill: new Fill({
            color: 'rgba(255, 0, 0, 0.5)'
          }),
          stroke: new Stroke({
            color: '#ff0000',
            width: 3
          })
        });
      } else if (properties.DEPTH2D < 1 && properties.DEPTH2D >= 0.5) {
        return new Style({
          fill: new Fill({
            color: 'rgb(238, 190, 119)'
          }),
          stroke: new Stroke({
            color: '#ff0000',
            width: 3
          })
        });
      } else if (properties.DEPTH2D < 0.5 && properties.DEPTH2D >= 0.3) {
        return new Style({
          fill: new Fill({
            color: 'rgb(238, 190, 119)'
          }),
          stroke: new Stroke({
            color: '#ff0000',
            width: 3
          })
        });
      } else if (properties.DEPTH2D < 0.3 && properties.DEPTH2D >= 0.25) {
        return new Style({
          fill: new Fill({
            color: 'rgb(238, 190, 119)'
          }),
          stroke: new Stroke({
            color: '#ff0000',
            width: 3
          })
        });
      } else if (properties.DEPTH2D < 0.25 && properties.DEPTH2D >= 0.2) {
        return new Style({
          fill: new Fill({
            color: 'rgb(121, 187, 255)'
          }),
          stroke: new Stroke({
            color: '#ff0000',
            width: 3
          })
        });
      } else if (properties.DEPTH2D < 0.2 && properties.DEPTH2D >= 0.15) {
        return new Style({
          fill: new Fill({
            color: 'rgb(198, 226, 255)'
          }),
          stroke: new Stroke({
            color: '#ff0000',
            width: 3
          })
        });
      }
      // 默认样式
      return new Style({
        fill: new Fill({
          color: 'rgb(51, 126, 204)'  // 半透明蓝色填充
        }),
        stroke: new Stroke({
          color: '#0066ff',  // 蓝色边框
          width: 2           // 边框宽度
        })
      });
    };

    // 创建矢量图层[1,2](@ref)
    return new VectorLayer({
      source: vectorSource,
      style: styleFunction
    });
  }
}

function createStationStyle(station) {
  // 根据水位值设置颜色[7](@ref)
  let color = '#3399CC'; // 默认蓝色
  if (station.ZZ > 5.0) {
    color = '#FF6B6B'; // 高水位用红色
  } else if (station.ZZ < 4.5) {
    color = '#4ECDC4'; // 低水位用绿色
  }

  return new Style({
    image: new RegularShape({
      points: 3, // 三角形
      radius: 8, // 大小
      fill: new Fill({
        color: '#FF5722' // 红色填充
      }),
      stroke: new Stroke({
        color: '#fff', // 白色边框
        width: 2
      }),
      angle: Math.PI // 旋转180度，使三角形倒置[1,4](@ref)
    }),
    text: new Text({
      text: station.STATIONNAME + '\n水位: ' + station.ZZ + 'm',
      offsetY: 20,
      font: '12px Microsoft YaHei, sans-serif',
      fill: new Fill({
        color: '#333'
      }),
      stroke: new Stroke({
        color: '#fff',
        width: 1
      }),
      backgroundFill: new Fill({
        color: 'transparent'
      }),
      padding: [2, 4, 2, 4]
    })
  });
}
function createPointlayer(dataJson) {
  const vectorSource = new VectorSource();

  // 为每个水文站创建要素[2,3](@ref)
  dataJson.forEach(station => {
    // 使用经纬度坐标创建点要素[5](@ref)
    const feature = new Feature({
      geometry: new Point([station.XX2000, station.YY2000]),
      name: station.STATIONNAME,
      waterLevel: station.ZZ,
      area: station.QUYU,
      river: station.HELIU,
      type: station.TYPE,
      // tm:,
      stationId: station.STATIONID
    });

    // 设置样式（根据水位值动态设置颜色）
    const style = createStationStyle(station);
    feature.setStyle(style);
    vectorSource.addFeature(feature);
  });

  // 创建矢量图层[1,4](@ref)
  const vectorLayer = new VectorLayer({
    source: vectorSource,
    // 可以设置图层属性便于后续管理
    properties: {
      name: 'hydrologicalStations',
      type: 'vector'
    }
  });

  // 将图层添加到地图


  return vectorLayer;
}

// 创建多边形图层
const pointLayer = ref(null)
const polygonLayer = ref(null)
const initMap = () => {

  let vecLayer = new TileLayer({
    source: new XYZ({
      url: "http://t0.tianditu.gov.cn/vec_w/wmts?" +
          "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
          "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}" +
          "&tk=9bb941214f10fbf9a3eab43f45cb2b7e",
    }),
  });
  let cvaLayer = new TileLayer({
    source: new XYZ({
      url: "http://t0.tianditu.gov.cn/cva_w/wmts?" +
          "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
          "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}" +
          "&tk=9bb941214f10fbf9a3eab43f45cb2b7e",
    }),
  });

  mapChart.value = new Map({
    target: 'mapChart',
    view: new View({
      center: [121.472644, 31.231706],
      zoom: 10,
      minZoom: 3,
      maxZoom: 16,
      projection: 'EPSG:4326',
    }),
    layers: [vecLayer, cvaLayer],
    // layers: [vecLayer],
    controls: defaultControls({
      zoom: false,//不显示放大放小按钮
      rotate: false,//不显示指北针控件
      attribution: false,//不显示右下角的地图信息控件
      scaleLine: false,//不显示比例尺控件
    })
  });

  mapChart.value.on('moveend', function (event) {
    var center = mapChart.value.getView().getCenter(); // 获取中心点位置
    var zoom = mapChart.value.getView().getZoom(); // 获取层级
    console.log('Center:', center); // 转换为经纬度格式
    console.log('Zoom:', zoom);
  });
};

const addVectorLayer = async (config) => {
  loadSource(config).then(source => {
    // 创建矢量图层
    const vectorLayer = new VectorLayer({
      id: config.id,
      zIndex: config.zIndex,
      source: source,
      style: config.style ? createDynamicStyle(config.style) : null,
      visible: config.visible !== false // 默认可见
    });
    // 添加到地图
    mapChart.value.addLayer(vectorLayer);
    // 添加事件监听
    if (config.events) {
      setupLayerEvents(vectorLayer, config.events);
    }
    return vectorLayer;
  })
};

// 设置图层事件监听
const setupLayerEvents = (layer, events) => {
  // 点击事件处理
  if (events.click) {
    mapChart.value.on('click', (event) => {
      const features = mapChart.value.getFeaturesAtPixel(event.pixel);
      if (features && features.length > 0) {
        // 处理点击事件，例如显示弹窗
        handleFeatureClick(features[0], events.click);
      }
    });
  }

  // 悬停事件处理
  if (events.hover) {
    mapChart.value.on('pointermove', (event) => {
      const features = mapChart.value.getFeaturesAtPixel(event.pixel);
      if (features && features.length > 0) {
        // 处理悬停事件，例如高亮显示
        handleFeatureHover(features[0], events.hover);
      }
    });
  }
};

// 处理要素点击事件
const handleFeatureClick = (feature, clickConfig) => {
  if (clickConfig.action === 'popup') {
    // 显示弹窗逻辑
    showFeaturePopup(feature, clickConfig.popupConfig);
  }
};

// 处理要素悬停事件
const handleFeatureHover = (feature, hoverConfig) => {
  if (hoverConfig.action === 'highlight') {
    // 高亮显示逻辑
    highlightFeature(feature);
  }
};

// 显示要素弹窗
const showFeaturePopup = (feature, popupConfig) => {
  // 清除已存在的弹窗
  clearPopups();

  const properties = feature.getProperties();
  const geometry = feature.getGeometry();
  const coordinates = geometry.getCoordinates();
  let center = coordinates

  if (isArray(coordinates)) {
    const extent = geometry.getExtent()
    center = getCenter(extent); // 计算包围盒的中心点坐标
  }

  // 创建弹窗元素
  const popupElement = document.createElement('div');
  popupElement.className = 'feature-popup';
  // 根据配置生成弹窗内容
  if (popupConfig && popupConfig.template) {
    popupElement.innerHTML = getPopupContentByTemplate(popupConfig.template, properties, popupElement);
  } else {
    // 生成默认弹窗内容
    let content = `
      <div class="popup-header">
        <h3>${properties.name || properties['测站名称'] || '未知站点'}</h3>
        <button class="popup-close" onclick="closePopup()">×</button>
      </div>
      <div class="popup-content">
        <div class="popup-info">
    `;
    // 添加属性信息
    Object.keys(properties).forEach(key => {
      if (key !== 'geometry' && key !== 'name' && key !== 'stationName') {
        content += `<div class="info-item"><span class="label">${key}:</span><span class="value">${properties[key]}</span></div>`;
      }
    });
    content += `
        </div>
      </div>
    `;
    popupElement.innerHTML = content;
  }

  // 添加关闭按钮事件监听
  const closeBtn = popupElement.querySelector('.popup-close');
  if (closeBtn) {
    closeBtn.onclick = () => {
      clearPopups();
    };
  }

  let popupOverlay = new Overlay({
    element: popupElement,
    positioning: popupConfig?.positioning || "bottom-center",
    stopEvent: popupConfig?.stopEvent !== undefined ? popupConfig.stopEvent : true,
    offset: popupConfig?.offset || [0, -10],
    autoPan: true
  });

  popupOverlay.setPosition(center);
  mapChart.value.addOverlay(popupOverlay);
  popupOverlays.value.push(popupOverlay);

  if (popupConfig && popupConfig.template) {
    loadPopupChartByTemplate(popupConfig.template, properties);
  }
};

// 高亮要素
const highlightFeature = (feature) => {
  // 获取要素的原始样式
  const originalStyle = feature.get('originalStyle') || feature.getStyle();

  // 保存原始样式以便恢复
  feature.set('originalStyle', originalStyle);

  // 创建高亮样式
  const highlightStyle = createDynamicStyle({
    fill: {
      color: 'rgba(255, 255, 0, 0.8)'  // 黄色填充
    },
    stroke: {
      color: '#ff0000',  // 红色边框
      width: 3
    },
    circle: {
      radius: 8,
      fill: {
        color: 'rgba(255, 255, 0, 0.8)'
      },
      stroke: {
        color: '#ff0000',
        width: 3
      }
    }
  });

  // 应用高亮样式
  feature.setStyle(highlightStyle);
};

let timerId = null

// 聚焦
function highlightPoint(center) {
  // 先清除已存在的高亮图层
  const existingHighlightOverlay = mapChart.value.getOverlays().getArray().find(ov => ov['id'] === 'highlight-point');
  if (existingHighlightOverlay) {
    mapChart.value.removeOverlay(existingHighlightOverlay);
    if (timerId) {
      clearTimeout(timerId);
    }
  }

  // 创建 Overlay 并绑定元素
  const overlayElement = document.createElement('div');
  overlayElement.className = 'highlight-point-overlay';

  const overlay = new Overlay({
    id: 'highlight-point',
    element: overlayElement,
    position: center,
    stopEvent: false,
    zIndex: 1000,
    offset: [-16, -18],
  });

  mapChart.value.addOverlay(overlay);

  // 3秒后删掉 - 改进的删除方式
  timerId = setTimeout(() => {
    if (mapChart.value) {
      try {
        const overlayToRemove = mapChart.value.getOverlays().getArray().find(ov => ov['id'] === 'highlight-point');
        if (overlayToRemove) {
          mapChart.value.removeOverlay(overlayToRemove);
        }
      } catch (error) {
        console.warn('删除高亮Overlay时出错:', error);
      }
    }
  }, 3000)
}


// 清除所有弹窗
const clearPopups = () => {
  popupOverlays.value.forEach(overlay => {
    mapChart.value.removeOverlay(overlay);
  });
  popupOverlays.value = [];
};

// 跳转到新中心点
function toCenter(center, zoom, duration = 500, highlight) {
  if (center && center.length >= 2) {
    mapChart.value.getView().animate({
      center: center,
      zoom: zoom ? zoom : mapChart.value.getView().getZoom(),
      duration: duration,
    });

    if (highlight) {
      highlightPoint(center);
    }
  }
}

async function loadLayers(layers) {
  for (const layer of layers) {
    switch (layer.type) {
      case 'vector':
        await addVectorLayer(layer)
    }
  }
}

bus.on('show-map-position', ({latitude, longitude}) => {
  toCenter([longitude, latitude], null, 1500, true)
})

// 实时更新地图
watch(() => props.config, async (config) => {
  if (config) {
    // 渲染配置
    // 1. 跳转中心点
    toCenter(config.center, config.zoom);
    // 渲染图层
    await loadLayers(config.layers);
  }
}, {deep: true});
</script>
<style scoped lang="scss">
.biz-data-card-header {
  width: 100%;
  height: 36px;
  background: url("@/assets/map/img/left-title.png") no-repeat;
  background-size: 100% 100%;
  font-size: 16px;
  font-family: 'PuHuiTi', sans-serif;
  font-weight: bolder;
  color: #fff;
  text-align: center;
  line-height: 34px;
}

/*滚动条里面轨道*/
::-webkit-scrollbar-track {
  background-color: rgba(20, 19, 19, 0);
}

/*关键设置 tbody出现滚动条*/
::-webkit-scrollbar-thumb {
  background-color: rgba(58, 100, 179, 0.5);
  border-radius: 8px 10px;
}

::v-deep(.el-scrollbar) {
  --el-scrollbar-bg-color: rgba(58, 100, 179);
  --el-scrollbar-hover-bg-color: rgba(58, 100, 179);
}

.map-index {
  height: 100%;
  width: 100%;
  position: relative;

  #mapChart {
    height: 100%;
    width: 100%;
  }

}
</style>
<style lang="scss">
.custom-popup {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  border: 1px solid #3498db;
  width: 172px;

  .popup-title {
    width: 100%;
    line-height: 15px;
    background-color: rgba(255, 23, 0);
    padding: 10px;
    text-align: center;
    color: #fff;
    font-size: 16px;
  }

  .popup-top {
    padding: 5px 10px;
    width: 100%;
    background-color: rgba(58, 100, 179);
    display: flex;
    flex-direction: column;
    color: #fff;
    font-size: 14px;
  }

  .popup-bottom {
    padding: 5px 10px;
    width: 100%;
    background-color: rgba(71, 146, 211);
    display: flex;
    flex-direction: column;
    color: #fff;
    font-size: 14px;
  }
}

.feature-popup {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  border: 1px solid #3498db;
  width: 250px;
  font-family: Arial, sans-serif;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: rgba(58, 100, 179);
    padding: 10px;
    border-radius: 8px 8px 0 0;

    h3 {
      margin: 0;
      color: white;
      font-size: 14px;
    }

    .popup-close {
      background: none;
      border: none;
      color: white;
      font-size: 18px;
      cursor: pointer;
    }
  }

  .popup-content {
    padding: 10px;
  }

  .popup-info {
    .info-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 5px;
      font-size: 12px;

      .label {
        font-weight: bold;
        color: #333;
      }

      .value {
        color: #666;
      }
    }
  }

  .popup-chart {
    border-top: 1px solid #eee;
    padding-top: 10px;

    canvas {
      width: 100%;
    }
  }
}

.highlight-point-overlay {
  width: 32px;
  height: 32px;
  background-image: url('@/assets/map/img/dyCenter.gif');
  background-size: contain;
  background-repeat: no-repeat;
}
</style>
<style scoped>
.horizontal-timeline-container {
  width: 100%;
  overflow-x: auto; /* 允许横向滚动 */
  padding: 20px 0;
}

.horizontal-timeline {
  display: flex;
  min-width: 800px; /* 根据时间轴项的数量调整最小宽度 */
  padding: 50px; /* 增加内边距 */
}

.timeline-item {
  flex: 1; /* 每个项平均分配宽度 */
  position: relative;
  min-width: 200px; /* 每个项的最小宽度 */
}

.content-wrapper {
  display: flex;
  flex-direction: column;
  text-align: center;
  padding: 0 10px;
}

.content-title {
  font-size: 16px;
  margin: 10px 0;
}

.content-people {
  color: #8c8c8c;
  font-size: 14px;
}

/* 使用 :deep() 穿透修改 Element Plus 组件内部样式 */
:deep(.horizontal-timeline .el-timeline-item) {
  flex: 1;
  position: relative;
}

:deep(.horizontal-timeline .el-timeline-item__tail) {
  border-left: none;
  border-top: 2px solid #e4e7ed;
  width: 100%;
  position: absolute;
  top: 12px;
  left: 0;
}

:deep(.horizontal-timeline .el-timeline-item__node) {
  position: absolute;
  top: 6px;
  left: 50%;
  transform: translateX(-50%);
}

:deep(.horizontal-timeline .el-timeline-item__wrapper) {
  padding-left: 0;
  position: absolute;
  top: 30px;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  width: 100%;
}

/* 激活状态样式 */
.active :deep(.el-timeline-item__node) {
  background-color: #409EFF; /* 使用 Element Plus 主色 */
}

.active :deep(.el-timeline-item__tail) {
  border-color: #409EFF;
}

.tooltip {
  position: absolute;
  background: #409EFF;
  color: white;
  padding: 8px 12px;
  border-radius: 4px;
  width: 100px;
  font-size: 12px;
  pointer-events: none;
  display: none; /* 初始隐藏 */
  box-shadow: 0 2px 4px #409EFF;
  max-width: 200px;
  z-index: 1000;
}

.tooltip-header {
  font-weight: bold;
  margin-bottom: 4px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  padding-bottom: 2px;
}

.tooltip-content {
  font-size: 11px;
  opacity: 0.9;
}
</style>