<template>
  <div class="amap-city-select">
    <el-input
      v-model="cityName"
      :placeholder="placeholder"
      @focus="openMapDialog"
      clearable
      readonly
    >
      <i slot="prefix" class="el-icon-location" style="color: #409eff"></i>
    </el-input>

    <el-dialog
      title="选择出差城市 / 地点"
      :visible.sync="dialogVisible"
      width="900px"
      :append-to-body="true"
      @opened="onDialogOpened"
    >
      <div class="map-selector">
        <div class="city-sidebar">
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="输入城市或具体地点搜索"
              size="small"
              prefix-icon="el-icon-search"
              @keyup.enter.native="searchLocation"
              clearable
              @clear="searchKeyword = ''"
            >
              <el-button slot="append" @click="searchLocation">搜索</el-button>
            </el-input>
          </div>
          
          <!-- 热门城市模块 -->
          <div class="hot-cities" v-if="!searchKeyword || searchResults.length === 0">
            <div class="section-title">热门城市</div>
            <div class="city-list">
              <span 
                v-for="city in hotCities" 
                :key="city" 
                class="city-item"
                @click="selectHotCity(city)"
              >
                {{ city }}
              </span>
            </div>
          </div>
          
          <!-- 搜索结果模块 -->
          <div class="search-results" v-if="searchResults.length > 0">
            <div class="section-title">搜索结果</div>
            <div class="result-list">
              <div 
                v-for="(result, index) in searchResults" 
                :key="index" 
                class="result-item"
                @click="selectLocation(result)"
              >
                <i class="el-icon-location-outline"></i>
                <div class="result-info">
                  <div class="poi-name">{{ result.name }}</div>
                  <div class="poi-address">{{ result.address }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="map-container">
          <div id="amapContainer" class="amap-wrapper"></div>
          <div class="map-tip">
            <i class="el-icon-info"></i> 点击地图上的位置或搜索地点，自动识别归属城市
          </div>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <div class="selected-info" v-if="selectedCity">
          识别城市：<span class="selected-city">{{ selectedCity }}</span>
          <span v-if="selectedPoi" style="margin-left: 10px; color: #909399; font-size: 12px;">
            ( {{ selectedPoi }} )
          </span>
        </div>
        <div v-else></div>
        <div>
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="confirmCity" :disabled="!selectedCity">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import { getAmapKey, getAmapSecurityKey } from '@/api/hrm/travel'

export default {
  name: 'AmapCitySelect',
  props: {
    value: { type: String, default: '' },
    placeholder: { type: String, default: '请选择出差地点' }
  },
  data() {
    return {
      cityName: '',
      dialogVisible: false,
      searchKeyword: '',
      searchResults: [],
      selectedCity: '', // 最终表单需要的城市名
      selectedPoi: '',  // 具体的地点名(仅用于展示)
      map: null,
      geocoder: null,
      placeSearch: null, // 新增地点搜索对象
      marker: null,
      AMap: null,
      hotCities: [
        '北京市', '上海市', '广州市', '深圳市', 
        '杭州市', '南京市', '成都市', '武汉市',
        '重庆市', '天津市', '苏州市', '西安市'
      ]
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) { this.cityName = val || '' }
    }
  },
  methods: {
    async onDialogOpened() {
      const AMap = await this.loadAMap()
      if (!AMap) return
      this.$nextTick(() => {
        this.initMap()
      })
    },
    
    async loadAMap() {
      if (this.AMap && window._AMapSecurityConfig) return this.AMap
      try {
        const [keyRes, securityRes] = await Promise.all([getAmapKey(), getAmapSecurityKey()])
        const amapkey = keyRes.data || keyRes.msg
        const securityKey = securityRes.data || securityRes.msg
        
        if (!amapkey) throw new Error('未获取到高德地图 Key')
        
        window._AMapSecurityConfig = { securityJsCode: securityKey }
        
        this.AMap = await AMapLoader.load({
          key: amapkey,
          version: '2.0',
          // 加入 PlaceSearch 插件
          plugins: ['AMap.Geocoder', 'AMap.PlaceSearch']
        })
        return this.AMap
      } catch (error) {
        console.error('地图加载失败:', error)
        this.$message.error('地图加载失败，请重试')
        return null
      }
    },

    initMap() {
      const container = document.getElementById('amapContainer')
      if (!container) {
        setTimeout(() => this.initMap(), 100)
        return
      }
      
      if (this.map) {
        this.map.destroy()
        this.map = null
      }
      
      this.map = new this.AMap.Map('amapContainer', {
        zoom: 12,
        center: [116.397428, 39.90923], // 默认北京
        resizeEnable: true
      })
      
      this.geocoder = new this.AMap.Geocoder()
      
      // 初始化地点搜索插件
      this.placeSearch = new this.AMap.PlaceSearch({
        pageSize: 15, // 单页显示结果条数
        pageIndex: 1, // 页码
        autoFitView: false // 禁用自动调整视图，我们自己控制
      })
      
      // 监听地图点击
      this.map.on('click', (e) => {
        const lng = e.lnglat.getLng()
        const lat = e.lnglat.getLat()
        this.selectedPoi = '地图选点'
        this.getCityByLngLat(lng, lat, true)
      })
    },
    
    // 通过经纬度逆解析城市
    getCityByLngLat(lng, lat, setCenter = false) {
      this.geocoder.getAddress([lng, lat], (status, result) => {
        if (status === 'complete' && result.regeocode) {
          const addrComp = result.regeocode.addressComponent
          let city = addrComp.city
          // 直辖市的 city 可能是空的，取 province
          if (!city || city === '[]' || city.length === 0) {
            city = addrComp.province
          }
          this.selectedCity = city
          this.addMarker(lng, lat)
          if(setCenter) {
            this.map.setCenter([lng, lat])
          }
        }
      })
    },
    
    // 在地图上打点
    addMarker(lng, lat) {
      if (this.marker) {
        this.marker.setMap(null)
      }
      this.marker = new this.AMap.Marker({ 
        position: [lng, lat], 
        map: this.map,
        animation: 'AMAP_ANIMATION_DROP' // 加上掉落动画
      })
    },
    
    openMapDialog() {
      this.dialogVisible = true
      this.selectedCity = this.value || ''
      this.selectedPoi = ''
      this.searchKeyword = ''
      this.searchResults = []
    },
    
    // 搜索地点核心方法
    async searchLocation() {
      if (!this.searchKeyword.trim()) {
        this.searchResults = []
        return
      }
      
      await this.loadAMap()
      
      // 使用 PlaceSearch 搜索具体地点
      this.placeSearch.search(this.searchKeyword, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          // 提取返回的 POI 列表
          const pois = result.poiList.pois
          this.searchResults = pois.map(poi => ({
            id: poi.id,
            name: poi.name,
            address: poi.address && typeof poi.address === 'string' ? poi.address : poi.adname,
            location: poi.location, // 包含 lng/lat 的对象
            city: poi.cityname || poi.pname // 城市名
          }))
        } else {
          this.searchResults = []
          this.$message.info('未找到相关地点，请尝试更换关键词')
        }
      })
    },
    
    // 选中左侧搜索结果列表的具体地点
    selectLocation(poi) {
      if (!poi.location) {
        this.$message.warning('该地点缺少坐标信息')
        return
      }
      
      const lng = poi.location.lng
      const lat = poi.location.lat
      
      // 设置地图中心点并放大(层级15看街道)
      this.map.setZoomAndCenter(15, [lng, lat])
      this.addMarker(lng, lat)
      
      // 更新选择数据
      this.selectedCity = poi.city
      this.selectedPoi = poi.name
      this.$message.success(`已定位到：${poi.name}`)
    },
    
    // 选中热门城市
    async selectHotCity(city) {
      await this.loadAMap()
      this.selectedCity = city
      this.selectedPoi = city
      
      // 获取城市中心点坐标
      this.geocoder.getLocation(city, (status, result) => {
        if (status === 'complete' && result.geocodes.length) {
          const loc = result.geocodes[0].location
          this.map.setZoomAndCenter(11, [loc.lng, loc.lat])
          this.addMarker(loc.lng, loc.lat)
        }
      })
    },
    
    confirmCity() {
      if (this.selectedCity) {
        this.cityName = this.selectedCity
        // 组件 v-model 抛出城市名
        this.$emit('input', this.selectedCity) 
        // 如果你需要具体的地点名，可以额外抛出一个事件
        this.$emit('poi-change', { city: this.selectedCity, poi: this.selectedPoi })
        this.closeDialog()
      }
    },
    
    closeDialog() {
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.amap-city-select { width: 100%; }
.map-selector { display: flex; gap: 20px; min-height: 450px;
  .city-sidebar { width: 300px; flex-shrink: 0; display: flex; flex-direction: column;
    .search-box { margin-bottom: 16px; }
    .section-title { font-size: 14px; font-weight: bold; color: #303133; margin-bottom: 12px; padding-bottom: 8px; border-bottom: 1px solid #ebeef5; }
    
    .hot-cities .city-list { display: flex; flex-wrap: wrap; gap: 10px;
      .city-item { padding: 6px 14px; background: #f4f4f5; color: #606266; border-radius: 4px; font-size: 13px; cursor: pointer; transition: all 0.2s;
        &:hover { background: #409eff; color: white; }
      }
    }
    
    /* 搜索结果列表样式升级 */
    .search-results {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
    .result-list { 
      flex: 1; overflow-y: auto; padding-right: 5px;
      
      /* 自定义滚动条 */
      &::-webkit-scrollbar { width: 4px; }
      &::-webkit-scrollbar-thumb { background: #dcdfe6; border-radius: 4px; }
      
      .result-item { 
        padding: 12px 10px; cursor: pointer; display: flex; align-items: flex-start; gap: 10px; border-bottom: 1px solid #ebeef5; transition: background 0.2s;
        &:hover { background: #f0f7ff; }
        i { color: #409eff; margin-top: 3px; font-size: 16px; }
        .result-info {
          flex: 1; overflow: hidden;
          .poi-name { font-size: 14px; color: #303133; font-weight: 500; margin-bottom: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
          .poi-address { font-size: 12px; color: #909399; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        }
      }
    }
  }
  
  .map-container { flex: 1; display: flex; flex-direction: column;
    .amap-wrapper { flex: 1; width: 100%; border: 1px solid #dcdfe6; border-radius: 6px; overflow: hidden; }
    .map-tip { margin-top: 10px; font-size: 12px; color: #909399; text-align: center; i { margin-right: 4px; color: #e6a23c; } }
  }
}
.dialog-footer { display: flex; justify-content: space-between; align-items: center;
  .selected-info { font-size: 14px; color: #606266; .selected-city { color: #409eff; font-weight: bold; font-size: 15px; } }
}
</style>