<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> -->
    <div class="left">
      <el-form-item label="" class="filter">
        <com-company
          v-model="state.deptId"
          :id="state.caseId"
          hideAll
        />
      </el-form-item>
      <el-form-item label="" class="filter">
        <el-input
          v-model:modelValue="keywordSearch"
          placeholder="输入关键字"
        ></el-input>
      </el-form-item>
    </div>
    <div class="right">
      <el-select
        style="width: 100px"
        v-model:modelValue="currentMaptype"
        v-if="currentType(0)"
      >
        <el-option key="2d" label="矢量图" :value="0" />
        <el-option key="state" label="卫星图" :value="1" />
      </el-select>
      <el-select style="width: 100px" v-model:modelValue="current">
        <el-option key="map" label="地图" :value="0" />
        <el-option key="card" label="卡片" :value="1" />
      </el-select>
    </div>
  </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 keywordSearch ? searchList : list"
        v-if="keywordSearch ? searchList.length > 0 : list.length > 0"
      >
        <el-card
          class="card"
          shadow="hover"
          @click="handCardClick(item.caseId)"
        >
          <img
            class="cover"
            :src="item.cover ? item.cover : emptyCover"
            style="width: 100%"
          />
          <div class="label-list">
            <span>
              项目:
              <el-tooltip placement="top" :content="item.projectName">
                {{
                  item.projectName.length > 20
                    ? item.projectName.slice(0, 20) + "..."
                    : item.projectName
                }}
              </el-tooltip>
            </span>
            <span>
              地址:
              <el-tooltip placement="bottom" :content="item.projectAddress">
                {{
                  item.projectAddress.length > 20
                    ? item.projectAddress.substr(0, 20) + "..."
                    : item.projectAddress
                }}
              </el-tooltip></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 { getSysSetting } from "@/request";
// 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";
import emptyCover from "@/assets/image/pic.jpg";

import { changeThemeColor } from "./theme";
const params = useUrlSearchParams("history");
console.log("params", params.deptId);
// const el = ref(document.documentElement);

// const primaryColor = useCssVar("--el-color-primary", document.documentElement);
// primaryColor.value = "#00C8AF";
// const primaryColor = useCssVar("--el-color-primary", el, {
//   initialValue: "#00C8AF",
// });

const current = ref(0);
const currentMaptype = ref(0);
const keywordSearch = ref("");
const list = ref<any>([]);
const searchList = ref<any>([]);
const state = reactive({
  deptId: String(params.deptId) || "",
  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 domain = location.protocol + "//" + location.host;

const queryURL = `${domain}/api/fusion/web/fireProject/queryProject`;

axios.get(getSysSetting).then((data) => {
  const { themeColour } = data.data;
  const setColor = themeColour ? `#${themeColour}` : "#00C8AF";
  console.log("setColor", setColor);
  changeThemeColor(setColor);
});
// 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[];
  const positions: any[] = [];
  list.value = data.filter((i) => i.latAndLong) as any[];
  console.log("list", list.value);
  Array.from(list.value).forEach((item: any) => {
    // console.log(item)
    const latlng = item.latAndLong;

    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.projectName,
      label: item.projectName,
      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 initKeywordMakers = async () => {
  const data = searchList.value;
  const positions: any[] = [];
  map.remove(markers.value);
  markers.value = [];
  // list.value = data.filter((i) => i.latAndLong) as any[];
  // console.log("list", list.value);
  Array.from(data).forEach((item: any) => {
    // console.log(item)
    const latlng = item.latAndLong;

    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.projectName,
      label: item.projectName,
      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",
  });

  (window as any).map = map = new AMap.Map(mapEl.value, {
    WebGLParams: {
      preserveDrawingBuffer: true,
    },

    mapStyle: "amap://styles/normal", // 默认地图样式,
    resizeEnable: true,
  });

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

  initMakers();
};

watch(
  keywordSearch,
  (val) => {
    searchList.value = list.value.filter((item) =>
      String(item.projectName).includes(val)
    );
    initKeywordMakers();
    console.log("searchList", searchList);
  },
  {
    immediate: true,
  }
);

watch(currentMaptype, (val) => {
  console.log("currentMaptype", val);
  if (val === 0) {
    const btn = document.querySelector(
      "input[data-id='AMap.TileLayer']"
    ) as any as HTMLInputElement;
    btn && btn.click();
  }
  if (val === 1) {
    const btn = document.querySelector(
      "input[data-id='AMap.TileLayer.Satellite']"
    ) as any as HTMLInputElement;
    btn && btn.click();
  }
});

onMounted(() => {
  // console.log("caseId", caseId);

  loadMap();
  // primaryColor.value = "#ff9800";
});
const handCardClick = (id: number) => {
  const url = getQuery(id, true);
  console.log("url", url);
  window.open(url);
};
</script>
<style>
body {
  padding: 0;
  margin: 0;
  background-color: #f0f2f5;
}

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

.tabbar {
  display: flex;
  width: calc(100% - 60px);
  position: fixed;
  top: 30px;
  z-index: 10000;
  justify-items: center;
  justify-content: space-between;
  padding: 0 30px;
}

.tabbar .left,
.tabbar .right {
  display: flex;
  flex-direction: row;
  gap: 0 20px;
}
.tabbar .left {
  gap: 0 10px;
}
.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;
  padding-bottom: 100px;
}

.card-list {
  margin: 0 auto;
  display: flex;
  gap: 50px 25px;
  width: 90%;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
}

.cover {
  cursor: pointer;
  height: 220px;
  width: 100%;
  object-fit: cover;
  margin-bottom: 20px;
}

.card {
  display: flex;
  flex-direction: column;
  cursor: pointer;
  gap: 10px;
  width: 382px;
  border-radius: 10px 10px 10px 10px;
}
.label-list {
  display: inline-flex;
  flex-direction: column;
  font-weight: 400;
  font-size: 14px;
  color: #282222;
  line-height: 16px;
  text-align: left;
  font-style: normal;
  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;
}
.amap-maptype {
  display: none;
}
</style>
