<template>
  <div class="map-select">
    <el-input
      v-model="address"
      placeholder="点击选择地址"
      readonly
      @click="showMapDialog"
    >
      <el-button slot="append" icon="el-icon-location" @click="showMapDialog"></el-button>
    </el-input>

    <el-dialog
      title="选择地址"
      :visible.sync="dialogVisible"
      width="800px"
      append-to-body
    >
      <div class="map-container">
        <div id="map" class="map"></div>
        <div class="search-box">
          <el-input
            v-model="searchKey"
            placeholder="搜索地址"
            clearable
            :loading="searching"
            @keyup.enter.native="searchAddress"
          >
            <el-button 
              slot="append" 
              icon="el-icon-search" 
              @click="searchAddress"
              :loading="searching"
            ></el-button>
          </el-input>
          <div class="current-location" v-if="currentLocation.address">
            <p>当前位置：{{ currentLocation.address }}</p>
          </div>
          <div class="search-result" v-if="searchResults.length">
            <ul>
              <li 
                v-for="(item, index) in searchResults" 
                :key="index"
                @click="selectSearchResult(item)"
              >
                {{ item.title }}
                <span class="address">{{ item.address }}</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmLocation" :disabled="!currentLocation.address">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import globalConfig from '@/utils/config/globalConfig'

export default {
  name: 'MapSelect',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      map: null,
      marker: null,
      geocoder: null,
      placeSearch: null,
      dialogVisible: false,
      address: this.value,
      searchKey: '',
      searchResults: [],
      searching: false,
      currentLocation: {
        lng: null,
        lat: null,
        address: ''
      }
    }
  },
  watch: {
    value(val) {
      this.address = val
    }
  },
  methods: {
    showMapDialog() {
      this.dialogVisible = true
      this.$nextTick(() => {
        // 设置安全密钥配置
        window._AMapSecurityConfig = {
          securityJsCode: globalConfig.aMap.secret
        }
        
        // 确保高德地图已加载
        this.$loadAMap().then(() => {
          this.initMap()
        }).catch(err => {
          this.$modal.msgError('地图加载失败，请检查网络后刷新重试')
          console.error('高德地图加载失败:', err)
          this.dialogVisible = false
        })
      })
    },
    initMap() {
      if (!this.map) {
        // 加载所需插件
        AMap.plugin([
          'AMap.Geocoder',
          'AMap.PlaceSearch',
          'AMap.Geolocation'
        ], () => {
          this.map = new AMap.Map('map', {
            zoom: 13
          })
          
          // 添加定位控件
          this.map.addControl(new AMap.Geolocation({
            position: 'RB'
          }))

          // 初始化地理编码服务
          this.geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          
          // 初始化搜索服务
          this.placeSearch = new AMap.PlaceSearch({
            pageSize: 10,
            citylimit: true,
            extensions: 'all'
          })

          // 点击地图事件
          this.map.on('click', (e) => {
            this.updateMarker(e.lnglat)
            this.getAddress(e.lnglat)
          })

          // 如果已有坐标，则定位到该位置
          if (this.currentLocation.lng && this.currentLocation.lat) {
            const lnglat = new AMap.LngLat(this.currentLocation.lng, this.currentLocation.lat)
            this.updateMarker(lnglat)
            this.map.setCenter(lnglat)
            this.getAddress(lnglat)
          } else {
            // 定位到当前位置
            const geolocation = new AMap.Geolocation()
            geolocation.getCurrentPosition((status, result) => {
              if (status === 'complete') {
                this.updateMarker(result.position)
                this.map.setCenter(result.position)
                this.getAddress(result.position)
              }
            })
          }
        })
      }
    },
    updateMarker(lnglat) {
      if (this.marker) {
        this.marker.setPosition(lnglat)
      } else {
        this.marker = new AMap.Marker({
          position: lnglat,
          map: this.map,
          draggable: true
        })
        
        // 拖动结束后获取地址
        this.marker.on('dragend', (e) => {
          this.getAddress(e.target.getPosition())
        })
      }
      this.currentLocation.lng = lnglat.getLng()
      this.currentLocation.lat = lnglat.getLat()
    },
    getAddress(lnglat) {
      this.geocoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          const address = result.regeocode
          this.currentLocation = {
            lng: lnglat.getLng(),
            lat: lnglat.getLat(),
            address: address.formattedAddress,
            province: address.addressComponent.province,
            city: address.addressComponent.city,
            district: address.addressComponent.district,
            street: address.addressComponent.street,
            streetNumber: address.addressComponent.streetNumber
          }
        }
      })
    },
    searchAddress() {
      console.log('搜索关键词:', this.searchKey)
      if (this.searchKey.trim()) {
        // 清除之前的搜索结果
        this.searchResults = []
        if (this.marker) {
          this.marker.setMap(null)
          this.marker = null
        }
        
        // 显示加载状态
        this.$set(this, 'searching', true)
        
        this.placeSearch.search(this.searchKey, (status, result) => {
          console.log('搜索结果:', status, result)
          this.searching = false
          
          if (status === 'complete') {
            this.searchResults = result.poiList.pois
            console.log('解析到的地点:', this.searchResults)
            
            // 更新搜索结果列表
            this.$nextTick(() => {
              if (this.searchResults.length > 0) {
                const firstResult = this.searchResults[0]
                const lnglat = new AMap.LngLat(firstResult.location.lng, firstResult.location.lat)
                this.updateMarker(lnglat)
                this.map.setCenter(lnglat)
                this.getAddress(lnglat)
              }
            })
          } else {
            console.error('搜索失败:', result)
            this.$message.error('搜索失败，请重试')
          }
        }, (error) => {
          console.error('搜索出错:', error)
          this.searching = false
          this.$message.error('搜索服务出错，请重试')
        })
      }
    },
    selectSearchResult(item) {
      const lnglat = new AMap.LngLat(item.location.lng, item.location.lat)
      this.updateMarker(lnglat)
      this.map.setCenter(lnglat)
      this.getAddress(lnglat)
      this.searchResults = []
      this.searchKey = ''
    },
    confirmLocation() {
      this.$emit('input', this.currentLocation.address)
      this.$emit('select', this.currentLocation)
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.map-select {
  width: 100%;
}

.map-container {
  position: relative;
  height: 500px;
}

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

.search-box {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 300px;
  z-index: 1;
  
  .current-location {
    margin-top: 10px;
    padding: 10px;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    
    p {
      margin: 0;
      font-size: 13px;
      color: #606266;
      word-break: break-all;
    }
  }
  
  .search-result {
    margin-top: 5px;
    background: #fff;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    max-height: 300px;
    overflow-y: auto;
    
    ul {
      margin: 0;
      padding: 0;
      list-style: none;
      
      li {
        padding: 8px 12px;
        cursor: pointer;
        border-bottom: 1px solid #eee;
        
        &:hover {
          background: #f5f7fa;
        }
        
        .address {
          font-size: 12px;
          color: #909399;
          margin-left: 5px;
        }
      }
    }
  }
}
</style> 