<template>
  <div class="main">
    <div class="tree">
      <el-input
        v-model="treeText"
        placeholder="Please enter keyword"
        @input="handleTreeFilter"
      />
      <el-tree-v2
        ref="ref_tree"
        :data="treeData"
        :props="{
          value: 'mapId',
          label: 'mapLabel',
          children: 'children'
        }"
        :height="800"
        :filter-method="filterMethod"
      >
        <template #default="{ node }">
          <div>
            <span>{{ node.label }}</span>
            <el-link v-if="!node.data._show" href="javascript:;" type="primary" @click.stop="onShow(node)">显示</el-link>
            <el-link v-else href="javascript:;" type="primary" @click.stop="onHide(node)">隐藏</el-link>
          </div>
        </template>
      </el-tree-v2>
    </div>
    <div class="map">
      <EasyMapGLComponent
        @easyMapGLLoad="mapGLLoad"/>
    </div>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  computed,
  onMounted,
  ref,
  reactive,
  watch,
  getCurrentInstance,
  ComponentInternalInstance,
  toRefs,
  nextTick, createApp
} from 'vue'
import {useStore} from 'vuex'
import {useRouter, useRoute} from 'vue-router'
import {ElMessage, ElMessageBox} from "element-plus";
import xqysJson from './xqys.json'
import * as format from "ol/format";
import defaultImg from "./img/AIS.svg";
import axBayonetListImg from "./img/tools-element-port-bayonet.svg";
import axSiteListImg from "./img/tools-element-port-industry.svg";
import governmentalListImg from "./img/tools-element-shoreline-government.svg";
import islandListImg from "./img/tools-element-shoreline-island.svg";
import monitoringListImg from "./img/tools-element-water-port.svg";
import radarListImg from "./img/tools-element-police-PDT.svg";
import terminalListImg from "./img/tools-element-shoreline-policing.svg";
import waterBasedFacilitiesListImg from "./img/tools-element-port-facilities.svg";
import deptInfoImg from "./img/tools-element-dept-0.svg";
import ShipHover from "@/views/ship-test/business/v2/ship-hover.vue";
import mapboxgl from "mapbox-gl";

export default defineComponent({
  name: '',
  components: {},
  props: {},
  setup(props, {emit}) {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const that = (getCurrentInstance() as ComponentInternalInstance).appContext.config.globalProperties
    const state = reactive({
      map: <any>null,
      mapFunc: <any>null,
      treeData: <any>[],
      sourceElement: 'source_element',
      popupHover: <any>null,
      treeText: ''
    })
    const ref_tree = ref()
    const mapGLLoad = (map, func) => {
      state.map = map
      state.mapFunc = func
      initMap()
      initTree()
    }
    const initTree = () => {
      state.treeData = []
      const formatData = (key, pName, idKey = 'id', labelKey = 'name') => {
        const obj = {
          mapId: key,
          mapLabel: pName,
          children: [],
          _show: true
        }
        xqysJson.data[key].forEach(v => {
          v.mapId = key + '_' + v[idKey]
          v.mapLabel = v[labelKey]
          v._show = true
          obj.children.push(v)
        })
        state.treeData.push(obj)
      }
      formatData('axAreaList', '岸线-预警区')
      formatData('axBayonetList', '岸线-卡口')
      formatData('axCoastlineList', '岸线-海岸线')
      formatData('axSiteList', '岸线-行业场所')
      formatData('deptInfo', '部门详情', 'deptId', 'deptName')
      formatData('districtList', '警务区')
      formatData('governmentalList', '政府机构')
      formatData('islandList', '岛屿')
      formatData('monitoringList', '视频监控')
      formatData('portList', '港区列表')
      formatData('radarList', '雷达')
      formatData('seaList', '水域-海域')
      formatData('terminalList', '自助报备终端')
      formatData('waterAreaList', '水域-警务区')
      formatData('waterBasedFacilitiesList', '水域-水上设施')
      setSourceData()
    }
    const initMap = () => {
      state.mapFunc.addImg('defaultImg', defaultImg)
      state.mapFunc.addImg('axBayonetListImg', axBayonetListImg)
      state.mapFunc.addImg('axSiteListImg', axSiteListImg)
      state.mapFunc.addImg('governmentalListImg', governmentalListImg)
      state.mapFunc.addImg('islandListImg', islandListImg)
      state.mapFunc.addImg('monitoringListImg', monitoringListImg)
      state.mapFunc.addImg('radarListImg', radarListImg)
      state.mapFunc.addImg('terminalListImg', terminalListImg)
      state.mapFunc.addImg('waterBasedFacilitiesListImg', waterBasedFacilitiesListImg)
      state.mapFunc.addImg('deptInfoImg', deptInfoImg)
      state.map.addSource(state.sourceElement, {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: []
        }
      })
      state.map.addLayer({
        id: 'layer_element-line',
        type: "line",
        source: state.sourceElement,
        layout: {
        },
        paint: {
          'line-color': ['get', 'lineColor'],
          'line-width': ['get', 'lineWidth'],
          // 'line-dasharray': ['get', 'lineDasharray']
        }
      })
      state.map.addLayer({
        id: 'layer_element-polygon',
        type: "fill",
        source: state.sourceElement,
        paint: {
          'fill-color': ['get', 'fillColor']
        }
      })
      state.map.addLayer({
        id: 'layer_element-symbol',
        type: "symbol",
        source: state.sourceElement,
        layout: {
          'icon-allow-overlap': true,
          'icon-ignore-placement': true,
          'icon-image': [
            'match',
            ['get', 'iconImage'], // 根据属性值'type'来匹配
            'axBayonetListImg', 'axBayonetListImg',
            'axSiteListImg', 'axSiteListImg',
            'governmentalListImg', 'governmentalListImg',
            'islandListImg', 'islandListImg',
            'monitoringListImg', 'monitoringListImg',
            'radarListImg', 'radarListImg',
            'terminalListImg', 'terminalListImg',
            'waterBasedFacilitiesListImg', 'waterBasedFacilitiesListImg',
            'deptInfoImg', 'deptInfoImg',
            '' // 默认样式
          ],
          "symbol-spacing": 1,
        },
        paint: {
          'icon-color': 'red',
          'icon-halo-color': '#000000',
          'icon-halo-width': 4,
        }
      })
      state.map.on('click', 'layer_element-line', (e) => {
        const features = state.map.queryRenderedFeatures(e.point);
        if (!features.length) {
          return;
        }
        const properties: any = features[0].properties;
        const html = '线_' + properties.mapLabel
        if (state.popupHover) {
          state.popupHover.setLngLat(e.lngLat).setHTML(html)
        } else {
          state.popupHover = new mapboxgl.Popup({
            closeOnClick: false
          }).setLngLat(e.lngLat).setHTML(html).addTo(state.map);
          state.popupHover.on('close', () => {
            state.popupHover = null
          })
        }
      });
      state.map.on('click', 'layer_element-polygon', (e) => {
        const features = state.map.queryRenderedFeatures(e.point);
        if (!features.length) {
          return;
        }
        const properties: any = features[0].properties;
        const html = '面_' + properties.mapLabel
        if (state.popupHover) {
          state.popupHover.setLngLat(e.lngLat).setHTML(html)
        } else {
          state.popupHover = new mapboxgl.Popup({
            closeOnClick: false
          }).setLngLat(e.lngLat).setHTML(html).addTo(state.map);
          state.popupHover.on('close', () => {
            state.popupHover = null
          })
        }
      });
      state.map.on('click', 'layer_element-symbol', (e) => {
        const features = state.map.queryRenderedFeatures(e.point);
        console.log(features)
        if (!features.length) {
          return;
        }
        const properties: any = features[0].properties;
        const html = '点_' + properties.mapLabel
        if (state.popupHover) {
          state.popupHover.setLngLat(e.lngLat).setHTML(html)
        } else {
          state.popupHover = new mapboxgl.Popup({
            closeOnClick: false
          }).setLngLat(e.lngLat).setHTML(html).addTo(state.map);
          state.popupHover.on('close', () => {
            state.popupHover = null
          })
        }
      });
    }
    const globalLineDash = [
      [0, 0], //实线
      [15, 15], //长虚线
      [5, 5] //虚线
    ]
    const setSourceData = () => {
      const arr: any = []
      state.treeData.forEach(p => {
        console.log(p)
        if (p.mapId === 'deptInfo') {

        } else {
          p.children.forEach(v => {
            try {
              const geometry: any = new format.WKT().readFeature(v.location).getGeometry()
              const obj = {
                type: 'Feature',
                geometry: {
                  type: geometry.getType(),
                  coordinates: geometry.getCoordinates()
                },
                properties: v
              }
              let fillColor = 'rgba(20, 129, 241, 0.3)'
              let lineColor = '#2860F1'
              let lineWidth = 1
              let lineDasharray = globalLineDash[0]
              if (v.regionalColor) {
                fillColor = v.regionalColor
              }
              if (v.segmentColor) {
                lineColor = v.segmentColor
              }
              if (v.segmentWidth) {
                lineWidth = v.segmentWidth
              }
              if (v.segmentType) {
                lineDasharray = globalLineDash[Number(v.segmentType)]
              }
              obj.properties.fillColor = fillColor
              obj.properties.lineColor = lineColor
              obj.properties.lineWidth = lineWidth
              obj.properties.lineDasharray = lineDasharray
              switch (p.mapId) {
                case 'axBayonetList': obj.properties.iconImage = 'axBayonetListImg'
                  break
                case 'axSiteList': obj.properties.iconImage = 'axSiteListImg'
                  break
                case 'governmentalList': obj.properties.iconImage = 'governmentalListImg'
                  break
                case 'islandList': obj.properties.iconImage = 'islandListImg'
                  break
                case 'monitoringList': obj.properties.iconImage = 'monitoringListImg'
                  break
                case 'radarList': obj.properties.iconImage = 'radarListImg'
                  break
                case 'terminalList': obj.properties.iconImage = 'terminalListImg'
                  break
                case 'waterBasedFacilitiesList': obj.properties.iconImage = 'waterBasedFacilitiesListImg'
                  break
              }
              arr.push(obj)
            } catch (e) {
            }
          })
        }
      })
      state.map.getSource(state.sourceElement).setData({
        type: 'FeatureCollection',
        features: arr
      })
    }
    const filterMethod = (text: string, node: any) => {
      return node.mapLabel?.includes(text)
    }
    const handleTreeFilter = (text) => {
      ref_tree.value?.filter(text)
    }
    const onShow = (node) => {
      console.log(node)
      node.data._show = true
      node.children?.forEach(v => {
        v._show = true
      })
      setSourceData()
    }
    const onHide = (node) => {
      console.log(node)
      node.data._show = false
      node.children?.forEach(v => {
        v._show = false
      })
      setSourceData()
    }
    onMounted(() => {
      console.log(xqysJson)
    })
    return {
      ...toRefs(state),
      mapGLLoad,
      setSourceData,
      filterMethod,
      handleTreeFilter,
      ref_tree,
      onShow,
      onHide
    }
  },
})
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  height: 100vh;
  display: flex;
  .tree {
    width: 400px;
    height: 100%;
  }
  .map {
    flex: 1;
  }
}
</style>
