<script setup lang="ts">
import { getDeviceState } from '@af-mobile-client-vue3/api/map/trackApi'
import XOlMap from '@af-mobile-client-vue3/components/data/XOlMap/index.vue'
import NormalDataLayout from '@af-mobile-client-vue3/components/layout/NormalDataLayout/index.vue'
import { showNotify } from 'vant'
import { onMounted, ref } from 'vue'
import { polygonTestData, trackTestData } from './testData'
import 'vant/lib/index.css'

const mapRef = ref()

// WMS 配置
const wmsConfig = {
  layers: [
    {
      phoneShow: false,
      show: false,
      id: 1,
      layerName: 'gis:lp',
      value: '低压管线',
    },
    {
      phoneShow: true,
      show: true,
      id: 2,
      layerName: 'gis:mp',
      value: '中压管线',
    },
    {
      phoneShow: false,
      show: false,
      id: 3,
      layerName: 'gis:surface_valve',
      value: '地面阀门',
    },
    {
      phoneShow: false,
      show: false,
      id: 4,
      layerName: 'gis:valve_chamber',
      value: '阀门井',
    },
    {
      phoneShow: false,
      show: false,
      id: 6,
      layerName: 'gis:hp',
      value: '高压管线',
    },
    {
      phoneShow: false,
      show: false,
      id: 5,
      layerName: 'gis:pressure_regulating_box',
      value: '调压箱',
    },
  ],
  wms: {
    workspace: 'gis',
    srs: 'EPSG:3857',
    format: 'image/png',
    version: '1.1.0',
    url: '/linepatrol/geoserver/gis/wms',
  },
}

// 初始化地图
onMounted(async () => {
  await mapRef.value.init({
    center: [108.948024, 34.263161], // 西安坐标
    zoom: 12,
  })
  await mapRef.value.addWMSLayers(wmsConfig)
})

// 地图控制函数
const handleSetCenter = () => mapRef.value.setCenter([116.404, 39.915]) // 切换到北京
const handleSetZoom = () => mapRef.value.setZoom(14) // 设置缩放级别为14
const handleGetZoom = () => showNotify({ type: 'primary', message: `当前缩放级别：${mapRef.value.getZoom()}` })
const handleSetCenterAndZoom = () => mapRef.value.setCenterAndZoom([120.153576, 30.287459], 15) // 切换到杭州

// 点位数据
const poiPoints = [
  {
    longitude: 108.988024,
    latitude: 34.283161,
    title: '大雁塔',
    extData: { type: 'poi' },
  },
  {
    longitude: 108.948024,
    latitude: 34.263161,
    title: '钟楼',
    extData: { type: 'poi' },
  },
  {
    longitude: 108.968024,
    latitude: 34.273161,
    title: '小寨',
    extData: { type: 'poi' },
  },
]

const schoolPoints = [
  {
    longitude: 108.968024,
    latitude: 34.273161,
    title: '西安电子科技大学',
    extData: {
      type: 'school',
      level: '985',
      studentCount: 25000,
      departments: ['通信学院', '计算机学院', '电子工程学院'],
    },
  },
]

const hospitalPoints = [
  {
    longitude: 108.948024,
    latitude: 34.263161,
    title: '西安市第一医院',
    extData: {
      type: 'hospital',
      level: '三甲',
      departments: ['急诊科', '内科', '外科'],
      contact: '029-12345678',
      address: '西安市雁塔区',
    },
  },
  {
    longitude: 108.978024,
    latitude: 34.278161,
    title: '西安市中心医院',
    extData: {
      type: 'hospital',
      level: '三甲',
      departments: ['急诊科', '内科', '外科'],
      contact: '029-87654321',
      address: '西安市新城区',
    },
  },
]

// 点位处理函数
function handlePointClick(point: any) {
  showNotify({
    type: 'primary',
    message: `点击了: ${point.title}\n类型: ${point.extData.type}`,
  })
}

// 添加点位示例
function handleAddPoints() {
  mapRef.value.addPointLayer({
    id: 1,
    value: '学校啊啊啊',
    show: true,
    showInControl: false, // 不添加图层控制按钮
    icon: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
    iconAnchor: [0.5, 1],
    onClick: handlePointClick,
    dataProvider: async () => {
      // 模拟从API获取学校数据
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve([
            {
              longitude: 108.968024,
              latitude: 34.273161,
              title: '普通点位',
              extData: {
                type: 'school',
                level: '985',
                studentCount: 25000,
              },
            },
          ])
        }, 1000)
      })
    },
  })
}

// 添加分类点位示例
function handleAddPointLayer() {
  // 添加学校点位图层
  mapRef.value.addPointLayer({
    id: 1,
    value: '学校',
    show: true,
    icon: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
    iconAnchor: [0.5, 1],
    onClick: handlePointClick,
    dataProvider: async () => {
      // 模拟从API获取学校数据
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve([
            {
              longitude: 108.958024,
              latitude: 34.283161,
              title: '西安交通大学',
              extData: {
                type: 'school',
                level: '985',
                studentCount: 30000,
                departments: ['机械学院', '电气学院', '管理学院'],
              },
            },
          ])
        }, 1000)
      })
    },
  })

  // 添加医院点位图层
  mapRef.value.addPointLayer({
    id: 2,
    value: '医院',
    show: true,
    icon: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
    iconAnchor: [0.5, 1],
    onClick: handlePointClick,
    dataProvider: async () => {
      // 模拟从API获取医院数据
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve([
            {
              longitude: 108.978024,
              latitude: 34.278161,
              title: '西安市中心医院',
              extData: {
                type: 'hospital',
                level: '三甲',
                departments: ['急诊科', '内科', '外科'],
                contact: '029-87654321',
                address: '西安市新城区',
              },
            },
          ])
        }, 1000)
      })
    },
  })
}

// 添加海量点示例
function handleAddMassPoints() {
  mapRef.value.addWebGLPoints({
    id: 3,
    value: '海量点',
    show: true,
    icon: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
    iconSize: [6, 6],
    onClick: handlePointClick,
    dataProvider: () => {
      // 生成10000个随机点
      return Array.from({ length: 10000 }, (_, index) => ({
        longitude: 108.948024 + (Math.random() - 0.5) * 0.1,
        latitude: 34.263161 + (Math.random() - 0.5) * 0.1,
        title: `点位${index + 1}`,
        extData: { type: 'mass' },
      }))
    },
  })
}

// 添加轨迹测试
function handleAddTrack() {
  trackTestData.forEach((track) => {
    mapRef.value.addTrackLayer(track)
  })
}

// 添加轨迹数组测试
async function handleAddTrackGroup() {
  const trackGroup = await getDeviceState('419879409793761282', '2026-04-13')
  mapRef.value.addTrackGroupLayer(trackGroup, { id: 10, name: '轨迹', color: '#fff' })
}

// 多边形处理函数
function handlePolygonClick(polygon: any) {
  console.log('>>>> polygon: ', JSON.stringify(polygon))
  showNotify({
    type: 'primary',
    message: `点击了多边形: ${polygon.name}\n类型: ${polygon.extData?.type || '未知'}`,
  })
}

// 添加多边形示例
function handleAddPolygonLayer() {
  mapRef.value.addPolygonLayer({
    id: 1,
    value: '行政区划',
    show: true,
    onClick: handlePolygonClick,
    dataProvider: async () => {
      // 模拟从API获取多边形数据
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(polygonTestData)
        }, 500)
      })
    },
  })
}

// 导航模式相关
const isNavigationMode = ref(false)

// 开启导航模式
function startNavigation() {
  isNavigationMode.value = true
  mapRef.value?.startNavigation()
}

// 停止导航模式
function stopNavigation() {
  isNavigationMode.value = false
  mapRef.value?.stopNavigation()
}
</script>

<template>
  <NormalDataLayout id="XOlMapView" title="XOlMap地图组件">
    <template #layout_content>
      <div class="demo-container">
        <div class="map-container">
          <XOlMap ref="mapRef" />
        </div>
        <div class="control-panel">
          <div class="control-group">
            <div class="group-title">
              地图控制
            </div>
            <van-button type="primary" size="small" @click="handleSetCenter">
              切换到北京
            </van-button>
            <van-button type="primary" size="small" @click="handleSetZoom">
              设置缩放级别14
            </van-button>
            <van-button type="primary" size="small" @click="handleGetZoom">
              获取当前缩放级别
            </van-button>
            <van-button type="primary" size="small" @click="handleSetCenterAndZoom">
              切换到杭州(级别15)
            </van-button>
          </div>

          <div class="control-group">
            <div class="group-title">
              点位示例
            </div>
            <van-button type="success" size="small" @click="handleAddPoints">
              添加普通点位
            </van-button>
            <van-button type="success" size="small" @click="handleAddPointLayer">
              添加分类点位
            </van-button>
            <van-button type="warning" size="small" @click="handleAddMassPoints">
              添加海量点(1万)
            </van-button>
          </div>

          <div class="control-group">
            <div class="group-title">
              轨迹示例
            </div>
            <van-button type="primary" size="small" @click="handleAddTrack">
              添加测试轨迹
            </van-button>
            <van-button type="primary" size="small" @click="handleAddTrackGroup">
              添加测试轨迹数组
            </van-button>
          </div>

          <div class="control-group">
            <div class="group-title">
              多边形示例
            </div>
            <van-button type="success" size="small" @click="handleAddPolygonLayer">
              添加行政区划
            </van-button>
          </div>

          <div class="control-group">
            <div class="group-title">
              导航模式测试
            </div>
            <van-button
              :type="isNavigationMode ? 'danger' : 'primary'"
              size="small"
              @click="isNavigationMode ? stopNavigation() : startNavigation()"
            >
              {{ isNavigationMode ? '停止导航' : '开始导航' }}
            </van-button>
          </div>
        </div>
      </div>
    </template>
  </NormalDataLayout>
</template>

<style scoped lang="less">
.demo-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.map-container {
  width: 100%;
  height: 100%;
}

.control-panel {
  position: absolute;
  left: 10px;
  top: 10px;
  z-index: 1000;
  background: white;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  gap: 16px;

  .control-group {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .group-title {
      font-size: 14px;
      font-weight: 500;
      color: #333;
      padding-left: 4px;
      border-left: 3px solid #1989fa;
    }

    :deep(.van-button) {
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  :deep(.van-button) {
    width: 140px;
  }
}

// 移动端适配
@media screen and (max-width: 768px) {
  .control-panel {
    left: 8px;
    top: 8px;
    padding: 8px;
    gap: 12px;

    .control-group {
      gap: 6px;

      .group-title {
        font-size: 12px;
      }
    }

    :deep(.van-button) {
      width: 120px;
      font-size: 12px;
    }
  }
}
</style>
