import { mergeObject } from "@/utils";
import { loadAirwallex, redirectToCheckout } from "airwallex-payment-elements";

/**
 * 空中云汇率,支付环境.
 */
export function getAirwallexEnv() {
  const env = process.env.ENV;
  if (env === "staging") {
    return "staging";
  }
  if (env === "production") {
    return "prod";
  }
  return "demo";
}

/**
 * 发起支付.
 * @param result 下单结果
 * @param callback 支付拉起加载回掉
 * @param props 空中云汇支付属性
 */
export function goAirwallex({ result, props, callback }) {
  const env = getAirwallexEnv();
  loadAirwallex({ env })
    .then(() => {
      callback({ code: "INIT-LOAD", msg: "init load success." });
      const param = mergeObject(
        {
          env,
          mode: "payment",
          currency: result.currency,
          intent_id: result.expand.id,
          client_secret: result.expand["client_secret"],
          methods: [result.factoryChannelCode],
          // country_code: result.countryCode,
          recurringOptions: {
            card: {
              next_triggered_by: "customer",
              merchant_trigger_reason: "unscheduled",
              currency: result.currency,
            },
          },
          theme: {
            // Must provide theme to display the checkout page properly
            fonts: [
              // Customizes the font for the payment elements
              {
                src: "https://checkout.airwallex.com/fonts/CircularXXWeb/CircularXXWeb-Regular.woff2",
                family: "AxLLCircular",
                weight: 400,
              },
            ],
          },
        },
        props
      );
      redirectToCheckout(param);
    })
    .catch((er) => {
      console.error(er);
      callback({ code: "FAIL", msg: "init fail!!!" });
    });
}
