<script setup lang="ts">
import type { LocationResult, PhoneLocationStatus } from '../types'
import { post } from '@af-mobile-client-vue3/services/restTools'
import { mobileUtil } from '@af-mobile-client-vue3/utils/mobileUtil'
import { Button } from 'vant'
import { nextTick, onMounted, ref, watch } from 'vue'
import XOlMap from '../index.vue'

interface Props {
  modelValue?: LocationResult
  defaultCenter?: [number, number]
  defaultZoom?: number
  serviceName?: string
  readonly?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  defaultCenter: () => [108.948024, 34.263161],
  defaultZoom: 16,
  readonly: false,
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: LocationResult): void
  (e: 'confirm', value: LocationResult): void
}>()

const mapRef = ref<InstanceType<typeof XOlMap>>()
const currentAddress = ref('')
const currentLocation = ref<[number, number]>(props.defaultCenter)
const fixedMarkerLayerId = 900001

function renderFixedMarker(center?: [number, number]) {
  if (!mapRef.value || !center)
    return
  mapRef.value.addPointLayer({
    id: fixedMarkerLayerId,
    value: '固定定位点',
    show: true,
    showInControl: false,
    icon: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
    iconAnchor: [0.5, 1],
    dataProvider: () => ([
      {
        longitude: Number(center[0]),
        latitude: Number(center[1]),
      },
    ]),
  })
}

// 处理地图中心点变化
async function handleCenterChange(center: [number, number]) {
  currentLocation.value = center
  // 获取地址信息
  if (mapRef.value) {
    currentAddress.value = await mapRef.value.getAddressInfo(center)
  }
}

// 处理确定按钮点击
function handleConfirm() {
  const result: LocationResult = {
    longitude: currentLocation.value[0],
    latitude: currentLocation.value[1],
    address: currentAddress.value,
  }
  emit('update:modelValue', result)
  emit('confirm', result)
}

// 组件挂载时初始化地图
onMounted(async () => {
  // 使用 nextTick 确保 DOM 已更新
  await nextTick()
  await mapRef.value.init({
    center: props.defaultCenter,
    zoom: props.defaultZoom,
  })
  try {
    const webConfig = await post(`/api/${props.serviceName || import.meta.env.VITE_APP_SYSTEM_NAME}/logic/openapi/getLiuliConfiguration`, { configName: 'webConfig' })
    const wms = webConfig.wms ?? {}
    if (Array.isArray(wms.layers) && wms.layers.length > 0 && wms.wms?.url) {
      await mapRef.value.addWMSLayers(wms)
    }
  }
  catch (e) {
    console.error('初始化地图wms图层失败', e)
  }
  // 只读模式下，使用传入中心点作为固定标记点
  if (props.readonly) {
    renderFixedMarker(props.defaultCenter)
  }
  // 初始化后尝试获取地址信息
  handleCenterChange(props.defaultCenter)

  if (props.readonly) {
    return
  }

  // 异步获取定位，获取到后更新 currentLocation 和地图中心
  try {
    mobileUtil.execute({
      param: {},
      funcName: 'getLocationResult',
      callbackFunc: (result) => {
        const res = result as PhoneLocationStatus
        if (res.status === 'success') {
          const locationResult = JSON.parse(res.data.location)
          if (locationResult.longitude && locationResult.latitude) {
            const newCenter: [number, number] = [locationResult.longitude, locationResult.latitude]
            currentLocation.value = newCenter
            // 设置地图中心
            if (mapRef.value && mapRef.value.setCenter) {
              mapRef.value.setCenter(newCenter)
            }
            handleCenterChange(newCenter)
          }
        }
      },
    })
  }
  catch (error) {
    console.error('获取位置信息失败:', error)
  }
})

// 监听弹窗状态变化
watch(() => props.modelValue, (newVal) => {
  if (!props.readonly && newVal) {
    renderFixedMarker([newVal.longitude, newVal.latitude])
  }
  // 当绑定值变化时，可能需要重新调整地图
  nextTick(() => {
    if (mapRef.value && mapRef.value.getMap()) {
      mapRef.value.getMap().updateSize()
    }
  })
}, { immediate: true })
</script>

<template>
  <div class="location-picker">
    <div class="map-container">
      <XOlMap
        ref="mapRef"
        class="map"
        @center-change="handleCenterChange"
      />
      <!-- 非只读模式显示中心点标记 -->
      <div v-if="!props.readonly" class="location-picker-marker">
        <div class="marker-icon" />
      </div>
    </div>

    <!-- 底部地址信息面板 -->
    <div v-if="!props.readonly" class="location-picker-panel">
      <div class="address-info">
        <div class="address-label">
          位置信息
        </div>
        <div class="address-text">
          {{ currentAddress }}
        </div>
        <div class="coordinates-text">
          经度: {{ currentLocation[0] }}, 纬度: {{ currentLocation[1] }}
        </div>
      </div>
      <Button type="primary" block @click="handleConfirm">
        确定
      </Button>
    </div>
  </div>
</template>

<style scoped lang="less">
.location-picker {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  overflow: hidden;
}

.map-container {
  position: relative;
  flex: 1;
  min-height: 0;
  border-radius: 40px;
  overflow: hidden;
  padding: 10px;
}

.map {
  width: 100%;
  height: 100%;
  min-height: 300px;
}

.location-picker-marker {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 1000;
  pointer-events: none;

  .marker-icon {
    width: 24px;
    height: 24px;
    background: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCI+PHBhdGggZmlsbD0iIzE5ODlmYSIgZD0iTTEyIDJDOC4xMyAyIDUgNS4xMyA1IDljMCA1LjI1IDcgMTMgNyAxM3M3LTcuNzUgNy0xM2MwLTMuODctMy4xMy03LTctN3ptMCA5LjVjLTEuMzggMC0yLjUtMS4xMi0yLjUtMi41czEuMTItMi41IDIuNS0yLjUgMi41IDEuMTIgMi41IDIuNS0xLjEyIDIuNS0yLjUgMi41eiIvPjwvc3ZnPg==')
      no-repeat center;
    background-size: contain;
  }
}

.location-picker-panel {
  background: white;
  padding: 12px 16px;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1);
  border-radius: 8px 8px 0 0;
  z-index: 1000;

  .address-info {
    margin-bottom: 12px;

    .address-label {
      font-size: 14px;
      color: #666;
      margin-bottom: 4px;
    }

    .address-text {
      font-size: 15px;
      color: #333;
      margin-bottom: 4px;
      word-break: break-all;
    }

    .coordinates-text {
      font-size: 12px;
      color: #999;
    }
  }
}

// 移动端适配
@media screen and (max-width: 768px) {
  .location-picker-panel {
    padding: 10px 12px;

    .address-info {
      margin-bottom: 10px;
    }
  }
}
</style>
