<template>
  <div class="layout">
    <div class="addres" @click="showPicker">
      {{ cityOrCounty == "" ? "请选择" : strsplit(cityOrCounty)  }}
    </div>
    <div class="search" @click="handleSearch">{{ res.list[0].title }}</div>
    <div class="shop" @click="toshop"></div>
    <m-city
      :provinceData="list"
      headTitle="区域选择"
      ref="cityPicker"
      @funcValue="getpickerParentValue"
      pickerSize="3"
    >
    </m-city>
  </div>
</template>
<script>
import config from "@/config/config";
import { postAdvertisementjw } from "@/api/home.js";
import gkcity from "@/components/m-city/m-city.vue";
import { Icon } from "uview-ui";
export default {
  components: {
    "m-city": gkcity,
    Icon,
  },
  title: "搜索栏",
  props: ["res"],
  data() {
    return {
      location: null,
      // 确保默认值正确读取
      cityOrCounty: uni.getStorageSync("cityOrCounty") || "",
      form: {},
      list: [
        {
          id: "",
          localName: "请选择",
          children: [],
        },
      ],
      // 添加本地存储的经纬度
      storedLat: uni.getStorageSync("latitude") || null,
      storedLon: uni.getStorageSync("longitude") || null,
    };
  },
  mounted() {
    // 页面加载时，若本地有存储数据就使用
    if (this.storedLat && this.storedLon) {
      this.form.lat = this.storedLat;
      this.form.lon = this.storedLon;
      this.getAdvertisementByLocation();
    }
    // 确保地区名称也被读取
    this.cityOrCounty = uni.getStorageSync("cityOrCounty") || "";
    // this.getLocation();
  },
  methods: {
    strsplit(str) {
      let arr = str.split("");
      return arr.slice(0, 3).join("")
    },
    toshop() {
      uni.navigateTo({
        url: "/pages/tabbar/cart/cartList",
      });
    },
    // 三级地址联动回调
    async getpickerParentValue(e) {
      // 将需要绑定的地址设置为空，并赋值
      this.form.consigneeAddressIdPath = [];
      this.form.consigneeAddressPath = [];
      let name = "";

      e.forEach((item, index) => {
        if (item.id) {
          // 遍历数据
          this.form.consigneeAddressIdPath.push(item.id);
          this.form.consigneeAddressPath.push(item.localName);
          name += item.localName;
          this.form.___path = name;
        }
        if (index == e.length - 1) {
          //如果是最后一个
          let _town = item.children.filter((_child) => {
            return _child.id == item.id;
          });

          this.form.lat = _town[0].center.split(",")[1];
          this.form.lon = _town[0].center.split(",")[0];
        }
      });

      const jwobj = {
        longitude: Number(this.form.lon),
        latitude: Number(this.form.lat),
      };

      const { data } = await postAdvertisementjw(jwobj);
      if (data.success) {
        // 确保保存的城市名称正确
        this.cityOrCounty = this.form.consigneeAddressPath[2];
        uni.setStorageSync("cityOrCounty", this.cityOrCounty);
        // 存储经纬度
        uni.setStorageSync("longitude", this.form.lon);
        uni.setStorageSync("latitude", this.form.lat);
        // 更新本地存储的经纬度
        this.storedLat = this.form.lat;
        this.storedLon = this.form.lon;
      }
    },
    // 根据经纬度获取广告信息
    async getAdvertisementByLocation() {
      const jwobj = {
        longitude: Number(this.storedLon),
        latitude: Number(this.storedLat),
      };
      const { data } = await postAdvertisementjw(jwobj);
      if (data.success) {
        // 更新页面内容
      }
    },
    showPicker() {
      this.$refs.cityPicker.show();
    },
    handleSearch() {
      uni.navigateTo({
        url: "/pages/navigation/search/searchPage",
      });
    },
    // async getLocation() {
    //   const permision = await import("@/js_sdk/wa-permission/permission.js");
    //   // #ifdef APP-PLUS
    //   if (plus.os.name == "iOS") {
    //     if (permision.judgeIosPermissionLocation()) {
    //       this.getLocationInfo();
    //     } else {
    //       this.refuseLocation();
    //     }
    //   } else {
    //     const result = await permision.requestAndroidPermission(
    //       "android.permission.ACCESS_FINE_LOCATION"
    //     );
    //     if (result == 1) {
    //       this.getLocationInfo();
    //     } else {
    //       this.refuseLocation();
    //     }
    //   }
    //   // #endif
    //   // #ifndef APP-PLUS
    //   this.getLocationInfo();
    //   // #endif
    // },
    // getLocationInfo() {
    //   uni.getLocation({
    //     type: "wgs84",
    //     success: async (resss) => {
    //       this.location = resss;
    //       console.log("当前位置：", resss);
    //       const jwobj = {
    //         latitude: resss.latitude,
    //         longitude: resss.longitude,
    //       };
    //       const { data } = await postAdvertisementjw(jwobj);
    //       if (data.success) {
    //         uni.request({
    //           url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${resss.latitude},${resss.longitude}&key=${config.aMapKey}`,
    //           success: (res) => {
    //             console.log("腾讯地图API接口返回信息", res);
    //             this.cityOrCounty = res.data.result.address_component.district || res.data.result.address_component.city;
    //             uni.setStorageSync('cityOrCounty', this.cityOrCounty);
    //             // 存储经纬度
    //             uni.setStorageSync('longitude', resss.longitude);
    //             uni.setStorageSync('latitude', resss.latitude);
    //             // 更新本地存储的经纬度
    //             this.storedLat = resss.latitude;
    //             this.storedLon = resss.longitude;
    //           },
    //           fail: (error) => {
    //             uni.showToast({
    //               title: "获取位置信息失败222腾讯",
    //               icon: "none"
    //             });
    //           }
    //         });
    //       }
    //     },
    //     fail: (err) => {
    //       console.error("获取位置失败：", err);
    //     },
    //   });
    // },
    // refuseLocation() {
    //   uni.showModal({
    //     title: "温馨提示",
    //     content: "您已拒绝定位,请开启",
    //     confirmText: "去设置",
    //     success(res) {
    //       if (res.confirm) {
    //         //打开授权设置
    //         // #ifndef MP-WEIXIN
    //         uni.getSystemInfo({
    //           success(res) {
    //             if (res.platform == "ios") {
    //               //IOS
    //               plus.runtime.openURL("app-settings://");
    //             } else if (res.platform == "android") {
    //               //安卓
    //               let main = plus.android.runtimeMainActivity();
    //               let Intent = plus.android.importClass(
    //                 "android.content.Intent"
    //               );
    //               let mIntent = new Intent("android.settings.ACTION_SETTINGS");
    //               main.startActivity(mIntent);
    //             }
    //           },
    //         });
    //         // #endif
    //       }
    //     },
    //   });
    // },
  },
};
</script>
<style lang="scss" scoped>
@import "./tpl.scss";
.search {
  width: 68%;
  height: 32px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ededed;
}
.layout {
  // background: #fff;
  display: flex;
  justify-content: space-between;
  background: transparent;
}
.addres {
  // width: 15%;
  width: 42px;
  height: 32px;
  padding: 0px 0px 0px 10px;
  // white-space: nowrap;
  // overflow: hidden;
  // text-overflow: ellipsis;
  line-height: 32px;
}
.layout {
  // background: #fff;
  background: transparent;
  display: flex;
  justify-content: space-between;
}
.shop {
  width: 10%;
  height: 32px;
  display: flex;
  background: url("@/static/shop.png") no-repeat;
  background-size: 100% 100%;
}
</style>
