import { defineComponent, inject, computed, ref, reactive, onUnmounted, watch, resolveComponent, openBlock, createElementBlock, Fragment, createVNode, unref, withCtx, createElementVNode, normalizeClass, createTextVNode, toDisplayString, renderList, createBlock, withModifiers, mergeProps } from "vue";
import { Plus, FolderOpened, Download, Delete, Search, LocationFilled, Edit } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import { X, M as MarkerDrawingAdapter, h as fromLonLat, t as toLonLat } from "./index-e8d5fc75.mjs";
import "ol";
import "proj4";
import "@supermapgis/iclient-ol";
const _hoisted_1 = { class: "markers-content" };
const _hoisted_2 = { class: "toolbar" };
const _hoisted_3 = { class: "search-filter" };
const _hoisted_4 = { class: "markers-list" };
const _hoisted_5 = { class: "marker-name" };
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "MyMarkersDialog",
  props: {
    modelValue: { type: Boolean },
    config: {},
    bookmarks: {}
  },
  emits: ["update:modelValue", "update:bookmarks", "marker-action", "close", "action", "bookmark-action"],
  setup(__props, { emit: __emit }) {
    const EPlusDialog = X;
    const props = __props;
    const emit = __emit;
    const mapRef = inject("map");
    const drawingManagerRef = inject("drawingManager");
    const map = computed(() => mapRef == null ? void 0 : mapRef.value);
    const drawingManager = computed(() => drawingManagerRef == null ? void 0 : drawingManagerRef.value);
    const dialogVisible = computed({
      get: () => props.modelValue,
      set: (value) => emit("update:modelValue", value)
    });
    const searchKeyword = ref("");
    const filterCategory = ref("");
    const markers = ref([]);
    const showAddDialog = ref(false);
    const editingIndex = ref(-1);
    let markerAdapter = null;
    const markerForm = reactive({
      name: "",
      category: "默认",
      description: "",
      longitude: 117.238548,
      latitude: 31.806682,
      color: "#409eff"
    });
    const cancelAddMarker = () => {
      showAddDialog.value = false;
      Object.assign(markerForm, {
        name: "",
        category: "默认",
        description: "",
        longitude: 117.238548,
        latitude: 31.806682,
        color: "#409eff"
      });
    };
    const categories = computed(() => {
      const cats = [...new Set(markers.value.map((m) => m.category))];
      return cats.filter((cat) => cat);
    });
    const filteredMarkers = computed(() => {
      let result = markers.value;
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase();
        result = result.filter(
          (marker) => marker.name.toLowerCase().includes(keyword) || marker.description.toLowerCase().includes(keyword)
        );
      }
      if (filterCategory.value) {
        result = result.filter(
          (marker) => marker.category === filterCategory.value
        );
      }
      return result;
    });
    const handleSearch = () => {
    };
    const isAddingMarker = ref(false);
    const mapClickHandler = ref(null);
    const initializeMarkerAdapter = () => {
      if (map.value && drawingManager.value && !markerAdapter) {
        markerAdapter = new MarkerDrawingAdapter(map.value);
        markerAdapter.on("markerAdded", (marker) => {
          markers.value.push(marker);
        });
        markerAdapter.on("markerUpdated", (marker) => {
          const index = markers.value.findIndex((m) => m.id === marker.id);
          if (index >= 0) {
            markers.value[index] = marker;
          }
        });
        markerAdapter.on("markerDeleted", (markerId) => {
          const index = markers.value.findIndex((m) => m.id === markerId);
          if (index >= 0) {
            markers.value.splice(index, 1);
          }
        });
        markerAdapter.on("markerClicked", (marker) => {
          console.log("标记被点击:", marker.name);
        });
        markerAdapter.on("markersCleared", () => {
          markers.value = [];
        });
      }
    };
    const showAddMarker = () => {
      isAddingMarker.value = !isAddingMarker.value;
      if (isAddingMarker.value) {
        initializeMarkerAdapter();
        startAddingMarker();
      } else {
        cancelAddingMarker();
      }
    };
    const startAddingMarker = () => {
      if (!map.value || !drawingManager.value)
        return;
      drawingManager.value.setMode("point", {
        allowContinuousDrawing: false
      });
      const handleDrawingEnd = (drawing) => {
        var _a;
        const coordinate = drawing.getCoordinates();
        if (coordinate) {
          (_a = drawingManager.value) == null ? void 0 : _a.removeDrawing(drawing);
          showMarkerInputDialog(coordinate);
        }
        cancelAddingMarker();
      };
      drawingManager.value.on("drawing-end", handleDrawingEnd);
      mapClickHandler.value = handleDrawingEnd;
    };
    const cancelAddingMarker = () => {
      if (!drawingManager.value)
        return;
      drawingManager.value.setMode("none");
      if (mapClickHandler.value) {
        drawingManager.value.off("drawing-end", mapClickHandler.value);
        mapClickHandler.value = null;
      }
      isAddingMarker.value = false;
    };
    const dialogProps = ref({
      top: "15vh",
      left: "50%",
      enableCache: true
    });
    const showMarkerInputDialog = (coordinate) => {
      var _a;
      const mapProjection = (_a = map.value) == null ? void 0 : _a.getView().getProjection().getCode();
      const lonLat = mapProjection === "EPSG:4326" || mapProjection === "EPSG:4490" ? coordinate : toLonLat(coordinate);
      if (map.value) {
        const pixel = map.value.getPixelFromCoordinate(coordinate);
        if (pixel) {
          const mapElement = map.value.getTargetElement();
          const rect = mapElement.getBoundingClientRect();
          dialogProps.value = {
            top: pixel[1] + rect.top + 20 + "px",
            left: pixel[0] + rect.left - 175 + "px",
            enableCache: false
            // 禁用缓存以强制使用新位置
          };
        }
      }
      editingIndex.value = -1;
      Object.assign(markerForm, {
        name: "",
        category: "默认",
        description: "",
        longitude: lonLat[0],
        latitude: lonLat[1],
        color: "#409eff"
      });
      showAddDialog.value = true;
    };
    const editMarker = (marker, index) => {
      editingIndex.value = index;
      Object.assign(markerForm, {
        name: marker.name,
        category: marker.category,
        description: marker.description,
        longitude: marker.longitude,
        latitude: marker.latitude,
        color: marker.color
      });
      if (map.value) {
        const mapProjection = map.value.getView().getProjection().getCode();
        const coordinate = mapProjection === "EPSG:4326" || mapProjection === "EPSG:4490" ? [marker.longitude, marker.latitude] : fromLonLat([marker.longitude, marker.latitude]);
        const pixel = map.value.getPixelFromCoordinate(coordinate);
        if (pixel) {
          const mapElement = map.value.getTargetElement();
          const rect = mapElement.getBoundingClientRect();
          dialogProps.value = {
            top: pixel[1] + rect.top + 20 + "px",
            left: pixel[0] + rect.left - 175 + "px",
            enableCache: false
          };
        }
      }
      showAddDialog.value = true;
    };
    const saveMarker = () => {
      var _a;
      if (!((_a = markerForm.name) == null ? void 0 : _a.trim())) {
        console.error("请输入标记名称");
        return;
      }
      if (!markerAdapter) {
        console.error("标记管理器未初始化");
        return;
      }
      const markerData = {
        id: editingIndex.value >= 0 ? markers.value[editingIndex.value].id : Date.now().toString(),
        name: markerForm.name,
        category: markerForm.category || "默认",
        description: markerForm.description || "",
        longitude: Number(markerForm.longitude),
        latitude: Number(markerForm.latitude),
        color: markerForm.color || "#409eff",
        createTime: editingIndex.value >= 0 ? markers.value[editingIndex.value].createTime : (/* @__PURE__ */ new Date()).toISOString()
      };
      try {
        if (editingIndex.value >= 0) {
          markerAdapter.updateMarker(markerData);
          console.log("标记更新成功");
        } else {
          markerAdapter.addMarker(markerData);
          console.log("标记添加成功");
        }
        emit("marker-action", {
          action: editingIndex.value >= 0 ? "update" : "add",
          marker: markerData
        });
        emit("action", {
          action: editingIndex.value >= 0 ? "update" : "add",
          marker: markerData
        });
        cancelAddMarker();
      } catch (error) {
        console.error("保存标记失败: " + error.message);
      }
    };
    const deleteMarker = (index) => {
      ElMessageBox.confirm("确定要删除这个标记吗？", "确认删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const marker = markers.value[index];
        if (markerAdapter) {
          try {
            markerAdapter.removeMarker(marker.id);
            console.log("标记删除成功");
            emit("marker-action", { action: "delete", marker });
            emit("action", { action: "delete", marker });
          } catch (error) {
            console.error("删除标记失败: " + error.message);
          }
        } else {
          console.error("标记管理器未初始化");
        }
      }).catch(() => {
      });
    };
    const locateMarker = (marker) => {
      if (markerAdapter) {
        try {
          markerAdapter.flyToMarker(marker.id);
          console.log(`正在定位到${marker.name}`);
        } catch (error) {
          console.error("定位标记失败: " + error.message);
        }
      } else {
        console.error("标记管理器未初始化");
      }
    };
    const clearAllMarkers = () => {
      ElMessageBox.confirm("确定要清空所有标记吗？此操作不可恢复！", "确认清空", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (markerAdapter) {
          try {
            markerAdapter.clearAllMarkers();
            console.log("已清空所有标记");
            emit("marker-action", { action: "clear" });
            emit("action", { action: "clear" });
          } catch (error) {
            console.error("清空标记失败: " + error.message);
          }
        } else {
          console.error("标记管理器未初始化");
        }
      }).catch(() => {
      });
    };
    const importMarkers = () => {
      const input = document.createElement("input");
      input.type = "file";
      input.accept = ".json";
      input.onchange = (e) => {
        var _a;
        const file = (_a = e.target.files) == null ? void 0 : _a[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = (e2) => {
            var _a2;
            try {
              const data = JSON.parse((_a2 = e2.target) == null ? void 0 : _a2.result);
              if (Array.isArray(data) && markerAdapter) {
                markerAdapter.clearAllMarkers();
                let successCount = 0;
                for (const item of data) {
                  try {
                    const marker = {
                      ...item,
                      createTime: typeof item.createTime === "string" ? item.createTime : new Date(item.createTime).toISOString()
                    };
                    markerAdapter.addMarker(marker);
                    successCount++;
                  } catch (error) {
                    console.warn("导入标记失败:", item, error);
                  }
                }
                console.log(`成功导入${successCount}个标记`);
              } else if (!Array.isArray(data)) {
                console.error("文件格式不正确");
              } else {
                console.error("标记管理器未初始化");
              }
            } catch (error) {
              console.error("文件解析失败");
            }
          };
          reader.readAsText(file);
        }
      };
      input.click();
    };
    const exportMarkers = () => {
      if (markers.value.length === 0) {
        console.warn("没有标记可以导出");
        return;
      }
      const data = JSON.stringify(markers.value, null, 2);
      const blob = new Blob([data], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `markers_${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.json`;
      a.click();
      URL.revokeObjectURL(url);
      console.log("标记导出成功");
    };
    const formatTime = (time) => {
      return new Date(time).toLocaleDateString();
    };
    const handleClose = () => {
      dialogVisible.value = false;
      searchKeyword.value = "";
      filterCategory.value = "";
      emit("close");
    };
    onUnmounted(() => {
      if (markerAdapter) {
        markerAdapter.destroy();
        markerAdapter = null;
      }
    });
    watch(
      [() => map.value, () => drawingManager.value],
      () => {
        if (map.value && drawingManager.value) {
          initializeMarkerAdapter();
          if (markerAdapter) {
            const existingMarkers = markerAdapter.getAllMarkers();
            markers.value = existingMarkers;
          }
        }
      },
      { immediate: true }
    );
    return (_ctx, _cache) => {
      const _component_el_button = resolveComponent("el-button");
      const _component_el_input = resolveComponent("el-input");
      const _component_el_option = resolveComponent("el-option");
      const _component_el_select = resolveComponent("el-select");
      const _component_el_icon = resolveComponent("el-icon");
      const _component_el_table_column = resolveComponent("el-table-column");
      const _component_el_table = resolveComponent("el-table");
      const _component_el_form_item = resolveComponent("el-form-item");
      const _component_el_form = resolveComponent("el-form");
      return openBlock(), createElementBlock(Fragment, null, [
        createVNode(unref(EPlusDialog), {
          modelValue: dialogVisible.value,
          "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => dialogVisible.value = $event),
          title: "我的标记",
          width: "600px",
          height: "600px",
          "before-close": handleClose,
          "show-modal": false,
          "modal-class": "pointer-events-none",
          "cache-id": "markers-dialog",
          class: "markers-dialog"
        }, {
          default: withCtx(() => [
            createElementVNode("div", _hoisted_1, [
              createElementVNode("div", _hoisted_2, [
                createVNode(_component_el_button, {
                  type: "primary",
                  icon: unref(Plus),
                  class: normalizeClass({ "adding-marker": isAddingMarker.value }),
                  onClick: showAddMarker
                }, {
                  default: withCtx(() => [
                    createTextVNode(toDisplayString(isAddingMarker.value ? "取消添加" : "添加标记"), 1)
                  ]),
                  _: 1
                }, 8, ["icon", "class"]),
                createVNode(_component_el_button, {
                  icon: unref(FolderOpened),
                  onClick: importMarkers
                }, {
                  default: withCtx(() => [..._cache[7] || (_cache[7] = [
                    createTextVNode(" 导入标记 ", -1)
                  ])]),
                  _: 1
                }, 8, ["icon"]),
                createVNode(_component_el_button, {
                  icon: unref(Download),
                  onClick: exportMarkers
                }, {
                  default: withCtx(() => [..._cache[8] || (_cache[8] = [
                    createTextVNode(" 导出标记 ", -1)
                  ])]),
                  _: 1
                }, 8, ["icon"]),
                createVNode(_component_el_button, {
                  icon: unref(Delete),
                  disabled: markers.value.length === 0,
                  onClick: clearAllMarkers
                }, {
                  default: withCtx(() => [..._cache[9] || (_cache[9] = [
                    createTextVNode(" 清空全部 ", -1)
                  ])]),
                  _: 1
                }, 8, ["icon", "disabled"])
              ]),
              createElementVNode("div", _hoisted_3, [
                createVNode(_component_el_input, {
                  modelValue: searchKeyword.value,
                  "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => searchKeyword.value = $event),
                  placeholder: "搜索标记名称或备注...",
                  "prefix-icon": unref(Search),
                  clearable: "",
                  style: { "width": "300px" },
                  onInput: handleSearch
                }, null, 8, ["modelValue", "prefix-icon"]),
                createVNode(_component_el_select, {
                  modelValue: filterCategory.value,
                  "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => filterCategory.value = $event),
                  placeholder: "筛选分类",
                  clearable: "",
                  style: { "width": "120px", "margin-left": "10px" }
                }, {
                  default: withCtx(() => [
                    createVNode(_component_el_option, {
                      label: "全部",
                      value: ""
                    }),
                    (openBlock(true), createElementBlock(Fragment, null, renderList(categories.value, (category) => {
                      return openBlock(), createBlock(_component_el_option, {
                        key: category,
                        label: category,
                        value: category
                      }, null, 8, ["label", "value"]);
                    }), 128))
                  ]),
                  _: 1
                }, 8, ["modelValue"])
              ]),
              createElementVNode("div", _hoisted_4, [
                createVNode(_component_el_table, {
                  data: filteredMarkers.value,
                  height: "100%",
                  class: "markers-table",
                  "empty-text": "暂无数据",
                  onRowClick: locateMarker
                }, {
                  default: withCtx(() => [
                    createVNode(_component_el_table_column, {
                      prop: "name",
                      label: "名称",
                      width: "120"
                    }, {
                      default: withCtx(({ row }) => [
                        createElementVNode("div", _hoisted_5, [
                          createVNode(_component_el_icon, {
                            color: row.color,
                            size: "16"
                          }, {
                            default: withCtx(() => [
                              createVNode(unref(LocationFilled))
                            ]),
                            _: 2
                          }, 1032, ["color"]),
                          createElementVNode("span", null, toDisplayString(row.name), 1)
                        ])
                      ]),
                      _: 1
                    }),
                    createVNode(_component_el_table_column, {
                      prop: "category",
                      label: "分类",
                      width: "80"
                    }),
                    createVNode(_component_el_table_column, {
                      prop: "description",
                      label: "备注",
                      "show-overflow-tooltip": ""
                    }),
                    createVNode(_component_el_table_column, {
                      prop: "createTime",
                      label: "创建时间",
                      width: "120"
                    }, {
                      default: withCtx(({ row }) => [
                        createTextVNode(toDisplayString(formatTime(row.createTime)), 1)
                      ]),
                      _: 1
                    }),
                    createVNode(_component_el_table_column, {
                      label: "操作",
                      width: "120"
                    }, {
                      default: withCtx(({ row, $index }) => [
                        createVNode(_component_el_button, {
                          link: "",
                          size: "small",
                          icon: unref(Edit),
                          onClick: withModifiers(($event) => editMarker(row, $index), ["stop"])
                        }, {
                          default: withCtx(() => [..._cache[10] || (_cache[10] = [
                            createTextVNode(" 编辑 ", -1)
                          ])]),
                          _: 2
                        }, 1032, ["icon", "onClick"]),
                        createVNode(_component_el_button, {
                          link: "",
                          size: "small",
                          icon: unref(Delete),
                          class: "delete-btn",
                          onClick: withModifiers(($event) => deleteMarker($index), ["stop"])
                        }, {
                          default: withCtx(() => [..._cache[11] || (_cache[11] = [
                            createTextVNode(" 删除 ", -1)
                          ])]),
                          _: 2
                        }, 1032, ["icon", "onClick"])
                      ]),
                      _: 1
                    })
                  ]),
                  _: 1
                }, 8, ["data"])
              ])
            ])
          ]),
          _: 1
        }, 8, ["modelValue"]),
        createVNode(unref(EPlusDialog), mergeProps({
          modelValue: showAddDialog.value,
          "onUpdate:modelValue": _cache[6] || (_cache[6] = ($event) => showAddDialog.value = $event),
          title: "添加标记",
          width: "350px",
          "show-modal": false,
          "append-to-body": ""
        }, dialogProps.value), {
          footer: withCtx(() => [
            createVNode(_component_el_button, { onClick: cancelAddMarker }, {
              default: withCtx(() => [..._cache[12] || (_cache[12] = [
                createTextVNode("取消", -1)
              ])]),
              _: 1
            }),
            createVNode(_component_el_button, {
              type: "primary",
              onClick: saveMarker
            }, {
              default: withCtx(() => [..._cache[13] || (_cache[13] = [
                createTextVNode("确定", -1)
              ])]),
              _: 1
            })
          ]),
          default: withCtx(() => [
            createVNode(_component_el_form, {
              model: markerForm,
              "label-width": "60px"
            }, {
              default: withCtx(() => [
                createVNode(_component_el_form_item, {
                  label: "名称",
                  required: ""
                }, {
                  default: withCtx(() => [
                    createVNode(_component_el_input, {
                      modelValue: markerForm.name,
                      "onUpdate:modelValue": _cache[3] || (_cache[3] = ($event) => markerForm.name = $event),
                      placeholder: "请输入标记名称",
                      maxlength: "20",
                      "show-word-limit": ""
                    }, null, 8, ["modelValue"])
                  ]),
                  _: 1
                }),
                createVNode(_component_el_form_item, { label: "分类" }, {
                  default: withCtx(() => [
                    createVNode(_component_el_select, {
                      modelValue: markerForm.category,
                      "onUpdate:modelValue": _cache[4] || (_cache[4] = ($event) => markerForm.category = $event),
                      filterable: "",
                      "allow-create": "",
                      "default-first-option": "",
                      placeholder: "请选择或输入分类",
                      style: { "width": "100%" }
                    }, {
                      default: withCtx(() => [
                        (openBlock(true), createElementBlock(Fragment, null, renderList(categories.value, (item) => {
                          return openBlock(), createBlock(_component_el_option, {
                            key: item,
                            label: item,
                            value: item
                          }, null, 8, ["label", "value"]);
                        }), 128))
                      ]),
                      _: 1
                    }, 8, ["modelValue"])
                  ]),
                  _: 1
                }),
                createVNode(_component_el_form_item, { label: "备注" }, {
                  default: withCtx(() => [
                    createVNode(_component_el_input, {
                      modelValue: markerForm.description,
                      "onUpdate:modelValue": _cache[5] || (_cache[5] = ($event) => markerForm.description = $event),
                      type: "textarea",
                      rows: 3,
                      placeholder: "请输入备注信息",
                      maxlength: "100",
                      "show-word-limit": ""
                    }, null, 8, ["modelValue"])
                  ]),
                  _: 1
                })
              ]),
              _: 1
            }, 8, ["model"])
          ]),
          _: 1
        }, 16, ["modelValue"])
      ], 64);
    };
  }
});
export {
  _sfc_main as default
};
