<template>
  <div class="place-search-map" :style="{width: width, height: height}" v-loading="loading">
    <div id="container"></div>
    <el-row class="search-row" :gutter="8" type="flex">
<!--      <el-col :span="6">-->
<!--        <area-text-select-->
<!--          :level="1"-->
<!--          :province.sync="area.province"-->
<!--          :city.sync="area.city"-->
<!--          @change="onChangeArea"/>-->
<!--      </el-col>-->
<!--      <el-col :span="10">-->
<!--        <el-input v-model="keyword" placeholder="请输入地址关键词"  />-->
<!--      </el-col>-->
<!--      <el-col>-->
<!--        <el-button type="primary" icon="el-icon-search" @click="doPlaceSearch(keyword)">搜索</el-button>-->
<!--        <el-button @click="doSearchNearByCenter(keyword)" >周边搜索</el-button>-->
<!--      </el-col>-->
    </el-row>
    <div id="panel"></div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import globalConfig from '@/utils/config/globalConfig'
import { debounce } from '@/utils'
import AreaTextSelect from '@/components/AreaTextSelect/index.vue'

export default {
  name: "LocationMap",
  components: { AreaTextSelect },
  props: {
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "100%"
    },
    initLng: {
      type: String,
      default: '120.250452'
    },
    initLat: {
      type: String,
      default: '27.101745'
    },
    status: {
      type: String,
      default: '0'
    },
    onlineStatus: {
      type: String,
      default: '0'
    },
    deviceSn: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      AMap: null,
      map: null,  // 地图实例
      placeSearch: null,  // POI查询
      geocoder: null, // 逆地理编码
      loading: false,
      keyword: null,
      markers: [],
      area: {
        province: '福建省',
        city: '宁德市',
      }
    }
  },
  mounted() {
    this.initAMap();
  },
  beforeDestroy() {
    this.destroyMap();
  },
  methods: {
    destroyMap() {
      this.map?.destroy();
    },
    onChangeArea() {
      this.loadPlaceSearch(this.area.province, this.area.city);
      if (this.keyword != null) {
        this.doPlaceSearch(this.keyword);
      } else {
        let city = this.area.city === '市辖区' ? this.area.province : this.area.city;
        this.doPlaceSearch(city + '人民政府');
      }
    },
    initAMap() {
      AMapLoader.load({
        key: globalConfig.aMap.key, // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.PlaceSearch"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        this.AMap = AMap;
        this.map = new AMap.Map("container", {
          // 设置地图容器id
          viewMode: "3D", // 是否为3D地图模式
          zoom: 16, // 初始化地图级别
          center: [this.initLng == null ? 120.250452 : this.initLng, this.initLat == null ? 27.101745 : this.initLat], // 初始化地图中心点位置
        });
        // this.map.on('click', this.onClickMap);

        // POI
        this.loadPlaceSearch(this.area.province, this.area.city);

        // 逆地理编码
        this.loadGeoCoder();

        // 加载初始地址
        this.initMarker();

      }).catch((e) => {
        console.log(e);
      });
    },
    async initMarker() {
      this.removeAllMarker();
      if (this.initLng != null && this.initLat != null) {
        this.getGeoAddress(this.initLng, this.initLat).then(res => {
          // 标点
          this.removeAllMarker();
          console.log("添加标记点")
          this.addMarker(this.initLng, this.initLat, this.deviceSn, this.status, this.onlineStatus);
          this.$emit('map-geo', res, this.initLng, this.initLat);

          // 地区
          let component = res.regeocode.addressComponent;
          this.area = {
            province: component.province,
            city: component.city === '' ? '市辖区' : component.city,
          }
        }).finally(() => {
          this.loading = false;
        })
      }
    },
    addMarker: function(lng, lat, title, status, onlineStatus) {
      //创建一个 Marker 实例：
      console.log('title===========' + title)
      let icon = this.formarStatus(status, onlineStatus)
      console.log('icon===========' + icon)
      let marker = new AMap.Marker({
        position: new AMap.LngLat(lng, lat), //经纬度对象
        icon: new AMap.Icon({
          image: icon,
          size: new AMap.Size(25, 30), // 设置图标的宽高
          imageSize: new AMap.Size(25, 30) // 设置图标的实际显示尺寸
        }),
        title: title,
        offset: new AMap.Pixel(-12.5, -35)
      })
      //将创建的点标记添加到已有的地图实例：
      this.map.add(marker)
      this.markers.push(marker)

      // 创建一个 Text 实例来显示标题
      let text = new AMap.Text({
        text: title,
        anchor: 'center', // 设置文本的锚点
        position: new AMap.LngLat(lng, lat), // 经纬度对象
        offset: new AMap.Pixel(0, -50),
        style: {
          'background-color': '#1890ff', // 背景颜色为蓝色
          'border': 'none', // 边框颜色与背景一致
          'border-radius': '5px', // 圆角 5px
          'color': 'white', // 文字颜色为白色
          'font-size': '14px', // 字体大小
          'padding': '5px 10px' // 内边距，调整文本框的大小
        }
      })

      // 将文本标签添加到地图实例
      this.map.add(text)
    },
    formarStatus(status,onlineStatus){
      if(onlineStatus == "0"){
        if(status == "3"){
          return globalConfig.icon.redyellow;
        }else if(status == "4"){
          return globalConfig.icon.orangered;
        }
        return globalConfig.icon.red;
      }else{
        if(status == "0"){
          return globalConfig.icon.gray;
        }else if(status == "1"){
          return globalConfig.icon.blue;
        }else if(status == "2"){
          return globalConfig.icon.green;
        }else if(status == "3"){
          return globalConfig.icon.yellow;
        }else if(status == "4"){
          return globalConfig.icon.orange;
        }else if(status == "8"){
          return globalConfig.icon.gray;
        }else if(status == "9"){
          return globalConfig.icon.gray;
        }
      }
    },
    // 删除所有的标记点
    removeAllMarker() {
      this.map.remove(this.markers);
      this.markers = [];
    },
    // 点击地图事件
    onClickMap(e) {
      console.log('clickMap', e);
      let lng = e.lnglat.lng;
      let lat = e.lnglat.lat;
      this.changeMarker(lng, lat);
    },
    // 逆地理编码，并标点
    changeMarker(lng, lat) {
      console.log('changeMarker', lng,lat);
      this.loading = true;
      this.getGeoAddress(lng, lat).then(res => {
        this.removeAllMarker();
        this.addMarker(lng, lat, res.regeocode.formattedAddress);
        this.$emit('map-geo', res, lng, lat);
      }).finally(() => {
        this.loading = false;
      })
    },
    // 获取逆地理编码
    getGeoAddress(lng, lat) {
      console.log('getGeoAddress', lng,lat);
      console.log('this.geocoder', this.geocoder);
      if(this.geocoder){
        return new Promise((resolve, reject) =>{
          this.geocoder.getAddress([lng, lat], (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              console.log('resolve', result);
              resolve(result);
            } else {
              console.log('reject', status,result);
              reject(status);
            }
          })
        })
      }
    },
    // 加载逆地理编码
    loadGeoCoder() {
      AMap.plugin('AMap.Geocoder', () => {
        this.geocoder = new AMap.Geocoder({
          city: '全国' // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
        })
      })
    },
    // 加载POI
    loadPlaceSearch(province, city) {
      if (city == null) {
        city = '北京市';
      }
      if (city === '市辖区') {
        city = province;
      }
      AMap.plugin(["AMap.PlaceSearch"], () => {
        //构造地点查询类
        this.placeSearch = new AMap.PlaceSearch({
          pageSize: 5, // 单页显示结果条数
          pageIndex: 1, // 页码
          city: city, // 兴趣点城市
          citylimit: true,  //是否强制限制在设置的城市内搜索
          map: this.map, // 展现结果的地图实例
          panel: "panel", // 结果列表将在此容器中进行展示。
          autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
      });
      // 事件绑定
      this.placeSearch.on('selectChanged', (data) => {
        this.$emit('select-changed', data);
      })
    },
    //关键字查询
    doPlaceSearch(keyword) {
      if (keyword == null) {
        return this.$message.warning("请输入关键词");
      }
      this.loading = true;
      this.placeSearch.search(keyword, (status, result) => {
        this.loading = false;
        console.log("POI", status, result);
      });
    },
    // 周边搜索
    doSearchNearBy(keyword, lng, lat, radius = 200) {
      if (keyword == null) {
        return this.$message.warning("请输入关键词");
      }
      this.loading = true;
      this.placeSearch.searchNearBy(keyword, [lng, lat], radius, (status, result) => {
        this.loading = false;
        console.log("POI NearBy", status, result);
      })
    },
    // 根据地图中心点查询周边
    doSearchNearByCenter(keyword) {
      let center = this.map.getCenter();
      this.doSearchNearBy(keyword, center.lng, center.lat, 1000);
    },
    // 监听输入事件
    onInputSearch: debounce(function () {
      this.doPlaceSearch(this.keyword)
    }, 600)
  },
};
</script>
<style scoped lang="scss">
.place-search-map {
  position: relative;
  overflow: hidden;

  .search-row {
    margin: 0.5em;
  }
  #container {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
  }
  #panel {
    position: absolute;
    background-color: white;
    max-height: 90%;
    overflow-y: auto;
    top: 10px;
    right: 10px;
    width: 280px;
  }
}
</style>
