<template>
  <el-dialog :title="!dataForm.id ? '新建' : isDetail ? '详情' : '编辑'" :close-on-click-modal="false" :visible.sync="visible"
             class="rv-dialog rv-dialog_center" lock-scroll width="800px">
    <el-row :gutter="15" class="">
      <el-col :span="8">
        <el-form ref="elForm" :model="dataForm" :rules="rules" size="small" label-width="70px" label-position="right"
                 :disabled="!!isDetail">
          <!--          <el-col :span="24">-->
          <!--            <el-form-item label="名称" prop="kqName">-->
          <!--              <el-input v-model="dataForm.kqName" placeholder="请输入" clearable :style="{ width: '100%' }">-->
          <!--              </el-input>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->

<!--          <el-col :span="24">-->
<!--            <el-form-item label="地点" prop="kqLocation">-->
<!--              <el-input v-model="dataForm.kqLocation" placeholder="自动带出" clearable :style="{ width: '100%' }" disabled>-->
<!--              </el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->

<!--          <el-col :span="24">-->
<!--            <el-form-item label="经度" prop="kqLongitude">-->
<!--              <el-input v-model="dataForm.kqLongitude" placeholder="自动带出" clearable :style="{ width: '100%' }" disabled>-->
<!--              </el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->

<!--          <el-col :span="24">-->
<!--            <el-form-item label="纬度" prop="kqLatitude">-->
<!--              <el-input v-model="dataForm.kqLatitude" placeholder="自动带出" clearable :style="{ width: '100%' }" disabled>-->
<!--              </el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->

          <!--          <el-col :span="24">-->
          <!--            <el-form-item label="单位" prop="kqWorkUnit">-->
          <!--              <el-input v-model="dataForm.kqWorkUnit" placeholder="请输入" clearable :style="{ width: '100%' }">-->
          <!--              </el-input>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->

          <!--          <el-col :span="24">-->
          <!--            <el-form-item label="授权" prop="cronkqAccredit">-->
          <!--              <uDSelect v-model="dataForm.cronkqAccredit" :multiple="true" placeholder="选择范围" title="选择范围" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->

          <!--          <el-col :span="24">-->
          <!--            <el-form-item label="有效签卡范围(米)" label-width="150px" prop="kqValidCardRange">-->
          <!--              <el-input v-model="dataForm.kqValidCardRange" placeholder="请输入" clearable :style="{ width: '100%' }">-->
          <!--              </el-input>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-form>
      </el-col>
      <el-col :span="24">
        <div style="width: 100%;">
          <div class="search_box">
            <div class="label">关键字搜索</div>
            <el-input v-model="input" placeholder="请输入内容" id="tipinput"></el-input>
            <el-button type="primary" style="background: #5875eb; border: 1px solid #5875eb; border-radius: 5px; margin-left: 10px;"
                       icon="el-icon-search" @click="searchMap"> 查询
            </el-button>

          </div>
          <div ref="gaode_Map" id="gaode_Map" style="width: 100%; height: 400px"></div>
        </div>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader"; //引入AMapLoader
window._AMapSecurityConfig = {
  // 设置安全密钥
  securityJsCode: "9e783bf4363ce4b0cb429d677736e823",
};
export default {
  components: {},
  props: [],
  data () {
    return {
      loading: false,
      visible: false,
      isDetail: false,
      dataForm: {
        kqName: undefined,
        kqLocation: undefined,
        kqLongitude: undefined,
        kqLatitude: undefined,
        kqWorkUnit: undefined,
        cronkqAccredit: [],
        kqValidCardRange: undefined,
      },
      rules: {},
      input: "",
      map: null,
      auto: null,
      placeSearch: null,
      lnglat: [],
      markers: [],
      position: {},
      form:{
        khlxdzjd:'',
        province:'',
        city:'',
        address:'',
        district:'',
        lng:'',
        lat:''
      }
    };
  },
  computed: {},
  watch: {},
  created () {
  },
  mounted () { },
  methods: {
    //初始事件
    openShow(){
      this.visible = true;
      this.input ='';
      this.form = {
        province:'',
        khlxdzjd:'',
        city:'',
        address:'',
        district:'',
        lng:'',
        lat:''
      }
      if (!this.map) {
        this.$nextTick(() => {
          console.log('打印是否触发这个事件');
          this.initMap();
        })
      } else {
        // that.setData({longitude, latitude})
      }

    },
    //点击确定按钮
    dataFormSubmit(){
      if(this.form.lat && this.form.lng){
        this.visible = false;
        this.$emit('onSubmit',this.form)
      }else{
        this.$message.warning('请选择地点!');
      }
      console.log('打印dataFormSubmit',this.form)
    },
    // 地图初始化
    initMap () {
      console.log('打印是否初始地图')
      let centerLen = [114.351469, 30.502236];
      AMapLoader.reset();
      AMapLoader.load({
        "key": "9bf3eb4233ce6790bbf47ac883a26e60",// 申请好的Web端开发者Key，首次调用 load 时必填
        "version": "2.0",   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.ControlBar', 'AMap.Geocoder', 'AMap.Marker',
          'AMap.CitySearch', 'AMap.Geolocation', 'AMap.AutoComplete', 'AMap.InfoWindow', 'AMap.PlaceSearch'],// 需要使用的的插件列表，如比例尺'AMap.Scale'等
        "AMapUI": {
          "version": "1.1",
          "plugins": []
        },
        Loca: {
          version: '2.0' //数据可视化
        }
      })
        .then((AMap) => {
          this.map = new AMap.Map("gaode_Map", {
            // 设置地图容器id
            viewMode: '3D', // 使用3D视图
            zoomEnable: true, // 地图是否可缩放，默认值为true
            dragEnable: true, // 地图是否可通过鼠标拖拽平移，默认为true
            doubleClickZoom: true, // 地图是否可通过双击鼠标放大地图，默认为true
            zoom: 13, // 初始化地图级别
            center: centerLen, // 初始化中心点坐标 山东济南
            resizeEnable: true,
            // mapStyle: "amap://styles/darkblue", // 设置颜色底层
            placeSearch: null // 搜索关键字
          });
          this.setMarker(centerLen);
          // 关键字查询
          this.searchMap();
          // 监听鼠标点击事件
          this.map.on("click", this.clickMapHandler);
        })
        .catch((e) => { });
    },
    //      关键字查询
    // keywordSearch(){
    //   let that = this;
    //   let geocoder = new AMap.Geocoder({
    //     radius: 1000,
    //     extensions: 'all'
    //   });
    //   geocoder.getLocation(this.input, function(status, result) {
    //     if (status === 'complete' && result.geocodes.length) {
    //       const { lng, lat } = result.geocodes[0].location;
    //       let formattedAddress = result.geocodes[0].formattedAddress;
    //       const sdata = { lng, lat, formattedAddress };
    //       that.searchSuccessData(sdata);
    //       that.marker.setPosition([lng, lat]);
    //       that.map.add(that.marker);
    //       that.map.setFitView(that.marker);
    //     } else {
    //       that.$message.error('根据地址查询位置失败');
    //     }
    //   })
    // },
    // 关键字查询
    searchMap () {
      console.log('打印shif chuf 这个事件')
      // 搜索框自动完成类
      this.auto = new AMap.AutoComplete({
        input: "tipinput", // 使用联想输入的input的id
      });
      //构造地点查询类
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map,
      });
      // 当选中某条搜索记录时触发
      this.auto.on("select", this.selectSite);
    },
    //选中查询出的记录
    selectSite (e) {
      console.log('打印e',e)
      if (e.poi.location) {
        // this.lnglat = [e.poi.location.lng, e.poi.location.lat];
        this.placeSearch.setCity(e.poi.adcode);
        this.placeSearch.search(e.poi.name); //关键字查询
        let geocoder = new AMap.Geocoder({});
        let that = this;
        geocoder.getAddress(this.lnglat, function (status, result) {
          if (status === "complete" && result.regeocode) {
            let province = result.regeocode.addressComponent.province;
            let city = result.regeocode.addressComponent.city;
            let district = result.regeocode.addressComponent.district;
            let s_addr =
              result.regeocode.addressComponent.province +
              "-" +
              result.regeocode.addressComponent.city +
              "-" +
              result.regeocode.addressComponent.district;
            let addreesd = result.regeocode.formattedAddress; // 全部地址名称
            let khlxdzjd = addreesd.substring(s_addr.length); // 获取具体街道
            //自己想要赋的值，根据自己的做修改
            that.$set(that.form, "province", province);
            that.$set(that.form, "city", city);
            that.$set(that.form, "district", district);
            that.$set(that.form, "khlxdzjd", khlxdzjd);
            that.$set(that.form, "address", e.poi.name);
            that.$set(
              that.form,
              "coordinate",
              e.poi.location.lng + "," + e.poi.location.lat
            ); //纬度，经度
          } else {
          }
        });
      } else {
        this.$message.error("查询地址失败，请重新输入地址");
      }
    },
    // 点击地图事件获取经纬度，并添加标记
    clickMapHandler (e) {
      console.log('打印e',e)
      this.dataForm.kqLongitude = e.lnglat.getLng();
      this.dataForm.kqLatitude = e.lnglat.getLat();
      this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      this.setMarker(this.lnglat);
      // 点击地图上的位置，根据经纬度转换成详细地址
      let geocoder = new AMap.Geocoder({});
      // 创建Geocoder实例
      // let geocoder = new AMap.Geocoder({
      //   radius: 1000,
      //   extensions: 'all'
      // });
      let that = this;
      geocoder.getAddress(this.lnglat, function (status, result) {
        console.log('打印status', status);
        if (status === "complete" && result.regeocode) {
          let province = result.regeocode.addressComponent.province;
          let city = result.regeocode.addressComponent.city;
          that.dataForm.kqLocation = result.regeocode.formattedAddress;
          let district = result.regeocode.addressComponent.district;
          let s_addr =
            result.regeocode.addressComponent.province +
            "-" +
            result.regeocode.addressComponent.city +
            "-" +
            result.regeocode.addressComponent.district;
          let addreesd = result.regeocode.formattedAddress; // 全部地址名称
          let khlxdzjd = addreesd.substring(s_addr.length); // 获取具体街道
          //自己想要赋的值，根据自己的做修改
          that.$set(that.form, "province", province);
          that.$set(that.form, "khlxdzjd", khlxdzjd);
          that.$set(that.form, "city", city);
          that.$set(that.form, "district", district);
          that.$set(that.form, "lat", e.lnglat.getLat());
          that.$set(that.form, "lng", e.lnglat.getLng());
          that.$set(that.form, "address", result.regeocode.formattedAddress);
          that.$set(
            that.form,
            "coordinate",
            e.lnglat.getLng() + "," + e.lnglat.getLat()
          ); //纬度，经度
        } else {
        }
      });
      this.position = {
        longitude: e.lnglat.getLng(),
        latitude: e.lnglat.getLat(),
        address: that.address,
      };
      this.input = that.address; //把查询到的地址赋值到输入框
    },
    //  添加标记
    setMarker (lnglat) {
      this.removeMarker();
      let marker = new AMap.Marker({
        position: lnglat,
      });
      marker.setMap(this.map);
      this.markers.push(marker);
    },
    // 删除之前后的标记点
    removeMarker () {
      if (this.markers) {
        this.map.remove(this.markers);
      }
    },
  },
};
</script>


<style lang="scss">
.search_box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 50px;

  .label {
    color: #000;
    width: 100px;
  }
}

.content {
  position: relative;
}

#panel {
  position: absolute;
  top: 50px;
  right: 20px;
}

#gaode_Map {
  overflow: hidden;
  width: 100%;
  height: 540px;
  margin: 0;
}

.amap-sug-result {
  z-index: 2999 !important;
}
</style>
