<template>
  <div class="container">
    <!-- 搜索框 -->
    <div class="search-container">
      <el-input v-model="keyword" placeholder="请输入地点名称" class="search-input" @keyup.enter.native="toSearch"
        @input="handleInput">
        <el-button slot="append" icon="el-icon-search" @click="toSearch"></el-button>
      </el-input>
      <!-- 搜索结果列表 -->
      <div class="search-results" v-if="searchBox && searchList.length > 0">
        <div class="search-item" v-for="(item, index) in searchList" :key="index" @click="centerMap(item)">
          <div class="item-name">{{ item.name }}</div>
          <div class="item-address">{{ item.address }}</div>
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="main-content">
      <!-- 地图 -->
      <div class="map-container">
        <div id="mars2dContainerSSS" class="mars2d-container"></div>
      </div>
    </div>
  </div>
</template>

<script>
import 'mars2d/mars2d.css';
import * as mars2d from 'mars2d';
import axios from 'axios';

export default {
  data() {
    const basePathUrl = window.basePathUrl || "";
    return {
      configUrl: basePathUrl + "config/config.json",
      mapOptions: {
        copyright: false,
        basemaps: [
          {
            id: 2021,
            chinaCRS: "GCJ02",
            pid: 10,
            name: "高德电子",
            icon: "img/basemaps/gaode_vec.png",
            type: "gaode",
            layer: "vec",
            show: true
          }
        ],
        center: { lat: 31.2304, lng: 120.6184 },
        zoom: 10,
        chinaCRS: 'GCJ02',
        center: { lat: 31.3256, lng: 120.7457 },
        zoom: 16,
        minZoom: 15,
        maxZoom: 20,
        zoomControl: true,
      },
      map: null,
      keyword: "", // 搜索关键词
      searchList: [], // 搜索结果列表
      searchBox: false, 
      searchDebounce: null, 
    };
  },
  methods: {
    // 初始化地图
    initMap() {
      this.map = new mars2d.Map('mars2dContainerSSS', this.mapOptions);
      this.map.on('load', this.onload);
    },

    // 地图加载完成后的回调
    onload() {},

    // 处理输入事件
    handleInput() {
      if (this.searchDebounce) {
        clearTimeout(this.searchDebounce);
      }
      this.searchDebounce = setTimeout(() => {
        this.toSearch();
      }, 300); 
    },

    // 搜索方法
    toSearch() {
      if (!this.keyword.trim()) {
        return;
      }

      let params = {
        key: "bd665f6310bb41cdaea4494ec86fcbfa",
        keywords: this.keyword,
        city: "亳州市",
      };

      axios({
        method: "GET",
        url: "https://restapi.amap.com/v3/place/text",
        params,
      }).then((res) => {
        console.log(res);
        if (res.status == 200) {
          if (res.data.pois && res.data.pois.length > 0) {
            this.searchList = res.data.pois;
            this.searchBox = true;
          } else {
            this.$message({
              message: "未搜索到结果！",
              type: "warning",
            });
          }
        }
      }).catch(error => {
        console.error('搜索失败:', error);
        this.$message.error('搜索失败，请稍后重试');
      });
    },

    // 定位到搜索结果
    centerMap(item) {
      const [lng, lat] = item.location.split(',').map(Number);

      // 更新输入框的值
      this.keyword = item.name;

      // 移动地图到指定位置
      this.map.flyTo([lat, lng], 17);

      // 关闭搜索结果框
      this.searchBox = false;
    }
  },
  mounted() {
    this.initMap();
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
    }
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  width: 100%;
  background-color: #FFFFFF;
  box-shadow: 0rem 0.13rem 0.63rem 0rem rgba(177, 177, 177, 0.1);
  border-radius: 0.5rem;
  overflow: auto;
}

.search-container {
  padding: 1rem;
  position: absolute;
  z-index: 1000;
  margin-left: 4rem;
}

.search-input {
  width: 100%;
  max-width: 600px;
}

.search-results {
  position: absolute;
  top: 100%;
  left: 1rem;
  width: 100%;
  max-width: 500px;
  max-height: 300px;
  overflow-y: auto;
  background-color: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.search-item {
  padding: 10px 15px;
  cursor: pointer;
  border-bottom: 1px solid #ebeef5;
}

.search-item:hover {
  background-color: #f5f7fa;
}

.item-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.item-address {
  color: #909399;
  font-size: 12px;
}

.main-content {
  display: flex;
  width: 74rem;
  padding: 0 1rem 1rem 0rem;
}

.map-container {
  width: 100%;
  height: 25rem;
  position: relative;
}

.mars2d-container {
  width: 100%;
  height: 100%;
  border-radius: 0.5rem;
}
</style>