<template>
  <section class="staffBoxFlexRow areaInfoBox">
    <div class="staffTitle">
      <strong>地理位置</strong>
      <span class="staffTitletips">选定位置后,系统将自动把"名称"、"省市区"、"详细地址"、""经纬度"信息分别带入至"驻勤点名称"、"驻勤点省市区"、"驻勤点详细地址"、"驻勤点经纬度"
</span>
      <el-button type="primary" @click="onSave">确定</el-button>
    </div>
    <div class="staffContext">
      <el-form ref="form" label-width="100px">
        <!-- <el-row :gutter="50">
          <el-col :span="12">
            <el-form-item label="定位坐标：" prop="xy">
              <el-input v-model="formList.xy" />
            </el-form-item>
          </el-col>
        </el-row> -->
        <!-- <el-row :gutter="50">
          <el-col :span="6">
            <el-form-item label="经度坐标：" prop="">
              <span class="labelvalue">{{longitude }}</span>
              <el-button type="primary" class="copyTextlong"  @click="onCopylong" style="width: 100px;">复制</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="纬度坐标：" prop="">
              <span class="labelvalue">{{latitude }}</span>
              <el-button type="primary" class="copyTextlat"  @click="onCopylat" style="width: 100px;">复制</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="位置：" prop="">
              <span class="labelvalue">{{address }}</span>
              <el-button type="primary" class="copyTextaddress"  @click="onCopyaddress" style="width: 100px;">复制</el-button>
            </el-form-item>
          </el-col>
        </el-row> -->
        <div class="infoBox"><strong>经纬坐标:</strong><span v-if="longitude"> [{{ longitude }}, {{ latitude }}] </span><strong>位置:</strong> {{ address }} <strong>名称：</strong>{{ attendanceSiteName }} <strong>省市区：</strong>{{ district }}</div>
        <el-row>
          <el-col :span="12">
            <el-amap-search-box
              class="search-box"
              :search-option="searchOption"
              :on-search-result="onSearchResult"
              placeholder="请输入搜索地址"
            ></el-amap-search-box>
          </el-col>
        </el-row>
        <el-row style="width:100%;height: 650px">
          <el-amap
            vid="amapDemo"
            :center="center"
            :zoom="zoom"
            class="amap-demo"
            :events="events"
            ref="map"
          >
             <el-amap-marker
              v-for="(marker,index) in markers"
              :key ="'marker'+index"
              :position ="marker" 
            > </el-amap-marker>

          </el-amap>
        </el-row>
      </el-form>
    </div>
  </section>
</template>
<script>
// import cityOptions from '@/assets/js/cityData.js'
// import {employessBaseInfoApi,staffDetailInfoApi} from "@/api/staffApi.js"
import VueAMap from "vue-amap";
let amapManager = new VueAMap.AMapManager();
import Clipboard from 'clipboard';
let Geocoder;
export default {
  name: "fence-manage",
  data() {
    let self = this;
    return {
      district:'',//省市区
      attendanceSiteName:'',
      searchValue:'',
      userInfo: {},
      formList: {
        xy:'',  
        address:''   
      },
      longitude:'0',
      latitude:'0',
      // cityOptions:cityOptions,
      amapManager,
      zoom: 15,
      center: [116.400128, 39.947276],
      address: "", // 地址
      lng: 0, // 经度
      lat: 0, // 维度
      xy: "", //经纬合并
      searchOption: {
        city: "",
        citylimit: false,
      },
      markers: [], 
      events: {
        init:(o)=> {
          // debugger
          console.log(o)          
          // o 是高德地图定位插件实例
          // o.getCurrentPosition((status, result) => {
          //   console.log('55',result)
          //   if (result && result.position) {
          //     self.lng = result.position.lng;
          //     self.lat = result.position.lat;
          //     self.center = [self.lng, self.lat];
          //     self.loaded = true;
          //     self.$nextTick();
          //   }
          // });
        },
        click(e) {
          let { lng, lat } = e.lnglat;
          self.lng = lng;
          self.lat = lat;
          self.formList.xy = self.lng + "," + self.lat;
          self.longitude=self.lng;
          self.latitude=self.lat;
          // 这里通过高德 SDK 完成。
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all",
          });
          geocoder.getAddress([lng, lat], function(status, result) {
            // debugger
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                console.log(result)
                self.address = result.regeocode.formattedAddress;
                self.attendanceSiteName = result.regeocode.pois[0].name;
                let city=''
                if(result.regeocode.addressComponent.city==''){
                  city='市辖区'
                  if(result.regeocode.addressComponent.province.indexOf('重庆市')>-1&&result.regeocode.addressComponent.district.indexOf('县')>-1){
                    city='县'
                  }
                }else{
                  city=result.regeocode.addressComponent.city
                }
                self.district = result.regeocode.addressComponent.province + city + result.regeocode.addressComponent.district;
                self.$nextTick();
                self.markers = [];    //标记点先清空
                self.markers.push([lng,lat])
              }
            }
          });
        },
      },
      // 当前地图需要的拓展插件需在该内容下放置  Geocoder为通过坐标获取地址信息
      plugin: [{
              pName: 'Geocoder',
              events: {
                  init(o) {
                      Geocoder = o
                  }
              },
          }
      ]
    };
  },
  mounted() {
     console.log(this.$route.query)
     if(this.$route.query){
      this.longitude=this.$route.query.longitude&&this.$route.query.longitude
      this.latitude=this.$route.query.latitude&&this.$route.query.latitude
      this.address=this.$route.query.address&&this.$route.query.address
      this.attendanceSiteName=this.$route.query.attendanceSiteName&&this.$route.query.attendanceSiteName
      this.district=this.$route.query.district&&this.$route.query.district
      if(this.$route.query.longitude){
        this.markers=[]
        this.center=[this.longitude,this.latitude]//居中地图位置
        this.markers.push([this.longitude,this.latitude])       
      }
      // if(this.$route.query.attendanceSiteName){
      //   document.querySelector(".search-box-wrapper input").value=this.attendanceSiteName
      // }      
     }
  },
  methods: {
    onSave(){ 
      if(!this.longitude){
        this.$message({type: "warning",message: "请搜索，再点击确定"});
        return
      }
      window.parent.postMessage({longitude:this.longitude,latitude:this.latitude,address:this.address,attendanceSiteName:this.attendanceSiteName,district:this.district},'*')     
    },
    onCopylong(){
      console.log(this.longitude)
      if(!this.longitude){
        this.$message({type: "warning",message: "请搜索，再点击复制"});
        return
      }
      let link=JSON.stringify(this.longitude)
      this.$nextTick(()=>{
          let clipboard=new Clipboard('.copyTextlong', {
              text: function () {
                return link
              }
            });
            clipboard.on("success", e => {
                this.$message({
                  type: "success",
                  message: "复制成功"
                });
                clipboard.destroy(); // 释放内存
          });
          clipboard.on("error", e => {
              this.$message({
                type: "warning",
                message: "该浏览器不支持自动复制!"
              }); // 不支持复制
              clipboard.destroy(); // 释放内存
          });
      });  
    },
    onCopylat(){
      console.log(this.latitude)
      if(!this.latitude){
        this.$message({type: "warning",message: "请搜索，再点击复制"});
        return
      }
      let link=JSON.stringify(this.latitude)
      this.$nextTick(()=>{
          let clipboard=new Clipboard('.copyTextlat', {
              text: function () {
                return link
              }
            });
            clipboard.on("success", e => {
                this.$message({
                  type: "success",
                  message: "复制成功"
                });
                clipboard.destroy(); // 释放内存
          });
          clipboard.on("error", e => {
              this.$message({
                type: "warning",
                message: "该浏览器不支持自动复制!"
              }); // 不支持复制
              clipboard.destroy(); // 释放内存
          });
      });
    },
    onCopyaddress(){
      console.log(this.address)
      if(!this.address){
        this.$message({type: "warning",message: "请搜索，再点击复制"});
        return
      }
      let link=JSON.stringify(this.address)
      this.$nextTick(()=>{
          let clipboard=new Clipboard('.copyTextaddress', {
              text: function () {
                return link
              }
            });
            clipboard.on("success", e => {
                this.$message({
                  type: "success",
                  message: "复制成功"
                });
                clipboard.destroy(); // 释放内存
          });
          clipboard.on("error", e => {
              this.$message({
                type: "warning",
                message: "该浏览器不支持自动复制!"
              }); // 不支持复制
              clipboard.destroy(); // 释放内存
          });
      });
    },
    getRefVal(val) {
      console.log('22',val);
      this.formList = val;
      if(this.formList.longitude){
        let lgat=this.formList.longitude+","+this.formList.latitude
        this.$set(this.formList,'xy',lgat)     
        let centerArr=[this.formList.longitude,this.formList.latitude]
        this.center=[centerArr[0],centerArr[1]]
      }
    },
    // 搜索
    onSearchResult(pois) {
      this.attendanceSiteName=document.querySelector(".search-box-wrapper input").value
      console.log(pois);
      let latSum = 0;
      let lngSum = 0;
      if (pois.length > 0) {
        pois.forEach((poi) => {
          let { lng, lat } = poi;
          lngSum += lng;
          latSum += lat;
          this.address=pois[0].address
        });
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length,
        };
        this.center = [center.lng, center.lat];       
        this.markers = [];    //标记点先清空  
        this.markers.push([pois[0].lng,pois[0].lat]) 
        this.formList.xy = pois[0].lng + "," + pois[0].lat;
        this.longitude=pois[0].lng;
        this.latitude=pois[0].lat;      
        this.$nextTick(()=>{
          this.$refs.map.$$getInstance().setFitView()//居中地图位置          
        })
        let self=this;
        // 这里通过高德 SDK 完成。
        var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all",
          });
          geocoder.getAddress([this.longitude, this.latitude], function(status, result) {
            // debugger
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                console.log(result)             
                let city=''
                if(result.regeocode.addressComponent.city==''){
                  city='市辖区'
                  if(result.regeocode.addressComponent.province.indexOf('重庆市')>-1&&result.regeocode.addressComponent.district.indexOf('县')>-1){
                    city='县'
                  }
                }else{
                  city=result.regeocode.addressComponent.city
                }  
                self.district = result.regeocode.addressComponent.province + city + result.regeocode.addressComponent.district;               
              }
            }
          });
      }
    },
  },
};
</script>
<style lang="scss">
.staffBoxFlexRow {
  display: flex;
  flex-direction: column;
  padding: 20px;
  .staffTitle {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #ebebeb;
    padding: 5px 0;
    margin-bottom: 10px;
    clear: both;
    align-items: center;
    strong {
      color: #000;
      font-weight: normal;
    }
    .staffTitletips{
     color: red;flex:1;margin-left:30px;font-weight: bold;
    }
    em {
      margin-right: 20px;
      i {
        color: #2e8ad7;
        margin-right: 20px;
        cursor: pointer;
      }
    }
  }
  .el-form {
    .el-input {
      width: 300px;
    }
    .el-textarea {
      width: 300px;
    }
  }
  .el-form-item {
    display: flex;
    flex-direction: row;
    .el-form-item__label {
      text-align: left;
    }
    .el-form-item__content {
      margin: 0 !important;
      display: flex;
      flex-direction: row;
      .el-cascader {
        margin-bottom: 10px;
      }
    }
  }

  .labelvalue{width: 100px;}
  .infoBox{
    padding: 10px 10px 20px;
    font-size: 16px;
    strong{font-weight: bold;margin-left: 20px;}
  }
}
</style>
<style lang="scss">
.areaInfoBox {
  .search-box {
    border: 1px solid #eee;
    position: absolute;
    top: 5px;
    left: 5px;
  }
}

</style>
