import { defineComponent, ref, inject, computed, shallowRef, reactive, watch, nextTick, onMounted, onUnmounted, resolveComponent, openBlock, createElementBlock, createVNode, unref, withCtx, createElementVNode, Fragment, renderList, createBlock, createCommentVNode } from "vue";
import { k as layerFactory, i as getUid, m as defaults, X, n as TileLayer, I as ImageLayer, V as VectorTileLayer, H as HeatmapLayer, o as VectorLayer, L as LayerGroup, b as _export_sfc } from "./index-e8d5fc75.mjs";
import { u as useMap } from "./useMap-8e3a2de5.mjs";
import { View, Map } from "ol";
import "@element-plus/icons-vue";
import "proj4";
import "@supermapgis/iclient-ol";
import "element-plus";
const _hoisted_1 = {
  key: 0,
  class: "quad-compare-dialog"
};
const _hoisted_2 = { class: "quad-content" };
const _hoisted_3 = { class: "map-row" };
const _hoisted_4 = { class: "map-container map-1" };
const _hoisted_5 = { class: "map-control" };
const _hoisted_6 = { class: "map-container map-2" };
const _hoisted_7 = { class: "map-control" };
const _hoisted_8 = { class: "map-row" };
const _hoisted_9 = { class: "map-container map-3" };
const _hoisted_10 = { class: "map-control" };
const _hoisted_11 = { class: "map-container map-4" };
const _hoisted_12 = { class: "map-control" };
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "QuadCompareDialog",
  props: {
    modelValue: { type: Boolean, default: false }
  },
  emits: ["update:modelValue", "close"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emit = __emit;
    const visible = ref(props.modelValue);
    const map = useMap();
    const mapManager = inject("mapManager");
    const layerManager = computed(
      () => {
        var _a;
        return ((_a = mapManager == null ? void 0 : mapManager.value) == null ? void 0 : _a.getLayerManager()) || null;
      }
    );
    const map1Target = ref(null);
    const map2Target = ref(null);
    const map3Target = ref(null);
    const map4Target = ref(null);
    const maps = [
      shallowRef(null),
      shallowRef(null),
      shallowRef(null),
      shallowRef(null)
    ];
    const layerIds = reactive(["", "", "", ""]);
    const layerOptions = ref([]);
    watch(
      () => props.modelValue,
      (val) => {
        visible.value = val;
        if (val) {
          nextTick(() => {
            initMaps();
          });
        } else {
          disposeMaps();
        }
      }
    );
    watch(visible, (val) => {
      emit("update:modelValue", val);
      if (!val) {
        disposeMaps();
      }
    });
    const cloneLayer = (originalLayer) => {
      let newLayer;
      const source = originalLayer.getSource();
      const options = {
        source,
        visible: originalLayer.getVisible(),
        opacity: originalLayer.getOpacity(),
        zIndex: originalLayer.getZIndex(),
        minResolution: originalLayer.getMinResolution(),
        maxResolution: originalLayer.getMaxResolution(),
        extent: originalLayer.getExtent()
      };
      if (originalLayer instanceof TileLayer) {
        newLayer = new TileLayer(options);
      } else if (originalLayer instanceof ImageLayer) {
        newLayer = new ImageLayer(options);
      } else if (originalLayer instanceof VectorTileLayer) {
        newLayer = new VectorTileLayer({
          ...options,
          style: originalLayer.getStyle()
        });
      } else if (originalLayer instanceof HeatmapLayer) {
        newLayer = new HeatmapLayer({
          ...options,
          blur: originalLayer.getBlur(),
          radius: originalLayer.getRadius(),
          gradient: originalLayer.getGradient()
        });
      } else if (originalLayer instanceof VectorLayer) {
        newLayer = new VectorLayer({
          ...options,
          style: originalLayer.getStyle()
        });
      } else {
        try {
          const Ctor = originalLayer.constructor;
          newLayer = new Ctor(options);
        } catch (e) {
          newLayer = new TileLayer(options);
        }
      }
      newLayer.set("id", getUid(originalLayer).toString());
      newLayer.set("title", originalLayer.get("title"));
      return newLayer;
    };
    const getAllLayers = (layers) => {
      let all = [];
      layers.forEach((layer) => {
        if (layer instanceof LayerGroup) {
          all = all.concat(getAllLayers(layer.getLayers().getArray()));
        } else {
          all.push(layer);
        }
      });
      return all;
    };
    const initMaps = async () => {
      if (!map.value)
        return;
      const targets = [
        map1Target.value,
        map2Target.value,
        map3Target.value,
        map4Target.value
      ];
      if (targets.some((t) => !t))
        return;
      const originalView = map.value.getView();
      const sharedView = new View({
        center: originalView.getCenter(),
        zoom: originalView.getZoom(),
        projection: originalView.getProjection(),
        rotation: originalView.getRotation()
      });
      const allLayers = [];
      const processedLayerIds = /* @__PURE__ */ new Set();
      if (layerManager.value) {
        const configs = layerManager.value.getAllLayerConfigs();
        const leafConfigs = configs.filter((c) => c.type !== "group");
        const currentMapLayers2 = getAllLayers(map.value.getLayers().getArray());
        for (const config of leafConfigs) {
          if (processedLayerIds.has(config.id))
            continue;
          if (!config.isCompare)
            continue;
          const existingLayer = currentMapLayers2.find(
            (l) => l.get("layerId") === config.id || l.get("id") === config.id
          );
          if (existingLayer) {
            allLayers.push(existingLayer);
          } else {
            try {
              const handler = layerFactory.createLayerHandler(config);
              const newLayer = await handler.createLayer();
              if (newLayer) {
                newLayer.set("id", config.id);
                newLayer.set("layerId", config.id);
                newLayer.set(
                  "title",
                  config.name || config.label || `图层 ${config.id}`
                );
                allLayers.push(newLayer);
              }
            } catch (e) {
              console.warn(
                `QuadCompareDialog: Failed to create layer from config ${config.id}`,
                e
              );
            }
          }
          processedLayerIds.add(config.id);
        }
      }
      const currentMapLayers = getAllLayers(map.value.getLayers().getArray());
      currentMapLayers.forEach((layer) => {
        const layerId = layer.get("layerId") || layer.get("id");
        const isCompare = layer.get("isCompare");
        if ((!layerId || !processedLayerIds.has(layerId)) && isCompare === true) {
          allLayers.push(layer);
          if (layerId)
            processedLayerIds.add(layerId);
        }
      });
      console.log(
        "QuadCompareDialog: Unified layers:",
        allLayers.length,
        allLayers
      );
      const options = [];
      allLayers.forEach((layer) => {
        const id = layer.get("id") || layer.get("layerId") || getUid(layer).toString();
        const title = layer.get("title") || layer.get("name") || `图层 ${id}`;
        options.push({ id, title, originalLayer: layer });
      });
      layerOptions.value = options;
      targets.forEach((target, index) => {
        const mapLayers = [];
        allLayers.forEach((layer) => {
          const cloned = cloneLayer(layer);
          const id = layer.get("id") || layer.get("layerId") || getUid(layer).toString();
          cloned.set("id", id);
          cloned.setVisible(layer.getVisible());
          mapLayers.push(cloned);
        });
        maps[index].value = new Map({
          target,
          layers: mapLayers,
          view: sharedView,
          controls: defaults({ zoom: false, attribution: false })
        });
      });
      for (let i = 0; i < 4; i++) {
        if (options.length > i) {
          if (!layerIds[i])
            layerIds[i] = options[i].id;
        } else if (options.length > 0) {
          if (!layerIds[i])
            layerIds[i] = options[i % options.length].id;
        }
      }
      updateVisibility();
    };
    const updateVisibility = () => {
      maps.forEach((mapRef, index) => {
        const mapInstance = mapRef.value;
        if (!mapInstance)
          return;
        const selectedId = layerIds[index];
        mapInstance.getLayers().forEach((layer) => {
          var _a;
          const id = layer.get("id");
          const originalVisible = (_a = layerOptions.value.find((o) => o.id === id)) == null ? void 0 : _a.originalLayer.getVisible();
          if (id === selectedId) {
            layer.setVisible(true);
          } else {
            layer.setVisible(originalVisible);
          }
        });
      });
    };
    const disposeMaps = () => {
      maps.forEach((mapRef) => {
        if (mapRef.value) {
          mapRef.value.setTarget(void 0);
          mapRef.value = null;
        }
      });
    };
    const handleClose = () => {
      emit("close");
    };
    onMounted(() => {
      if (visible.value) {
        nextTick(() => {
          initMaps();
        });
      }
    });
    onUnmounted(() => {
      disposeMaps();
    });
    return (_ctx, _cache) => {
      const _component_el_option = resolveComponent("el-option");
      const _component_el_select = resolveComponent("el-select");
      return visible.value ? (openBlock(), createElementBlock("div", _hoisted_1, [
        createVNode(unref(X), {
          modelValue: visible.value,
          "onUpdate:modelValue": _cache[4] || (_cache[4] = ($event) => visible.value = $event),
          title: "四屏对比",
          width: "90vw",
          top: "5vh",
          "close-on-click-modal": false,
          onClose: handleClose
        }, {
          default: withCtx(() => [
            createElementVNode("div", _hoisted_2, [
              createElementVNode("div", _hoisted_3, [
                createElementVNode("div", _hoisted_4, [
                  createElementVNode("div", {
                    ref_key: "map1Target",
                    ref: map1Target,
                    class: "map-target"
                  }, null, 512),
                  createElementVNode("div", _hoisted_5, [
                    createVNode(_component_el_select, {
                      modelValue: layerIds[0],
                      "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => layerIds[0] = $event),
                      placeholder: "图层1",
                      size: "small",
                      onChange: updateVisibility,
                      style: { "width": "180px" }
                    }, {
                      default: withCtx(() => [
                        (openBlock(true), createElementBlock(Fragment, null, renderList(layerOptions.value, (layer) => {
                          return openBlock(), createBlock(_component_el_option, {
                            key: layer.id,
                            label: layer.title,
                            value: layer.id
                          }, null, 8, ["label", "value"]);
                        }), 128))
                      ]),
                      _: 1
                    }, 8, ["modelValue"])
                  ])
                ]),
                createElementVNode("div", _hoisted_6, [
                  createElementVNode("div", {
                    ref_key: "map2Target",
                    ref: map2Target,
                    class: "map-target"
                  }, null, 512),
                  createElementVNode("div", _hoisted_7, [
                    createVNode(_component_el_select, {
                      modelValue: layerIds[1],
                      "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => layerIds[1] = $event),
                      placeholder: "图层2",
                      size: "small",
                      onChange: updateVisibility,
                      style: { "width": "180px" }
                    }, {
                      default: withCtx(() => [
                        (openBlock(true), createElementBlock(Fragment, null, renderList(layerOptions.value, (layer) => {
                          return openBlock(), createBlock(_component_el_option, {
                            key: layer.id,
                            label: layer.title,
                            value: layer.id
                          }, null, 8, ["label", "value"]);
                        }), 128))
                      ]),
                      _: 1
                    }, 8, ["modelValue"])
                  ])
                ])
              ]),
              createElementVNode("div", _hoisted_8, [
                createElementVNode("div", _hoisted_9, [
                  createElementVNode("div", {
                    ref_key: "map3Target",
                    ref: map3Target,
                    class: "map-target"
                  }, null, 512),
                  createElementVNode("div", _hoisted_10, [
                    createVNode(_component_el_select, {
                      modelValue: layerIds[2],
                      "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => layerIds[2] = $event),
                      placeholder: "图层3",
                      size: "small",
                      onChange: updateVisibility,
                      style: { "width": "180px" }
                    }, {
                      default: withCtx(() => [
                        (openBlock(true), createElementBlock(Fragment, null, renderList(layerOptions.value, (layer) => {
                          return openBlock(), createBlock(_component_el_option, {
                            key: layer.id,
                            label: layer.title,
                            value: layer.id
                          }, null, 8, ["label", "value"]);
                        }), 128))
                      ]),
                      _: 1
                    }, 8, ["modelValue"])
                  ])
                ]),
                createElementVNode("div", _hoisted_11, [
                  createElementVNode("div", {
                    ref_key: "map4Target",
                    ref: map4Target,
                    class: "map-target"
                  }, null, 512),
                  createElementVNode("div", _hoisted_12, [
                    createVNode(_component_el_select, {
                      modelValue: layerIds[3],
                      "onUpdate:modelValue": _cache[3] || (_cache[3] = ($event) => layerIds[3] = $event),
                      placeholder: "图层4",
                      size: "small",
                      onChange: updateVisibility,
                      style: { "width": "180px" }
                    }, {
                      default: withCtx(() => [
                        (openBlock(true), createElementBlock(Fragment, null, renderList(layerOptions.value, (layer) => {
                          return openBlock(), createBlock(_component_el_option, {
                            key: layer.id,
                            label: layer.title,
                            value: layer.id
                          }, null, 8, ["label", "value"]);
                        }), 128))
                      ]),
                      _: 1
                    }, 8, ["modelValue"])
                  ])
                ])
              ])
            ])
          ]),
          _: 1
        }, 8, ["modelValue"])
      ])) : createCommentVNode("", true);
    };
  }
});
const QuadCompareDialog = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-7f8e7ad9"]]);
export {
  QuadCompareDialog as default
};
