<template>
  <div class="search-container">
    <div class="search-box">
      <input
        v-model="searchText"
        type="text"
        placeholder="搜索地名或经纬度，例如：北京 或 116.4074, 39.9042"
        @keyup.enter="search"
        @input="handleInput"
      />
      <button @click="search">搜索</button>
    </div>
    <div class="search-results" v-if="showResults && searchResults.length > 0">
      <div
        v-for="(result, index) in searchResults"
        :key="index"
        class="search-result-item"
        @click="selectResult(result)"
      >
        {{ result.name }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onUnmounted } from 'vue';
import { PROXY_TIANDITU_API, TIANDITU_KEY } from "../../config/server_config.js";

const props = defineProps({
  viewer: {
    type: Object,
    required: true
  }
});

const searchText = ref('');
const showResults = ref(false);
const searchResults = ref([]);
const isSearching = ref(false);

// 天地图 API 密钥来自外部配置 supermap.config.js

// 处理输入
const handleInput = async () => {
  if (searchText.value.trim()) {
    try {
      isSearching.value = true;
      // 调用天地图API获取搜索结果
      const results = await getLocationByTianditu(searchText.value.trim());
      searchResults.value = results;
      showResults.value = true;
    } catch (error) {
      console.error('搜索失败:', error);
      searchResults.value = [];
      showResults.value = false;
    } finally {
      isSearching.value = false;
    }
  } else {
    searchResults.value = [];
    showResults.value = false;
  }
};

// 搜索
const search = async () => {
  if (searchText.value.trim()) {
    try {
      // 先尝试解析经纬度
      const latLng = parseLatLng(searchText.value.trim());
      if (latLng) {
        flyToLocation(latLng);
        showResults.value = false;
        return;
      }
      
      // 如果不是经纬度，调用天地图API获取位置信息
      const location = await getLonLatByTianditu(searchText.value.trim());
      if (location) {
        flyToLocation(location);
        showResults.value = false;
      }
    } catch (error) {
      console.error('搜索失败:', error);
      alert('搜索失败: ' + error.message);
    }
  }
};

// 解析经纬度字符串
// 支持格式: "116.4074, 39.9042" 或 "116.4074 39.9042"
const parseLatLng = (text) => {
  // 匹配经纬度格式：数字, 数字 或 数字 数字
  const regex = /^\s*(-?\d+\.?\d*)\s*[,，\s]\s*(-?\d+\.?\d*)\s*$/;
  const match = text.match(regex);
  
  if (match) {
    const lng = parseFloat(match[1]);
    const lat = parseFloat(match[2]);
    
    // 验证经纬度范围
    if (lng >= -180 && lng <= 180 && lat >= -90 && lat <= 90) {
      return { name: `${lng}, ${lat}`, lng: lng, lat: lat, height: 3000 };
    }
  }
  
  return null;
};

// 选择搜索结果
const selectResult = (result) => {
  searchText.value = result.name;
  flyToLocation(result);
  showResults.value = false;
};

// 天地图地理编码 API
const getLonLatByTianditu = async (keyword) => {
  const url = `${PROXY_TIANDITU_API}/geocoder?ds={"keyWord":"${encodeURIComponent(keyword)}"}&tk=${TIANDITU_KEY}`;

  const res = await fetch(url);
  const data = await res.json();

  // 天地图返回成功
  if (data.status === "0" && data.location) {
    const lon = parseFloat(data.location.lon);
    const lat = parseFloat(data.location.lat);
    return { name: keyword, lng: lon, lat: lat, height: 3000 };
  } else {
    throw new Error("未找到该地点");
  }
};

// 天地图搜索 API
const getLocationByTianditu = async (keyword) => {
  // 由于天地图的搜索API可能需要不同的接口，这里使用地理编码API作为示例
  // 实际项目中可以根据天地图API文档使用专门的搜索接口
  try {
    const location = await getLonLatByTianditu(keyword);
    return [location];
  } catch (error) {
    return [];
  }
};

// 飞行到指定位置
const flyToLocation = (location) => {
  if (props.viewer) {
    // 设置一个更高的高度，确保能够看到周围区域
    const height = 200000; // 100公里高度
    
    props.viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(
        location.lng,
        location.lat,
        height
      ),
      orientation: {
        heading: Cesium.Math.toRadians(0),
        pitch: Cesium.Math.toRadians(-90), // 俯仰角-45度
        roll: 0.0
      },
      duration: 1.8 // 飞行时间
    });
  }
};

// 点击外部关闭搜索结果
const handleClickOutside = (event) => {
  const searchContainer = document.querySelector('.search-container');
  if (searchContainer && !searchContainer.contains(event.target)) {
    showResults.value = false;
  }
};

// 监听点击事件
window.addEventListener('click', handleClickOutside);

// 组件销毁时移除事件监听
onUnmounted(() => {
  window.removeEventListener('click', handleClickOutside);
});
</script>

<style scoped>
.search-container {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  width: 300px;
}

.search-box {
  display: flex;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.search-box input {
  flex: 1;
  padding: 10px 15px;
  border: none;
  outline: none;
  font-size: 14px;
}

.search-box button {
  padding: 0 20px;
  background: #409eff;
  color: white;
  border: none;
  cursor: pointer;
  font-size: 14px;
}

.search-box button:hover {
  background: #66b1ff;
}

.search-results {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  max-height: 200px;
  overflow-y: auto;
  margin-top: 2px;
}

.search-result-item {
  padding: 10px 15px;
  cursor: pointer;
  font-size: 14px;
}

.search-result-item:hover {
  background: #f5f7fa;
}
</style>