<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">
            <div class="search-box-td" v-if="mapType==='tiandimap'">
              <div class="search-wraper">
                <input class="search-input" ref="tiandiSearchInput" />
                <span class="search-btn" @click="onSearchMap">搜索</span>
              </div>
            </div>
            <el-amap-search-box
              v-else
              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">
          <div id="mapDiv" class="mapBox" v-if="mapType==='tiandimap'"></div>
          <el-amap
            vid="amapDemo"
            :center="center"
            :zoom="zoom"
            class="amap-demo"
            :events="events"
            ref="map"
            v-else
          >
             <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 gcoord from "gcoord";
// import cityOptions from '@/assets/js/cityData.js'
import { getPlaceByTiandi } 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 {
      mapType: 'gaode',
      tiandiMap: null,
      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: [], 
      placeSearch: null, // 高德地图搜索对象
      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.mapType === 'tiandimap') {
      this.initTiandiMap();
      // 确保高德地图API已加载完成
      if (window.AMap) {
        this.initAMapSearch();
      } else {
        // 如果高德地图API尚未加载完成，等待加载
        const checkAMap = setInterval(() => {
          if (window.AMap) {
            clearInterval(checkAMap);
            this.initAMapSearch();
          }
        }, 100);
      }
     }
     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.mapType === 'tiandimap') {
          if(this.longitude && this.latitude) {
            // 高德坐标（GCJ02）转天地图坐标（WGS84）
            const result = gcoord.transform(
              [this.longitude, this.latitude],    // 经纬度坐标
              gcoord.GCJ02,                       // 当前坐标系
              gcoord.WGS84,                       // 目标坐标系
            );
            this.addTiandiMarker(result[0], result[1]);
            
            // 如果没有传入地址、名称或省市区信息，使用高德地图API获取
            if (!this.address || !this.attendanceSiteName || !this.district) {
              // 确保高德地图API已加载完成
              if (window.AMap) {
                this.getLocationInfoFromAMap([this.longitude, this.latitude]);
              } else {
                // 如果高德地图API尚未加载完成，等待加载
                const checkAMap = setInterval(() => {
                  if (window.AMap) {
                    clearInterval(checkAMap);
                    this.getLocationInfoFromAMap([this.longitude, this.latitude]);
                  }
                }, 100);
              }
            }
          }
        }    
      }
     }
  },
  methods: {
    // 初始化高德地图搜索
    initAMapSearch() {
      try {
        // 初始化高德地图的PlaceSearch对象
        this.placeSearch = new AMap.PlaceSearch({
          pageSize: 10,
          pageIndex: 1,
          city: "", // 全国范围搜索
          citylimit: false
        });
        console.log('高德地图搜索初始化成功');
      } catch (error) {
        console.error('高德地图搜索初始化失败:', error);
      }
    },
    // 清除天地图marker
    clearTiandiMap() {
      let newMarker = this.tiandiMap.getOverlays(); // 获取到了地图上的所有点
      for (let i = 0; i < newMarker.length; i++) {
        this.tiandiMap.removeOverLay(newMarker[i])
      };
    },
    // 添加天地图marker
    addTiandiMarker(lng, lat) {
      const marker = new T.Marker(new T.LngLat(lng, lat));
      //向地图上添加标注
      this.tiandiMap.addOverLay(marker);
      const _this = this;
      setTimeout(function () {
        _this.tiandiMap.panTo(new T.LngLat(Number(lng), Number(lat)));
      }, 500);
    },
    // 从高德地图API获取位置信息
    getLocationInfoFromAMap(gcjCoord) {
      const geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: "all"
      });
      
      geocoder.getAddress(gcjCoord, (status, result) => {
        if (status === "complete" && result.info === "OK") {
          if (result && result.regeocode) {
            // 如果没有地址信息，则设置
            if (!this.address) {
              this.address = result.regeocode.formattedAddress;
            }
            
            // 如果没有名称信息，则设置
            if (!this.attendanceSiteName) {
              if (result.regeocode.pois && result.regeocode.pois.length > 0) {
                this.attendanceSiteName = result.regeocode.pois[0].name;
              } else {
                this.attendanceSiteName = this.address.split('区').pop() || this.address;
              }
            }
            
            // 如果没有省市区信息，则设置
            if (!this.district) {
              const addressComponent = result.regeocode.addressComponent;
              let city = '';
              
              if (addressComponent.city === '') {
                city = '市辖区';
                if (addressComponent.province.indexOf('重庆市') > -1 && 
                    addressComponent.district.indexOf('县') > -1) {
                  city = '县';
                }
              } else {
                city = addressComponent.city;
              }
              
              this.district = addressComponent.province + city + addressComponent.district;
            }
          }
        }
      });
    },
    
    // 天地图逆地址编码（保留但不再使用）
    getAddressZh(lng, lat, needAddr) {
      // 使用高德地图API替代
      const wgsCoord = [lng, lat];
      const gcjCoord = gcoord.transform(
        wgsCoord,
        gcoord.WGS84,
        gcoord.GCJ02
      );
      this.getLocationInfoFromAMap(gcjCoord);
    },
    // 天地图搜索（使用高德地图API）
    onSearchMap() {
      const keywords = this.$refs.tiandiSearchInput.value;
      if (!keywords) {
        this.$message({type: "warning", message: "请输入搜索关键词"});
        return;
      }
      
      this.attendanceSiteName = keywords;
      
      // 确保placeSearch已初始化
      if (!this.placeSearch) {
        this.initAMapSearch();
        if (!this.placeSearch) {
          this.$message({type: "error", message: "搜索功能初始化失败，请刷新页面重试"});
          return;
        }
      }
      
      // 使用初始化好的placeSearch对象
      this.placeSearch.search(keywords, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          const pois = result.poiList.pois;
          if (pois && pois.length > 0) {
            const poi = pois[0]; // 取第一个结果
            this.address = poi.address || '';
            
            // 高德坐标（GCJ02）转天地图坐标（WGS84）
            const gcjCoord = [poi.location.lng, poi.location.lat];
            const wgsCoord = gcoord.transform(
              gcjCoord,
              gcoord.GCJ02,
              gcoord.WGS84
            );
            
            // 清除天地图markers并添加新标记
            this.clearTiandiMap();
            this.addTiandiMarker(wgsCoord[0], wgsCoord[1]);
            
            // 保存GCJ02坐标用于表单提交
            this.formList.xy = gcjCoord[0] + "," + gcjCoord[1];
            this.longitude = gcjCoord[0]?.toFixed(6);
            this.latitude = gcjCoord[1]?.toFixed(6);
            
            // 直接使用高德地图的地址信息
            this.address = poi.address || '';
            this.attendanceSiteName = poi.name || keywords;
            
            // 使用高德地图的Geocoder获取省市区信息
            const geocoder = new AMap.Geocoder({
              radius: 1000,
              extensions: "all"
            });
            
            geocoder.getAddress(gcjCoord, (status, result) => {
              if (status === "complete" && result.info === "OK") {
                if (result && result.regeocode) {
                  const addressComponent = result.regeocode.addressComponent;
                  let city = '';
                  
                  if (addressComponent.city === '') {
                    city = '市辖区';
                    if (addressComponent.province.indexOf('重庆市') > -1 && 
                        addressComponent.district.indexOf('县') > -1) {
                      city = '县';
                    }
                  } else {
                    city = addressComponent.city;
                  }
                  
                  this.district = addressComponent.province + city + addressComponent.district;
                }
              }
            });
          } else {
            this.$message({type: "warning", message: "未找到相关地点"});
          }
        } else {
          this.$message({type: "warning", message: "搜索失败，请重试"});
        }
      });
    },
    // 点击天地图事件
    onMapClick(e) {
      // 天地图坐标（WGS84）转高德坐标（GCJ02）
      const wgsCoord = [e.lnglat.getLng(), e.lnglat.getLat()];
      const gcjCoord = gcoord.transform(
        wgsCoord,
        gcoord.WGS84,
        gcoord.GCJ02
      );
      
      // 保存高德坐标用于表单提交
      this.longitude = gcjCoord[0]?.toFixed(6);
      this.latitude = gcjCoord[1]?.toFixed(6);
      this.formList.xy = gcjCoord[0] + "," + gcjCoord[1];
      
      // 清除并添加新标记
      this.clearTiandiMap();
      this.addTiandiMarker(wgsCoord[0], wgsCoord[1]);
      
      // 使用高德地图的Geocoder获取位置信息
      const geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: "all"
      });
      
      geocoder.getAddress(gcjCoord, (status, result) => {
        if (status === "complete" && result.info === "OK") {
          if (result && result.regeocode) {
            // 设置地址信息
            this.address = result.regeocode.formattedAddress;
            
            // 设置名称信息
            if (result.regeocode.pois && result.regeocode.pois.length > 0) {
              this.attendanceSiteName = result.regeocode.pois[0].name;
            } else {
              this.attendanceSiteName = this.address.split('区').pop() || this.address;
            }
            
            // 设置省市区信息
            const addressComponent = result.regeocode.addressComponent;
            let city = '';
            
            if (addressComponent.city === '') {
              city = '市辖区';
              if (addressComponent.province.indexOf('重庆市') > -1 && 
                  addressComponent.district.indexOf('县') > -1) {
                city = '县';
              }
            } else {
              city = addressComponent.city;
            }
            
            this.district = addressComponent.province + city + addressComponent.district;
          }
        }
      });
    },
    // 天地图初始化
    initTiandiMap() {
      this.tiandiMap = new T.Map('mapDiv');
      const lnglat = new T.LngLat(116.40969,39.89945);
      this.tiandiMap.centerAndZoom(lnglat,12);
      this.tiandiMap.addEventListener("click", this.onMapClick);
    },
    onSave(){ 
      if(!this.longitude){
        this.$message({type: "warning",message: "请搜索，再点击确定"});
        return
      }
      console.log('hahahhah', this.longitude)
      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;
  }
}

.mapBox {
  position: absolute;
  width: 100%;
  height: 650px;
  z-index: 1;
}

.search-box-td {
  border: 1px solid #eee;
  position: absolute;
  top: 5px;
  left: 5px;
  width: 360px;
  height: 45px;
  background: #fff;
  box-shadow: 0 2px 2px rgba(0, 0, 0, .15);
  border-radius: 2px 3px 3px 2px;
  z-index: 10;
  .search-wraper {
    position: absolute;
    display: flex;
    align-items: center;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
  }
  .search-input {
    flex: 1;
    height: 20px;
    line-height: 20px;
    letter-spacing: .5px;
    font-size: 14px;
    text-indent: 10px;
    box-sizing: border-box;
    border: none;
    outline: none;
  }
  .search-btn {
    width: 45px;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: transparent;
    cursor: pointer;
  }
}

</style>