import { ref, reactive, nextTick } from 'vue'
// #ifdef H5
import { createElement, loadAirwallex, getElement } from 'airwallex-payment-elements'
// #ifdef H5
import { SHOP_SUBMIT_PAY } from '@/api'
import { getLan } from "@/locale"
import verConfig from '@/ver.config'


let appleInstance = ref(null);
let appleParams = reactive({})

const init = (callback) => {
  loadAirwallex({
    env: 'staging',
    env: 'prod',
    origin: window.location.origin,
    // origin: verConfig.origin,
    locale: getLan(),
  }).then(() => {
    appleInstance.value = createElement('applePayButton', {
      ...appleParams
    });
    appleInstance.value.mount('apple_pay_card');
    callback && callback();
  })
}

const unmountCard = () => {
  let card = getElement('applePayButton');
  card.destroy();
  card.unmount();
  appleInstance.value = null;
}



const fetchCardPaymentInfo = (params = {}, callback) => {
  return new Promise((resolve, reject) => {
    const query = {
      payType: 'airwallex',
      ...params
    }
    SHOP_SUBMIT_PAY(query).then(result => {
      const { id, client_secret, amount, currency, countryCode } = result.data;
      appleParams.intent_id = id;
      appleParams.client_secret = client_secret;
      appleParams.amount = {
        value: amount,
        currency,
      };
      appleParams.countryCode = countryCode
      nextTick(() => {
        init(callback);
      })
      resolve(result.data)
    }).catch(err => { reject(err) })
  })
}

export const useAppleInfo = () => {
  return { appleInstance, init, unmountCard, fetchCardPaymentInfo }
}