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

let googleInstance = ref(null);
let googleParams = reactive({})

const init = (callback) => {
  loadAirwallex({
    env: 'prod',
    origin: window.location.origin,
    locale: getLan()
  }).then(() => {
    googleInstance.value = createElement('googlePayButton', {
      ...googleParams
    });
    googleInstance.value.mount('google_pay_card');
    callback && callback();
  })
}

const unmountCard = () => {
  let card = getElement('googlePayButton');
  card.destroy();
  card.unmount();
  googleInstance.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;
      googleParams.intent_id = id;
      googleParams.client_secret = client_secret;
      googleParams.amount = {
        value: amount,
        currency,
      };
      googleParams.countryCode = countryCode
      nextTick(() => {
        console.log('---- googleParams ----', googleParams)
        init(callback);
      })
      resolve(result.data)
    }).catch(err => { reject(err) })
  })
}

export const useGoogleInfo = () => {
  return { googleInstance, init, unmountCard, fetchCardPaymentInfo }
}