<template>
  <div ref="mapRef" class="map" />
</template>

<script lang="ts" setup>
import { onMounted, ref, nextTick } from 'vue'
import useInitMap from '@/hooks/useInitMap'
import useJsApi from '@/hooks/useJsApi'
import clientLayersOperate from '@/util/clientLayersOperate'
import sceneViewPopup from '@/util/sceneViewPopup'
import axios from 'axios'

const mapRef = ref<HTMLElement | undefined>()
const camera = {
  heading: 0,
  tilt: 75,
  fov: 55,
  position: [0.065, -0.09, 1800],
}
const array1 = ['CB6W6201', 'CB6V650D', 'CB6X660C']
const array2 = ['CB6U640H02', 'CB6U640H01', 'CB6T630C']

onMounted(async () => {
  await nextTick()
  if (mapRef.value) {
    // eslint-disable-next-line
    await useInitMap(mapRef.value, camera)
  }
})

/** 重置地图 */
function resetMap() {
  if (!window.graphiclayer || !window.sceneView) return
  window.graphiclayer.removeAll()
  window.sceneView.popup.close()
  if (window.modelHighlight) {
    window.modelHighlight.remove()
  }
  window.sceneView.goTo(camera)
}

/** 切换为白模 */
function switchBM() {
  const uniqueValueInfos: any[] = []

  //array1中为楼内1-10人的模型名称
  array1.forEach((item) => {
    uniqueValueInfos.push({
      value: item,
      symbol: {
        type: 'mesh-3d',
        symbolLayers: [
          {
            type: 'fill',
            material: {
              color: [120, 200, 239, 0.7],
              colorMixMode: 'replace',
            },
            edges: {
              type: 'solid',
              color: [0, 0, 0, 0.4],
              size: 1,
            },
          },
        ],
      },
    })
  })

  //array1中为楼内10人以上的模型名称
  array2.forEach((item) => {
    uniqueValueInfos.push({
      value: item,
      symbol: {
        type: 'mesh-3d',
        symbolLayers: [
          {
            type: 'fill',
            material: {
              color: [191, 77, 102, 0.7],
              colorMixMode: 'replace',
            },
            edges: {
              type: 'solid',
              color: [0, 0, 0, 0.4],
              size: 1,
            },
          },
        ],
      },
    })
  })

  window.sceneLayer0.renderer = {
    type: 'unique-value',
    field: 'NAME',
    defaultSymbol: {
      type: 'mesh-3d',
      symbolLayers: [
        {
          type: 'fill',
          material: {
            color: [255, 255, 255, 0.7],
            colorMixMode: 'replace',
          },
          edges: {
            type: 'solid',
            color: [0, 0, 0, 0.4],
            size: 1,
          },
        },
      ],
    },
    uniqueValueInfos: uniqueValueInfos,
  }
}

/** 切换为精模 */
function switchJM() {
  window.sceneLayer0.renderer = {
    type: 'simple',
    symbol: {
      type: 'mesh-3d',
    },
  }
}

async function queryBound(layerId: number, name: string) {
  const [QueryTask, Query, GraphicsLayer] = await useJsApi([
    'esri/tasks/QueryTask',
    'esri/tasks/support/Query',
    'esri/layers/GraphicsLayer',
  ])

  const jdLayerUrl = `https://hm.metrodata.cn/cehuiyuan/changsanjiao/rest/services/HM_BOUND_3857/MapServer/${layerId}`
  const queryTask = new QueryTask({
    url: jdLayerUrl,
  })
  const query = new Query()
  query.returnGeometry = true
  query.outFields = ['*']
  if (layerId === 3) {
    query.where = '1=1'
  } else {
    query.where = `名称='${name}'`
  }

  queryTask.execute(query).then(function (results: any) {
    results.features[0].symbol = {
      type: 'simple-fill',
      color: [221, 80, 94, 0.2],
      style: 'solid',
      outline: {
        color: '#DD505E',
        width: 2,
      },
    }
    window.graphiclayer.removeAll()
    window.graphiclayer.add(results.features[0])
    // const cam = that.sceneView.camera.clone();
    // cam.tilt =55;
    // that.sceneView.camera = cam
    window.sceneView.goTo(results.features[0])
  })
}

function showStreet(name: string = '花木街道') {
  queryBound(3, name)
}
function showArea(name: string) {
  queryBound(2, name)
}
function showCommittee(name: string) {
  queryBound(1, name)
}
function showCommunity(name: string) {
  queryBound(0, name)
}

function showBuilding(name: string) {
  if (!window.sceneView) return
  window.sceneView
    .whenLayerView(window.sceneLayer0)
    .then(async (layerView: any) => {
      const query = window.sceneLayer0.createQuery()
      query.outFields = ['*']
      const objectId =
        (
          await axios.get(
            `https://hm.metrodata.cn/cehuiyuan/changsanjiao/rest/services/HM_BOUND_3857/MapServer/4/query?where=NAME=%27${name}%27&f=json&outFields=*`,
          )
        )?.data?.features?.[0]?.attributes?.id || null
      if (!objectId) return

      query.objectIds = [objectId]
      layerView
        .queryExtent(query)
        .then((result: any) => {
          window.sceneView.goTo(result.extent.expand(7))
          if (window.modelHighlight) {
            window.modelHighlight.remove()
          }

          window.modelHighlight = layerView.highlight(objectId)
        })
        .catch(console.error)
    })
}

async function addPoints(name: string, data: any[]) {
  await clientLayersOperate.displayJSONData(name, { result: data })
}

function clearPoints(name?: string) {
  if (!window.pointLayers) return
  window.pointLayers.forEach((item) => {
    // TODO 看是否能根据name删除指定图层
    item.visible = false
  })
}

defineExpose({
  resetMap,
  switchBM,
  switchJM,
  showStreet,
  showArea,
  showCommittee,
  showCommunity,
  showBuilding,
  addPoints,
  clearPoints,
})
</script>

<style lang="stylus" scoped>
.map
  position fixed
  top 0
  left 0
  width 100vw
  height 100vh
</style>
