import { onBeforeUnmount } 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'
import store from '@/store'

export default async function useInitMap(
  el: HTMLElement,
  camera: any,
  showCommittee: any,
  showBuilding: any,
) {
  const config = api.MAP_CONFIG
  let map: any = null
  let sceneView: any = null
  let graphiclayer: any = null
  let timer: 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(
      //   'https://changsanjiao.shsmi.com',
      //   'http://10.108.3.48',
      // )
    },
  })
  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
  sceneView.when(function () {
    sceneView.qualitySettings.memoryLimit = 4096
  })
  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(
    api.MAP_URL + '/changsanjiao/rest/services/Hosted/Base_Map/MapServer',
    {
      id: 'zhengwuBasemap',
      visible: true,
      opacity: 1,
      title: '政务底图',
    },
  )

  const sjgyLayer = new TileLayer(
    api.MAP_URL + '/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:
      api.MAP_URL +
      '/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)

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

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

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

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

  timer = setInterval(function () {
    map.layers.add(modelGroupLayer)
  }, 15000)

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

  addEventListener()

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

  function addEventListener() {
    window.sceneView.on('click', function (event) {
      window.sceneView.popup.close()
      if (window.modelHighlight) {
        window.modelHighlight.remove()
      }
      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)
                  if (data?.['类别']?.includes('居民区')) {
                    const areas =
                      data?.['管辖范围']?.map(
                        (item: any) => item?.['范围名称'],
                      ) || []
                    areas.forEach((area) => showCommittee(area))
                    // TODO 待测试
                  } else if (data?.['类别']?.includes('两新')) {
                    const buildings =
                      data?.['管辖楼宇']?.map((item: any) => item?.OBJECTID) ||
                      []
                    buildings.forEach((building) => showBuilding(building))
                    // window.modelHighlight = buildings.map((building) => building && layerView.highlight(building))
                    // TODO 待测试
                  }
                } else if (data?.isList) {
                  html = transListHtml(data)
                } else if (data?.NAME || data?.OBJECTID) {
                  store.dispatch(
                    'getBuildingDetail',
                    data?.NAME || data?.OBJECTID,
                  )
                } else {
                  if (window.modelHighlight) {
                    window.modelHighlight.remove()
                  }
                }

                if (!html) return

                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)
          })
        }
      })
    })
  }

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