<template>
  <div class="onemap-page">
    <!-- 图层目录 -->
    <LayerMenu @layerToggle="onLayerToggle" />

    <!-- 地图 -->
    <MapContent ref="mapRef" @mapReady="onMapReady" @mapClick="onMapClick" />

    <!-- 点击要素弹窗 -->
    <FeaturePopup ref="featurePopupRef" />
    <!-- 右侧详情面板 (河档/河段) -->
    <InfoPanel ref="infoPanelRef" />
  </div>
</template>

<script setup>
import { ref, shallowRef } from 'vue'
import MapContent from './mapContent.vue'
import LayerMenu from './components/LayerMenu.vue'
import FeaturePopup from './components/FeaturePopup.vue'
import InfoPanel from './components/InfoPanel.vue'
import WebTileLayer from '@arcgis/core/layers/WebTileLayer'

const mapRef = ref(null)
const viewRef = shallowRef(null)
const featurePopupRef = ref(null)
const infoPanelRef = ref(null)
const addedLayers = new Map()

const onMapReady = ({ view }) => {
  viewRef.value = view
}

// 从 ArcGIS MapServer REST API 查询要素全部属性
const queryFeatureAttributes = async (layerUrl, objectId) => {
  if (!layerUrl || !objectId) return null
  try {
    const url = `${layerUrl}/query?f=json&objectIds=${objectId}&returnGeometry=false&outFields=*`
    const res = await fetch(url)
    const data = await res.json()
    if (data.features && data.features.length > 0) {
      return data.features[0].attributes
    }
  } catch (e) {
    console.warn('Query attributes failed:', e)
  }
  return null
}

const onMapClick = async (evt) => {
  if (!evt.attributes || !Object.keys(evt.attributes).length) return

  const lid = evt.layerId || ''
  let attrs = evt.attributes
  const isServiceLayer = lid.startsWith('th_') || lid.startsWith('anxian')

  // 要素服务层: 如果属性只有 OBJECTID，则通过 REST API 查询完整属性
  if (isServiceLayer && evt.layerUrl) {
    const attrKeys = Object.keys(attrs)
    if (attrKeys.length <= 2 || (attrKeys.length <= 3 && attrKeys.includes('SHAPE'))) {
      const objectId = attrs.OBJECTID || attrs.FID || attrs.objectId
      if (objectId) {
        const fullAttrs = await queryFeatureAttributes(evt.layerUrl, objectId)
        if (fullAttrs) attrs = fullAttrs
      }
    }
  }

  // 显示弹窗
  if (lid.startsWith('th_') || lid.startsWith('anxian') || lid.startsWith('oneMap_')) {
    const keyAttrs = {}
    Object.entries(attrs).forEach(([k, v]) => {
      if (typeof v === 'string' && v.length > 200) return
      if (['Shape', 'SHAPE', 'the_geom', 'geometry'].includes(k)) return
      keyAttrs[k] = v
    })

    featurePopupRef.value?.show({
      title: evt.layerTitle || lid,
      attributes: keyAttrs,
      x: evt.x + 20,
      y: evt.y + 10,
      actions: [
        {
          label: '查看详情',
          handler: () => showDetailPanel(lid, evt.layerTitle, attrs)
        }
      ]
    })
  }
}

const showDetailPanel = (layerId, layerTitle, attrs) => {
  featurePopupRef.value?.close()
  const tabs = []
  const keys = Object.keys(attrs).filter(k => !['Shape', 'SHAPE', 'the_geom', 'geometry'].includes(k))
  tabs.push({ name: '基本信息', type: 'kv', data: attrs, loading: false })
  tabs.push({ name: '全部属性', type: 'html',
    html: '<pre style="font-size:12px;max-height:400px;overflow:auto">' +
      JSON.stringify(attrs, null, 2).replace(/</g, '&lt;') + '</pre>',
    loading: false })
  infoPanelRef.value?.show({ title: layerTitle || layerId, tabs })
}

// ---- 图层切换 ----
const onLayerToggle = ({ layer, checked }) => {
  const view = viewRef.value
  if (!view) return

  const noUrlIds = ['js', 'zj', 'sh', 'ah', 'fj']
  if (noUrlIds.includes(layer.id) || layer.id.startsWith('anxian')) return

  // 预加载的 ArcGIS 要素服务层 → toggle visibility
  const existLayer = view.map.findLayerById(layer.id)
  if (existLayer) {
    existLayer.visible = checked
    return
  }

  // WMTS 瓦片图层
  if (checked && layer.url) {
    let wmtsLayer = addedLayers.get(layer.id)
    if (!wmtsLayer) {
      const svcName = layer.tileMatrixSet
        ? layer.tileMatrixSet.replace(/^Custom_/, '')
        : layer.id
      const urlTemplate = 'http://{subDomain}.1.58.34' + layer.url
        + '&SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile'
        + '&LAYER=' + svcName
        + '&STYLE=Default&FORMAT=image/png'
        + '&TILEMATRIXSET=' + (layer.tileMatrixSet || '')
        + '&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}'
      wmtsLayer = new WebTileLayer({
        id: layer.id, title: layer.name,
        urlTemplate, subDomains: ['10'], visible: true
      })
      addedLayers.set(layer.id, wmtsLayer)
    }
    view.map.add(wmtsLayer)
  } else if (!checked) {
    const wmtsLayer = addedLayers.get(layer.id)
    if (wmtsLayer) view.map.remove(wmtsLayer)
  }
}
</script>

<style scoped>
.onemap-page {
  width: 100%; height: calc(100vh - 60px);
  position: relative; overflow: hidden;
}
</style>
