"use strict";
const common_vendor = require("../../common/vendor.js");
const common_assets = require("../../common/assets.js");
const util_index = require("../../util/index.js");
const config_url = require("../../config/url.js");
const config_user = require("../../config/user.js");
const utils_mapUtils = require("../../utils/mapUtils.js");
if (!Array) {
  const _easycom_uv_notice_bar2 = common_vendor.resolveComponent("uv-notice-bar");
  const _easycom_uv_icon2 = common_vendor.resolveComponent("uv-icon");
  (_easycom_uv_notice_bar2 + _easycom_uv_icon2)();
}
const _easycom_uv_notice_bar = () => "../../node-modules/@climblee/uv-ui/components/uv-notice-bar/uv-notice-bar.js";
const _easycom_uv_icon = () => "../../node-modules/@climblee/uv-ui/components/uv-icon/uv-icon.js";
if (!Math) {
  (_easycom_uv_notice_bar + MapComponent + _easycom_uv_icon)();
}
const MapComponent = () => "../../components/MapComponent.js";
const _sfc_main = {
  __name: "index",
  setup(__props) {
    const searchKeyword = common_vendor.ref("");
    const userLocation = common_vendor.ref(null);
    const positionList = common_vendor.ref([]);
    const filteredPositions = common_vendor.ref([]);
    const isExpanded = common_vendor.ref(false);
    const isLoading = common_vendor.ref(false);
    const showPhoneAuthPopup = common_vendor.ref(false);
    const isLocationInitialized = common_vendor.ref(false);
    const showLocationPopup = common_vendor.ref(false);
    const guideSteps = common_vendor.ref([
      {
        title: "扫码使用",
        desc: "找到附近设备，扫描设备上的二维码即可开始租借"
      },
      {
        title: "免押金支付",
        desc: "无需支付押金，使用支付分免押即可完成租借"
      },
      {
        title: "开始使用",
        desc: "设备自动解锁，风扇弹出后取出即可开始使用"
      },
      {
        title: "归还设备",
        desc: "使用完毕后，按照设备规格要求将风扇还入即可结束订单"
      }
    ]);
    const noticeText = common_vendor.ref("消费规则：每小时5元，不足1小时按1小时计费，最高24小时封顶，请爱护设备，使用后请及时归还");
    const formatDistance = (distanceInMeters) => {
      if (distanceInMeters < 1e3) {
        return `${Math.round(distanceInMeters)}m`;
      } else {
        return `${(distanceInMeters / 1e3).toFixed(1)}km`;
      }
    };
    const mapRef = common_vendor.ref(null);
    common_vendor.computed(() => {
      if (userLocation.value && userLocation.value.address) {
        return `${userLocation.value.district || "当前位置"} - 搜索附近场地`;
      }
      return "搜索附近场地";
    });
    common_vendor.onMounted(() => {
      init();
    });
    common_vendor.onUnmounted(() => {
    });
    const init = async () => {
      isLoading.value = true;
      try {
        if (true) {
          utils_mapUtils.testDistanceCalculation();
        }
        await getUserLocationAndAddress();
        await loadPositions();
      } catch (error) {
        common_vendor.index.__f__("error", "at pages/index/index.vue:241", "初始化失败:", error);
        await loadPositions();
      } finally {
        isLoading.value = false;
      }
    };
    const getUserLocationAndAddress = async () => {
      try {
        const location = await utils_mapUtils.getUserLocation();
        userLocation.value = {
          longitude: location.longitude,
          latitude: location.latitude
        };
        try {
          common_vendor.index.setStorageSync("userLocation", {
            longitude: location.longitude,
            latitude: location.latitude
          });
        } catch (e) {
          common_vendor.index.__f__("warn", "at pages/index/index.vue:267", "缓存基础定位信息失败:", e);
        }
        if (!isLocationInitialized.value) {
          isLocationInitialized.value = true;
        }
        try {
          const addressResult = await utils_mapUtils.getRegeo(location.longitude, location.latitude);
          if (addressResult.success) {
            const addressInfo = addressResult.data;
            userLocation.value.address = addressInfo.formatted_address;
            userLocation.value.city = addressInfo.addressComponent.city;
            userLocation.value.district = addressInfo.addressComponent.district;
            try {
              common_vendor.index.setStorageSync("userLocation", {
                longitude: userLocation.value.longitude,
                latitude: userLocation.value.latitude,
                address: userLocation.value.address,
                city: userLocation.value.city,
                district: userLocation.value.district
              });
            } catch (e) {
              common_vendor.index.__f__("warn", "at pages/index/index.vue:294", "缓存带地址的定位信息失败:", e);
            }
          }
        } catch (error) {
        }
        setTimeout(async () => {
          await loadPositions();
          common_vendor.index.hideLoading();
        }, 800);
      } catch (error) {
        common_vendor.index.__f__("error", "at pages/index/index.vue:309", "获取位置失败:", error);
        common_vendor.index.showToast({
          title: "获取位置失败，显示默认地图",
          icon: "none"
        });
      }
    };
    const loadPositions = async () => {
      try {
        if (!common_vendor.index.getStorageSync("token")) {
          await util_index.wxLogin();
        }
        const res = await common_vendor.index.request({
          url: `${config_url.URL}/device/position/app/list`,
          method: "GET",
          header: {
            "Authorization": "Bearer " + common_vendor.index.getStorageSync("token"),
            "Clientid": common_vendor.index.getStorageSync("client_id")
          },
          data: {
            latitude: userLocation.value.latitude,
            longitude: userLocation.value.longitude
          }
        });
        if (res.statusCode === 200 && res.data.code === 200) {
          positionList.value = res.data.rows || [];
          calculateDistances();
          filteredPositions.value = [...positionList.value];
        } else {
          common_vendor.index.__f__("error", "at pages/index/index.vue:341", "获取场地列表失败:", res.data.msg);
        }
      } catch (error) {
        common_vendor.index.__f__("error", "at pages/index/index.vue:344", "获取场地列表异常:", error);
      }
    };
    const calculateDistances = async (centerPoint = null) => {
      var _a;
      const center = centerPoint || userLocation.value || ((_a = mapRef.value) == null ? void 0 : _a.mapCenter);
      if (!center || typeof center.longitude === "undefined" || typeof center.latitude === "undefined") {
        return;
      }
      positionList.value.forEach((item) => {
        if (item.longitude && item.latitude) {
          try {
            const distanceInMeters = utils_mapUtils.calculateDistanceSync(
              center.latitude,
              center.longitude,
              parseFloat(item.latitude),
              parseFloat(item.longitude)
            );
            item.distance = formatDistance(distanceInMeters);
            item.distanceInMeters = distanceInMeters;
          } catch (error) {
            common_vendor.index.__f__("error", "at pages/index/index.vue:372", "计算距离异常:", error, item);
            item.distance = "999.0km";
            item.distanceInMeters = 999e3;
          }
        }
      });
      positionList.value.sort((a, b) => {
        return (a.distanceInMeters || 999e3) - (b.distanceInMeters || 999e3);
      });
    };
    const loadPositionsByCenter = async (center) => {
      try {
        if (!common_vendor.index.getStorageSync("token")) {
          await util_index.wxLogin();
        }
        const res = await common_vendor.index.request({
          url: `${config_url.URL}/device/position/list`,
          method: "GET",
          header: {
            "Authorization": "Bearer " + common_vendor.index.getStorageSync("token"),
            "Clientid": common_vendor.index.getStorageSync("client_id")
          }
        });
        if (res.statusCode === 200 && res.data.code === 200) {
          positionList.value = res.data.rows || [];
          calculateDistances(center);
          const maxDistanceInMeters = 1e4;
          filteredPositions.value = positionList.value.filter((item) => {
            return !item.distanceInMeters || item.distanceInMeters <= maxDistanceInMeters;
          });
        } else {
          common_vendor.index.__f__("error", "at pages/index/index.vue:413", "根据地图中心加载场地失败:", res.data.msg);
          positionList.value = [];
          filteredPositions.value = [];
        }
      } catch (error) {
        common_vendor.index.__f__("error", "at pages/index/index.vue:418", "根据地图中心加载场地异常:", error);
      }
    };
    const handleRelocate = async () => {
      common_vendor.index.showLoading({
        title: "定位中..."
      });
      common_vendor.index.reLaunch({
        url: "/pages/index/index"
      });
    };
    const onMapCenterChange = (center) => {
      loadPositionsByCenter(center);
    };
    const selectPosition = (position) => {
      common_vendor.index.showActionSheet({
        itemList: ["扫码使用", "导航前往"],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              handleScan();
              break;
            case 1:
              navigateToPosition(position);
              break;
          }
        }
      });
    };
    const selectPositionFromPopup = (position) => {
      hideLocationList();
      setTimeout(() => {
        selectPosition(position);
      }, 200);
    };
    const navigateToPosition = (position) => {
      const latitude = parseFloat(position.latitude);
      const longitude = parseFloat(position.longitude);
      common_vendor.index.openLocation({
        latitude,
        longitude,
        name: position.name,
        address: position.location
      });
    };
    const handleScan = async () => {
      try {
        const scanResult = await new Promise((resolve, reject) => {
          common_vendor.index.scanCode({
            success: resolve,
            fail: reject
          });
        });
        let deviceNo = util_index.getQueryString(scanResult.path, "deviceNo");
        if (!deviceNo) {
          common_vendor.index.showToast({
            title: "无效的设备二维码",
            icon: "none"
          });
          return;
        }
        if (!common_vendor.index.getStorageSync("token")) {
          await util_index.wxLogin();
        }
        const inUseRes = await common_vendor.index.request({
          url: `${config_url.URL}/app/order/inUse`,
          method: "GET",
          header: {
            "Authorization": "Bearer " + common_vendor.index.getStorageSync("token"),
            "Clientid": common_vendor.index.getStorageSync("client_id")
          }
        });
        if (inUseRes.statusCode == 200 && inUseRes.data.code == 200 && inUseRes.data.data) {
          const inUseOrder = inUseRes.data.data;
          common_vendor.index.reLaunch({
            url: `/pages/return/index?orderId=${inUseOrder.orderId}&deviceId=${deviceNo || inUseOrder.deviceNo}`
          });
          return;
        }
        const orderRes = await common_vendor.index.request({
          url: `${config_url.URL}/app/order/unpaid`,
          method: "GET",
          header: {
            "Authorization": "Bearer " + common_vendor.index.getStorageSync("token"),
            "Clientid": common_vendor.index.getStorageSync("client_id")
          }
        });
        if (orderRes.statusCode == 200 && orderRes.data.code == 200 && orderRes.data.data) {
          const unpaidOrder = orderRes.data.data;
          common_vendor.index.navigateTo({
            url: `/pages/order/payment?orderId=${unpaidOrder.orderId}`
          });
        } else {
          try {
            const deviceInfoRes = await config_user.getDeviceInfo(deviceNo);
            if (deviceInfoRes.code == 200 && deviceInfoRes.data && deviceInfoRes.data.device) {
              const deviceInfo = deviceInfoRes.data.device;
              if (deviceInfo.feeConfig) {
                try {
                  const feeConfig = JSON.parse(deviceInfo.feeConfig);
                  common_vendor.index.navigateTo({
                    url: `/pages/device/detail?deviceNo=${deviceNo}&feeConfig=${encodeURIComponent(deviceInfo.feeConfig)}`
                  });
                } catch (e) {
                  common_vendor.index.navigateTo({
                    url: `/pages/device/detail?deviceNo=${deviceNo}`
                  });
                }
              } else {
                common_vendor.index.navigateTo({
                  url: `/pages/device/detail?deviceNo=${deviceNo}`
                });
              }
            } else {
              common_vendor.index.showToast({
                title: "获取设备信息失败",
                icon: "none"
              });
              common_vendor.index.navigateTo({
                url: `/pages/device/detail?deviceNo=${deviceNo}`
              });
            }
          } catch (error) {
            common_vendor.index.__f__("error", "at pages/index/index.vue:581", "获取设备信息异常:", error);
            common_vendor.index.navigateTo({
              url: `/pages/device/detail?deviceNo=${deviceNo}`
            });
          }
        }
      } catch (error) {
        common_vendor.index.__f__("error", "at pages/index/index.vue:588", "扫码处理失败:", error);
        common_vendor.index.showToast({
          title: "扫码失败",
          icon: "none"
        });
      }
    };
    const showLocationList = () => {
      showLocationPopup.value = true;
    };
    const hideLocationList = () => {
      showLocationPopup.value = false;
    };
    const onGetPhoneNumber = (e) => {
      if (e.detail.errMsg === "getPhoneNumber:ok") {
        showPhoneAuthPopup.value = false;
      }
    };
    return (_ctx, _cache) => {
      return common_vendor.e({
        a: common_assets._imports_0$1,
        b: common_vendor.p({
          text: noticeText.value,
          mode: "link",
          speed: 50,
          ["show-icon"]: true,
          color: "#2196F3",
          ["bg-color"]: "#E3F2FD",
          icon: "volume"
        }),
        c: !isLoading.value && userLocation.value
      }, !isLoading.value && userLocation.value ? {
        d: common_vendor.sr(mapRef, "1cf27b2a-1", {
          "k": "mapRef"
        }),
        e: common_vendor.o(handleRelocate),
        f: common_vendor.o(handleScan),
        g: common_vendor.o(showLocationList),
        h: common_vendor.o(selectPosition),
        i: common_vendor.o(onMapCenterChange),
        j: common_vendor.p({
          userLocation: userLocation.value,
          positionList: positionList.value,
          filteredPositions: filteredPositions.value,
          searchKeyword: searchKeyword.value
        })
      } : {}, {
        k: common_vendor.f(guideSteps.value, (step, index, i0) => {
          return {
            a: common_vendor.t(index + 1),
            b: common_vendor.t(step.title),
            c: common_vendor.t(step.desc),
            d: index
          };
        }),
        l: isLoading.value || !userLocation.value
      }, isLoading.value || !userLocation.value ? {} : {}, {
        m: showLocationPopup.value
      }, showLocationPopup.value ? common_vendor.e({
        n: common_vendor.o(hideLocationList),
        o: common_vendor.t(filteredPositions.value.length),
        p: common_vendor.p({
          name: "close"
        }),
        q: common_vendor.o(hideLocationList),
        r: common_vendor.f(filteredPositions.value, (item, index, i0) => {
          return common_vendor.e({
            a: common_vendor.t(item.name),
            b: common_vendor.t(item.status === "online" ? "可租借/归还" : "不可租借/归还"),
            c: common_vendor.n(item.status),
            d: item.workTime && item.workTime !== "0"
          }, item.workTime && item.workTime !== "0" ? {
            e: common_vendor.t(item.workTime)
          } : {}, {
            f: item.distance
          }, item.distance ? {
            g: common_vendor.t(item.distance)
          } : {}, {
            h: common_vendor.t(item.status === "online" ? "营业中" : "暂停服务"),
            i: common_vendor.n(item.status),
            j: common_vendor.o(($event) => navigateToPosition(item), item.positionId),
            k: item.positionId,
            l: common_vendor.o(($event) => selectPositionFromPopup(item), item.positionId)
          });
        }),
        s: filteredPositions.value.length === 0 && !isLoading.value
      }, filteredPositions.value.length === 0 && !isLoading.value ? {
        t: common_assets._imports_0
      } : {}, {
        v: isExpanded.value ? 1 : ""
      }) : {}, {
        w: isLoading.value
      }, isLoading.value ? {} : {}, {
        x: showPhoneAuthPopup.value
      }, showPhoneAuthPopup.value ? {
        y: common_vendor.o(($event) => showPhoneAuthPopup.value = false),
        z: common_vendor.o(onGetPhoneNumber),
        A: common_vendor.o(($event) => showPhoneAuthPopup.value = false)
      } : {});
    };
  }
};
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["__scopeId", "data-v-1cf27b2a"]]);
wx.createPage(MiniProgramPage);
//# sourceMappingURL=../../../.sourcemap/mp-weixin/pages/index/index.js.map
