import { onBeforeUnmount, onMounted } from 'vue'
import * as esriloader from 'esri-loader'
import useJsApi from '@/hooks/useJsApi'
import senceViewPopup from '@/util/senceViewPopup'

export default async function useInitMap(el: HTMLElement, camera: any) {
  console.log('use---', el, camera)
  const config = {
    jsApiUrl: 'http://10.108.3.41/arcgis_js_api/library/4.18/init.js',
    cssUrl: 'http://10.108.3.41/arcgis_js_api/library/4.18/esri/css/main.css',
  }
  let map: any = null
  let sceneView: any = null
  let graphiclayer: any = null

  esriloader.loadScript({ url: config.jsApiUrl })

  esriloader.loadCss(config.cssUrl) //添加样式

  const [
    esriConfig,
    Map,
    Basemap,
    SceneView,
    MapView,
    SpatialReference,
    IdentityManager,
    Camera,
    LayerList,
    Expand,
    Fullscreen,
    Legend,
    GroupLayer,
    TileLayer,
    SceneLayer,
    FeatureLayer,
    GraphicsLayer,
    DirectLineMeasurement3D,
    AreaMeasurement3D,
    Graphic,
    watchUtils,
    urlUtils,
  ] = await useJsApi([
    'esri/config',
    'esri/Map',
    'esri/Basemap',
    'esri/views/SceneView',
    'esri/views/MapView',
    'esri/geometry/SpatialReference',
    'esri/identity/IdentityManager',
    'esri/Camera',
    'esri/widgets/LayerList',
    'esri/widgets/Expand',
    'esri/widgets/Fullscreen',
    'esri/widgets/Legend',
    'esri/layers/GroupLayer',
    'esri/layers/TileLayer',
    'esri/layers/SceneLayer',
    'esri/layers/FeatureLayer',
    'esri/layers/GraphicsLayer',
    'esri/widgets/DirectLineMeasurement3D',
    'esri/widgets/AreaMeasurement3D',
    'esri/Graphic',
    'esri/core/watchUtils',
    'esri/core/urlUtils',
  ])

  console.log('~~~', esriConfig)

  esriConfig.request.useIdentity = false

  esriConfig.request.interceptors.push({
    urls: 'https://changsanjiao.shsmi.com/',

    /*
     * 在请求发出去之前，把请求中的机器名改成ip
     * */
    before: function (params: any) {
      const newUrl = params.url.replace(
        'http://changsanjiao.shsmi.com',
        'http://10.108.3.48',
      )
      params.url = newUrl
    },
  })

  map = new Map({
    ground: {
      // surfaceColor: "#021425",
    },
  })

  sceneView = new SceneView({
    container: el,
    viewingMode: 'local',
    map,
    camera: camera,
    popup: {
      defaultPopupTemplateEnabled: true,
    },
  })
  sceneView.popup.autoOpenEnabled = false
  window.sceneView = sceneView

  const layerList = new LayerList({
    view: window.sceneView,
  })

  const layerListExpand = new Expand({
    expandTooltip: '图层控制',
    view: window.sceneView,
    content: layerList,
  })

  window.sceneView.ui.add([layerListExpand], 'top-right')
  window.sceneView.ui.remove([
    'zoom',
    'navigation-toggle',
    'attribution',
    'compass',
  ])

  const baseLayer = new TileLayer(
    'http://10.108.3.48/changsanjiao/rest/services/Hosted/Base_Map/MapServer',
    {
      id: 'zhengwuBasemap',
      visible: true,
      opacity: 1,
      title: '政务底图',
    },
  )

  const sjgyLayer = new TileLayer(
    'http://10.108.3.48/changsanjiao/rest/services/sjgy_3857/MapServer',
    {
      id: 'sjgy',
      visible: true,
      opacity: 1,
      title: '世纪公园',
    },
  )

  const baseMapGroupLayer = new GroupLayer({
    title: '基础底图',
    visible: true,
    visibilityMode: 'independent',
    layers: [baseLayer, sjgyLayer],
    // layers: [baseLayer],
    opacity: 1,
  })
  map.layers.add(baseMapGroupLayer)

  const sceneLayer0 = new SceneLayer({
    url: 'http://10.108.3.48/changsanjiao/rest/services/Hosted/HM_BUILDING0826/SceneServer',
    visible: true,
    title: '精模',
    id: 'jingmo',
    outFields: ['*'],
    elevationInfo: {
      mode: 'absolute-height',
      offset: 3,
    },
  })
  map.add(sceneLayer0)
  window.sceneLayer0 = sceneLayer0

  const sceneLayer3 = new SceneLayer({
    url: 'http://10.108.3.48/changsanjiao/rest/services/Hosted/HM_ROAD0730/SceneServer',
    visible: true,
    title: '全息道路路面',
    elevationInfo: {
      mode: 'absolute-height',
      offset: 3,
    },
  })

  const sceneLayer4 = new SceneLayer({
    url: 'http://10.108.3.48/changsanjiao/rest/services/Hosted/HM_BUJIAN0730/SceneServer',
    visible: true,
    title: '全息道路部件',
    elevationInfo: {
      mode: 'absolute-height',
      offset: 3,
    },
    minScale: 2500,
  })

  const sceneLayer7 = new SceneLayer({
    url: 'http://10.108.3.48/changsanjiao/rest/services/Hosted/HM_WHITEMODEL_OUTSIDE0320/SceneServer',
    visible: true,
    title: '周边白模',
    popupEnabled: false,
  })

  graphiclayer = new GraphicsLayer()
  map.add(graphiclayer)

  const modelGroupLayer = new GroupLayer({
    title: '其他模型',
    visible: true,
    visibilityMode: 'independent',
    layers: [sceneLayer3, sceneLayer4, sceneLayer7],
    opacity: 1,
  })
  setInterval(function () {
    map.layers.add(modelGroupLayer)
  }, 15000)

  watchUtils.whenFalse(sceneView.popup, 'visible', () => {
    if (window.modelHighlight) {
      window.modelHighlight.remove()
    }
  })
  window.sceneView.on('click', function (event: any) {
    window.sceneView.popup.close()
    sceneView.hitTest(event).then(async function (response: any) {
      if (response.results.length > 0) {
        const layername = response.results[0].graphic.layer.id
        let objectId: any = null
        objectId = response.results[0].graphic.attributes.OBJECTID
        console.log(layername)
        switch (layername) {
          //可根据图层名称对应不同操作
          case 'jingmo':
            window.sceneView
              .whenLayerView(sceneLayer0)
              .then(function (layerView: any) {
                const query = sceneLayer0.createQuery()
                query.outFields = ['*']
                query.objectIds = [objectId]
                layerView
                  .queryFeatures(query)
                  .then(function (result: any) {
                    if (result.features.length > 0) {
                      const buildingName = result.features[0].attributes.NAME
                      //根据buildingName查询接口，获取信息
                      //组装html中的内容

                      const html =
                        '<div>根据接口获取信息，构造弹出内容' + '</div>'
                      const title = '获取到的楼名'

                      const contentParam = {
                        dockpoint: response.ground.mapPoint,
                        title: title,
                        content: {
                          type: 'html',
                          html: html,
                        },
                      }

                      togglePopupTemplate(false)
                      setPopupContent(contentParam)

                      if (window.modelHighlight) {
                        window.modelHighlight.remove()
                      }
                      window.modelHighlight = layerView.highlight(objectId)
                    }
                  })
                  .catch(console.error)
              })
            break
          default:
        }
      }
    })
  })
  window.map = map

  onBeforeUnmount(() => {
    map = null
    window.map = null
    sceneView = null
    window.sceneView = null
    graphiclayer = null
    window.graphiclayer = null
    window.sceneLayer0 = null
    window.modelHighlight = null
  })

  return [map, sceneView, graphiclayer]
}

function togglePopupTemplate(trueOrFalse: boolean) {
  if (trueOrFalse === true) {
    window.sceneView.popup.autoOpenEnabled = true
  } else {
    window.sceneView.popup.autoOpenEnabled = false
  }
}
// 设置 弹窗内容
async function setPopupContent(Parameters: any) {
  window.sceneView.popup.open({
    actions: [],
    location: Parameters.dockpoint,
    title: Parameters.title,
    collapseEnabled: false,
    dockEnabled: false,
    content: senceViewPopup.createCustompopup(Parameters.content),
  })
}
