<template>
  <el-dialog v-loading='loading' element-loading-text="拼命加载中" width="80%" destroy-on-close :visible.sync="dialogTableVisible" append-to-body show-close>
    <el-form v-if="showSearch" ref="ruleForm" class="demo-form-inline" :inline="true">
      <el-form-item class="search-box">
        <el-input size="small" @keydown.enter.native="seachEnterFun" v-model="searchKey" type="search" id="search" style="width: 280px" placeholder="请输入关键字进行搜索" />
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" class="map-btn" @click="searchMap">搜索</el-button>
      </el-form-item>
      <div class="tip-box" id="searchTip"></div>
      <el-form-item label="经度" prop="lng">
        <el-input size="small" maxlength="11" v-model="lng" style="width: 140px" disabled></el-input>
      </el-form-item>
      <el-form-item label="纬度：" prop="lat">
        <el-input size="small" maxlength="10" v-model="lat" style="width: 140px" disabled></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" class="map-btn" @click="clickSureMap">确定</el-button>
      </el-form-item>
      <div v-show="showAddressList" class="address-list">
        <div class="address" @click="getGeoCode(v)" v-for="(v,i) in promptList" :key="i">
          <span class="name">{{v.name}}</span>
          <span class="district">{{v.district}}{{v.address}}</span>
        </div>
      </div>
    </el-form>
    <amap @click="onMapClick" ref="map" :zoom="zoom" :center="center" style="height: 700px;" class="amap-demo">
      <amap-marker v-for="(marker,index) in markers" :key="index" :offset="marker.offset" :position="marker.position" :icon="marker.icon" :label="marker.label" />
    </amap>
    <!-- 关闭按钮 -->
    <img @click="dialogTableVisible = false" class="close" src="../../../static/image/icon_close3.png" alt="">
  </el-dialog>
</template>

<script>
import {
  getInputPrompt,
  getGeoCode,
  getMapData,
  getLocation,
} from "../../api/order.js";
// import AmapVue from "@amap/amap-vue";
export default {
  data() {
    return {
      searchKey: "",
      dialogTableVisible: false,
      order: {},
      markers: [],
      texts: [],
      defaultCity: "北京",
      zoom: 18,
      center: [116.39747132275389, 39.908857325556404],
      promptList: [],
      address: "",
      addressDetail: {},
      lng: "",
      lat: "",
      showAddressList: false,
      showSearch: false,
      loading: false,
    };
  },
  created() {},
  mounted() {},
  methods: {
    seachEnterFun(e) {
      var keyCode = window.event ? e.keyCode : e.which;
      if (keyCode == 13) {
        this.searchMap();
      }
    },
    getGeoCode(v) {
      this.showAddressList = false;
      let splitPoint = v.location.indexOf(",");
      this.lng = v.location.slice(0, splitPoint);
      this.lat = v.location.slice(splitPoint + 1);
      this.center = [this.lng, this.lat];
      this.markers = [
        {
          id: 1,
          position: this.center,
          icon: require("/static/image/map_current.png"),
        },
      ];
      this.getLocation();
    },
    searchMap() {
      if (!this.searchKey.trim()) {
        return this.$message({
          type: "error",
          message: "请先输入关键字后再搜索！",
        });
      }
      getInputPrompt({ keywords: this.searchKey }).then((res) => {
        if (res.code === 200) {
          if (res.data.length) {
            this.promptList = res.data;
            this.showAddressList = true;
          }
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    init(data, mapData) {
      let orderDistance =
        mapData.orderDistance > 1000
          ? (mapData.orderDistance / 1000).toFixed(1) + "公里"
          : mapData.orderDistance + "米";
      let sendM = {
        id: 1,
        position: [data.sendLng, data.sendLat],
        icon: require("/static/image/map-fa.png"),
        label: {
          content: `商家距离目的地${orderDistance}`,
          direction: "top",
          offset: [-10, -20],
        },
      };
      let receiptM = {
        id: 2,
        position: [data.receiptLng, data.receiptLat],
        icon: require("/static/image/map-shou.png"),
      };

      // 中心点
      this.center = [
        ((data.receiptLng * 1 + data.sendLng * 1) / 2).toFixed(6),
        ((data.receiptLat * 1 + data.sendLat * 1) / 2).toFixed(6),
      ];
      // marker标记
      this.markers = [sendM, receiptM];
      if (mapData.shipperLng && mapData.shipperLat) {
        let distance =
          mapData.shipperDistance > 1000
            ? (mapData.shipperDistance / 1000).toFixed(1) + "公里"
            : mapData.shipperDistance + "米";
        let riderM = {
          id: 3,
          position: [mapData.shipperLng, mapData.shipperLat],
          icon: require("/static/image/map-rider.png"),
          label: {
            content:
              data.buttonStatus === 2
                ? `骑手距离商家${distance} | 预计${mapData.riderArriveMinute}分钟后到店`
                : data.buttonStatus === 3
                ? `骑手距离目的地${distance} | 预计${mapData.estimateArriveTime}送达`
                : "",
            direction: "top",
            offset: [-10, -20],
          },
        };
        this.markers.push(riderM);
      }
      this.$nextTick(() => {
        console.log("显示地图", this.$refs.map.$map);
        this.$refs.map.$map.setFitView();
        setTimeout(() => {
          this.$refs.map.$map.setFitView();
        }, 2000);
      });
    },
    setDialogStatus(data) {
      this.dialogTableVisible = true;
      this.loading = true;
      getMapData({ orderId: data.id }).then((res) => {
        if (res.code === 200) {
          this.loading = false;
          this.init(data, res.data);
        } else {
          this.loading = false;
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    chooseLocation() {
      this.dialogTableVisible = true;
      this.showSearch = true;
      // this.getCurrentLocation();
      this.searchKey = "";
      this.promptList = [];
      this.lat = "";
      this.lng = "";
    },
    clickSureMap() {
      this.$emit("getAddressDetail", this.addressDetail, this.lng, this.lat);
      this.dialogTableVisible = false;
    },
    // 点击地图选点
    onMapClick(e) {
      // 只有选点才可以点击地图选点
      if (!this.showSearch) {
        return;
      }
      if (e.lnglat) {
        this.lng = e.lnglat.lng;
        this.lat = e.lnglat.lat;
        this.markers = [
          {
            id: 1,
            position: [this.lng, this.lat],
            icon: require("/static/image/map_current.png"),
          },
        ];
        this.getLocation();
      } else {
        this.position = null;
      }
    },
    // 获取当前点详细地址信息
    getLocation() {
      this.$axios
        .get("https://restapi.amap.com/v3/geocode/regeo", {
          params: {
            key: "5ae8644771ef9abf9cfb3ea23b1df6ca",
            location: `${this.lng},${this.lat}`,
            extensions: "all",
          },
        })
        .then((res) => {
          let data = res.data;
          let address = data.regeocode.formatted_address.split(
            data.regeocode.addressComponent.township
          );
          this.searchKey = address[address.length - 1];
          this.addressDetail = {
            address: this.searchKey,
            province: data.regeocode.addressComponent.province,
            city: data.regeocode.addressComponent.city.length
              ? data.regeocode.addressComponent.city
              : data.regeocode.addressComponent.province,
            citycode: data.regeocode.addressComponent.citycode,
            district: data.regeocode.addressComponent.district,
          };
        })
        .catch((res) => {
          console.log(res);
        });
    },
    // 定位
    getCurrentLocation() {
      AMap.plugin("AMap.Geolocation", function () {
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000,
          // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
          buttonOffset: new AMap.Pixel(10, 20),
          //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          zoomToAccuracy: true,
          //  定位按钮的排放位置,  RB表示右下
          buttonPosition: "RB",
        });

        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, "complete", onComplete);
        AMap.event.addListener(geolocation, "error", onError);

        function onComplete(data) {
          // data是具体的定位信息
          console.log(1111, data);
          console.log(data.message);
        }

        function onError(data) {
          // 定位出错
          console.log(2222, data);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-form-item {
  display: flex;
  .el-form-item__label {
    flex-shrink: 0;
  }
}
/deep/ .amap-marker-label {
  font-size: 12px;
  background: #fc7200;
  color: #fff;
  padding: 4px 8px;
  border: none;
}
/deep/ .amap-marker-label:before {
  content: "";
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-top: 10px solid #fc7200;
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
}
.map-btn {
  background: #fc7200;
  border: none;
}
.demo-form-inline {
  position: relative;
  display: flex;
  align-items: center;
  .address-list {
    position: absolute;
    left: 0;
    top: 45px;
    border: 2px solid #3333;
    background: #fff;
    padding: 0 10px;
    z-index: 2;
    .address {
      line-height: 30px;
      cursor: pointer;
      .name {
        color: #333333;
      }
      .district {
        color: #999999;
        margin-left: 10px;
      }
    }
  }
}
/* 图标大小修改 */
/deep/ .el-dialog__header {
  display: none !important;
}
#container {
  width: 100%;
  height: 400px;
}
// /deep/ .amap-marker {
//   top: -139px !important;
//   left: 83px !important;
// }
/deep/ .amap-marker img {
  width: 40px !important;
  height: 66px !important;
  top: -25px !important;
  left: -10px !important;
}
.close {
  position: absolute;
  top: -30px;
  right: -25px;
  width: 30px;
  height: 30px;
  cursor: pointer;
}
</style>
