<template>
  <div class="map-wrapper">
    <div id="map" ref="mapContainer" class="map-container"></div>

    <div class="legend-panel">
      <Legend :legendData="legendItems" />

      <IndicatorSelector
        :indicators="Object.keys(indicatorData)"
        v-model="selectedIndicator"
      />

      <!-- 返回按钮 -->
      <button
        v-if="currentLevel === 'street'"
        class="back-btn"
        @click="backToDistrict"
      >
        返回区级
      </button>
    </div>
  </div>
  <PlotPopup
  :visible="popupVisible"
  :data="popupData"
  :position="popupPos"
  @enter-sample="showSamples"
  @enter-side="showSideTrees"
/>
<SamplePopup
  :visible="samplePopupVisible"
  :data="samplePopupData"
  :position="samplePopupPos"
/>

</template>

<script setup>
import { onMounted, onBeforeUnmount, ref, watch } from "vue";
import maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import { TDT_KEY } from "../assets/tdt_key.js";
import IndicatorSelector from "./IndicatorSelector.vue";
import Legend from "./Legend.vue";
import { plotGeoJSON, samplePlots, sideTrees } from "../assets/mockPlotData.js";
import PlotPopup from "./PlotPopup.vue";
import SamplePopup from "./SamplePopup.vue";
import bbox from "@turf/bbox";

const popupVisible = ref(false);
const popupData = ref({});
const popupPos = ref({ x: 0, y: 0 });

// 天津市行政区划数据（区级）
const districtUrl =
  "https://geo.datav.aliyun.com/areas_v3/bound/120000_full.json";

// 区级与街道级指标（模拟数据）
const indicatorData = {
  完成状态: {
    和平区: "已完成",
    河东区: "未完成",
    河西区: "已完成",
    南开区: "未开始",
    河北区: "未完成",
    红桥区: "已完成",
    滨海新区: "未完成",
  },
  图斑面积: {
    和平区: 230,
    河东区: 340,
    河西区: 410,
    南开区: 300,
    河北区: 500,
    红桥区: 270,
    滨海新区: 1200,
  },
  图斑数量: {
    和平区: 45,
    河东区: 80,
    河西区: 70,
    南开区: 60,
    河北区: 85,
    红桥区: 50,
    滨海新区: 150,
  },
};

// 模拟街道级指标（真实项目应从接口获取）
const streetIndicatorData = {
  完成状态: {
    光复道街道: "已完成",
    建昌道街道: "未完成",
    王串场街道: "未开始",
  },
  图斑面积: {
    光复道街道: 200,
    建昌道街道: 350,
    王串场街道: 120,
  },
  图斑数量: {
    光复道街道: 40,
    建昌道街道: 55,
    王串场街道: 30,
  },
};

// 状态管理
const selectedIndicator = ref("完成状态");
const currentLevel = ref("district"); // 当前层级
const currentDistrict = ref(""); // 当前区名

const mapContainer = ref(null);
let map = null;
const legendItems = ref([]);
let allStreetsData = null;

// 加载街道
async function loadAllStreets() {
  if (!allStreetsData) {
    const res = await fetch("/data/tianjin_street.geojson");
    allStreetsData = await res.json();
  }
}

// 定义点击区级多边形的处理函数
async function handleDistrictClick(e) {
  const districtName = e.features[0].properties.name;
  showStreetLevel(districtName);
}

// 定义点击空白返回的处理函数
function handleMapClick(e) {
  const queryLayers = ["tianjin-fill"];
  if (map.getLayer("street-fill")) queryLayers.push("street-fill");

  const features = map.queryRenderedFeatures(e.point, {
    layers: queryLayers,
  });
  if (!features.length && currentLevel.value === "street") {
    backToDistrict();
  }
}

// 初始化地图
onMounted(async () => {
  map = new maplibregl.Map({
    container: mapContainer.value,
    style: {
      version: 8,
      sources: {
        tdt_vec: {
          type: "raster",
          tiles: Array.from(
            { length: 8 },
            (_, i) =>
              `https://t${i}.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=${TDT_KEY}`
          ),
          tileSize: 256,
        },
        tdt_cva: {
          type: "raster",
          tiles: Array.from(
            { length: 8 },
            (_, i) =>
              `https://t${i}.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=${TDT_KEY}`
          ),
          tileSize: 256,
        },
      },
      layers: [
        { id: "tdt_vec", type: "raster", source: "tdt_vec" },
        { id: "tdt_cva", type: "raster", source: "tdt_cva" },
      ],
    },
    center: [117.2, 39.13],
    zoom: 8,
  });

  const res = await fetch(districtUrl);
  const geojson = await res.json();

  map.on("load", () => {
    map.addSource("tianjin", { type: "geojson", data: geojson });

    map.addLayer({
      id: "tianjin-fill",
      type: "fill",
      source: "tianjin",
      paint: { "fill-color": ["get", "color"], "fill-opacity": 0.6 },
    });

    map.addLayer({
      id: "tianjin-outline",
      type: "line",
      source: "tianjin",
      paint: { "line-color": "#333", "line-width": 1 },
    });

    updateMapColors();

    // 点击区多边形，下钻街道级
    map.off("click", "tianjin-fill", handleDistrictClick);
    map.on("click", "tianjin-fill", handleDistrictClick);
    // 点击空白返回
    map.off("click", handleMapClick);
    map.on("click", handleMapClick);
  });

  // 缩放监听：14级以上显示图斑
  map.on("zoom", () => {
    const zoom = map.getZoom();
    if (zoom >= 14) {
      showPlotLayer();
    } else {
      hidePlotLayer();
    }
  });
});

// 更新地图着色
function updateMapColors(level = currentLevel.value) {
  const sourceId = level === "district" ? "tianjin" : "street";
  const data = map.getSource(sourceId)?._data;
  if (!data) return;

  const indicator = level === "district" ? indicatorData : streetIndicatorData;
  const selected = selectedIndicator.value;

  if (selected === "完成状态") {
    const colors = { 已完成: "#4CAF50", 未完成: "#FFC107", 未开始: "#BDBDBD" };
    data.features.forEach((f) => {
      const name = f.properties.name;
      const val = indicator[selected][name];
      f.properties.color = colors[val] || "#ccc";
    });
    map.getSource(sourceId).setData(data);
    legendItems.value = Object.entries(colors).map(([k, v]) => ({
      color: v,
      range: k,
    }));
  } else {
    const values = Object.values(indicator[selected]);
    const min = Math.min(...values);
    const max = Math.max(...values);
    const colors = ["#f2f0f7", "#cbc9e2", "#9e9ac8", "#756bb1", "#54278f"];
    const getColor = (v) =>
      colors[Math.floor(((v - min) / (max - min)) * (colors.length - 1))];
    data.features.forEach((f) => {
      const name = f.properties.name;
      const v = indicator[selected][name];
      f.properties.color = v ? getColor(v) : "#ccc";
    });
    map.getSource(sourceId).setData(data);
    legendItems.value = colors.map((c, i) => {
      const start = min + (i / colors.length) * (max - min);
      const end = min + ((i + 1) / colors.length) * (max - min);
      return { color: c, range: `${start.toFixed(1)} - ${end.toFixed(1)}` };
    });
  }
}

// 下钻显示街道级
async function showStreetLevel(districtName) {
  await loadAllStreets();

  // ✅ 筛选出该区所有街道
  const filteredFeatures = allStreetsData.features.filter(
    (f) => f.properties.县 === districtName
  );

  if (filteredFeatures.length === 0) {
    alert(`区【${districtName}】没有找到街道数据`);
    return;
  }

  // ✅ 构建新的 GeoJSON（只包含这个区的街道）
  const streetGeo = {
    type: "FeatureCollection",
    features: filteredFeatures,
  };

  // ✅ 清除旧图层
  if (map.getSource("street")) {
    map.removeLayer("street-fill");
    map.removeLayer("street-outline");
    map.removeSource("street");
  }

  // ✅ 添加新的街道层
  map.addSource("street", {
    type: "geojson",
    data: streetGeo,
  });

  map.addLayer({
    id: "street-fill",
    type: "fill",
    source: "street",
    paint: {
      "fill-color": ["get", "color"], // 根据指标设色
      "fill-opacity": 0.65,
    },
  });

  map.addLayer({
    id: "street-outline",
    type: "line",
    source: "street",
    paint: { "line-width": 1, "line-color": "#333" },
  });

  currentLevel.value = "street";
  currentDistrict.value = districtName;

  updateMapColors("street");

  // ✅ 隐藏区级图层
  if (map.getLayer("tianjin-fill"))
    map.setLayoutProperty("tianjin-fill", "visibility", "none");

  if (map.getLayer("tianjin-outline"))
    map.setLayoutProperty("tianjin-outline", "visibility", "none");

  // ✅ 自动缩放到该区所有街道范围
  const extent = bbox(streetGeo); // [minX, minY, maxX, maxY]

  map.fitBounds(
    [
      [extent[0], extent[1]],
      [extent[2], extent[3]],
    ],
    {
      padding: 40,
      duration: 800,
    }
  );
}

// 返回区级图层
function backToDistrict() {
  if (map.getLayer("street-fill")) {
    map.removeLayer("street-fill");
    map.removeLayer("street-outline");
    map.removeSource("street");
  }
  map.setLayoutProperty("tianjin-fill", "visibility", "visible");
  map.setLayoutProperty("tianjin-outline", "visibility", "visible");
  currentLevel.value = "district";
  map.flyTo({ center: [117.2, 39.13], zoom: 8 });
  updateMapColors("district");
}

// 点击图斑显示弹窗
function handlePlotClick(e) {
  const feature = e.features[0];
  let prop = feature.properties;

  // --- 解析属性 ---
  let images = prop.images;
  let videos = prop.videos;

  if (typeof images === "string") {
    try {
      images = JSON.parse(images);
    } catch {
      images = [];
    }
  }
  if (typeof videos === "string") {
    try {
      videos = JSON.parse(videos);
    } catch {
      videos = [];
    }
  }

  // 计算屏幕像素位置
  const canvas = map.getCanvas().getBoundingClientRect();
  const pos = map.project(e.lngLat);
  popupPos.value = {
    x: pos.x + canvas.left,
    y: pos.y + canvas.top,
  };

  popupData.value = { ...prop, images, videos };
  popupVisible.value = true;
}

// 点击空白关闭弹窗
function handleMapClickClosePopup(e) {
  const features = map.queryRenderedFeatures(e.point, {
    layers: ["plot-fill"],
  });
  if (!features.length) popupVisible.value = false;
}

// === 图斑层控制 ===
function showPlotLayer() {
  // 已存在则直接显示
  if (map.getLayer("plot-fill")) {
    map.setLayoutProperty("plot-fill", "visibility", "visible");
    map.setLayoutProperty("plot-outline", "visibility", "visible");
  } else {
    map.addSource("plot", { type: "geojson", data: plotGeoJSON });

    const typeColors = {
      乔木林: "#4CAF50",
      灌木林: "#8BC34A",
      草地: "#CDDC39",
    };

    map.addLayer({
      id: "plot-fill",
      type: "fill",
      source: "plot",
      paint: {
        "fill-color": [
          "match",
          ["get", "type"],
          "乔木林",
          typeColors["乔木林"],
          "灌木林",
          typeColors["灌木林"],
          "草地",
          typeColors["草地"],
          "#ccc",
        ],
        "fill-opacity": 0.7,
      },
    });

    map.addLayer({
      id: "plot-outline",
      type: "line",
      source: "plot",
      paint: { "line-color": "#333", "line-width": 1 },
    });
  }

  // 隐藏行政区划与街道层
  if (map.getLayer("tianjin-fill"))
    map.setLayoutProperty("tianjin-fill", "visibility", "none");
  if (map.getLayer("tianjin-outline"))
    map.setLayoutProperty("tianjin-outline", "visibility", "none");
  if (map.getLayer("street-fill"))
    map.setLayoutProperty("street-fill", "visibility", "none");
  if (map.getLayer("street-outline"))
    map.setLayoutProperty("street-outline", "visibility", "none");

  // 更新图例为图斑类型
  legendItems.value = [
    { color: "#4CAF50", range: "乔木林" },
    { color: "#8BC34A", range: "灌木林" },
    { color: "#CDDC39", range: "草地" },
  ];

  // === 小班点击事件 ===
  map.off("click", "plot-fill", handlePlotClick);
  map.off("click", handleMapClickClosePopup);

  map.on("click", "plot-fill", handlePlotClick);
  map.on("click", handleMapClickClosePopup);
}

// === 显示样地 ===
// === 显示样地（Polygon） ===
function showSamples() {
  // 如果之前存在，则移除旧图层和数据源
  if (map.getLayer("samples-fill")) map.removeLayer("samples-fill");
  if (map.getLayer("samples-outline")) map.removeLayer("samples-outline");
  if (map.getSource("samples")) map.removeSource("samples");

  // 添加样地数据源
  map.addSource("samples", {
    type: "geojson",
    data: samplePlots, // ✅ 样地 Polygon 数据
  });

  // 添加填充图层（样地面）
  map.addLayer({
    id: "samples-fill",
    type: "fill",
    source: "samples",
    paint: {
      "fill-color": "#1976d2",
      "fill-opacity": 0.5,
    },
  });

  // 添加轮廓线图层（边界线）
  map.addLayer({
    id: "samples-outline",
    type: "line",
    source: "samples",
    paint: {
      "line-color": "#0d47a1",
      "line-width": 2,
    },
  });

  map.off("click", "samples-fill", handleSampleClick);
  map.on("click", "samples-fill", handleSampleClick);

  map.off("click", handleCloseSamplePopup);
  map.on("click", handleCloseSamplePopup);
}

// === 显示四旁树 ===
function showSideTrees() {
  if (map.getSource("sideTrees")) map.removeSource("sideTrees");
  if (map.getLayer("sideTrees")) map.removeLayer("sideTrees");

  map.addSource("sideTrees", { type: "geojson", data: sideTrees });
  map.addLayer({
    id: "sideTrees",
    type: "circle",
    source: "sideTrees",
    paint: { "circle-radius": 6, "circle-color": "#388e3c" },
  });
}

function hidePlotLayer() {
  // 隐藏图斑层
  if (map.getLayer("plot-fill")) {
    map.setLayoutProperty("plot-fill", "visibility", "none");
    map.setLayoutProperty("plot-outline", "visibility", "none");
    map.setLayoutProperty("samples-fill", "visibility", "none");
    map.setLayoutProperty("samples-outline", "visibility", "none");
    map.setLayoutProperty("sideTrees", "visibility", "none");
  }

  // 恢复行政区划或街道层显示
  if (currentLevel.value === "district") {
    map.setLayoutProperty("tianjin-fill", "visibility", "visible");
    map.setLayoutProperty("tianjin-outline", "visibility", "visible");
  } else if (currentLevel.value === "street") {
    map.setLayoutProperty("street-fill", "visibility", "visible");
    map.setLayoutProperty("street-outline", "visibility", "visible");
  }

  // 恢复行政区划/街道的图例
  updateMapColors(currentLevel.value);
}

// === 样地弹窗状态 ===
const samplePopupVisible = ref(false);
const samplePopupData = ref({});
const samplePopupPos = ref({ x: 0, y: 0 });

// === 样地点击事件 ===
function handleSampleClick(e) {
  const feature = e.features[0];
  let prop = feature.properties;

  // 模拟解析样地属性
  let images = JSON.parse(prop.images || "[]");
  let videos = JSON.parse(prop.videos || "[]");
  let trees = JSON.parse(prop.trees || "[]");

  const canvas = map.getCanvas().getBoundingClientRect();
  const pos = map.project(e.lngLat);
  samplePopupPos.value = { x: pos.x + canvas.left, y: pos.y + canvas.top };

  samplePopupData.value = { ...prop, images, videos, trees };
  samplePopupVisible.value = true;
}

// 点击空白关闭样地弹窗
function handleCloseSamplePopup(e) {
  const features = map.queryRenderedFeatures(e.point, {
    layers: ["samples-fill"],
  });
  if (!features.length) samplePopupVisible.value = false;
}

// 监听指标变化
watch(selectedIndicator, () => updateMapColors());

// 页面卸载时销毁地图，释放 WebGL 上下文
onBeforeUnmount(() => {
  if (map) {
    map.off("click", "tianjin-fill", handleDistrictClick);
    map.off("click", handleMapClick);
    map.off("click", "plot-fill", handlePlotClick);
    map.off("click", handleMapClickClosePopup);
    map.remove();
    map = null;
  }
});
</script>

<style scoped>
.html,
body,
#app,
.map-wrapper,
.map-container {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.map-wrapper {
  position: relative;
}

.map-container {
  width: 100%;
  height: 100%;
}
.legend-panel {
  position: absolute;
  right: 20px;
  bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.legend-panel > * {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  padding: 8px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}

.back-btn {
  border: none;
  background: #1976d2;
  color: white;
  border-radius: 6px;
  padding: 6px 10px;
  cursor: pointer;
}
.back-btn:hover {
  background: #1565c0;
}
</style>
