"use strict";
const common_vendor = require("../common/vendor.js");
const utils_wz_option = require("./wz_option.js");
const utils_wz_wifi = require("./wz_wifi.js");
const utils_wz_req_obj = require("./wz_req_obj.js");
let ak = "";
let wz_option = {};
let isAndroid = false;
let timerLocation = null;
let isToUni = false;
let isNeedScan = false;
let uniLocation = {
  timestamp: 0,
  longitude: 0,
  latitude: 0,
  speed: 0,
  accuracy: 0,
  source: "",
  address: ""
};
let wzLocation = {
  source: "",
  timestamp: 0,
  longitude: 0,
  latitude: 0,
  accuracy: 0,
  spatialReference: "",
  address: "",
  place: {}
};
let mGnss = {
  timestamp: 0,
  point: {
    longitude: 0,
    latitude: 0
  },
  accuracy: 0
};
let scanIntervalId;
let isScanning = true;
function initOption(accessKey, deViceId, isLocateOnce, interval) {
  ak = accessKey;
  wz_option = utils_wz_option.defaultOption;
  wz_option.deviceId = deViceId;
  wz_option.isLocateOnce = isLocateOnce;
  if (interval > wz_option.interval) {
    wz_option.interval = interval;
  }
}
function getLocation(success, error2) {
  try {
    const sysInfo = common_vendor.index.getSystemInfoSync();
    const platOS = sysInfo.osName;
    isAndroid = platOS === "android";
    const osVersion = sysInfo.osVersion;
    const deviceType = sysInfo.deviceType;
    const uniPlatForm = sysInfo.uniPlatform;
    if (uniPlatForm === "app" || uniPlatForm === "mp-weixin") {
      if (isEnableLocation(error2)) {
        const requestUrl = utils_wz_option.default_host + utils_wz_option.default_api + "?access_key=" + ak;
        common_vendor.index.__f__("log", "at utils/wz_location.js:71", "getLocation：", isAndroid, requestUrl);
        if (isAndroid) {
          utils_wz_req_obj.locationTrack.asset.id = wz_option.deviceId;
          utils_wz_wifi.firstStartWifi().then(
            (res) => {
              isNeedScan = true;
              common_vendor.index.__f__("log", "at utils/wz_location.js:77", "getLocation：", "准备请求--->");
              getLocationFromServer(success, error2);
            },
            (erro) => {
              getLocationFromUniapp(success, error2);
            }
          );
        } else {
          getLocationFromUniapp(success, error2);
        }
      }
    } else {
      common_vendor.index.__f__("log", "at utils/wz_location.js:89", "uniPlatForm：", uniPlatForm);
      isNeedScan = false;
      getLocationFromUniapp(success, error2);
    }
  } catch (erroInfo) {
    error2({
      code: 2001,
      msg: erroInfo
    });
  }
}
function isEnableLocation(error2) {
  const systemSetting = common_vendor.index.getSystemSetting();
  common_vendor.index.__f__("log", "at utils/wz_location.js:103", "systemSetting：", systemSetting);
  const lEnable = systemSetting && typeof systemSetting.locationEnabled !== "undefined" ? systemSetting.locationEnabled : true;
  systemSetting && typeof systemSetting.wifiEnabled !== "undefined" ? systemSetting.wifiEnabled : false;
  if (!lEnable) {
    error2({
      code: 1001,
      msg: "定位权限未开"
    });
    return false;
  }
  if (!ak) {
    error2({
      code: 1003,
      msg: "您尚未配置 appKey"
    });
    return false;
  }
  if (!wz_option) {
    error2({
      code: 1004,
      msg: "option 参数未配置"
    });
    return false;
  }
  if (!wz_option.deviceId) {
    error2({
      code: 1005,
      msg: "option 参数非法, 需提供设备 ID "
    });
    return false;
  }
  return true;
}
function poiSearch(searchkey, city, page_index = 1, page_size = 20) {
  return new Promise((resolve, reject) => {
    if (!ak) {
      reject({
        code: 1003,
        msg: "您尚未配置 appKey"
      });
      return;
    }
    const requestUrl = utils_wz_option.default_host + utils_wz_option.poi_search_api + "?access_key=" + ak + "&name=" + searchkey + "&city=" + city + "&page_index=" + page_index + "&page_size=" + page_size;
    getRequest(requestUrl, resolve, reject);
  });
}
function poiNearbySearch(keyword, category, location, radius = 5e3, orderby = "distance_score", page_index = 1, page_size = 20) {
  return new Promise((resolve, reject) => {
    if (!ak) {
      reject({
        code: 1003,
        msg: "您尚未配置 appKey"
      });
      return;
    }
    if (!location) {
      return reject({
        code: 1008,
        msg: "请先获取定位"
      });
    }
    if (!keyword) {
      return reject({
        code: 1009,
        msg: "请填写搜索关键词"
      });
    }
    const requestUrl = utils_wz_option.default_host + utils_wz_option.nearby_search_api + "?access_key=" + ak + "&keywords=" + keyword + "&category=" + category + "&location=" + location + "&radius=" + radius + "&orderby=" + orderby + "&page_index=" + page_index + "&page_size=" + page_size;
    getRequest(requestUrl, resolve, reject);
  });
}
function getGeoCode(address, city) {
  return new Promise((resolve, reject) => {
    if (!ak) {
      reject({
        code: 1003,
        msg: "您尚未配置 appKey"
      });
      return;
    }
    const requestUrl = utils_wz_option.default_host + utils_wz_option.geocode_api + "?access_key=" + ak + "&address=" + address + "&city=" + city;
    getRequest(requestUrl, resolve, reject);
  });
}
function getReverseCode(longitude, latitude, spatialReference) {
  return new Promise((resolve, reject) => {
    if (!ak) {
      reject({
        code: 1003,
        msg: "您尚未配置 appKey"
      });
      return;
    }
    const requestUrl = utils_wz_option.default_host + utils_wz_option.default_api + "?access_key=" + ak;
    uniLocation = {
      latitude,
      longitude,
      source: "",
      speed: 0,
      accuracy: 30,
      altitude: 0,
      spatialReference,
      timestamp: (/* @__PURE__ */ new Date()).getTime()
    };
    formatUniLocation();
    requestReverseBody(requestUrl, utils_wz_req_obj.lngLatTrack, resolve, reject);
  });
}
function getLocationFromServer(success, error2) {
  if (wz_option.isLocateOnce) {
    startInterval();
    setTimeout(function() {
      return stopInterval(success, error2);
    }, 5e3);
    reqByWifi(success, error2);
  } else {
    startSysGpsLocation();
    reqByWifi(success, error2);
    timerLocation = setInterval(() => {
      reqByWifi(success, error2);
    }, wz_option.interval);
  }
}
function getLocationFromUniapp(success, error2) {
  const requestUrl = utils_wz_option.default_host + utils_wz_option.default_api + "?access_key=" + ak;
  isToUni = true;
  if (wz_option.isLocateOnce) {
    common_vendor.index.getLocation({
      type: "wgs84",
      isHighAccuracy: true,
      success: (res) => {
        common_vendor.index.__f__("log", "at utils/wz_location.js:265", "当前位置的经度：" + res.longitude);
        common_vendor.index.__f__("log", "at utils/wz_location.js:266", "当前位置的纬度：" + res.latitude);
        uniLocation = {
          latitude: res.latitude,
          longitude: res.longitude,
          source: "",
          speed: res.speed,
          accuracy: res.accuracy,
          altitude: res.altitude,
          spatialReference: "wgs84",
          timestamp: (/* @__PURE__ */ new Date()).getTime()
        };
        formatUniLocation();
        requestBody(requestUrl, utils_wz_req_obj.lngLatTrack, success, error2);
      },
      fail: (err) => {
        common_vendor.index.__f__("log", "at utils/wz_location.js:282", "err：" + JSON.stringify(err));
        getIPLocation(success, error2);
      },
      complete: (res) => {
      }
    });
  } else {
    common_vendor.index.startLocationUpdate({
      type: "wgs84",
      success: (res) => {
        common_vendor.index.onLocationChange((res2) => {
          const { latitude, longitude, speed, accuracy, altitude } = res2;
          if (!latitude || !longitude || latitude === 0 || longitude === 0) {
            error2({
              code: 10015,
              msg: "【定位异常】经纬度为空或无效值"
            });
            return;
          }
          uniLocation = {
            latitude: res2.latitude,
            longitude: res2.longitude,
            source: "",
            speed: res2.speed,
            accuracy: res2.accuracy,
            altitude: res2.altitude,
            spatialReference: "wgs84",
            timestamp: (/* @__PURE__ */ new Date()).getTime()
          };
          formatUniLocation();
          requestBody(requestUrl, utils_wz_req_obj.lngLatTrack, success, error2);
        });
      },
      fail: (err) => {
        error2({
          code: 10011,
          msg: err.errMsg
        });
      },
      complete: (msg) => {
      }
    });
  }
}
function startSysGpsLocation() {
  isToUni = true;
  common_vendor.index.startLocationUpdate({
    type: "wgs84",
    success: (res) => {
      common_vendor.index.onLocationChange((res2) => {
        mGnss = {
          timestamp: (/* @__PURE__ */ new Date()).getTime(),
          point: {
            longitude: res2.longitude,
            latitude: res2.latitude
          },
          accuracy: res2.accuracy
        };
      });
    },
    fail: (err) => {
      error({
        code: 10011,
        msg: err.errMsg
      });
    },
    complete: (msg) => {
    }
  });
}
function getIPLocation(resolve, reject) {
  const ipUrl = utils_wz_option.IPBaseUrl + "?access_key=" + ak;
  common_vendor.index.__f__("log", "at utils/wz_location.js:366", "getIPLocation");
  common_vendor.index.request({
    url: ipUrl,
    method: "GET",
    success: (res) => {
      common_vendor.index.__f__("log", "at utils/wz_location.js:371", "request success ： ", res);
      const resData = res.data || {};
      if (res.statusCode === 200 && resData && resData.location) {
        const location = resData.location;
        if (location.address && location.address.name) {
          wzLocation = formatIPLocation(resData);
          resolve(wzLocation);
          return;
        }
      }
      const errMsg = res.statusCode === 200 ? "定位服务返回成功，但地址数据不完整" : `定位服务返回失败，状态码：${res.statusCode}`;
      const errObj = { code: res.statusCode || 10011, msg: errMsg };
      reject(errObj);
    },
    fail: (error2) => {
      common_vendor.index.__f__("error", "at utils/wz_location.js:391", "IP定位请求接口失败：", error2);
      const errObj = {
        code: 10011,
        msg: "定位返回失败：" + (error2.errMsg || JSON.stringify(error2))
      };
      reject(errObj);
    },
    // 兜底：无论成功失败，防止请求卡死（可选但建议加）
    complete: () => {
      common_vendor.index.__f__("log", "at utils/wz_location.js:400", "定位请求完成");
    }
  });
}
function reqByWifi(success, error2) {
  const requestUrl = utils_wz_option.default_host + utils_wz_option.default_api + "?access_key=" + ak;
  common_vendor.index.__f__("log", "at utils/wz_location.js:409", "开始扫描 WIFI ： ");
  isScanning = true;
  utils_wz_wifi.scanWifi().then(
    (res) => {
      common_vendor.index.__f__("log", "at utils/wz_location.js:413", "扫描 WIFI成功回调 ： ");
      if (scanIntervalId) {
        clearInterval(scanIntervalId);
      }
      isScanning = false;
      const wifiList = utils_wz_wifi.scanWifiList;
      if (wifiList.length === 0 && wz_option.isLocateOnce) {
        getLocationFromUniapp(success, error2);
      } else {
        utils_wz_req_obj.locationTrack.location.wifis = wifiList;
        utils_wz_req_obj.locationTrack.location.gnss = mGnss;
        requestBody(requestUrl, utils_wz_req_obj.locationTrack, success, error2);
      }
    },
    (fail) => {
      isScanning = false;
      utils_wz_wifi.stopScanWifi();
      getLocationFromUniapp(success, error2);
    }
  );
}
function startInterval() {
  common_vendor.index.__f__("log", "at utils/wz_location.js:440", "startInterval ： ");
  scanIntervalId = setInterval(() => {
    common_vendor.index.__f__("log", "at utils/wz_location.js:442", "This runs every 1 second");
  }, 1e3);
}
function stopInterval(success, error2) {
  clearInterval(scanIntervalId);
  const wifiList = utils_wz_wifi.scanWifiList;
  common_vendor.index.__f__("log", "at utils/wz_location.js:452", "stopInterval isScanning ", isScanning);
  if (isScanning) {
    const requestUrl = utils_wz_option.default_host + utils_wz_option.default_api + "?access_key=" + ak;
    if (wifiList && wifiList.length >= 0) {
      utils_wz_req_obj.locationTrack.location.wifis = wifiList;
      utils_wz_req_obj.locationTrack.location.gnss = mGnss;
      requestBody(requestUrl, utils_wz_req_obj.locationTrack, success, error2);
    } else {
      error2({
        code: 10010,
        msg: "定位服务返回失败"
      });
    }
    utils_wz_wifi.stopScanWifi();
  }
}
function requestBody(reqUrl, data, callBack, fail) {
  common_vendor.index.__f__("log", "at utils/wz_location.js:480", "requestBody ： ", data);
  common_vendor.index.request({
    url: reqUrl,
    method: "POST",
    data,
    success: (res) => {
      common_vendor.index.__f__("log", "at utils/wz_location.js:486", "request success ： " + JSON.stringify(res));
      const resData = res.data;
      if (res.statusCode == 200 && resData != null && resData.location != null && resData.location.address != null) {
        wzLocation = formatLocation(resData);
        if (wz_option.isLocateOnce) {
          stopLocation();
        }
        callBack(wzLocation);
      } else {
        fail({
          code: res.statusCode,
          msg: "定位服务返回失败"
        });
      }
    },
    fail: (error2) => {
      common_vendor.index.__f__("log", "at utils/wz_location.js:507", error2);
      fail({
        code: 10010,
        msg: "定位返回失败：" + error2
      });
    }
  });
}
function requestReverseBody(reqUrl, data, callBack, fail) {
  common_vendor.index.__f__("log", "at utils/wz_location.js:525", "requestReverseBody ： ", data);
  common_vendor.index.request({
    url: reqUrl,
    method: "POST",
    data,
    success: (res) => {
      common_vendor.index.__f__("log", "at utils/wz_location.js:531", "request success ： " + JSON.stringify(res));
      const resData = res.data;
      if (res.statusCode == 200 && resData != null && resData.location != null && resData.location.address != null) {
        wzLocation = formatLocation(resData);
        callBack(wzLocation);
      } else {
        fail({
          code: res.statusCode,
          msg: "定位服务返回失败"
        });
      }
    },
    fail: (error2) => {
      common_vendor.index.__f__("log", "at utils/wz_location.js:549", error2);
      fail({
        code: 10010,
        msg: "定位返回失败：" + error2
      });
    }
  });
}
function getRequest(reqUrl, callBack, fail) {
  common_vendor.index.__f__("log", "at utils/wz_location.js:566", "request:", reqUrl);
  common_vendor.index.request({
    url: reqUrl,
    method: "GET",
    success: (res) => {
      const resData = res.data;
      if (res.statusCode == 200 && resData != null) {
        callBack(resData);
        return;
      }
      fail({ code: res.statusCode, msg: "请求异常" });
    },
    fail: (error2) => {
      common_vendor.index.__f__("log", "at utils/wz_location.js:579", error2);
      fail({
        code: 10010,
        msg: "定位返回失败：" + error2
      });
    }
  });
}
function stopLocation() {
  common_vendor.index.__f__("log", "at utils/wz_location.js:589", "stopLocation");
  if (isToUni && !wz_option.isLocateOnce) {
    isToUni = false;
    common_vendor.index.stopLocationUpdate();
    common_vendor.index.offLocationChange(function(res) {
    });
  }
  if (utils_wz_wifi.wifiManager != null && isNeedScan) {
    utils_wz_wifi.stoWifi();
  }
  if (timerLocation) {
    clearInterval(timerLocation);
    timerLocation = null;
  }
}
function setAk(accessKey) {
  ak = accessKey;
}
const formatLocation = (res) => {
  const {
    address,
    place,
    position: {
      source,
      accuracy,
      spatialReference,
      timestamp,
      point: {
        longitude,
        latitude
      }
    }
  } = res.location;
  return {
    source,
    timestamp,
    longitude,
    latitude,
    accuracy,
    spatialReference,
    address,
    place
  };
};
const formatIPLocation = (res) => {
  const {
    location: {
      address,
      place = "",
      // 原数据无此字段，兜底空字符串
      position: {
        source = "",
        // 原数据无此字段，兜底空字符串
        accuracy = 0,
        // 原数据无此字段，兜底数字0
        spatialReference = "",
        // 原数据无此字段，兜底空字符串
        timestamp = (/* @__PURE__ */ new Date()).getTime(),
        // 原数据无此字段，兜底空字符串
        point: {
          longitude,
          latitude
        }
      }
    }
  } = res;
  return {
    source,
    timestamp,
    longitude,
    latitude,
    accuracy,
    spatialReference,
    address,
    place
  };
};
function formatUniLocation() {
  const {
    source,
    timestamp,
    longitude,
    latitude,
    accuracy,
    spatialReference
  } = uniLocation;
  utils_wz_req_obj.lngLatTrack.location.position = {
    point: {
      longitude,
      latitude
    },
    source,
    timestamp,
    accuracy,
    spatialReference
  };
}
exports.getGeoCode = getGeoCode;
exports.getLocation = getLocation;
exports.getReverseCode = getReverseCode;
exports.initOption = initOption;
exports.poiNearbySearch = poiNearbySearch;
exports.poiSearch = poiSearch;
exports.setAk = setAk;
exports.stopLocation = stopLocation;
//# sourceMappingURL=../../.sourcemap/mp-weixin/utils/wz_location.js.map
