<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",
        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",
          method: "POST",
          data: {
            originalText: signText,
            privateKey:
              "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCtIkIJLbZYI9NvTRkRbqtjJ73gkAUJZBJw88Z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TNyExThOzZVJG0qNEombVOeu2zyq/aECunoktnzWllim96CrdcsJPZAk+Z7rNOcdu6sfa7teph4HZs9pT00VOK4jZ0a+GV71uUDHEkplhNhxAoGAMDOi5BxFe/595KIR7C/xboMUaQh/iDuPn2dzxmcUx0LLPUfkFPhEBV1mhAIzFFDI/JJYK6HR5m/fe7Q7DritRbaddCTtlB4NVK5k1gOJ3oN4s9ZD3Jxt5p/GuQ1sP7F9Zs3QP4KSkL34MwgGx9zdbPFofACnV4TWdN+KrJGjYMsCgYAE0CMM7rYHGY3Vt3/WZZJ+DPlKE6Q+uvFDomtsB1IavCeEJyjBP9+GhBHat86aA3mCFjf4emj1or7OEgPc0gCMtKBG6m10CrzLjzdWnOTveqWVUW/FS2gf17cIO5/FK/4KmAjH/QN24KXm395Qu8C0UFfgA66yysakJFkvXVBiPg==",
          },
          header: {
            "content-type": "application/json",
          },
          success(res) {
            console.log("resresresresresresres", res);
            resolve(res.data.data);
          },
        });
      });
      console.log("sign", sign);

      req.sign = sign;

      const mapPointData = await new Promise((resolve, reject) => {
        uni.request({
          url: `https://sxgzh.etclife.cn/etc/api/v1/wx/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>
