function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { eventCodeEnum, RedirectType, TargetEnum } from "../../types";
import { ServiceProvider } from "../service";
import { isPC } from "../../util";
import CallApp from "../../util/intl-callapp/es/index";
import { EVENT } from "../../constant";

/**
 * @author 谦彧 <zhangmian.zm@alipay.com>
 * @date 2024/9/19
 */
export var redirect = function redirect(payload, instanceId) {
  var serviceProvider = ServiceProvider.getInstance(instanceId);
  var logService = serviceProvider.getService('Log');
  logService.logInfo({
    title: 'sdk_event_call_url_start'
  }, _objectSpread({}, payload)).send();
  try {
    if (payload.isCallApp && payload.schemeUrl) {
      var detectSuccessDelay = payload.callAppDetectSuccessDelay;
      var _callAppLib = new CallApp({
        successCb: function successCb() {
          successCallback(payload, RedirectType.SchemeUrl, payload.schemeUrl, serviceProvider);
        },
        resultJudgmentTime: detectSuccessDelay
      });
      _callAppLib.open({
        scheme: payload.schemeUrl,
        fallback: function fallback() {
          failCallback(payload, RedirectType.SchemeUrl, payload.schemeUrl, serviceProvider);
        }
      });
      return;
    }
    // 支持 target: _blank，新开tab页打开
    if (payload.browserLinkTarget === TargetEnum.BLANK) {
      if (!payload.url) return failCallback(payload, RedirectType.NormalUrl, '', serviceProvider);
      successCallback(payload, RedirectType.NormalUrl, payload.url, serviceProvider);
      window.open(payload.url);
      return;
    }
    if (payload.browserLinkTarget === TargetEnum.REPLACE && !(payload !== null && payload !== void 0 && payload.applinkUrl) && !(payload !== null && payload !== void 0 && payload.schemeUrl)) {
      if (!payload.url) return failCallback(payload, RedirectType.NormalUrl, '', serviceProvider);
      successCallback(payload, RedirectType.NormalUrl, payload.url, serviceProvider);
      window.location.replace(payload.url);
      return;
    }
    if (isPC()) {
      if (!payload.url) return failCallback(payload, RedirectType.NormalUrl, '', serviceProvider);
      successCallback(payload, RedirectType.NormalUrl, payload.url, serviceProvider);
      window.location.href = payload.url;
      return;
    }
    if (!payload.schemeUrl && !payload.applinkUrl) {
      if (!payload.url) return failCallback(payload, RedirectType.NormalUrl, '', serviceProvider);
      successCallback(payload, RedirectType.NormalUrl, payload.url, serviceProvider);
      window.location.href = payload.url;
      return;
    }
    // Use callApp lib to evoke
    var callAppLib = new CallApp({
      successCb: function successCb(evokeAppBy) {
        var type = evokeAppBy.type == 'Scheme' ? RedirectType.SchemeUrl : RedirectType.ApplinkUrl;
        successCallback(payload, type, evokeAppBy.url, serviceProvider);
      }
    });
    var callApplinkUrl = function callApplinkUrl() {
      try {
        callAppLib.open({
          link: payload.applinkUrl,
          fallback: function fallback() {
            failCallback(payload, RedirectType.ApplinkUrl, payload.applinkUrl, serviceProvider);
            // Applink evoke failed, try to use scheme url
            callSchemeUrl();
          }
        });
      } catch (error) {
        failCallback(payload, RedirectType.ApplinkUrl, payload.applinkUrl, serviceProvider);
        // Applink evoke failed, try to use scheme url
        callSchemeUrl();
      }
    };
    var callSchemeUrl = function callSchemeUrl() {
      try {
        callAppLib.open({
          scheme: payload.schemeUrl,
          fallback: function fallback() {
            failCallback(payload, RedirectType.SchemeUrl, payload.schemeUrl, serviceProvider);
            if (!payload.url) return failCallback(payload, RedirectType.NormalUrl, '', serviceProvider);
            successCallback(payload, RedirectType.NormalUrl, payload.url, serviceProvider);
            window.location.href = payload.url;
          }
        });
      } catch (error) {
        failCallback(payload, RedirectType.SchemeUrl, payload.schemeUrl, serviceProvider);
        if (!payload.url) return failCallback(payload, RedirectType.NormalUrl, '', serviceProvider);
        successCallback(payload, RedirectType.NormalUrl, payload.url, serviceProvider);
        window.location.href = payload.url;
      }
    };
    if (payload.applinkUrl) {
      callApplinkUrl();
    } else if (payload.schemeUrl) {
      callSchemeUrl();
    }
  } catch (e) {
    serviceProvider.getService('Log').logInfo({
      title: 'sdk_event_call_url_failed'
    }, {
      redirectInfo: JSON.stringify(payload),
      errorMessage: JSON.stringify(e)
    }).send();
  }
};
var successCallback = function successCallback(payload, type, url, serviceProvider) {
  serviceProvider.getService('EventCenter').emit(EVENT.eventCallback.name, {
    code: eventCodeEnum.SDK_CALL_URL_SUCCESS,
    message: "Successfully opened the app,".concat(type, ": ").concat(url)
  });
  serviceProvider.getService('Log').logInfo({
    title: 'sdk_event_call_url_success'
  }, {
    redirectInfo: JSON.stringify(payload),
    openType: type,
    url: url
  }).send();
};
var failCallback = function failCallback(payload, type, url, serviceProvider) {
  serviceProvider.getService('EventCenter').emit(EVENT.eventCallback.name, {
    code: eventCodeEnum.SDK_LAUNCH_PAYMENT_APP_ERROR,
    message: "Failed to open app,applinkUrl: ".concat(payload === null || payload === void 0 ? void 0 : payload.applinkUrl, " schemeUrl: ").concat(payload === null || payload === void 0 ? void 0 : payload.schemeUrl, " normalUrl: ").concat(payload === null || payload === void 0 ? void 0 : payload.url)
  });
  serviceProvider.getService('Log').logInfo({
    title: 'sdk_error_call_url_failed'
  }, {
    redirectInfo: JSON.stringify(payload),
    openType: type,
    url: url
  }).send();
};
var UA_MATCH_RULES = [{
  matchRule: 'AppleWebKit\\/([0-9\\.]+).* Version\\/([0-9\\._]+) Mobile\\/([0-9\\._A-Z]+) Safari\\/([0-9\\._]+)$',
  iosScheme: 'https',
  andScheme: ''
}, {
  matchRule: 'HeyTapBrowser',
  iosScheme: '',
  andScheme: ''
}, {
  matchRule: 'HuaweiBrowser',
  iosScheme: '',
  andScheme: ''
}, {
  matchRule: 'Kwai',
  iosScheme: 'kwai',
  andScheme: ''
}, {
  matchRule: 'MQQBrowser',
  iosScheme: 'mttbrowser',
  andScheme: ''
}, {
  matchRule: 'MicroMessenger',
  iosScheme: '',
  andScheme: ''
}, {
  matchRule: 'MiuiBrowser',
  iosScheme: '',
  andScheme: ''
}, {
  matchRule: 'Mozilla\\/([0-9\\.]+).* AppleWebKit\\/([0-9\\.]+).* CriOS\\/([0-9\\._]+) Mobile\\/([0-9\\._A-Z\\._a-z]+) Safari\\/([0-9\\._]+)$',
  iosScheme: 'googlechrome',
  andScheme: ''
}, {
  matchRule: 'Mozilla\\/([0-9\\.]+).* AppleWebKit\\/([0-9\\.]+).* Version\\/([0-9\\._]+) Mobile Safari\\/([0-9\\._]+)$',
  iosScheme: 'googlechrome',
  andScheme: ''
}, {
  matchRule: 'NewsArticle',
  iosScheme: 'snssdk141',
  andScheme: ''
}, {
  matchRule: 'UCBrowser',
  iosScheme: 'ucbrowser',
  andScheme: ''
}, {
  matchRule: 'VideoArticle',
  iosScheme: 'snssdk32',
  andScheme: ''
}, {
  matchRule: 'VivoBrowser',
  iosScheme: '',
  andScheme: ''
}, {
  matchRule: 'ZhongAnWebView',
  iosScheme: 'zaapp',
  andScheme: ''
}, {
  matchRule: 'aweme',
  iosScheme: 'snssdk1128',
  andScheme: ''
}, {
  matchRule: 'aweme_lite',
  iosScheme: 'snssdk2329',
  andScheme: ''
}, {
  matchRule: 'com.xs.fm',
  iosScheme: 'novelfm3040',
  andScheme: ''
}, {
  matchRule: 'netdisk',
  iosScheme: '',
  andScheme: ''
}, {
  matchRule: 'qqnews',
  iosScheme: 'qqnews',
  andScheme: ''
}];

/**
 * 通过配置规则检测 UA 和获得回跳 scheme
 */
export function getBackScheme(mockUa, logger) {
  var ua = mockUa || window.navigator.userAgent || '';
  // 获取规则
  var uaMatchedRule = UA_MATCH_RULES;
  var matchedRule;
  var matched = null;
  for (var i = 0; i < uaMatchedRule.length; i++) {
    var rule = uaMatchedRule[i];
    matched = ua.match(rule.matchRule);
    if (matched) {
      matchedRule = rule;
      break;
    }
  }
  if (!matchedRule) {
    logBackScheme(logger, ua, '');
    return;
  }
  if (isAndroid(ua)) {
    logBackScheme(logger, ua, matchedRule.andScheme);
    return matchedRule.andScheme;
  }
  if (isIOS(ua)) {
    logBackScheme(logger, ua, matchedRule.iosScheme);
    return matchedRule.iosScheme;
  }
}
function logBackScheme(logger, userAgent, scheme) {
  if (logger) {
    logger.logInfo({
      title: 'a3753.b101271.c377460'
    }, {
      eventMessage: scheme
    });
  }
}

/**
 * 当前运行环境是否 Android
 */
function isAndroid(mockUA) {
  var ua = (mockUA || navigator.userAgent).toLowerCase();
  return /android|adr|linux/.test(ua);
}

/**
 * 当前运行环境是否 IOS
 */
function isIOS(mockUA) {
  var ua = (mockUA || navigator.userAgent).toLowerCase();
  return /iphone|ipad|ipod|ios|macintosh/.test(ua);
}