import { ref, reactive, nextTick } from 'vue'
// #ifdef H5
import { init, createElement } from '@airwallex/components-sdk';
// #endif
import { SHOP_SUBMIT_PAY } from '@/api'
import { getLan } from "@/locale"
import verConfig from '@/ver.config'


export const useDropInPayInfo = () => {

	let dropInElement = ref(null);
	let createOptions = reactive({});


	// 初始化
	const handleInit = async (callback) => {
		try {
			await init({
				env: 'prod',
				enabledElements: ['payments'],
				locale: getLan()
			});
			dropInElement.value = await createElement('dropIn', {
				...createOptions,
				appearance: {
					mode: 'light',
					variables: {
						colorBrand: '#612FFF',
					},
				}
			});
			nextTick(() => {
				dropInElement.value && dropInElement.value.mount('dropIn');
				callback && callback();
			})
		}
		catch (err) {
			console.log('--- err ---', err)
		}
	}

	// 卸载&销毁
	const handleUnmount = () => {
		if (dropInElement.value) {
			dropInElement.value.unmount();
			dropInElement.value.destroy();
			dropInElement.value = null;
		}
	}


	// 获取初始化配置数据
	const fetchPaymentInitData = (params = {}, callback) => {
		return new Promise((resolve, reject) => {
			SHOP_SUBMIT_PAY({
				payType: 'airwallex',
				...params
			}).then(result => {
				const {
					id,
					client_secret,
					amount,
					currency,
					countryCode
				} = result.data;
				createOptions.intent_id = id;
				createOptions.client_secret = client_secret;
				/* createOptions.amount = {
					value: amount,
					currency,
				}; */
				createOptions.currency = currency
				createOptions.countryCode = countryCode
				nextTick(() => {
					console.log('---- createOptions ----', createOptions)
					handleInit(callback);
				})
				resolve(result.data)
			}).catch(err => {
				reject(err)
			})
		})
	}


	return {
		dropInElement,
		handleInit,
		handleUnmount,
		fetchPaymentInitData
	}
}