<template>
  <el-dialog :visible.sync="dialogFormVisible" :title="type=='edit'?'地图选点':'位置查看'" width="50%" append-to-body>
    <div class="form-div">
      <div class="form-left" style="height:300px;">
        <map-view ref="map" @click="click">
          <l-marker v-if="marker!=null" :lat-lng="marker" :icon="iconOptions"/>
        </map-view>
      </div>
    </div>
    <div v-show="type=='edit'" slot="footer" class="dialog-footer">
      <el-button :disabled="!canEdit" type="primary" @click="saveData">确定</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import MapView from './mapView'
import { LMarker, LPopup } from 'vue2-leaflet'
import { icon } from 'leaflet'
import * as L from 'leaflet'
export default {
  name: 'ChoosePointDialog',
  components: { MapView, LMarker, LPopup },
  data() {
    return {
      type: 'readonly', // 弹窗类型，readonly只读， edit编辑
      map: null, // map对象
      center: this.baseConfig.center, // 地图中心
      dialogFormVisible: false, // 对话框是否显示
      canEdit: true, // 保存按钮是否可以点击
      marker: null, // 图标坐标点，LatLng格式
      iconOptions: icon({
        iconUrl: require('../../assets/icons/icon-position.png'), // 图片路径
        iconSize: [32], // 图片大小
        iconAnchor: [16, 32] // 偏移x,y，针对图片的左上角
      }) // 图标配置
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    // 地图点击事件
    click(e) {
      if (this.type === 'edit') {
        console.log('onclick', e.latlng)
        this.marker = e.latlng
      }
    },
    /**
     * 初始化对话框
     * @param type 弹窗类型只读还是选点
     * @param position 默认位置
     */
    initDialog: function(type, position) {
      this.type = type
      this.dialogFormVisible = true
      if (position) {
        const lat = parseFloat(position.lat)
        const lng = parseFloat(position.lng)
        this.marker = L.latLng(lat, lng)
        this.center = L.latLng(lat, lng)
      } else {
        this.marker = null
      }
    },
    // 保存数据
    saveData: function() {
      if (this.marker) {
        this.$emit('choose', this.marker)
        this.dialogFormVisible = false
      } else {
        this.$message.info('尚未选点')
      }
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .form-div{
    width:100%;
    height:100%;
    display:flex;
    justify-content: space-between;
  }
  .form-left{
    flex:1;
    height:100%;
  }
  .form-right{
    width: 180px;
    height:100%;
    .avatar{
      margin-bottom: 10px;
    }
    text-align: center;
  }
</style>
