import { defineComponent, ref, inject, computed, shallowRef, watch, nextTick, onMounted, onUnmounted, resolveComponent, openBlock, createElementBlock, createVNode, unref, withCtx, createElementVNode, normalizeClass, normalizeStyle, 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 { DCaret } from "@element-plus/icons-vue";
import "proj4";
import "@supermapgis/iclient-ol";
import "element-plus";
const _hoisted_1 = {
  key: 0,
  class: "swipe-compare-dialog"
};
const _hoisted_2 = { class: "map-control left-control" };
const _hoisted_3 = { class: "map-control right-control" };
const _hoisted_4 = { class: "slider-handle" };
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "SwipeCompareDialog",
  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 containerRef = ref(null);
    const leftMap = shallowRef(null);
    const rightMap = shallowRef(null);
    const leftLayerId = ref("");
    const rightLayerId = ref("");
    const layerOptions = ref([]);
    const swipeValue = ref(50);
    const isDragging = ref(false);
    const leftMapStyle = computed(() => {
      return {
        position: "absolute",
        top: 0,
        left: 0,
        width: "100%",
        height: "100%",
        zIndex: 1,
        clipPath: `inset(0 ${100 - swipeValue.value}% 0 0)`,
        WebkitClipPath: `inset(0 ${100 - swipeValue.value}% 0 0)`
        // 兼容性
      };
    });
    const rightMapStyle = computed(() => {
      return {
        position: "absolute",
        top: 0,
        left: 0,
        width: "100%",
        height: "100%",
        zIndex: 2,
        clipPath: `inset(0 0 0 ${swipeValue.value}%)`,
        WebkitClipPath: `inset(0 0 0 ${swipeValue.value}%)`
        // 兼容性
      };
    });
    watch(
      () => props.modelValue,
      (val) => {
        visible.value = val;
        if (val) {
          nextTick(() => {
            initMaps();
          });
        } else {
          disposeMaps();
        }
      }
    );
    watch(visible, (val) => {
      emit("update:modelValue", val);
      if (!val) {
        disposeMaps();
      }
    });
    const handleMouseMove = (e) => {
      if (!isDragging.value || !containerRef.value)
        return;
      const rect = containerRef.value.getBoundingClientRect();
      const x = e.clientX - rect.left;
      let percent = x / rect.width * 100;
      if (percent < 0)
        percent = 0;
      if (percent > 100)
        percent = 100;
      swipeValue.value = percent;
    };
    const handleMouseUp = () => {
      isDragging.value = false;
      window.removeEventListener("mousemove", handleMouseMove);
      window.removeEventListener("mouseup", handleMouseUp);
    };
    const handleMouseDown = (e) => {
      isDragging.value = true;
      e.preventDefault();
      window.addEventListener("mousemove", handleMouseMove);
      window.addEventListener("mouseup", handleMouseUp);
    };
    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(
                `SwipeCompareDialog: 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(
        "SwipeCompareDialog: 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);
        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) => {
        const id = layer.get("id");
        layer.setVisible(id === leftLayerId.value);
      });
      rightMap.value.getLayers().forEach((layer) => {
        const id = layer.get("id");
        layer.setVisible(id === rightLayerId.value);
      });
    };
    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();
      window.removeEventListener("mousemove", handleMouseMove);
      window.removeEventListener("mouseup", handleMouseUp);
    });
    return (_ctx, _cache) => {
      const _component_el_option = resolveComponent("el-option");
      const _component_el_select = resolveComponent("el-select");
      const _component_el_icon = resolveComponent("el-icon");
      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", {
              class: normalizeClass(["swipe-content", { "is-dragging": isDragging.value }]),
              ref_key: "containerRef",
              ref: containerRef
            }, [
              createElementVNode("div", {
                class: "map-container left-map",
                style: normalizeStyle(leftMapStyle.value)
              }, [
                createElementVNode("div", {
                  ref_key: "leftMapTarget",
                  ref: leftMapTarget,
                  class: "map-target"
                }, null, 512),
                createElementVNode("div", _hoisted_2, [
                  _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
                  }, {
                    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"])
                ])
              ], 4),
              createElementVNode("div", {
                class: "map-container right-map",
                style: normalizeStyle(rightMapStyle.value)
              }, [
                createElementVNode("div", {
                  ref_key: "rightMapTarget",
                  ref: rightMapTarget,
                  class: "map-target"
                }, null, 512),
                createElementVNode("div", _hoisted_3, [
                  _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
                  }, {
                    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"])
                ])
              ], 4),
              createElementVNode("div", {
                class: "swipe-slider",
                style: normalizeStyle({ left: swipeValue.value + "%" }),
                onMousedown: handleMouseDown
              }, [
                createElementVNode("div", _hoisted_4, [
                  createVNode(_component_el_icon, null, {
                    default: withCtx(() => [
                      createVNode(unref(DCaret))
                    ]),
                    _: 1
                  })
                ])
              ], 36)
            ], 2)
          ]),
          _: 1
        }, 8, ["modelValue"])
      ])) : createCommentVNode("", true);
    };
  }
});
const SwipeCompareDialog = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-e9514c00"]]);
export {
  SwipeCompareDialog as default
};
