import { onUnmounted } from 'vue'
import * as esriloader from 'esri-loader'
import useJsApi from '@/hooks/useJsApi'
import sceneViewPopup from '@/util/sceneViewPopup'
import {
  transOrgHtml,
  transMemberHtml,
  transListHtml,
  transActivityHtml,
} from '@/util/data2html'
import { api } from '@/ajax'

export default async function useInitMap(el: HTMLElement, camera: any) {
  const config = api.MAP_CONFIG
  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',
  ])

  esriConfig.request.useIdentity = false

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

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

  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.add([], '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

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

  watchUtils.whenFalse(sceneView.popup, 'visible', () => {
    if (window.modelHighlight) {
      window.modelHighlight.remove()
    }
    if (window.poiHighlight) {
      window.poiHighlight.remove()
    }
  })
  window.map = map
  window.graphiclayer = graphiclayer

  addEventListener()

  onUnmounted(() => {
    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 addEventListener() {
  window.sceneView.on('click', function (event) {
    window.sceneView.popup.close()
    window.sceneView.hitTest(event).then(async function (response) {
      if (response.results.length > 0) {
        const { layer } = response.results[0].graphic
        const layername = response.results[0].graphic.layer.id
        const objectId = response.results[0].graphic.attributes.OBJECTID
        window.sceneView.whenLayerView(layer).then(function (layerView) {
          const query = layer.createQuery()
          query.outFields = ['*']
          query.objectIds = [objectId]
          layerView
            .queryFeatures(query)
            .then(function ({ features }) {
              if (!features || features.length === 0) return
              let html = ''
              const title = ''

              let data = features[0]?.attributes
              data.json && (data = JSON.parse(data.json))
              console.log('click data: ', data)
              if (data?.['活动名称']) {
                html = transActivityHtml(data)
              } else if (data?.['姓名']) {
                html = transMemberHtml(data)
              } else if (data?.['党组织名称']) {
                html = transOrgHtml(data)
              } else if (data?.isList) {
                html = transListHtml(data)
              }

              if (!html) return

              // switch (layername) {
              //   //可根据图层名称对应不同操作,构造对应的信息面板内容
              //   case 'jingmo':
              //     const buildingName = result.features[0].attributes.NAME
              //     //根据buildingName查询接口，获取信息
              //     //组装html中的内容

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

              //     break
              //   case '党组织撒点图层':
              //     console.log('click-data: ', result)
              //     const poiName = result.features[0].attributes['党组织名称']
              //     //根据poiName查询接口，获取信息
              //     //组装html中的内容

              //     html =
              //       '<div class="pop-container">根据接口获取信息，构造弹出内容' +
              //       '</div>'
              //     title = '获取到的poi名称'
              //     break
              //   default:
              //     break
              // }

              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)
        })
      }
    })
  })
}
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: sceneViewPopup.createCustompopup(Parameters.content),
  })
}
