<template>
  <div id="globalMap">
    <div class="global-map">
      <MapLogical v-if="activeMap === 'logical'" :map-data="mapData" />
      <YztMap
        v-else-if="YMapType.includes(activeMap)"
        ref="map2Ref"
        :active-map="activeMap"
        :point-type="pointType"
        v-model:showMask="showMask"
        @handle-show-video="handleShowVideo"
        @handle-show-warehouse="handleShowWarehouse"
        @handle-show-people="handleShowPeople"
      />
      <Map
        v-else
        ref="mapRef"
        :active-map="activeMap"
        :point-type="pointType"
        v-model:showMask="showMask"
        @handle-show-video="handleShowVideo"
        @handle-show-warehouse="handleShowWarehouse"
        @handle-show-people="handleShowPeople"
      />
      <!--左侧菜单-->
      <LeftMenu
        ref="leftMenuRef"
        style="position: absolute; top: 20px; left: 20px"
        @click-menu="clickMenu"
        @select-search-marker="selectSearchMarker"
      />
      <!--右侧菜单-->
      <RightMenu ref="rightMenuRef" :active-map="activeMap" :point-type="pointType" />
      <!--更换地图类型-->
      <SwitchMapTool :active-map="activeMap" class="tool-box" @switch-map="switchMap" />
      <!--时间轴-->
      <TimeAxis />
      <DrawTools v-if="showDrawTools" :active-map="activeMap" @handle-analysis-data="handleAnalysisData" />
      <NearbyVideos v-if="showNearbyVideos" v-model="showNearbyVideos" :location="location" />
      <GridPointRainfall v-if="showRainfall" v-model="showRainfall" :location="location" />
      <MaterialDetail v-if="showWarehouse" v-model="showWarehouse" :warehouse-data="warehouseData" />
      <CommunicationSupport v-if="communicationSupport.show" @close="handleHideCommunicationSupport" />
      <EmergencyCrew v-if="showPeople" :id="teamId" v-model="showPeople" />
    </div>
  </div>
</template>

<script lang="ts" setup name="globalMap">
import Map from '@/components/Map/index.vue';
import YztMap from '@/components/Map/YztMap/index.vue';
import MapLogical from '@/components/Map/MapLogical.vue';
import { iconList, logicalData } from './data/mapData';
import SwitchMapTool from '@/views/globalMap/SwitchMapTool.vue';
import LeftMenu from './LeftMenu.vue';
import MaterialDetail from './MaterialDetail.vue';
import TimeAxis from '@/components/TimeAxis/index.vue';
import { deepClone } from '@/utils';
import { getPointInfo } from '@/api/globalMap';
import RightMenu from './RightMenu/index.vue';
import { PointType } from '@/api/globalMap/type';
import DrawTools from '@/views/globalMap/RightMenu/DrawTools.vue';
import CommunicationSupport from '@/views/globalMap/RightMenu/CommunicationSupport.vue';
import GridPointRainfall from '@/views/globalMap/RightMenu/GridPointRainfall.vue';
import EmergencyCrew from '@/views/globalMap/RightMenu/EmergencyCrew.vue';

const AMapType = ['vectorgraph', 'satellite'];
const YMapType = ['satellite2', 'satellite3', 'imageMap', 'imageMap2'];
const rightMenuRef = ref(null);
const mapData = reactive(logicalData);
let map;
let mapRef = ref(null);
let map2Ref = ref(null);
let leftMenuRef = ref(null);
let showMask = ref(true);
//  vectorgraph satellite imageMap imageMap3 logical satellite2 satellite3
let activeMap = ref('satellite');
// 附近视频菜单数据
let tempMenu = ref({
  name: '',
  checked: false
});
const communicationSupport = reactive({
  show: false,
  data: {}
});

const switchMap = (key) => {
  activeMap.value = key;
};
let pointType = ref<PointType[]>([]);
let markerList = ref([]);
const addMarkers = (item) => {
  const dom = ['satellite2', 'satellite3', 'imageMap', 'imageMap2'].includes(activeMap.value) ? map2Ref.value : mapRef.value;
  if (dom) {
    if (!item.checked) {
      let index = pointType.value.findIndex((item2) => item.component === item2.component);
      if (index > -1) {
        pointType.value.splice(index, 1);
      }
      if (pointType.value && pointType.value.length === 0) {
        dom.clearMarker('point');
        return;
      }
    } else {
      // 右侧图层分析状态
      item.checked2 = true;
      pointType.value.push(item);
    }
    let path = [];
    pointType.value.forEach((item) => {
      path.push(item.component);
    });
    getPointInfo(path.toString()).then((res) => {
      const data = res.data && res.data.list ? res.data?.list : [];
      markerList.value = data;
      data.forEach((item2) => {
        // 获取图标
        if (iconList[item2.dataType]) {
          item2.icon = iconList[item2.dataType].image;
          item2.image = iconList[item2.dataType].image;
          item2.imageHover = iconList[item2.dataType].imageHover;
          item2.size = iconList[item2.dataType].size;
        } else {
          item2.icon = iconList['common'].image;
          item2.image = iconList['common'].image;
          item2.imageHover = iconList['common'].imageHover;
          item2.size = iconList['common'].size;
        }
        if (item2.materia_name) {
          item2.name = item2.materia_name;
        }
        item2.parentId = item.component;
        item2.lnglat = [item2.longitude, item2.latitude];
      });
      dom.addMarker(data);
    });
  }
};
// 跳转指定地点
const toAddress = (item) => {
  const dom = activeMap.value === 'imageMap' ? map2Ref.value : mapRef.value;
  dom.setCenter(item);
};

let showDrawTools = ref(false);
// 右侧菜单

// 点击菜单
const clickMenu = (item, dataList) => {
  if (item.path === '1') {
    // 空间分析
    if (item.component === 'spatial') {
      showDrawTools.value = !showDrawTools.value;
    }
    rightMenuRef.value.updateMenu(item.checked ? '1' : '2', item);
  } else if (item.path === '2') {
    let checked = item.checked ? '1' : '2';
    // 打点信息
    addMarkers(item);

    if (
      [
        '易涝隐患点',
        '无人机',
        '铁塔运行监测',
        // '物资与装备',
        '通讯保障',
        '路网视频',
        '江湖河库',
        '防溺水',
        '森林防火',
        '防灾救援',
        '救援队伍'
      ].includes(item.name)
    ) {
      rightMenuRef.value.updateMenu(checked, item);
    } else {
      let index = findChecked(dataList, item.name);
      if (item.checked && index > 0) {
        // 已有图层分析直接切换到该index
        rightMenuRef.value.showIndexMenu('图层分析');
      } else if (item.checked || (!item.checked && index === 0)) {
        rightMenuRef.value.updateMenu(checked, { name: '图层分析', meta: { icon: 'icon1' } });
      }
    }
  } else if (item.path === '3') {
    // 通讯保障
    communicationSupport.show = !communicationSupport.show;
    communicationSupport.data = item;
  } else if (item.path === '4') {
    tempMenu.value = item;
    // 附近视频
    map = getMap();
    //为地图注册click事件获取鼠标点击出的经纬度坐标
    map.on('click', handleClickMap);
  }
};
const handleHideCommunicationSupport = () => {
  communicationSupport.show = false;
  leftMenuRef.value.setMenuChange(communicationSupport.data, false);
};
const findChecked = (dataList, name) => {
  let index = 0;
  dataList.forEach((item) => {
    if (item.name !== name && item.path === '2' && !!item.checked) {
      index++;
    }
    if (item.children && item.children.length > 0) {
      let res = findChecked(item.children, name);
      index += res;
    }
  });
  return index;
};
// 点击搜索结果，添加标注
const selectSearchMarker = (item) => {
  const dom = YMapType.includes(activeMap.value) ? map2Ref.value : mapRef.value;
  let item2 = deepClone(item);
  // 获取图标
  if (iconList[item2.dataType]) {
    item2.icon = iconList[item2.dataType].imageHover;
    item2.image = iconList[item2.dataType].image;
    item2.imageHover = iconList[item2.dataType].imageHover;
    item2.size = iconList[item2.dataType].size;
  } else {
    item2.icon = iconList['common'].imageHover;
    item2.image = iconList['common'].image;
    item2.imageHover = iconList['common'].imageHover;
    item2.size = iconList['common'].size;
  }
  item2.lnglat = [item2.longitude, item2.latitude];
  dom.addSearchMarker(item2);
};
const handleAnalysisData = (data) => {
  rightMenuRef.value.handleMenu('空间分析', data);
};
const getMapUtils = () => {
  if (YMapType.includes(activeMap.value)) {
    return map2Ref.value.getMapUtils();
  } else if (AMapType.includes(activeMap.value)) {
    return mapRef.value.getMapUtils();
  }
  return {};
};
// 获取地图元素操作
const getMap = () => {
  if (YMapType.includes(activeMap.value)) {
    return map2Ref.value.getMap();
  } else if (AMapType.includes(activeMap.value)) {
    return mapRef.value.getMap();
  }
  return {};
};
const showDetail = (data, dataType) => {
  if (YMapType.includes(activeMap.value)) {
    return map2Ref.value.handleHover(data, dataType);
  } else if (AMapType.includes(activeMap.value)) {
    return mapRef.value.handleHover(data, dataType);
  }
  return {};
};
const getDrawTool = () => {
  if (YMapType.includes(activeMap.value)) {
    return map2Ref.value.getMapUtils();
  } else if (AMapType.includes(activeMap.value)) {
    return mapRef.value.drawTool;
  }
  return {};
};
const getMarkers = () => {
  if (YMapType.includes(activeMap.value)) {
    return map2Ref.value.getMarkers();
  } else if (AMapType.includes(activeMap.value)) {
    return mapRef.value.getMarkers();
  }
  return {};
};
const getPlaceSearch = () => {
  if (YMapType.includes(activeMap.value)) {
    return map2Ref.value.getPlaceSearch();
  } else if (AMapType.includes(activeMap.value)) {
    return mapRef.value.getPlaceSearch();
  }
  return {};
};
const trackPlayback = (data) => {
  if (YMapType.includes(activeMap.value)) {
    return map2Ref.value.getMapUtils().trackPlayback(data);
  } else if (AMapType.includes(activeMap.value)) {
    return mapRef.value.trackPlayback(data);
  }
  return {};
};
let showNearbyVideos = ref(false);
let showRainfall = ref(false);
let location = ref([]);
watch(showNearbyVideos, () => {
  if (!showNearbyVideos.value) {
    location.value = [];
    if (!!tempMenu.value && !!tempMenu.value.name) {
      leftMenuRef.value.setMenuChange(tempMenu.value, false);
      tempMenu.value = {};
      if (AMapType.includes(activeMap.value)) {
        map.off('click', handleClickMap);
      } else {
        map.un('click', handleClickMap);
      }
    }
  }
});
watch(showRainfall, () => {
  if (!showRainfall.value) {
    location.value = [];
    if (!!tempMenu.value && !!tempMenu.value.name) {
      leftMenuRef.value.setMenuChange(tempMenu.value, false);
      tempMenu.value = {};
      if (AMapType.includes(activeMap.value)) {
        map.off('click', handleClickMap);
      } else {
        map.un('click', handleClickMap);
      }
    }
  }
});
// 显示附近视频
const handleShowVideo = (data) => {
  location.value = [data.longitude, data.latitude];
  showNearbyVideos.value = true;
};
const handleClickMap = (e) => {
  if (AMapType.includes(activeMap.value)) {
    location.value = [e.lnglat.lng, e.lnglat.lat];
  } else {
    location.value = e.coordinate;
  }
  if (!!tempMenu.value && tempMenu.value.name === '附近视频') {
    showNearbyVideos.value = true;
  } else if (!!tempMenu.value && tempMenu.value.name === '格点雨量') {
    showRainfall.value = true;
  } else if (!!tempMenu.value && tempMenu.value.name === '定点分析') {
    const item = deepClone(tempMenu.value);
    const nowLocation = deepClone(location.value);
    tempMenu.value = {};
    if (AMapType.includes(activeMap.value)) {
      map.off('click', handleClickMap);
    } else {
      map.un('click', handleClickMap);
    }
    rightMenuRef.value.updateMenu(item.checked ? '1' : '2', item, nowLocation);
  }
};
let showWarehouse = ref(false);
let warehouseData = ref('');
const handleShowWarehouse = (data) => {
  warehouseData.value = data;
  showWarehouse.value = true;
};

// 救援队伍人员列表
let showPeople = ref(false);
let teamId = ref('');
const handleShowPeople = (data) => {
  teamId.value = data.id;
  showPeople.value = true;
};
// onMounted(() => {
//   mapRef.value.addEventListener('resize', handleResize);
// })
onBeforeUnmount(() => {
  if (!!map) {
    if (AMapType.includes(activeMap.value)) {
      map.off('click', handleClickMap);
    } else {
      map.un('click', handleClickMap);
    }
  }
});

provide('getMapUtils', getMapUtils);
provide('getMap', getMap);
provide('trackPlayback', trackPlayback);
provide('showDetail', showDetail);
provide('getDrawTool', getDrawTool);
provide('getMarkers', getMarkers);
provide('getPlaceSearch', getPlaceSearch);
</script>

<style lang="scss" scoped>
#globalMap {
  width: 100%;
  height: 100%;
}
.global-map {
  width: 100%;
  height: 100%;
  position: relative;
  //overflow: hidden;
  .tool-box {
    position: absolute;
    right: 430px;
    bottom: 180px;
    z-index: 10;
    color: #fff;
  }
}
.box {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 300px;
  background-color: #041d55;
  display: flex;
  flex-direction: column;
  padding: 20px;
  color: #fff;
  font-size: 16px;
  height: 500px;
  max-height: 90%;
  div {
    line-height: 30px;
    cursor: pointer;
  }
}
.fixed {
  position: fixed !important;
}
</style>
