<template>
    <BasePage :back="back" title="订单支付">
        <div class="pay">
            <div class="amount">
                <span>￥</span>{{ orderInfo.needpay }}
            </div>
            <div class="trade-code">
                订单号：{{ orderInfo.ordernum }}
            </div>

            <van-cell-group class="pay-method" inset>
                <van-checkbox-group v-model="payMethod" disabled>
                    <!-- 余额支付 -->
                    <van-cell class="balance-pay" title="余额支付" is-link @click="payMethod = ['balance']">
                        <template #icon>
                            <img class="pay-icon" src="/img/pay_balance.png" />
                        </template>
                        <template #right-icon>
                            <van-checkbox name="balance" :class="{ selected: payMethod.includes('balance') }" />
                        </template>
                        <template #label>
                            <span>剩余: {{ wallet.totalsum || 0 }}</span>
                        </template>
                    </van-cell>

                    <!-- 支付宝支付 -->
                    <van-cell title="支付宝支付" is-link @click="payMethod = ['alipay']">
                        <template #icon>
                            <img class="pay-icon" src="/img/pay_alipay.png" />
                        </template>
                        <template #right-icon>
                            <van-checkbox name="alipay" :class="{ selected: payMethod.includes('alipay') }" />
                        </template>
                    </van-cell>

                    <!-- 微信支付 -->
                    <van-cell title="微信支付" is-link @click="payMethod = ['wechat']">
                        <template #icon>
                            <img class="pay-icon" src="/img/pay_weixin.png" />
                        </template>
                        <template #right-icon>
                            <van-checkbox name="wechat" :class="{ selected: payMethod.includes('wechat') }" />
                        </template>
                    </van-cell>

                    <van-cell v-if="!hide" title="快捷支付HJ(更顺畅)" is-link @click="payMethod = ['bankcard']">
                        <template #icon>
                            <img class="pay-icon" src="/img/pay_bankcard.png" />
                        </template>
                        <template #right-icon>
                            <van-checkbox name="bankcard" :class="{ selected: payMethod.includes('bankcard') }" />
                        </template>
                    </van-cell>
                </van-checkbox-group>

                <van-button type="primary" size="large" round="" style="width: 100%;margin-top: 6.67vw;"
                    :disabled="payMethod.length !== 1" @click="doPay">立即支付</van-button>
            </van-cell-group>

            <!-- 支付结果弹窗 -->
            <van-dialog v-model:show="showPayResult" title="支付结果" :close-on-click-overlay="false" show-confirm-button
                show-cancel-button confirm-button-text="重新支付" confirm-button-color="#f00" cancel-button-color="#1989fa"
                cancel-button-text="已完成支付" @cancel="onPayCompleted" @confirm="onRePay">
                <van-loading vertical style="margin: 3.333vw 0;">
                    <template #icon>
                        <van-icon name="gem-o" size="30" />
                    </template>
                    支付中...
                </van-loading>
            </van-dialog>
        </div>
    </BasePage>
</template>

<script>
export default {
    name: 'Pay',
    data() {
        return {
            ordernum: '',
            orderInfo: {
                ordernum: '',
                needpay: 0,
                state: 0,
            },
            hide: true,
            wallet: {
                totalsum: 0,
            },
            payMethod: ['balance'],
            showPayResult: false,
            paychannelList: [],
        }
    },
    mounted() {
        this.ordernum = this.$route.query.ordernum || this.$route.query.TradeCode;
        if (!this.ordernum) {
            this.$showFailToast('订单不存在');
            this.$router.replace('/My');
            return;
        }
        this.loadData();
        this.$get('/v1/client/FOrdersClient/paychannel').then(res => {
            this.paychannelList = res.data || [];
        })
    },
    methods: {
        back() {
            this.$router.push('/Tradelist');
        },
        async loadData() {
            try {
                // 获取订单详情
                const orderRes = await this.$get(`/v1/client/FOrdersClient/${this.ordernum}`);
                this.orderInfo = orderRes.data;

                // 获取钱包余额
                const walletRes = await this.$get('/v1/client/DUsermoneysClient/statistics');
                this.wallet = walletRes.data;
            } catch (err) {
                this.$showFailToast(err.message || '加载失败');
            }
        },
        async doPay() {
            const method = this.payMethod[0];
            // 获取对应的 Paychannel 值
            const channelMap = {
                balance: 4,
                alipay: 2,
                wechat: 1,
                bankcard: 3
            };
            const paychannel = channelMap[method];
            const openid = localStorage.getItem('openid') || '';

            try {
                const res = await this.$post(`/v1/client/FOrdersClient/${this.ordernum}/pay`, {
                    Paychannel: paychannel,
                    Openid: method === 'wechat' ? openid : ''
                });
                if (res.data && res.data.startsWith('http')) {
                    // 返回链接则跳转
                    location.href = res.data;
                } else if (res.status === 200) {
                    // 余额支付成功
                    this.$showSuccessToast(res.message || '支付成功');
                    setTimeout(() => {
                        this.onPayCompleted();
                    }, 1500);
                }
                this.showPayResult = true;
            } catch (err) {
                this.showPayResult = false;
                this.$showFailToast(err.message || '支付失败');
            }
        },
        onPayCompleted() {
            this.$router.replace('/Tradelist');
        },
        onRePay() {
            this.showPayResult = false;
        },
    }
}
</script>

<style lang="less">
:root {
    --van-primary-color: #ca2904;
}

.pay {
    text-align: center;
    padding-top: 16.667vw;

    .amount {
        font-size: 10.667vw;
        font-weight: bold;

        span {
            font-size: 5vw;
        }
    }

    .trade-code {
        margin-top: 1.667vw;
        font-size: 4.333vw;
    }

    .pay-method {
        margin-top: 9.667vw;

        .van-cell__title {
            display: flex;
            align-items: center;
        }
    }

    .pay-icon {
        width: 9.667vw;
        margin-right: 10px;
    }

    .balance-pay .van-cell__title {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: flex-start !important;
        font-size: 3.667vw;
    }

    .normal-pay .van-cell__title {
        display: flex;
        align-items: center;
        font-size: 3.667vw;
    }

    .van-cell__right-icon {
        height: auto;
        display: flex;
        align-items: center;
    }

    .van-checkbox__icon--disabled .van-icon {
        background-color: unset;
    }

    .van-checkbox__icon--disabled.van-checkbox__icon--checked .van-icon {
        color: var(--van-primary-color);
    }

    .selected .van-checkbox__icon--disabled .van-icon {
        border-color: var(--van-primary-color);
    }
}
</style>