<template>
  <div class="app-container map-contain">
    <el-dialog title="选择坐标" :visible.sync="mapOpen" @close="handleClose" width="1200px">
      <div>
        <div>
          <el-form ref="form" :model="form" label-width="50px">
            <el-row>
              <el-col :span="6" >
                <el-form-item label="地址" prop="lng">
                  <el-input v-model="form.address" readonly="readonly" />
                </el-form-item>
              </el-col>
              <el-col :span="6"  >
                <el-form-item label="经度" prop="lng">
                  <el-input v-model="form.lng"  />
                </el-form-item>
              </el-col>
              <el-col :span="6" >
                <el-form-item label="纬度" prop="lat">
                  <el-input v-model="form.lat"  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="map-coord">
            <el-select
              class="address-select"
              v-model="searchValue"
              filterable
              remote
              value-key="id"
              placeholder="请输入关键词"
              :remote-method="remoteMethod"
              @change="changeArea"
              :loading="loading">
              <el-option
                v-for="item in areaOptions"
                :key="item.id"
                :label="item.title"
                :value="item.location"
              />
            </el-select>
            <div v-if="mapOpen" id="mapCoord"></div>
          </div>
        </div>
        <div id="container"></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeMap">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import markerDefault from '@/assets/images/markerDefault.png';

export default {
  data() {
    return {
      map: null, // 地图实例
      markerDefault: markerDefault, // 默认图片
      mapOpen: false,
      markerLayer: null,
      form: {
        address: '',
        lat: 36.060249948,
        lng: 103.826524828,
      },
      searchValue: '', // 地图搜索值
      loading: false,
      areaOptions: [] // 地图搜索地址
    }
  },
  methods: {
    init() {
      this.form.address = ''
      // 默认省政府
      this.form.lat = 36.060249948
      this.form.lng = 103.826524828
      this.form.map = null
      this.form.markerLayer = null
      this.mapOpen = true
      this.$nextTick(() => {
        let that = this
        // 初始化地图
        this.map = new TMap.Map('mapCoord', {
          center: new TMap.LatLng(this.form.lat,this.form.lng), // 地图显示中心点
          zoom:18	// 缩放级别
        });
        this.getAddress()
        this.creatPoint()
      
        this.map.on("click",function(evt){
          if(evt.poi) {
            that.form.address = evt.poi.name
          } else {
            that.form.address = ''
          }
          that.form.lat = evt.latLng.getLat().toFixed(6);
          that.form.lng= evt.latLng.getLng().toFixed(6);
          that.getAddress()
          that.creatPoint()
        })

      })
    },
    // 逆地址解析
    getAddress() {
      let location = this.form.lat + ',' + this.form.lng
      this.$jsonp("https://apis.map.qq.com/ws/geocoder/v1/", {
        location: location,
        key: "UZQBZ-SYQL3-LYF3K-Y7FAL-N3656-2DBJ4",
        output:"jsonp"
      })
      .then(res => {
        // 结合知名地点形成的描述性地址，更具人性化特点
        this.form.address = res.result.formatted_addresses.recommend
      })
    },
    // 绘点
    creatPoint(){
      if (this.markerLayer) {
        this.markerLayer.setMap(null);
        this.markerLayer = null;
      }
      this.markerLayer = new TMap.MultiMarker({
        map: this.map,  //指定地图容器
        //样式定义
        styles: {
          //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
          "myStyle": new TMap.MarkerStyle({ 
            "width": 25,  // 点标记样式宽度（像素）
            "height": 35, // 点标记样式高度（像素）
            "src": markerDefault,  //图片路径
            "anchor": { x: 16, y: 32 }  
          }) 
        },
        //点标记数据数组
        geometries: [{
          "id": "1",   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
          "styleId": 'myStyle',  //指定样式id
          "position": new TMap.LatLng(this.form.lat,this.form.lng),  //点标记坐标位置
          "properties": {//自定义属性
            "title": "marker1"
          }
        }]
      });
    },
    // 地图搜索事件
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        this.$jsonp("https://apis.map.qq.com/ws/place/v1/suggestion/", {
          region: "兰州",
          keyword: query,
          key: "UZQBZ-SYQL3-LYF3K-Y7FAL-N3656-2DBJ4",
          output:"jsonp"
        })
        .then(res => {
          this.loading = false
          if(res.data.length > 0) {
            this.areaOptions = res.data
          }
        })
        .catch(err => {
          this.loading = false
        });
      } else {
        this.options = [];
      }
    },
    // 选择地区
    changeArea() {
      if(this.searchValue) {
        this.form.lat = this.searchValue.lat
        this.form.lng = this.searchValue.lng
        this.map.setCenter(new TMap.LatLng(this.searchValue.lat,this.searchValue.lng));
        this.creatPoint()
        this.getAddress()
      }
    },
    // 提交数据
    closeMap(){
      this.map.destroy();
      this.mapOpen=false;
      this.$emit('refreshDataList',this.form)
    },
    // 关闭弹窗事件
    handleClose() {
      this.map.destroy();
      this.mapOpen=false;
    }
  }
}
</script>

<style lang="scss" scoped>
  .map-contain{
    /deep/.el-dialog{
      margin-top: 2vh !important;
    }
  }
  #mapCoord{
    width: 100%;
    height: 70vh;
  }
  .map-coord{
    position: relative;
    /deep/.address-select{
      position: absolute;
      top: 10px;
      left: 10px;
      z-index: 2000;
    }
  }
</style>