<template>
  <view class="life-page" :class="{ 'life-page--elder': $uiStyle === 'elder' }">
    <!-- 绑定输入事件 -->
    <van-sticky>
      <uni-search-bar
        class="custom-search"
        v-model="backfill"
        cancelButton="none"
        radius="20"
        placeholder="搜搜"
        bgColor="rgba(255,255,255,0.2)"
        @focus="handleFocus"
      ></uni-search-bar>
    </van-sticky>
    <!-- 关键词输入提示列表渲染 -->
    <view v-for="(item, index) in suggestion" :key="index">
      <!-- 绑定回填事件 -->

      <view>
        <!-- 根据需求渲染相应数据 -->
        <!-- 渲染地址title -->
        <view style="text-align: center" @tap="backfillFun" :id="index">{{
          item.title
        }}</view>
        <!-- 渲染详细地址 -->
        <view style="font-size: 12px; color: #666; text-align: center">{{
          item.addr
        }}</view>
      </view>
    </view>
    <map
      class="map"
      :markers="markers"
      :latitude="latitude"
      :longitude="longitude"
      @markertap="handleMarkerTap"
    >
      <cover-view class="map-cover">
        <view class="address">
          <text class="address__detail">{{ addressInfo.title }}</text>
          <text class="address__area">{{ addressInfo.address }}</text>
        </view>
        <view
          class="navigation"
          :data-addressinfo="addressInfo"
          @tap="handleAddressGo"
        >
          <image
            class="navagation-icon"
            src="/static/images/home/navigation.png"
          ></image>
        </view>
      </cover-view>
    </map>
    <view class="tabs-title">
      <text>探索周边15分钟生活圈</text>
    </view>
    <van-tabs :active="activeTab" @change="handleTabChange">
      <block v-for="(item, index) in tabs" :key="index">
        <van-tab :title="item"></van-tab>
      </block>
    </van-tabs>
    <view class="address-list">
      <view class="list-cell" v-for="(item, index) in addressList" :key="index">
        <view
          class="list-cell__cont"
          @click="handleMarker"
          :data-addressinfo="item"
        >
          <image
            class="point-icon"
            mode="aspectFit"
            src="/static/images/common/life_point.png"
          >
          </image>
          <view>
            <view class="list-cell__title">{{ item.title }}</view>
            <view class="list-cell__distance">距离{{ item.distance }}KM</view>
            <view class="list-cell__address">{{ item.address }}</view>
          </view>
        </view>
        <image
          class="phone-icon"
          src="/static/images/common/phone_icon.png"
          @click="handlePhoneCall(item)"
        ></image>
      </view>
    </view>
  </view>
</template>

<script>
import { geocoder, apiSearch } from "@/api/map.js";
import { maskPhoneCall, getPointResByLabel } from "@/utils";
/* const QQMapWX = require("@/libs/qqmap-wx-jssdk.min.js");

const qqmapsdk = new QQMapWX({
  key: "ZA2BZ-CIVCD-VZZ4M-PQD2X-V6YBJ-NBFXT",
}); */
const app = getApp();
export default {
  data() {
    return {
      activeTab: 0,
      tabs: ["文物古迹", "超市", "美食", "加油站", "酒店", "学校"],
      backfill: "",
      // 当前门牌地址经纬度
      latitude: 29.65945,
      longitude: 121.4405,

      markers: [
        {
          id: 1,
          iconPath: "/static/images/common/point.png",
          latitude: 29.65945,
          longitude: 121.4405,
          width: 32,
          height: 52,
        },
      ],

      addressList: [],
      //当前要导航的地址
      addressInfo: {
        title: "",
        address: "",
        latitude: 29.65945,
        longitude: 121.4405,
      },

      suggestion: "",
    };
  },
  onLoad: function () {
    this.setAddressInfo();
  },
  methods: {
    /* 获取门牌信息后初始化打点 */
    initDoorMarker() {
      /* 打点 */
      this.doorMarker = [
        {
          id: 10000,
          iconPath: "/static/images/common/point_common.png",
          longitude: this.longitude,
          latitude: this.latitude,
          width: 22,
          height: 32,
        },
      ];
    },
    async setAddressInfo() {
      let address = "";
       // 为了防止请求经纬度失败去展示默认信息
      this.addressInfo = {
        title: app.globalData.doorInfo.baseInfo.bzdz,
        address: app.globalData.doorInfo.baseInfo.bzdz1,
      };
      if (
        app.globalData.doorInfo.baseInfo.x1 &&
        app.globalData.doorInfo.baseInfo.y1
      ) {
        this.longitude = app.globalData.doorInfo.baseInfo.x1;
        this.latitude = app.globalData.doorInfo.baseInfo.y1;
      } else {
        address = app.globalData.doorInfo.baseInfo.bzdz1;
        if (
          app.globalData.doorInfo.baseInfo.bzdz1.indexOf("宁波市奉化区") === -1
        ) {
          address = "宁波市奉化区" + app.globalData.doorInfo.baseInfo.bzdz1;
        } else {
          address = app.globalData.doorInfo.baseInfo.bzdz1;
        }
       try {
          const res = await geocoder({
            address,
          });
          const location = res.geocodes[0].location.split(",").map(Number);
          this.longitude = location[0];
          this.latitude = location[1];
        } catch {
          uni.showToast({ title: "该门牌地址没有经纬度" });
        }
      }
        /* 设置门牌地址信息，用于搜索周边 */
      this.addressInfo = {
        ...this.addressInfo,
        longitude: this.longitude,
        latitude: this.latitude,
      };
      this.initDoorMarker();
      this.nearbySearch();
    },
    async nearbySearch() {
      const { addressList, markers } = await apiSearch({
        location: `${this.longitude},${this.latitude}`,
        keyword: this.tabs[this.activeTab],
      });
      this.addressList = addressList;
      const pointRes = getPointResByLabel(this.tabs[this.activeTab]);
      markers.forEach((item) => {
        item.iconPath = pointRes.iconPath;
        item.width = 40;
        item.height = 40;
      });
      this.markers = [...this.doorMarker, ...markers];
    },

    handleTabChange(e) {
      // #ifdef MP-WEIXIN || MP-ALIPAY
      this.setData({
        activeTab: e.detail.index,
      });
      // #endif
      // #ifdef H5
      this.setData({
        activeTab: e,
      });
      // #endif
      console.log("activeTab", this.activeTab);
      this.nearbySearch();
    },

    //数据回填方法
    backfillFun(e) {
      var id = e.currentTarget.id;

      for (var i = 0; i < this.suggestion.length; i++) {
        if (i == id) {
          this.setData({
            backfill: this.suggestion[i].title,
          });
        }
      }
    },

    handleFocus() {
      console.log("输入框聚焦");

      const _this = this;

      uni.chooseLocation({
        latitude: 29.65945,
        longitude: 121.4405,

        success(res) {
          console.log(res, "wx.chooseLocation");

          _this.setData({
            backfill: res.name,
            addressInfo: { ...res, title: res.name },
          });

          _this.marker();
          _this.nearbySearch();
        },
      });
    },

    handleMarker(e) {
      console.log("打点位置", e.currentTarget.dataset["addressinfo"]);
      this.addressInfo = e.currentTarget.dataset["addressinfo"];
      this.marker();
    },

    marker() {
      const targetAddress = this.addressInfo;
      const pointRes = getPointResByLabel(this.tabs[this.activeTab]);
      let markers = JSON.parse(JSON.stringify(this.markers));
      markers.forEach((item) => {
        if (item.title === targetAddress.title) {
          item.iconPath = pointRes.iconPathSelected;
          item.width = 50;
          item.height = 54;
        } else {
          if (item.id !== 10000) {
            item.iconPath = pointRes.iconPath;
            item.width = 40;
            item.height = 40;
          }
        }
      });
      this.markers = markers;
      this.latitude = targetAddress.latitude;
      this.longitude = targetAddress.longitude;
    },

    handleAddressGo(e) {
      console.log("导航去那些位置");
      console.log(e);
      console.log(e.currentTarget.dataset["addressinfo"]);
      const targetAddress = e.currentTarget.dataset["addressinfo"];
      uni.openLocation({
        latitude: targetAddress.latitude,
        longitude: targetAddress.longitude,
        scale: 5,
        name: targetAddress.title,
        address: targetAddress.address,

        success(res) {
          console.log(res, "wx.getLocation");
        },
      });
    },
    handlePhoneCall(item) {
      if (!item.tel.length) {
        uni.showToast({
          title: "该商家暂未提供电话",
        });
        return;
      }
      const phoneNumber = item.tel.split(";")[0];
      maskPhoneCall(phoneNumber);
    },
    //触发关键词输入提示事件
    getsuggest(e) {
      var _this = this; //调用关键词提示接口

      qqmapsdk.getSuggestion({
        //获取输入框值并设置keyword参数
        keyword: e.detail.value,
        //用户输入的关键词，可设置固定值,如keyword:'KFC'
        //region:'北京', //设置城市名，限制关键词所示的地域范围，非必填参数
        success: function (res) {
          //搜索成功后的回调
          console.log(res);
          var sug = [];

          for (var i = 0; i < res.data.length; i++) {
            sug.push({
              // 获取返回结果，放到sug数组中
              title: res.data[i].title,
              id: res.data[i].id,
              addr: res.data[i].address,
              city: res.data[i].city,
              district: res.data[i].district,
              latitude: res.data[i].location.lat,
              longitude: res.data[i].location.lng,
            });
          }

          _this.setData({
            //设置suggestion属性，将关键词搜索结果以列表形式展示
            suggestion: sug,
          });
        },
        fail: function (error) {
          console.error(error);
        },
        complete: function (res) {
          console.log(res);
        },
      });
    },
    /* 地图上点击的打点 */
    handleMarkerTap(e) {
      console.log("地图上被点击的点", e.detail.markerId);
      // 10000代表门牌地址
      if (e.detail.markerId === 10000) {
        return;
      }
      const pointRes = getPointResByLabel(this.tabs[this.activeTab]);
      let markers = JSON.parse(JSON.stringify(this.markers));
      markers.forEach((item) => {
        if (item.id === e.detail.markerId) {
          console.log("选中的点", item);
          item.iconPath = pointRes.iconPathSelected;
          item.width = 50;
          item.height = 54;
          this.addressInfo = {
            title: item.title,
            address: "宁波市奉化区" + item.address,
            latitude: item.latitude,
            longitude: item.longitude,
          };
        } else {
          if (item.id !== 10000) {
            item.iconPath = pointRes.iconPath;
            item.width = 40;
            item.height = 40;
          }
        }
      });

      this.markers = markers;
    },
  },
};
</script>
<style>
@import "./life.css";
</style>
<style lang="scss" scoped>
.address-list {
  flex: 1;
  overflow-y: scroll;
  display: flex;
  flex-direction: column;
  margin-bottom: 20rpx;
  background: #fff;
  .list-cell {
    display: flex;
    padding: 20rpx 40rpx;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px dashed #dedede;
    &__cont {
      flex: 1;
      display: flex;
      .point-icon {
        width: 16px;
        height: 16px;
        margin-right: 5px;
        margin-top: 8px;
      }
    }
    &__title {
      font-size: 28rpx;
      font-weight: bold;
      padding: 14rpx 0;
    }
    &__distance {
      font-size: 20rpx;
      line-height: 28rpx;
      color: #999999;
    }
    &__address {
      font-size: 20rpx;
      line-height: 28rpx;
      color: #999999;
    }
    /* 电话图标 */
    .phone-icon {
      width: 36px;
      height: 36px;
    }
  }
}
.life-page--elder {
  .map {
    .address {
      &__detail {
        font-size: calc(18px * $zlb-elder-font-scale);
        line-height: calc(28px * $zlb-elder-font-scale);
      }
      &__area {
        font-size: calc(13px * $zlb-elder-font-scale);
        line-height: calc(24px * $zlb-elder-font-scale);
      }
    }
  }
  .custom-tabs ::v-deep .txt {
    font-size: calc(14px * $zlb-elder-font-scale);
  }
  .tabs-title {
    font-size: calc(18px * $zlb-elder-font-scale);
    // line-height: 28px;
  }
  ::v-deep .van-tabs .van-tab {
    font-size: calc(14px * $zlb-elder-font-scale);
  }
  .address-list {
    .list-cell {
      &__title {
        font-size: calc(14px * $zlb-elder-font-scale);
      }
      &__distance {
        font-size: calc(10px * $zlb-elder-font-scale);
        line-height: calc(14px * $zlb-elder-font-scale);
      }
      &__address {
        font-size: calc(10px * $zlb-elder-font-scale);
        line-height: calc(14px * $zlb-elder-font-scale);
      }
    }
    .phone-icon {
      width: calc(36px * $zlb-elder-font-scale);
      height: calc(36px * $zlb-elder-font-scale);
    }
  }
}
</style>
