<template>
  <div class="gis-layout">
    <EasyMapComponent
        class="map"
        @easyMapLoad="mapLoad"
    />
    <div class="gis-menu">
      <img class="gis-menu-bottom" src="@/assets/images/gis-layout/gis-layout-menu_bottom.png" alt=""/>
      <template v-for="item in menuCpt">
        <div class="gis-menu-item __hover" :class="{active: $route.name === item.name, max: String(item.meta.title).length >5}" @click="$router.push({name: item.name})">
          {{item.meta.title}}
        </div>
      </template>
    </div>
    <div class="gis-tools" v-if="map">
      <div class="gt-search __box-shadow">
        <el-autocomplete
            ref="ref_search"
            v-model="searchInput"
            :fetch-suggestions="searchHandleMapSearch"
            popper-class="__gis-search_popper"
            clearable
            :debounce="800"
            placeholder="请输入关键字进行搜索"
            @select="searchToMapLocation"
        >
          <template #default="{ item }">
            <div class="search-item __hover">
              <img :src="item.icon" alt=""/>
              <div class="name">{{item.name}}</div>
            </div>
          </template>
        </el-autocomplete>
        <div class="search-icon __hover" @click="ref_search.focus()">
          <SvgIcon name="search" color="#ffffff"/>
        </div>
      </div>
      <div class="gt-tools __box-shadow">
        <template v-for="(item, index) in ToolsMapper">
          <div class="tools-line" v-if="index > 0"/>
          <div class="tools-item __hover" :class="{active: toolsType === item.value, disabled: item.disabled || (item.value === 'analysis' && toolsType === item.value)}" @click="(item.disabled || (item.value === 'analysis' && toolsType === item.value)) ? undefined : toolsHandleClick(item)">
            {{item.label}}
          </div>
        </template>
      </div>
      <div class="gt-tools-component" v-if="toolsType && toolsType !== 'clear' && toolsCom">
        <Component :is="toolsCom" :map="map" :mapFunc="mapFunc" v-model:transfer="toolsParams[toolsType]" @cancel="toolsType = ''"/>
      </div>
    </div>
    <div class="gis-content">
      <RouterViewCom/>
    </div>
    <VideoPlayKedaCom v-if="$store.state.gis.videoParams.show" v-model:layout="videoLayout" :form="$store.state.gis.videoParams" @close="$store.dispatch('gis/LOAD_VIDEO_PARAMS', {show: false})"/>
<!--    <div class="mockButtons">-->
<!--      <el-button @click="mockSB1">模拟设备1</el-button>-->
<!--      <el-button @click="mockSB2">模拟设备2</el-button><br/>-->
<!--      <el-button @click="mockJQ1">模拟景区1</el-button><br/>-->
<!--      <el-button @click="mockLG1">模拟旅馆1</el-button><br/>-->
<!--      <el-button @click="mockCZW1">模拟出租屋1</el-button><br/>-->
<!--      <el-button @click="mockHCZ1">模拟火车站1</el-button>-->
<!--    </div>-->
  </div>
  <GisDefaultDom ref="ref_gisDefault"/>
  <GisQyDom ref="ref_gisQy"/>
</template>

<script lang="ts">
import {
  defineComponent,
  computed,
  onMounted,
  ref,
  reactive,
  watch,
  getCurrentInstance,
  ComponentInternalInstance,
  toRefs,
  nextTick,
  markRaw
} from 'vue'
import {useStore} from 'vuex'
import {useRouter, useRoute} from 'vue-router'
import {ElMessage, ElMessageBox} from "element-plus";
import RouterViewCom from '@/layout/router-view.vue'
import ElementCom from './tools/element.vue'
import SelectCom from './tools/select.vue'
import AnalysisCom from './tools/analysis.vue'
import ToolCom from './tools/tool.vue'
import PositionCom from './tools/position.vue'
import BaseCom from './tools/base.vue'
import ExampleCom from './tools/example.vue'
import VideoPlayKedaCom from "@/views/gis/business/common/VideoPlayKeda.vue";
import {clearLocationDom} from '@/components/easyMap/func/location'
import {clearMeasureDom} from '@/components/easyMap/func/measure'
import GisDefaultDom from '../map-info/overlay/default/index.vue'
import GisQyDom from '../map-info/overlay/qy/index.vue'
import axios from "axios";
import store from "@/store";

export default defineComponent({
  name: '',
  components: {
    RouterViewCom,
    ElementCom,
    SelectCom,
    AnalysisCom,
    ToolCom,
    PositionCom,
    BaseCom,
    ExampleCom,
    VideoPlayKedaCom,
    GisDefaultDom,
    GisQyDom,
  },
  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,
      searchInput: '',
      toolsType: '',
      toolsCom: null,
      toolsParams: {
        element: null,
        position: null
      },
      videoLayout: {
        width: 640,
        height: 366,
        left: 1200,
        top: 460
      },
    })
    const ToolsMapper = [
      {label: '图层', value: 'element', com: ElementCom, disabled: false},
      {label: '框选', value: 'select', com: SelectCom, disabled: false},
      {label: '周边分析', value: 'analysis', com: AnalysisCom, disabled: false},
      {label: '工具', value: 'tool', com: ToolCom},
      {label: '定位', value: 'position', com: PositionCom},
      {label: '清空标绘', value: 'clear', com: undefined},
      {label: '底图', value: 'base', com: BaseCom},
      {label: '图例', value: 'example', com: ExampleCom},
    ]
    const ref_search = ref()
    const ref_gisDefault = ref()
    const ref_gisQy = ref()
    const mapLoad = (map, func) => {
      state.map = map
      store.dispatch('gis/LOAD_GIS_MAP', {
        map: state.map,
        defaultDom: ref_gisDefault.value,
        qyDom: ref_gisQy.value,
      })
      state.mapFunc = func
      store.dispatch('gis/LOAD_GIS_ELEMENT')
    }
    const menuCpt = computed(() => {
      return router.options.routes.filter(v => v.name === store.state.gis.menuRootName)[0].children?.filter(v => !v.meta.noMenu)
    })
    const searchHandleMapSearch = (queryString: string, cb: (arg: any) => void) => {
      if (queryString.trim()) {
        const arr: any = []
        const typeName: any = []
        store.state.dictionary.elementTypeList.forEach(v => {
          if (['sb', 'qy'].includes(v.dictType)) {
            typeName.push(v.geoType)
          }
        })
        axios({
          url: store.state.gis.element.layer.getSource().getUrls()[0],
          method: 'get',
          params: {
            service: 'WFS',
            version: '1.0.0',
            request: 'GetFeature',
            typename: typeName.join(','),
            srsName: 'EPSG:4326',
            outputFormat: 'application/json',
            CQL_FILTER: `name like '%${queryString.trim()}%'`
          }
        }).then(res => {
          res.data.features?.forEach(v => {
            const obj = {
              info: v.properties,
              id: v.properties.dataId,
              name: v.properties.name,
              typeValue: v.properties.typeValue,
              wkt: `POINT(${v.geometry.coordinates.join(' ')})`,
              icon: store.getters['dictionary/elementTypeMapObj'].get(v.properties.typeValue).icon,
              featureType: '',
            }
            if (['lgszyjkscsb', 'jgzzmgs', 'lgsjkyfl'].includes(v.properties.typeValue)) {
              obj.featureType = 'qy'
            } else if (['gal', 'shl', 'myl'].includes(v.properties.typeValue)) {
              obj.featureType = 'sb'
            }
            arr.push(obj)
          })
          cb(arr)
        }).catch(() => {
          cb(arr)
        })
      } else {
        cb([])
      }
    }
    const searchToMapLocation = (val) => {
      state.searchInput = val.name
      switch (val.featureType) {
        case 'qy': {
          console.log(1)
          store.dispatch('gis/LOAD_GIS_PARAMS_QY_RESET')
          store.dispatch('gis/LOAD_GIS_PARAMS_QY', {
            wkt: val.wkt,
            id: val.id,
            info: val.info
          })
        } break
        case 'sb': {
          console.log(2)
          store.dispatch('gis/LOAD_GIS_PARAMS_DEFAULT_RESET')
          store.dispatch('gis/LOAD_GIS_PARAMS_DEFAULT_SB', {
            wkt: val.wkt,
            id: val.id,
            info: val.info
          })
        } break
      }
    }
    const toolsHandleClick = (item) => {
      if (item.value === 'clear') {
        //  工具-标绘'layerName', 'toolDrawViewsLayer'
        state.map.getLayers().getArray().filter(v => v.get('layerName') === 'toolDrawViewsLayer')?.[0]?.getSource()?.clear()
        state.map.getOverlayById('toolOverlay')?.setPosition(undefined)
        //  工具-测量'layerName', 'measureLayer'
        state.map.getLayers().getArray().filter(v => v.get('layerName') === 'measureLayer')?.[0]?.getSource()?.clear()
        clearMeasureDom(state.map)
        //  定位'layerName', 'positionLayer'
        state.map.getLayers().getArray().filter(v => v.get('layerName') === 'positionLayer')?.[0]?.getSource()?.clear()
        clearLocationDom()
      } else {
        state.toolsCom = markRaw(item.com)
        state.toolsType = (state.toolsType === item.value ? '' : item.value)
      }
    }
    const mockSB1 = () => {
      store.dispatch('gis/LOAD_GIS_PARAMS_DEFAULT_SB', {
        type: 'sb',
        wkt: 'POINT(110.73667031084902 19.011386491828695)',
        id: 1,
        info: {
          "pn": "2526",
          "groupid": "89800003866",
          "monitorid": "18678",
          "name": "测试通道2526",
          "online": "0",
          "savestatus": "1",
          "ptztype": "3",
          "deviceid": "46012003001310000011  aaa",
          "areacode": "4.60E+19",
          "longitude": "110.455893",
          "latitude": "19.89477",
          "faultedflag": "0",
          "status": "OFF",
          "isfront": "363658824",
          "type": "公安类",
          "civilcode": "46012003"
        }
      })
    }
    const mockSB2 = () => {
      store.dispatch('gis/LOAD_GIS_PARAMS_DEFAULT_SB', {
        type: 'sb',
        wkt: 'POINT(110.95227700030215 19.027865984016195)',
        id: 1,
        info: {
          "pn": "2526",
          "groupid": "89800003866",
          "monitorid": "18678",
          "name": "2526测试通道2526测试通道2526测试通道2526测试通道2526测试通道",
          "online": "0",
          "savestatus": "1",
          "ptztype": "3",
          "deviceid": "46012003001310000011",
          "areacode": "4.60E+19",
          "longitude": "110.455893",
          "latitude": "19.89477",
          "faultedflag": "0",
          "status": "OFF",
          "isfront": "363658824",
          "type": "公安类",
          "civilcode": "46012003"
        }
      })
    }
    const mockJQ1 = () => {
      store.dispatch('gis/LOAD_GIS_PARAMS_DEFAULT_JQ', {
        type: 'jq',
        wkt: 'POINT(110.74277601017481 18.85289817214939)',
        id: 1,
        info: {
          "name": "海南省博物馆",
          "address": "在海南省海口市琼山区国兴大道68号线",
          "level": "4A",
        }
      })
    }
    const mockLG1 = () => {
      store.dispatch('gis/LOAD_GIS_PARAMS_DEFAULT_LG', {
        type: 'lg',
        wkt: 'POINT(110.74277601017481 18.85289817214939)',
        id: 1,
        info: {
          "name": "佳捷连锁酒店(解放西路)",
          "address": "海口市龙华区解放西路9号金棕榈商业广场F3",
        }
      })
    }
    const mockCZW1 = () => {
      store.dispatch('gis/LOAD_GIS_PARAMS_DEFAULT_CZW', {
        type: 'czw',
        wkt: 'POINT(110.74277601017481 18.85289817214939)',
        id: 1,
        info: {
          "name": "大英出租屋",
          "address": "海口市龙华区解放西路9号金棕榈商业广场F3",
        }
      })
    }
    const mockHCZ1 = () => {
      store.dispatch('gis/LOAD_GIS_PARAMS_DEFAULT_HCZ', {
        type: 'hcz',
        wkt: 'POINT(110.74277601017481 18.85289817214939)',
        id: 1,
        info: {
          "name": "海口东站",
          "address": "海口市龙华区解放西路9号金棕榈商业广场F3",
        }
      })
    }
    onMounted(() => {
      if (window.cusConfig?.internetAuth) {
        if (!sessionStorage.getItem('auth')) {
          if(navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Chrome") != -1){
            window.location.href = "about:blank";
            window.close();
          }else{
            window.opener = null;
            window.open("", "_self");
            window.close();
          }
        }
      }
    })
    return {
      ...toRefs(state),
      mapLoad,
      ToolsMapper,
      ref_search,
      menuCpt,
      searchHandleMapSearch,
      searchToMapLocation,
      toolsHandleClick,
      ref_gisDefault,
      ref_gisQy,
      mockSB1,
      mockSB2,
      mockJQ1,
      mockLG1,
      mockCZW1,
      mockHCZ1,
    }
  },
})
</script>

<style scoped lang="scss">
.gis-layout {
  width: 100%;
  height: 100vh;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  .map {
    z-index: 1;
  }
  .gis-menu {
    $diff: 14px;
    $menuBottom: 16px;
    position: absolute;
    z-index: 2;
    bottom: $menuBottom;
    display: flex;
    justify-content: center;
    align-items: center;
    &:before, &:after {
      content: '';
      background-image: url("@/assets/images/gis-layout/gis-layout-menu_side.png");
      width: 246px;
      height: 39px;
      position: absolute;
      bottom: -$menuBottom;
    }
    &:before {
      left: calc((#{$diff} + 246px) * -1);
    }
    &:after {
      right: calc((#{$diff} + 246px) * -1);
      transform: rotateY(180deg);
    }
    .gis-menu-bottom {
      position: absolute;
      height: 9px;
      width: calc(100% + 10px + #{$diff} * 2);
      bottom: -$menuBottom;
    }
    .gis-menu-item {
      width: 95px;
      height: 36px;
      background-image: url("@/assets/images/gis-layout/gis-layout-menu_item-min.png");
      background-size: 100% 100%;
      background-repeat: no-repeat;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
      font-family: YouSheBiaoTiHei;
      font-weight: 400;
      color: #60AEFF;
      &:not(&:last-child) {
        margin-right: 4px;
      }
      &.active {
        color: #FFFFFF;
        background-image: url("@/assets/images/gis-layout/gis-layout-menu_item-min_active.png");
      }
      &.max {
        width: 125px;
        background-image: url("@/assets/images/gis-layout/gis-layout-menu_item-max.png");
        &.active {
          background-image: url("@/assets/images/gis-layout/gis-layout-menu_item-max_active.png");
        }
      }
    }
  }
  .gis-tools {
    position: absolute;
    z-index: 3;
    top: 10px;
    right: 10px;
    width: 404px;
    >div {
      box-sizing: border-box;
    }
    .gt-search {
      height: 38px;
      width: 100%;
      display: flex;
      align-items: center;
      .search-icon {
        width: 54px;
        height: 100%;
        background-color: #3e8ef7;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      :deep(.el-autocomplete) {
        flex: 1;
        height: 100%;
        .el-input {
          width: 100%;
          height: 100%;
          .el-input__wrapper {
            border-radius: 0;
          }
        }
      }
    }
    .gt-tools {
      width: 100%;
      height: 38px;
      margin-top: 2px;
      background-color: #FFFFFF;
      border: 1px solid #C7CFDE;
      display: flex;
      align-items: center;
      justify-content: space-around;
      padding: 0 8px;
      .tools-item {
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #AEAEAE;
        &.active {
          color: #1174DB;
          font-weight: bold;
        }
        &.disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }
      .tools-line {
        width: 1px;
        height: 16px;
        background: linear-gradient(0deg, rgba(174,174,174,0) 0%, rgba(213,213,213,0.99) 50%, rgba(174,174,174,0) 100%);
      }
    }
    .gt-tools-component {
      width: 100%;
      margin-top: 2px;
    }
  }
  .gis-content {
    z-index: 4;
  }
}

.mockButtons {
  position: absolute;
  top: 0;
  left: 500px;
}
</style>
