<template>
  <view class="main">
    <view class="mapBox">
      <map id="myMap" :longitude="longitude" :latitude="latitude" :markers="markers" class="map" show-location></map>
    </view>

    <view :style="{
      transform: showLong ? 'translateY(-20vh)' : 'translateY(-32rpx)',
      height: showLong ? '80vh' : '60vh',
    }" class="bigBox">
      <view class="topBox" @click="handleChangeLong">
        <image class="packUp" src="https://eshangtech.com/ShopICO/ahyd-BID/service/packUp.svg" />
      </view>
      <scroll-view class="listBox" :scroll-y="true" :style="{
        height: showLong ? 'calc(80vh - 32rpx)' : 'calc(60vh - 32rpx)',
      }">
        <view class="list">
          <view :class="selectId === item.id ? 'itemBox selectItemBox' : 'itemBox'" v-for="(item, index) in dataList"
            :key="index" @click="handleChangePlace(item)">
            <view class="itemLeft">
              <view class="title">{{ item.name || "" }}</view>
              <view class="phone">{{ item.phone || "" }}</view>
              <view class="distance">{{ item.distance ? item.distance + "km" : "" }}
                <span v-if="item.recently" class="recently">距离最近</span>
              </view>
            </view>
            <view class="itemRight" @click="handleGoMap(item)">
              <image class="mapIcon" src="/static/images/home/navigationIcon.svg" />
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>
<script>
import ETCdata from "./data";
export default {
  data() {
    return {
      mapCtx: "",
      showLong: false, // 是否显示更长
      dataList: [],
      longitude: "",
      latitude: "",
      seatInfo: {}, // 用户实际经纬度
      selectId: 0, // 选择的id
      markers: [],
    };
  },
  onLoad() {
    this.mapCtx = uni.createMapContext("myMap");

    console.log("this.dataList", this.dataList);
    let seatInfo = uni.getStorageSync("seatInfo");
    if (seatInfo) {
      this.seatInfo = JSON.parse(seatInfo);
    }
    this.handleGetPointMapData();
    // let list = ETCdata.list;
    // console.log("this.seatInfo", this.seatInfo);

    // // this.longitude = this.seatInfo.longitude;
    // // this.latitude = this.seatInfo.latitude;

    // if (list && list.length > 0) {
    //   list.forEach((item) => {
    //     let distance = this.getDistance(
    //       this.seatInfo.longitude,
    //       this.seatInfo.latitude,
    //       item.lng,
    //       item.lat
    //     );
    //     item.distance = distance;
    //   });
    // }

    // for (let i = 0; i < list.length - 1; i++) {
    //   for (let j = 0; j < list.length - i - 1; j++) {
    //     if (list[j].distance > list[j + 1].distance) {
    //       let temp = list[j];
    //       list[j] = list[j + 1];
    //       list[j + 1] = temp;
    //     }
    //   }
    // }
    // list[0].recently = true;
    // this.dataList = list;

    // this.longitude = this.dataList[0].lng;
    // this.latitude = this.dataList[0].lat;

    // this.selectId = this.dataList[0].id;
    // this.markers = [
    //   {
    //     id: this.dataList[0].id, // 使用时间戳作为唯一ID
    //     latitude: this.dataList[0].lat,
    //     longitude: this.dataList[0].lng,
    //     width: 20,
    //     height: 30,
    //     label: {
    //       // 文本标签
    //       content: this.dataList[0].name,
    //       color: "#3EC273",
    //       fontSize: 14,
    //       bgColor: "#ffffff",
    //       borderRadius: 4,
    //       padding: 5,
    //       textAlign: "center",
    //     },
    //   },
    // ];
  },
  methods: {
    // 用接口拿到点位数据的方法
    async handleGetPointMapData() {
      let params = {
        page: 1, // 开始时间
        limit: 9999, // 结束时间
      };
      let time = Math.ceil(new Date().getTime() / 1000);

      let req = {
        // app_id: "530000301",
        app_id: "530000301",
        biz_content: JSON.stringify(params),
        charset: "UTF-8",
        pid: "530000301",
        service: "trawe.eats.etc",
        utc_timestamp: time,
        version: "1.0",
        sign_type: "RSA2",
      };
      let signText = `app_id=${req.app_id}&biz_content=${req.biz_content}&charset=UTF-8&pid=${req.app_id}&service=trawe.eats.etc&utc_timestamp=${req.utc_timestamp}&version=1.0`;
      console.log("handleGetHighwayHeadlines", req);
      console.log("signText", signText);

      // 签名
      const sign = await new Promise((resolve, reject) => {
        uni.request({
          // url: "http://10.104.1.159:8080/RSA/sign", 
          url: "https://admin.es.eshangtech.com/platform/RSA/sign",
          method: "POST",
          data: {
            originalText: signText,
            privateKey:
              "MIIEuwIBADANBgkqhkiG9w0BAQEFAASCBKUwggShAgEAAoIBAQCPXwG/nb3FcwBGftuxm0mS3BjZorB5YEKnNpQLjpsOWEO+AMi6l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jYQncv7PKON5hPheBvzV3GVgl1j5ksIb8T61o1FCr68A6JSByYwoYYP3QKFWGgbrhdopPKIcLFeOJkJBtkrDy+/cIJJkSPEQKBgAeG8f7a10mVyVbgyYAwzOFfpXgJYCMfoDlmLuGVZRjjhD1uF4JMK2FMkmzKSKukSPveAOwNml3Z16oZ/oRabkjX8jXETc5SsO3pfFw+yLemnEkQN8SSqDcIl2WziMKhOX6d9MxN37eBMkthjbRcABi0Jfq7QZEthi2UHlwOlx4pAn9C9zkkAmanv6zrsiw5ymcRkEZj+AnMN7m79XQ4fAmDcg4gAYWhJWlM8/g2ww596Qpkl+AkXrJVxFCjMOc2odPKtLhmfgLVvPrRXgQl/+Dj3op54sTS1xHYyKc3/JBHuSE40K/TgB+sMQb1plSa9v6hw6MrleEo24jU82ZVLs8v"
          },
          header: {
            "content-type": "application/json",
          },
          success(res) {
            console.log("resresresresresresres", res);
            resolve(res.data.Result_Desc);
          },
        });
      });
      console.log("sign", sign);

      req.sign = sign;

      const mapPointData = await new Promise((resolve, reject) => {
        uni.request({
          url: `https://tuozhan.yns-etc.com/gzh/api/v1/gzh/point/outlets`,
          method: "POST",
          data: req,
          header: {
            "content-type": "application/x-www-form-urlencoded",
          },
          success(res) {
            console.log("resresresresresresresresres", res);
            resolve(res.data.response.data.records);
            // let data = res.data.CollectionObject;
            // if (data && data.length > 0) {
            //   resolve(data);
            // } else {
            //   resolve([]);
            // }
          },
        });
      });
      console.log("mapPointData", mapPointData);
      if (mapPointData && mapPointData.length > 0) {
        if (mapPointData && mapPointData.length > 0) {
          mapPointData.forEach((item) => {
            let distance = this.getDistance(
              this.seatInfo.longitude,
              this.seatInfo.latitude,
              item.lng,
              item.lat
            );
            item.distance = distance;
          });
        }

        this.longitude = mapPointData[0].lng;
        this.latitude = mapPointData[0].lat;
        mapPointData[0].recently = true;
        this.dataList = mapPointData;
        this.selectId = mapPointData[0].id;
        this.markers = [
          {
            id: mapPointData[0].id, // 使用时间戳作为唯一ID
            latitude: mapPointData[0].lat,
            longitude: mapPointData[0].lng,
            width: 20,
            height: 30,
            label: {
              // 文本标签
              content: mapPointData[0].name,
              color: "#3EC273",
              fontSize: 14,
              bgColor: "#ffffff",
              borderRadius: 4,
              padding: 5,
              textAlign: "center",
            },
          },
        ];
      }
    },
    // 计算经纬度的实际距离的方法
    getDistance(lat1, lon1, lat2, lon2) {
      const toRad = (d) => (d * Math.PI) / 180; // 角度转弧度
      const R = 6371.0; // 地球半径（单位：km）
      const dLat = toRad(lat2 - lat1);
      const dLon = toRad(lon2 - lon1);
      const a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(toRad(lat1)) *
        Math.cos(toRad(lat2)) *
        Math.sin(dLon / 2) *
        Math.sin(dLon / 2);

      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      return (R * c).toFixed(2); // 返回单位：米
    },
    // 打开地图的跳转
    handleGoMap(obj) {
      uni.openLocation({
        latitude: obj.lat * 1,
        longitude: obj.lng * 1,
        scale: 16, // 缩放比例
        name: obj.name,
        // address: "", // 这个可能会影响地图的定位，所以可以选择不填
        success(data) {
          console.log(data);
        },
        fail(err) {
          console.log(err);
        },
      });
    },
    // 修改显示列表长度
    handleChangeLong() {
      this.showLong = !this.showLong;
      this.$forceUpdate();
    },
    // 切换点位
    handleChangePlace(obj) {
      this.longitude = obj.lng;
      this.latitude = obj.lat;
      this.selectId = obj.id;
      this.markers = [
        {
          id: obj.id, // 使用时间戳作为唯一ID
          latitude: obj.lat,
          longitude: obj.lng,
          width: 20,
          height: 30,
          label: {
            // 文本标签
            content: obj.name,
            color: "#3EC273",
            fontSize: 14,
            bgColor: "#ffffff",
            borderRadius: 4,
            padding: 5,
            textAlign: "center",
          },
        },
      ];
    },
  },
};
</script>

<style lang="less" scoped>
.main {
  width: 100vw;
  height: 100vh;
  background: #f5f7f9;

  .mapBox {
    width: 100%;
    height: 40vh;

    .map {
      width: 100%;
      height: 100%;
    }
  }

  .bigBox {
    width: 100%;
    background: #fff;
    border-top-right-radius: 32rpx;
    border-top-left-radius: 32rpx;

    .topBox {
      width: 100%;
      height: 32rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .packUp {
        width: 32rpx;
        height: 64rpx;
      }
    }

    .listBox {
      width: 100%;
      box-sizing: border-box;
      padding: 32rpx;

      .itemBox {
        width: 100%;
        box-sizing: border-box;
        margin-bottom: 32rpx;
        border-radius: 16rpx;
        border: 1px solid #dfe0e0;
        padding: 16rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .itemLeft {
          width: calc(100% - 80rpx);

          .title {
            width: 100%;
            font-family: "PingFangSC";
            font-weight: 400;
            font-size: 30rpx;
            color: #130f05;
            line-height: 40rpx;
            text-align: left;
            font-style: normal;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
          }

          .phone {
            width: 100%;
            font-family: "PingFangSC";
            font-weight: 400;
            font-size: 24rpx;
            color: #716f69;
            line-height: 36rpx;
            text-align: left;
            font-style: normal;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
          }

          .distance {
            width: 100%;
            font-family: "PingFangSC";
            font-weight: 400;
            font-size: 24rpx;
            color: #716f69;
            line-height: 36rpx;
            text-align: left;
            font-style: normal;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;

            .recently {
              background: #e8f8ee;
              border-radius: 4rpx;
              padding: 2rpx 8rpx;
              color: #3ec272;
              font-size: 24rpx;
              margin-left: 16rpx;
            }
          }
        }

        .itemRight {
          width: 64rpx;
          height: 64rpx;

          .mapIcon {
            width: 64rpx;
            height: 64rpx;
          }
        }
      }

      .selectItemBox {
        border: 1px solid #43c577;
      }
    }

    .listBox ::-webkit-scrollbar {
      display: none;
      width: 0;
    }
  }
}
</style>
