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


let cardNumber = '4035501000000008'	// 测试用卡号


export const useSplitCardInfo = () => {
	let paymentInfo = ref(null)
	let intent_id = ref('')
	let client_secret = ref('')

	const elementTypeList = reactive({
		cardNumber: {
			instance: null,
			type: "cardNumber",
			container: "split_card_number",
			options: {}
		},
		expiry: {
			instance: null,
			type: "expiry",
			container: "split_card_expiry",
			options: {}
		},
		cvc: {
			instance: null,
			type: "cvc",
			container: "split_card_cvc",
			options: {}
		},
	})


	// 初始化
	const onInit = () => {
		const options = {
			env: 'prod', // 'staging | 'demo' | 'prod'
			enabledElements: ['payments'],
			locale: getLan(),
		}
		init(options).then(() => {
			for (let key in elementTypeList) {
				onMountElement(elementTypeList[key])
			}
		});
	}

	// 挂载元素
	const onMountElement = async (elementInfo) => {
		elementInfo.instance = await createElement(elementInfo.type, elementInfo.options);
		elementInfo.instance && elementInfo.instance.mount(elementInfo.container);
	}

	// 卸载元素
	const onUnmountElement = () => {
		for (let key in elementTypeList) {
			const info = elementTypeList[key]
			if (info.instance) {
				info.instance.destroy();
				info.instance.unmount();
				info.instance = null;
			}
		}
	}

	// 支付信息
	const fetchPaymentInfo = (params = {}) => {
		return new Promise((resolve, reject) => {
			const query = {
				payType: 'airwallex',
				...params
			}
			SHOP_SUBMIT_PAY(query).then((result) => {
				paymentInfo.value = result.data ? result.data : null
				intent_id.value = paymentInfo.value ? paymentInfo.value.id : ''
				client_secret.value = paymentInfo.value ? paymentInfo.value.client_secret : ''
				resolve(result.data)
			}).catch(err => {
				reject(err)
			})
		})
	}


	return {
		elementTypeList,
		intent_id,
		client_secret,
		onInit,
		onUnmountElement,
		fetchPaymentInfo
	}
}