<template>
  <div class="map-picker-container">
    <a-form-item :label="label">
      <a-auto-complete
        v-model:value="searchAddress"
        :options="searchOptions"
        placeholder="输入地址搜索"
        @change="handleSearch"
        @select="handleSelect"
        :loading="searchLoading"
        allow-clear
        class="map-picker-input"
      />
    </a-form-item>

    <a-form-item label="地图选点" required>
      <div class="map-container">
        <div :id="mapContainerId" style="height: 300px;"></div>
      </div>
      <div class="form-item-tip">在地图上点击选择准确位置，或通过上方搜索框搜索地址</div>
    </a-form-item>

    <a-form-item label="详细地址" required>
      <a-input v-model:value="address" placeholder="请输入详细地址" />
      <div class="form-item-tip">地址将用于配送员导航和定位，请确保准确</div>
    </a-form-item>

    <!-- 隐藏经纬度输入字段，但保持功能不变 -->
    <div style="display: none;">
      <a-input-number v-model:value="longitude" :min="-180" :max="180" disabled />
      <a-input-number v-model:value="latitude" :min="-90" :max="90" disabled />
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick, watch } from 'vue'
import { message } from 'ant-design-vue'
import { loadAMap, createMap, createAutoComplete, createGeocoder } from '@/utils/amap.js'

export default {
  name: 'MapPicker',
  props: {
    label: {
      type: String,
      default: '地址搜索'
    },
    modelValue: {
      type: Object,
      default: () => ({
        address: '',
        longitude: null,
        latitude: null
      })
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const mapContainerId = `map-container-${Date.now()}`
    const map = ref(null)
    const marker = ref(null)
    const searchAddress = ref('')
    const searchOptions = ref([])
    const searchLoading = ref(false)

    // 双向绑定的值
    const address = ref(props.modelValue.address)
    const longitude = ref(props.modelValue.longitude)
    const latitude = ref(props.modelValue.latitude)

    // 监听props变化
    watch(() => props.modelValue, (newVal, oldVal) => {
      console.log('props变化:', newVal, oldVal)
      // 避免无限循环：只有当值真正变化时才更新
      if (
        newVal.address !== address.value ||
        newVal.longitude !== longitude.value ||
        newVal.latitude !== latitude.value
      ) {
        console.log('更新本地值:', newVal)
        address.value = newVal.address
        longitude.value = newVal.longitude
        latitude.value = newVal.latitude
        
        // 如果地图已初始化且有有效的经纬度，更新地图标记和中心点
        if (map.value && newVal.longitude && newVal.latitude) {
          console.log('更新地图标记和中心点:', newVal.longitude, newVal.latitude)
          // 使用nextTick确保DOM更新后再操作地图
          nextTick(() => {
            try {
              if (marker.value) {
                marker.value.setPosition([newVal.longitude, newVal.latitude])
              } else {
                marker.value = new window.AMap.Marker({
                  position: [newVal.longitude, newVal.latitude],
                  map: map.value
                })
              }
              map.value.setCenter([newVal.longitude, newVal.latitude])
            } catch (error) {
              console.error('更新地图标记失败:', error)
            }
          })
        }
      }
    }, { deep: true, immediate: true })

    // 监听本地值的变化
    watch([address, longitude, latitude], () => {
      updateValue()
    })

    // 更新值到父组件
    const updateValue = () => {
      // 避免无限循环：只有当值真正变化时才触发更新
      if (
        address.value !== props.modelValue.address ||
        longitude.value !== props.modelValue.longitude ||
        latitude.value !== props.modelValue.latitude
      ) {
        emit('update:modelValue', {
          address: address.value,
          longitude: longitude.value,
          latitude: latitude.value
        })
      }
    }

    // 更新标记位置
    const updateMarkerPosition = (lng, lat) => {
      // 避免重复设置相同的值
      if (lng === longitude.value && lat === latitude.value && marker.value) {
        return
      }
      
      console.log('更新标记位置:', lng, lat)
      longitude.value = lng
      latitude.value = lat

      try {
        if (marker.value) {
          marker.value.setPosition([lng, lat])
        } else if (map.value) {
          marker.value = new window.AMap.Marker({
            position: [lng, lat],
            map: map.value
          })
        }
      } catch (error) {
        console.error('更新标记位置失败:', error)
      }
      // updateValue会通过watch自动触发
    }

    // 初始化地图
    const initMap = async () => {
      try {
        await loadAMap()
        
        if (!map.value) {
          console.log('初始化地图，初始位置：', props.modelValue)
          map.value = createMap(mapContainerId, {
            zoom: 13,
            viewMode: '2D'
          })

          // 添加点击事件
          map.value.on('click', async (e) => {
            const { lng, lat } = e.lnglat
            updateMarkerPosition(lng, lat)
            
            // 逆地理编码获取地址
            const geocoder = createGeocoder()
            geocoder.getAddress([lng, lat], (status, result) => {
              if (status === 'complete' && result.info === 'OK') {
                address.value = result.regeocode.formattedAddress
                updateValue()
              } else {
                message.error('获取地址信息失败')
              }
            })
          })

          // 如果有初始值，设置标记
          if (props.modelValue.longitude && props.modelValue.latitude) {
            console.log('MapPicker初始化，设置初始位置：', props.modelValue)
            // 确保在地图加载完成后再添加标记
            map.value.on('complete', () => {
              updateMarkerPosition(props.modelValue.longitude, props.modelValue.latitude)
              map.value.setCenter([props.modelValue.longitude, props.modelValue.latitude])
            })
            
            // 同时也立即尝试添加标记，以防地图已经加载完成
            updateMarkerPosition(props.modelValue.longitude, props.modelValue.latitude)
            map.value.setCenter([props.modelValue.longitude, props.modelValue.latitude])
          }
        }
      } catch (error) {
        console.error('初始化地图失败:', error)
        message.error('初始化地图失败')
      }
    }

    // 地址搜索
    const handleSearch = async (value) => {
      if (!value || value.length < 2) {
        searchOptions.value = []
        return
      }

      try {
        searchLoading.value = true
        await loadAMap()
        
        const autoComplete = createAutoComplete()
        await new Promise((resolve, reject) => {
          autoComplete.search(value, (status, result) => {
            if (status === 'complete') {
              searchOptions.value = result.tips.map(tip => ({
                value: tip.name,
                label: `${tip.name} (${tip.district})`,
                location: tip.location
              }))
              resolve(result)
            } else {
              reject(new Error(status))
            }
            searchLoading.value = false
          })
        })
      } catch (error) {
        console.error('搜索地址失败:', error)
        searchLoading.value = false
        message.error('搜索地址失败')
      }
    }

    // 选择地址
    const handleSelect = (value, option) => {
      const selected = searchOptions.value.find(opt => opt.value === value)
      if (selected && selected.location) {
        const { lng, lat } = selected.location
        updateMarkerPosition(lng, lat)
        map.value.setCenter([lng, lat])
        
        // 使用逆地理编码获取完整地址
        const geocoder = createGeocoder()
        geocoder.getAddress([lng, lat], (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            address.value = result.regeocode.formattedAddress
            updateValue()
          } else {
            address.value = value
            updateValue()
          }
        })
      }
    }

    onMounted(() => {
      nextTick(() => {
        initMap()
      })
    })

    return {
      mapContainerId,
      searchAddress,
      searchOptions,
      searchLoading,
      address,
      longitude,
      latitude,
      handleSearch,
      handleSelect
    }
  }
}
</script>

<style scoped>
.map-picker-container {
  width: 100%;
}

.map-picker-input {
  width: 100%;
}

.map-container {
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 8px;
  width: 100%;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.form-item-tip {
  margin-top: 8px;
  font-size: 0.8em;
  color: #999;
}
</style> 