<template>
  <!-- <div>地图页面</div> -->
  <div class="tabbar">
    <div class="nav">
      <el-button-group class="ml-4">
        <el-button
          :type="currentType(0) ? 'primary' : 'default'"
          @click="handleSelect(0)"
          >地图</el-button
        >
        <el-button
          :type="currentType(1) ? 'primary' : 'default'"
          @click="handleSelect(1)"
          >卡片</el-button
        >
      </el-button-group>
    </div>
    <el-form-item label="所属架构：" class="filter">
      <com-company v-model="state.deptId" :id="state.caseId" hideAll />
    </el-form-item>
  </div>
  <div ref="mapEl" class="map-container" v-show="currentType(0)"></div>
  <div class="card-container" v-show="currentType(1)">
    <div class="card-list">
      <template v-for="item of list" v-if="list.length > 0">
        <el-card
          style="width: 480px"
          shadow="hover"
          @click="handCardClick(item.caseId)"
        >
          <img
            class="cover"
            :src="
              item.cover
                ? item.cover
                : 'https://test-mix3d.4dkankan.com/code/assets/pic.d5781b0c.jpg'
            "
            style="width: 100%"
          />
          <div class="card">
            <span> 项目: {{ item.projectName }}</span>
            <span> 地址: {{ item.projectAddress }}</span>
            <span> 类别: {{ item.projectSite }}</span>
          </div>
        </el-card>
      </template>
      <template v-else>
        <div class="no-data">
          <img :src="emptyBG" />
          <span>暂无数据</span>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, onBeforeMount } from "vue";
// import { useRouteQuery } from "@vueuse/router";
import AMapLoader from "@amap/amap-jsapi-loader";
import axios from "axios";
import { getFuseCodeLink } from "../../view/case/help";
import comCompany from "./company-select/index.vue";
import { reactive } from "vue";
import { watch } from "vue";
import { ElLoading } from "element-plus";
import linkIco from "@/assets/image/fire.ico";
import { useUrlSearchParams } from "@vueuse/core";
import emptyBG from "@/assets/image/empty__empty.png";

const params = useUrlSearchParams("history");
console.log("params", params.deptId);

const current = ref(0);
const list = ref<any>([]);

const state = reactive({
  deptId: params.deptId || "",
  // caseId: params.caseId || "",
});

const link = document.querySelector<HTMLLinkElement>("#app-icon")!;
link.setAttribute("href", linkIco);

document.title = "案件显示";

const currentType = computed(() => (type: number) => current.value === type);
const handleSelect = (type: number) => {
  current.value = type;
};

const markers = ref<any>([]);

const getQuery = (
  caseId: number,
  share: boolean = false,
  single: boolean = false
) =>
  `${getFuseCodeLink(caseId, true)}${share ? "&share=1" : ""}${
    single ? "&single=1" : ""
  }#show/summary`;

const request = axios.create({
  baseURL: "",
  timeout: 1000,
  headers: {
    share: 1,
    "Content-Type": "application/json",
  },
});
const mapEl = ref<HTMLDivElement>();
let AMap, map;

const queryURL = `${import.meta.env.VITE_SEVER_URL}/fusion-xj/web/fireProject/queryProject`

// debugger;
const getDataQuest = () => {
  return new Promise(async (reslove, reject) => {
    const res = await request.post(
      queryURL,
      {
        pageNum: 1,
        pageSize: 10000,
        deptId: state.deptId,
      }
    );
    console.log("res.data", res);
    if (res.status === 200 && res.data.code === 0) {
      reslove(res.data.data.list);
    } else {
      reslove([]);
    }
  });
};

const refresh = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  map.remove(markers.value);
  markers.value = [];
  initMakers();
  loading.close();
};

watch(
  () => state.deptId,
  () => {
    refresh();
  },
  {
    immediate: false,
    deep: true,
  }
);
const initMakers = async () => {
  const data = (await getDataQuest()) as any as any[];
  console.log("data", data);
  const positions: any[] = [];
  list.value = data as any[];
  Array.from(data).forEach((item: any) => {
    // console.log(item)
    const latlng = item.latlng;
    const coord = latlng.split(",");

    console.log("coord", coord, item.caseId);
    const url = getQuery(item.caseId, true);
    console.log("url", url);
    const icon = new AMap.Icon({
      image:
        "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
      size: new AMap.Size(22, 28), //图标所处区域大小
      imageSize: new AMap.Size(22, 28), //图标大小
    });

    const pos = coord.reverse();
    positions.push(pos);
    const marker = new AMap.Marker({
      icon: icon,
      position: pos,
      title: item.title,
      label: item.title,
      extData: { url: url, id: item.caseId },
      // offset: new AMap.Pixel(-26, -54),
    });
    markers.value.push(marker);
    marker.setMap(map);

    marker.on("click", () => {
      const data = marker.getExtData();
      window.open(data.url);
      console.log("click", data);
    });
  });

  var polygon = new AMap.Polygon({
    path: positions,
    map: map,
    strokeOpacity: 0, //透明
    fillOpacity: 0, //透明
    bubble: true, //事件穿透到地图
  });
  var overlaysList = map.getAllOverlays("polygon"); //获取多边形图层
  map.setFitView(); //自适应显示
};
const loadMap = async () => {
  AMap = await AMapLoader.load({
    plugins: ["AMap.PlaceSearch"],
    key: "e661b00bdf2c44cccf71ef6070ef41b8",
    version: "2.0",
  });

  map = new AMap.Map(mapEl.value, {
    WebGLParams: {
      preserveDrawingBuffer: true,
    },
    resizeEnable: true,
  });

  //添加插件
  AMap.plugin(
    ["AMap.ToolBar", "AMap.Scale", "AMap.HawkEye", "AMap.MapType"],
    function () {
      //异步同时加载多个插件
      // map.addControl(new AMap.HawkEye()); //显示缩略图
      map.addControl(new AMap.Scale()); //显示当前地图中心的比例尺
      map.addControl(new AMap.MapType()); //显示当前地图中心的比例尺
    }
  );
  console.log("map", map);

  initMakers();
};

onMounted(() => {
  // console.log("caseId", caseId);
  loadMap();
});
const handCardClick = (id: number) => {
  const url = getQuery(id, true);
  console.log("url", url);
  window.open(url);
};
</script>
<style>
body {
  padding: 0;
  margin: 0;
}

.map-container {
  width: 100%;
  height: 100vh;
}

.tabbar {
  display: flex;
  width: 100%;
  position: fixed;
  top: 30px;
  z-index: 10000;
  justify-items: center;
  justify-content: center;
}

.tabbar .nav {
  display: flex;
  /* background: white; */
  justify-content: center;
  align-items: center;
}
.el-form-item {
  margin-bottom: 0px !important;
}

.tabbar .nav .nav_item {
  padding: 10px;
  cursor: pointer;
}

.card-container {
  width: 100%;
  padding-top: 100px;
}

.card-list {
  margin: 0 auto;

  display: flex;
  gap: 50px 25px;
  width: 90%;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
}

.cover {
  cursor: pointer;
  max-height: 220px;
  object-fit: cover;
}

.card {
  display: flex;
  flex-direction: column;
  cursor: pointer;
  gap: 10px;
}

.filter {
  margin: 0;
  margin-left: 20px;
}

.amap-ctrl-list-layer {
  z-index: 100000;
}
.no-data {
  width: 100%;
  height: 100%;
  /* background: red; */
  min-height: 530px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.no-data span {
  color: #999;
}
</style>
