<template>
  <div class="search-layout">
    <el-input
      v-model="keyword"
      placeholder="输入名称搜索"
      style="width: 350px"
      clearable
    >
      <template #append>
        <el-button :icon="Search" />
      </template>
    </el-input>
    <div class="rrr">
      <div
        class="search-result"
        v-show="keyword && showSearch"
        ref="resultEl"
      ></div>
      <div class="search-sh" v-show="keyword">
        <el-button style="width: 100%" @click="showSearch = !showSearch">
          {{ showSearch ? "收起" : "展开" }}搜索结果
        </el-button>
      </div>
    </div>
  </div>
  <div class="def-select-map-layout">
    <GoogleMap v-if="mapType=='google'"
    :api-key="ggMapKey"
    class="def-select-map"
    :center="center"
    :zoom="15"
    >
        <Marker :options="{ position: center }" />
    </GoogleMap>
    <div v-else class="def-select-map" ref="mapEl"></div>
  </div>

  <div class="def-map-info" v-if="info">
    <p><span>纬度</span>{{ info.lat }}</p>
    <p><span>经度</span>{{ info.lng }}</p>
    <p><span>缩放级别</span>{{ info.zoom }}</p>
  </div>
</template>

<script setup lang="ts">
import AMapLoader from "@amap/amap-jsapi-loader";
import { Search } from "@element-plus/icons-vue";
import { ref, watchEffect, onMounted, computed } from "vue";
import { GoogleMap, Marker } from 'vue3-google-map'
import { getTipsList, getTipsNames, getCaseInfo } from "@/store/case";
import { QuiskExpose } from "@/helper/mount";
import { debounce } from "@/util";
import html2canvas from "html2canvas";
import { router } from "@/router";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
export type MapImage = { blob: Blob | null; search: MapInfo | null };
type MapInfo = { lat: number; lng: number; zoom: number; text: string };

const keyword = ref("");
const ggMapKey = ref("AIzaSyBGUvCR1bppO9pfuS0MUWzuftiZ127y4Os");
const showSearch = ref(true);
const info = ref<MapInfo>();
const searchInfo = ref<MapInfo>();
const caseInfoData = ref<any>(null);
const mapType = ref("gaode");
const center = ref({
  lat: 113.0,
  lng: 22.61,
});
const caseId = computed(() => {
  const caseId = router.currentRoute.value.params.caseId;
  if (caseId) {
    return Number(caseId);
  }
});

watchEffect(() => {
  if (keyword.value) {
    showSearch.value = true;
  }
});

const mapEl = ref<HTMLDivElement>();
const resultEl = ref<HTMLDivElement>();
const searchAMap = ref<any>();

const renderMapGd = async () => {
  const AMap = await AMapLoader.load({
    plugins: ["AMap.PlaceSearch", "AMap.Event"],
    key: "e661b00bdf2c44cccf71ef6070ef41b8",
    version: "2.0",
  });
  const map = new AMap.Map(mapEl.value, {
    WebGLParams: {
      preserveDrawingBuffer: true,
    },
    resizeEnable: true,
    center: [center.value.lat, center.value.lng], //中心坐标
    zoom: 10, //缩放级别
  });
  const placeSearch = new AMap.PlaceSearch({
    pageSize: 5,
    showCover: false,
    pageIndex: 1,
    map: map,
    panel: resultEl.value,
    autoFitView: true,
  });
  const setSearch = (data) => {
    console.log("setSearch", data);
    let city =
      data.cityname == data.adname
        ? data.cityname
        : data.cityname + data.adname;
    searchInfo.value = {
      text: data.pname + city + data.address,
      lat: data.location.lat,
      lng: data.location.lng,
      zoom: 0,
    };
  };

  placeSearch.on("listElementClick", (e) => {
    setSearch(e.data);
    showSearch.value = false;
  });
  let clickMarker;
  //绑定地图移动与缩放事件
  map.on("moveend", () => {
    info.value = getMapInfo();
  });
  map.on("zoomend", () => {
    info.value = getMapInfo();
  });
  map.on("click", async function (e) {
    // 获取点击位置的经纬度坐标
    const KEY = "e661b00bdf2c44cccf71ef6070ef41b8";
    var latitude = e.lnglat.lat;
    var longitude = e.lnglat.lng;
    let location = [longitude, latitude];
    const res = await regeocoder(location);
    console.log(e, res, "function");
    searchInfo.value = {
      text: "",
      lat: latitude,
      lng: longitude,
      zoom: 0,
    };
    clickMarker && map.remove(clickMarker);
    clickMarker = null;
    // 在地图上添加标记
    clickMarker = new AMap.Marker({
      position: [longitude, latitude],
      title: "点击位置",
    });

    map.add(clickMarker);
  });
  placeSearch.on("complete", function (result) {
    setTimeout(() => {
      const markers = map.getAllOverlays("marker");
      for (const marker of markers) {
        marker.on("click", () => {
          clickMarker && map.remove(clickMarker);
          clickMarker = null;
          setSearch(marker._data);
        });
      }
    }, 500);
  });
  async function regeocoder(lnglatXY) {
    return AMap.plugin("AMap.Geocoder", function () {
      var geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: "all",
      });
      return geocoder.getAddress(lnglatXY, function (status, result) {
        if (status === "complete" && result.info === "OK") {
          console.log(
            result.regeocode.formattedAddress,
            "result.regeocode.formattedAddress"
          );
          searchInfo.value.text = result.regeocode.formattedAddress;
          return result.regeocode.formattedAddress;
        }
      });
      // if(!marker){
      //     marker = new AMap.Marker();
      //     map.add(marker);
      // }
      // marker.setPosition(lnglatXY);
    });
  }
  const getMapInfo = (): MapInfo => {
    var zoom = map.getZoom(); //获取当前地图级别
    var centers = map.getCenter();
    return {
      text: "",
      zoom,
      lat: centers.lat,
      lng: centers.lng,
    };
  };
  searchAMap.value = placeSearch;
};
const renderGgMapGd = async () => {
  // const map = new google.maps.Map(mapEl.value, {
  //   zoom: 10,
  //   center: center.value,
  //   mapTypeId: "roadmap",
  // });
};
onMounted(async () => {
  caseInfoData.value = await getCaseInfo(caseId.value);
  if (caseInfoData.value?.latAndLong) {
    let centerObj = caseInfoData.value.latAndLong.split(",").reverse()
    center.value.lat = parseFloat(centerObj[0]);
    center.value.lng = parseFloat(centerObj[1]);
  }
  renderMapGd()
  renderGgMapGd()
});
watchEffect(async (onCleanup) => {
  if (!mapEl.value || !resultEl.value) {
    return;
  }

  // onCleanup(() => {
  //   searchAMap.value = null;
  //   map.destroy();
  // });
});
var dataURLtoBlob = function (dataurl) {
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
};
const search = debounce((keyword: string) => {
  searchAMap.value.search(keyword);
}, 1000);
watchEffect(() => {
  searchAMap.value && search(keyword.value);
});

defineExpose<QuiskExpose>({
  submit() {
    return new Promise<MapImage>((resolve) => {
      console.log("searchInfo", searchInfo.value, mapEl.value);
      if (mapEl.value) {
        const canvas = mapEl.value.querySelector("canvas") as HTMLCanvasElement;
        console.log(canvas, "canvas");
        canvas &&
          canvas.toBlob((blob) => resolve({ blob, search: searchInfo.value! })); // || resolve({ search: searchInfo.value! });
        if (!canvas) {
          //div内容生成图片
          html2canvas(mapEl.value, {
            useCORS: true, // 添加这个选项以解决跨域问题
          }).then((canvas) => {
            let imgUrl = canvas.toDataURL("image/png");
            let blob = dataURLtoBlob(imgUrl);
            resolve({ blob, search: searchInfo.value! });
          });
        }
      } else {
        resolve({ blob: null, search: null });
      }
    });
  },
});
</script>

<style lang="scss" scoped>
.search-layout {
  display: inline-block;
  position: relative;
  margin-bottom: 15px;
  z-index: 2;
}

.rrr {
  position: absolute;
  left: 0;
  right: 0;
  z-index: 1;
}

.search-sh,
.search-result {
  overflow: hidden;

  &.show {
    max-height: 450px;
    overflow-y: auto;
  }
}

.def-map-info {
  margin-top: 10px;
  p {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.85);
    display: inline;
    &:not(:last-child)::after {
      content: ",";
      margin-right: 6px;
    }
  }

  span::after {
    content: "：";
  }
}

.def-select-map-layout {
  --scale: 1.5;
  width: 100%;
  padding-top: calc((390 / 540) * 100%);
  position: relative;
  z-index: 1;
}

.def-select-map {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
</style>
