<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>
        <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';


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

        onMounted(async () => {
            try {
                // 获取从 beneficiary 页面获取到的 beneficiaryId
                // const beneficiaryId = router.currentRoute.value.query.beneficiaryId;
                const beneficiaryId = route.query.beneficiaryId;
                console.log("beneficiaryId >>> " + beneficiaryId);

                // 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,
                        // payment_currency: 'USD',
                    }
                });

                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,
                        }
                    })
                }
            }
        }

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

        //         const {
        //             values, additionalInfo
        //         } = formResult;

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


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

        //         // const reason = ref(additionalInfo.reason);

        //         // 
        //         // setTimeout(() => {
        //         //     additionalInfo.value = {
        //         //         reason: {
        //         //             label: "Audiovisual services",
        //         //             value: "audio_visual_services"
        //         //         },
        //         //         // 其他理由...
        //         //     }
        //         // }, 1000)

        //         // const reason = additionalInfo.value.additionalInfo
        //         // const regference = additionalInfo

        //         // 把这些参数都带去新的页面，然后再去新的页面获取reason 和 sdfsdfs，最后再去请问

        //         // 构建请求数据对象
        //         // 后端必须的参数 
        //         // beneficiary_id, 
        //         // payment_currency, 
        //         // payment_method, 
        //         // reason, 
        //         // reference, 
        //         // request_id, 
        //         // source_currency
        //         const caPaymentReq = {
        //             beneficiary_id: beneficiary_id,
        //             payment_currency: payment_currency,
        //             payment_method: payment_method,
        //             // reason: reason,
        //             // reference: reference,
        //             // request_id: request_id,
        //             source_currency: source_currency
        //         }

        //         // 请求后端接口
        //         const resultsResp = await createPayment(caPaymentReq);
        //         console.log("resultResp>>>", resultsResp);

        //         // if 成功，将 
        //         // if (resultsResp.code === "00000") {
        //         //     router.push({
        //         //         path: '/caPayment',
        //         //         query: { beneficiaryId: beneficiaryId }
        //         //     })
        //         // }

        //     }
        // };


        // 生成 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>