import { defineComponent, ref, inject, computed, shallowRef, 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: "split-compare-dialog"
};
const _hoisted_2 = { class: "split-content" };
const _hoisted_3 = { class: "map-container left-map" };
const _hoisted_4 = { class: "map-control" };
const _hoisted_5 = { class: "map-container right-map" };
const _hoisted_6 = { class: "map-control" };
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "SplitCompareDialog",
  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 leftMapTarget = ref(null);
    const rightMapTarget = ref(null);
    const leftMap = shallowRef(null);
    const rightMap = shallowRef(null);
    const leftLayerId = ref("");
    const rightLayerId = ref("");
    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 || !leftMapTarget.value || !rightMapTarget.value)
        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(
                `SplitCompareDialog: 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(
        "SplitCompareDialog: Unified layers:",
        allLayers.length,
        allLayers
      );
      const leftLayers = [];
      const rightLayers = [];
      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 });
        const lClone = cloneLayer(layer);
        lClone.set("id", id);
        const rClone = cloneLayer(layer);
        rClone.set("id", id);
        lClone.setVisible(layer.getVisible());
        rClone.setVisible(layer.getVisible());
        leftLayers.push(lClone);
        rightLayers.push(rClone);
      });
      layerOptions.value = options;
      leftMap.value = new Map({
        target: leftMapTarget.value,
        layers: leftLayers,
        view: sharedView,
        controls: defaults({ zoom: false, attribution: false })
      });
      rightMap.value = new Map({
        target: rightMapTarget.value,
        layers: rightLayers,
        view: sharedView,
        controls: defaults({ zoom: false, attribution: false })
      });
      if (options.length > 0) {
        if (!leftLayerId.value)
          leftLayerId.value = options[0].id;
        if (!rightLayerId.value)
          rightLayerId.value = options.length > 1 ? options[1].id : options[0].id;
        updateLayerVisibility();
      }
    };
    const updateLayerVisibility = () => {
      if (!leftMap.value || !rightMap.value)
        return;
      leftMap.value.getLayers().forEach((layer) => {
        var _a;
        const id = layer.get("id");
        if (id === leftLayerId.value) {
          layer.setVisible(true);
        }
        const originalVisible = (_a = layerOptions.value.find((o) => o.id === id)) == null ? void 0 : _a.originalLayer.getVisible();
        if (id === leftLayerId.value) {
          layer.setVisible(true);
        } else {
          layer.setVisible(originalVisible);
        }
      });
      rightMap.value.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 === rightLayerId.value) {
          layer.setVisible(true);
        } else {
          layer.setVisible(originalVisible);
        }
      });
    };
    const disposeMaps = () => {
      if (leftMap.value) {
        leftMap.value.setTarget(void 0);
        leftMap.value = null;
      }
      if (rightMap.value) {
        rightMap.value.setTarget(void 0);
        rightMap.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[2] || (_cache[2] = ($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", {
                  ref_key: "leftMapTarget",
                  ref: leftMapTarget,
                  class: "map-target"
                }, null, 512),
                createElementVNode("div", _hoisted_4, [
                  _cache[3] || (_cache[3] = createElementVNode("span", { class: "label" }, "左侧图层：", -1)),
                  createVNode(_component_el_select, {
                    modelValue: leftLayerId.value,
                    "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => leftLayerId.value = $event),
                    placeholder: "选择图层",
                    size: "small",
                    onChange: updateLayerVisibility,
                    style: { "width": "200px" }
                  }, {
                    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_5, [
                createElementVNode("div", {
                  ref_key: "rightMapTarget",
                  ref: rightMapTarget,
                  class: "map-target"
                }, null, 512),
                createElementVNode("div", _hoisted_6, [
                  _cache[4] || (_cache[4] = createElementVNode("span", { class: "label" }, "右侧图层：", -1)),
                  createVNode(_component_el_select, {
                    modelValue: rightLayerId.value,
                    "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => rightLayerId.value = $event),
                    placeholder: "选择图层",
                    size: "small",
                    onChange: updateLayerVisibility,
                    style: { "width": "200px" }
                  }, {
                    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 SplitCompareDialog = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-8c896c25"]]);
export {
  SplitCompareDialog as default
};
