import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import { _ as __awaiter } from '../tslib.es6-848120af.js';
import { LocationDefaultOptions } from './location-default-options.mjs';
import locationHandle from './location-handle-web.mjs';
import { LocationFlag } from './location-interface.mjs';
import LocationStorage from './location-storage.mjs';
import TencentMapApiLocation from './platform/tencent-map-api-location.mjs';
import '../env/env.mjs';
import './platform/h5-geolocation-location.mjs';
import './platform/msdk-location.mjs';
import '../msdk/msdk.mjs';
import '@babel/runtime/helpers/typeof';
import '../loader/little-loader.mjs';
import './platform/slug-sdk-location.mjs';
import './platform/tencent-map-location.mjs';
import '../city/city.mjs';
import '../city/data.mjs';
import '../loader/loader-unity.mjs';
import '../loader/loader.mjs';
import './platform/tip-sdk-location.mjs';
import './platform/wechat-sdk-location.mjs';
import '../storage/persist-data.mjs';
import 'axios';
import '../lodash-mini/get.mjs';
import '@babel/runtime/helpers/toConsumableArray';
import '@babel/runtime/helpers/toArray';

// import Dialog from '../widget/vant/dialog';
var LocationWeb = /*#__PURE__*/function () {
  /**
   * @classdesc 定位工具，支持腾讯地图定位、微信的sdk定位、游戏人生sdk定位
   * @constructor
   */
  function LocationWeb() {
    _classCallCheck(this, LocationWeb);
    this.locationHandle = null;
  }
  return _createClass(LocationWeb, null, [{
    key: "getInstance",
    value: function getInstance() {
      return this.instance;
    }
  }, {
    key: "getLocationPreCheck",
    value: function getLocationPreCheck(options) {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        return _regeneratorRuntime.wrap(function (_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              return _context.abrupt("return", new Promise(function (resolve) {
                var _a;
                var alertTips = window.sessionStorage.getItem('tip_is_show_location_usage_alert') || '0';
                if (options.showTipLocationUsageAlert && alertTips !== '1') {
                  window.sessionStorage.setItem('tip_is_show_location_usage_alert', '1');
                  if (!options.Dialog) {
                    resolve(false);
                  }
                  (_a = options.Dialog) === null || _a === void 0 ? void 0 : _a.confirm({
                    title: '地理位置信息使用申请',
                    message: options.tipLocationUsageDesc
                  }).then(function () {
                    resolve(true);
                  })["catch"](function () {
                    resolve(false);
                  });
                } else {
                  resolve(true);
                }
              }));
            case 1:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }));
    }
    /**
     * 获取定位信息
     * @static
     * @param {object} options 定位参数
     * @param {number} options.timeout 定位超时时间
     * @param {boolean} options.useWxSdk  在微信环境下，是否优先使用微信Sdk定位，微信Sdk定位返回的信息将没有省市信息
     * @param {boolean} options.useTipSdk 在游戏内环境，是否优先使用特权Sdk定位，目前只有和平和地主游戏支持
     * @param {boolean} options.useSlugSdk 在游戏内环境，是否优先使用微社区Sdk定位，目前只有和平游戏支持
     * @param {boolean} options.useMsdk 在游戏内环境，是否优先使用Msdk定位，目前只有地主支持
     * @param {boolean} options.useTencentMap 是否用腾讯地图定位请求经纬度(默认为此种方式,走的是前端授权定位)
     * @param {boolean} options.useTencentMapIfFail 使用特权Sdk定位失败的情况下，是否用腾讯地图定位兜底
     * @param {boolean} options.useTencentMapApi 是否使用腾讯地图api定位(后台IP定位)
     * @param {boolean} options.sessionCache 是否使用sessionStorage缓存，推荐使用
     * @param {boolean} options.localCache 是否使用localStorage缓存
     * @param {number} options.localExpireMs localStorage缓存过期时间
     *
     * @example
     *
     * import Location from 'src/common/location';
     *
     * Location.getLocation({
     *   timeout: 3000,
     *   useWxSdk: false,
     *   useTipSdk: false,
     *   useSlugSdk: false,
     *   useTencentMap: true,
     *   useTencentMapIfFail: false,
     *   useTencentMapApi: false,
     *   sessionCache: false,
     *   localCache: false,
     *   localExpireMs: 100000
     * })
     *   .then((res) => {
     *     window.app.position = res.location;
     *   })
     *   .catch(() => {
     *   });
     *
     */
  }, {
    key: "getLocation",
    value: function getLocation(options) {
      var _this = this;
      var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
      // 填充默认数据
      options.timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : LocationDefaultOptions.defaultTimeout;
      options.useWxSdk = (_b = options.useWxSdk) !== null && _b !== void 0 ? _b : LocationDefaultOptions.defaultUseWxSdk;
      options.useTipSdk = (_c = options.useTipSdk) !== null && _c !== void 0 ? _c : LocationDefaultOptions.defaultUseTipSdk;
      options.useSlugSdk = (_d = options.useSlugSdk) !== null && _d !== void 0 ? _d : LocationDefaultOptions.defaultUseSlugSdk;
      options.useMsdk = (_e = options.useMsdk) !== null && _e !== void 0 ? _e : LocationDefaultOptions.defaultUseMsdk;
      options.useTencentMap = (_f = options.useTencentMap) !== null && _f !== void 0 ? _f : LocationDefaultOptions.defaultUseTencentMap;
      options.useTencentMapIfFail = (_g = options.useTencentMapIfFail) !== null && _g !== void 0 ? _g : LocationDefaultOptions.defaultUseTencentMapIfFail;
      options.useTencentMapApi = (_h = options.useTencentMapApi) !== null && _h !== void 0 ? _h : LocationDefaultOptions.defaultUseTencentMapApi;
      options.sessionCache = (_j = options.sessionCache) !== null && _j !== void 0 ? _j : LocationDefaultOptions.defaultCache;
      options.localCache = (_k = options.localCache) !== null && _k !== void 0 ? _k : LocationDefaultOptions.defaultLocalCache;
      options.localExpireMs = (_l = options.localExpireMs) !== null && _l !== void 0 ? _l : LocationDefaultOptions.defaultLocalExpireMs;
      options.tipLocationUsageDesc = (_m = options.tipLocationUsageDesc) !== null && _m !== void 0 ? _m : LocationDefaultOptions.defaultTipLocationUsageDesc;
      options.needAllowLocation = (_o = options.needAllowLocation) !== null && _o !== void 0 ? _o : LocationDefaultOptions.defaultNeedAllowLocation;
      options.forceUpdateLocation = (_p = options.forceUpdateLocation) !== null && _p !== void 0 ? _p : LocationDefaultOptions.defaultForceUpdateLocation;
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(function (resolve) {
        return __awaiter(_this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
          var _this2 = this;
          var isAllowLocation, flag, _flag, storedTime, failCallback;
          return _regeneratorRuntime.wrap(function (_context2) {
            while (1) switch (_context2.prev = _context2.next) {
              case 0:
                if (!options.needAllowLocation) {
                  _context2.next = 2;
                  break;
                }
                _context2.next = 1;
                return this.getLocationPreCheck(options);
              case 1:
                isAllowLocation = _context2.sent;
                if (!(isAllowLocation == false)) {
                  _context2.next = 2;
                  break;
                }
                resolve({
                  location: LocationDefaultOptions.defaultLocation,
                  flag: LocationFlag.LocationFailed
                });
                return _context2.abrupt("return");
              case 2:
                if (options.forceUpdateLocation) {
                  _context2.next = 4;
                  break;
                }
                if (!(options.sessionCache && LocationStorage.getLocationFromSessionStorage())) {
                  _context2.next = 3;
                  break;
                }
                flag = LocationFlag.LocationSuccess;
                if (LocationStorage.getLocationFromSessionStorage().type === 'ip') {
                  flag = LocationFlag.LocationIpSuccess;
                }
                resolve({
                  location: LocationStorage.getLocationFromSessionStorage(),
                  flag: flag
                });
                return _context2.abrupt("return");
              case 3:
                if (!(options.localCache && LocationStorage.getLocationFromLocalStorage())) {
                  _context2.next = 4;
                  break;
                }
                _flag = LocationFlag.LocationSuccess;
                if (LocationStorage.getLocationFromLocalStorage().type === 'ip') {
                  _flag = LocationFlag.LocationIpSuccess;
                }
                resolve({
                  location: LocationStorage.getLocationFromLocalStorage(),
                  flag: _flag
                });
                return _context2.abrupt("return");
              case 4:
                this.getInstance().locationHandle = locationHandle(options);
                // 读取本地存储的定位时间，和对象存储的比较，取大的，再判断时间（避免重复请求）
                storedTime = parseInt(window.localStorage.getItem('tip_locate_time') || '0');
                if (this.locateTime < storedTime) {
                  this.locateTime = storedTime;
                }
                // 如果当前时间距离上次定位时间超过10s，则可以重新定位（这里避免的是重复请求，其他情况可以打开localCache）
                if (new Date().getTime() - this.locateTime > 10000 && this.getInstance().locationHandle) {
                  this.getInstance().locationHandle.getLocation(options).then(function (res) {
                    resolve(res);
                    _this2.storeLocationInfo(res.location, options);
                  })["catch"](function (error) {
                    failCallback(error);
                  });
                } else {
                  resolve({
                    location: LocationDefaultOptions.defaultLocation,
                    flag: LocationFlag.LocationFailed
                  });
                }
                // 特殊处理下特权sdk定位失败，降级到腾讯地图定位
                failCallback = function failCallback(error) {
                  var failHandle = locationHandle.failHandle(options, _this2.getInstance().locationHandle);
                  if (failHandle) {
                    _this2.getInstance().locationHandle = failHandle;
                    _this2.getInstance().locationHandle.getLocation(options).then(function (res) {
                      resolve(res);
                      _this2.storeLocationInfo(res.location, options);
                    })["catch"](function (error) {
                      console.log(error);
                      resolve({
                        location: LocationDefaultOptions.defaultLocation,
                        flag: LocationFlag.LocationFailed,
                        errorMsg: (error === null || error === void 0 ? void 0 : error.errorMsg) || (error === null || error === void 0 ? void 0 : error.errMsg)
                      });
                    });
                  } else {
                    console.log(error);
                    resolve({
                      location: LocationDefaultOptions.defaultLocation,
                      flag: LocationFlag.LocationFailed,
                      errorMsg: (error === null || error === void 0 ? void 0 : error.errorMsg) || (error === null || error === void 0 ? void 0 : error.errMsg)
                    });
                  }
                };
              case 5:
              case "end":
                return _context2.stop();
            }
          }, _callee2, this);
        }));
      });
    }
  }, {
    key: "getAreaInfoByLatAndLng",
    value: function getAreaInfoByLatAndLng(lat, lng) {
      return TencentMapApiLocation.getAreaInfoByLatAndLng(lat, lng);
    }
    /**
     * 存储定位成功和缓存位置信息
     *
     * @param {object} location 位置信息
     * @param {object} options 定位配置信息
     * @private
     */
  }, {
    key: "storeLocationInfo",
    value: function storeLocationInfo(location, options) {
      // 缓存位置信息
      if (location) {
        // 定位成功后，再读取当前时间，并存储
        this.locateTime = new Date().getTime();
        window.localStorage.setItem('tip_locate_time', "".concat(this.locateTime));
        LocationStorage.setLocationToStorage(location, options.localExpireMs);
      }
    }
  }]);
}();
LocationWeb.locationFlag = LocationFlag;
LocationWeb.instance = new LocationWeb();
LocationWeb.locateTime = 0;

export { LocationWeb };
