<template>
    <div class="airwallexPayment">
        <s-header :name="$t('airwallex.payout')" :noback="false"></s-header>
        <br>
        <div class="form-container">
            <div id="payout-form-container" class="payout-form-container" style="height: 100%;"></div>
        </div>
        <br>
        <br>
        <br>
        <div class="button-container">
            <van-button type="primary" class="cancel" @click="handleCancel">取消</van-button>
            <van-button type="primary" class="register" @click="handleSubmit">继续</van-button>
        </div>
    </div>
</template>

<script>
import sHeader from "@/components/SimpleHeader";
import { init, createElement } from '@airwallex/payouts-web-sdk';
import { Base64 } from 'js-base64';
import { AIRWALLEX_ADMIN_CLIENTID } from '@/constants/const.js';
import { getAuthCode } from '@/service/airwallex/index';
import { onMounted, ref } from 'vue';
import { styleUrl } from '../../common/js/utils';
import { useRouter, useRoute } from 'vue-router';
import { getWallet } from '@/service/airwallex/index';



export default {
    components: { sHeader },
    setup() {
        const router = useRouter();
        const route = useRoute();
        const ready = ref(false);
        let payoutComponent;

        const loginUserStr = localStorage.getItem("loginUser");
        const loginUser = JSON.parse(loginUserStr);
        const userId = loginUser.id;
        // console.log("userId是 >>> " + userId);

        onMounted(async () => {
            try {
                // 获取从 beneficiary 页面获取到的 beneficiaryId
                // const beneficiaryId = router.currentRoute.value.query.beneficiaryId;
                const beneficiaryId = route.query.beneficiaryId;
                console.log("beneficiaryId >>> " + beneficiaryId);
                
                // 请求后端接口: 获取钱包信息
                const resp = await getWallet(userId);
                const sourceAmount = resp.data.accountAmount;
                // console.log("sourceAmount >>> " + sourceAmount);

                

                // generate code_verifier
                const codeVerifier = generateCodeVerifier();

                // generate code_challenge
                const codeChallengeStr = await generateCodeChallengeFromVerifier(codeVerifier);

                // getAuthCode 接口参数
                const getAuthCodeDTO = {
                    code_challenge: codeChallengeStr,
                    scope: [
                        "w:awx_action:transfers_edit"
                    ]
                };

                console.log("getAuthCodeDTO", getAuthCodeDTO);

                // generate authCode
                const authCodeResponse = await getAuthCode(getAuthCodeDTO);
                const authCodeStr = authCodeResponse.data.authorization_code;

                await init({
                    langKey: 'en',
                    env: 'demo',
                    authCode: authCodeStr,
                    clientId: AIRWALLEX_ADMIN_CLIENTID,
                    codeVerifier: codeVerifier,
                });

                // 调用 SDK 的 createElement 方法创建付款交易单/收款方模块
                payoutComponent = await createElement(eleType, {
                    defaultValues: {
                        beneficiary_id: beneficiaryId,
                        source_amount: sourceAmount,
                        source_currency: 'USD',
                        // payment_currency: 'USD',
                    },
                    customizations: {
                        fields: {
                            source_amount: {
                                disabled: true,
                            },
                            source_currency: {
                                disabled: true,
                            },
                            payment_amount: {
                                disabled: true,
                            },
                            // payment_currency: {
                            //     disabled: true,
                            // },
                            // swift_charge_option: {
                            //     disabled: true, // 禁用swift方式下的选框
                            //     hidden: true, // 隐藏swift方式下的选框
                            // },
                        }
                    }
                });


                payoutComponent.mount('#payout-form-container');

                payoutComponent.on('ready', () => {
                    ready.value = true;
                    // 添加组件渲染后的逻辑
                    console.log('组件呈现后的逻辑...');
                });
            } catch (error) {
                console.error(error);
                // 处理异常情况
            }
        });

        const handleCancel = async () => {
            router.push({
                path: '/airwallex',
            })
        }

        const handleSubmit = async () => {
            if (ready.value) {
                const formResult = await payoutComponent.submit();
                // Handle form results
                console.log('submit 执行结果：', formResult);

                const {
                    values
                } = formResult;

                const {
                    beneficiary_id,
                    payment_currency,
                    payment_method,
                    source_currency,
                    source_amount,
                    fee_paid_by,
                    payment_date,
                } = values;

                // 校验 values 参数
                if (
                    !beneficiary_id ||
                    !payment_currency ||
                    !payment_method ||
                    !source_currency
                    // !reason ||
                    // !reference ||
                ) {
                    throw new Error('缺少必要参数');
                }

                if (formResult) {
                    router.push({
                        path: '/caPayment',
                        query: {
                            beneficiary_id: beneficiary_id,
                            payment_currency: payment_currency,
                            payment_method: payment_method,
                            // reason: reason,
                            // reference: reference,
                            source_currency: source_currency,
                            // request_id: request_id,
                            source_amount: source_amount,
                            fee_paid_by: fee_paid_by,
                            payment_date: payment_date,
                        }
                    })
                }
            }
        }


        // 生成 code_verifier
        const dec2hex = (dec) => {
            return ('0' + dec.toString(16)).slice(-2);
        };

        const generateCodeVerifier = () => {
            // 生成 random length for code_verifier which should be between 43 and 128
            const length = Math.random() * (129 - 43) + 43;
            const array = new Uint32Array(length / 2);
            window.crypto.getRandomValues(array);

            return Array.from(array, dec2hex).join('');
        };


        // 生成 code_challenge
        const sha256 = (plain) => {
            const encoder = new TextEncoder();
            const data = encoder.encode(plain);
            return window.crypto.subtle.digest('SHA-256', data);
        };

        const base64urlencode = (hashed) => {
            const bytes = new Uint8Array(hashed);
            const base64encoded = Base64.fromUint8Array(bytes, true);
            return base64encoded;
        };

        const generateCodeChallengeFromVerifier = async (codeVerifier) => {
            const hashed = await sha256(codeVerifier);
            const base64encoded = base64urlencode(hashed);
            return base64encoded;
        };

        // type 字段：payoutForm（可选）,beneficiaryForm
        const eleType = "payoutForm";

        styleUrl("airwallex");
        return {
            ready,
            handleSubmit,
            handleCancel
        }
    }
}
</script>