<template>
    <BasePage>
        <div class="cart_tj_xzdz">
            <div class="xzdz" @click="$refs.ad_selector.showSelector()">
                <img src="/img/addr.png" alt="">

                <span style="color: #333;" v-if="address.ReceiveName">
                    <p>
                        {{ address.ReceiveName }}
                        {{ address.ReceivePhone }}
                    </p>
                    {{ address.province }}-{{ address.city }}-{{ address.county }}-{{
                        address.ReceiveAddress
                    }}
                </span>
                <span v-else>请选择收货地址</span>
                <van-icon name="arrow" />
            </div>
            <!-- <div class="b_l_w cart_tj_xzdz_di"></div> -->
        </div>
        <div class="tradeconfirm">
            <div class="product">
                <img :src="$file(product.img)" />
                <div class="prodetail">
                    <b>{{ product.name }}</b>
                    <div>
                        <p>{{ product.typename }}订单</p>

                        <b class="r" v-if="product.mallstate !== 5"><span>￥</span>{{ product.saleprice?.toFixed(2)
                        }}</b>
                        <b class="r" v-else><span>{{ product.saleprice?.toFixed(2) }}</span>积分</b>

                    </div>
                    <div>
                        <p>规格：{{ product.skuname }}</p>
                        <van-stepper class="r" v-model="product.buynums" :min="1" :max="999" input-width="7vw"
                            button-size="6vw" integer></van-stepper>
                    </div>
                </div>
            </div>

            <div class="payway" v-if="product.mallstate !== 5">
                <div class="deduction">
                    <div class="top">
                        <span>商品金额</span>
                        <b class="r"><span>￥</span>{{ totalPrice }}</b>
                    </div>
                    <div class="radio-group">
                        <div class="way" :class="{ active: checked === '1' }" @click="toggleRadio('1')">
                            <div class="radio-content">
                                <div class="line">
                                    <img src="/img/point_icon.png" alt="">
                                    <span>使用积分抵扣</span>
                                </div>
                                <p>
                                    (当前可用：{{ (userInfo.xiaofeijifen || 0)?.toFixed(2) }}，本次可抵：{{
                                        actualJifenDeduct?.toFixed(2) }})
                                </p>
                            </div>
                            <div class="radio-icon">
                                <van-icon v-if="checked === '1'" name="success" />
                            </div>
                        </div>
                        <div class="way" :class="{ active: checked === '2' }" @click="toggleRadio('2')">
                            <div class="radio-content">
                                <div class="line">
                                    <img src="/img/vip_icon.png" alt="">
                                    <span>使用会员卡抵扣</span>
                                </div>
                                <p>
                                    (当前可用：{{ (userInfo.xiaofeiquan || 0)?.toFixed(2) }}，本次可抵：{{
                                        actualQuanDeduct?.toFixed(2) }})
                                </p>
                            </div>

                            <div class="radio-icon">
                                <van-icon v-if="checked === '2'" name="success" />
                            </div>
                        </div>
                    </div>
                    <div class="count">
                        <div v-if="freight > 0">
                            <span>运费</span>
                            <span class="price">￥{{ freight.toFixed(2) }}</span>
                        </div>
                        <div v-if="checked">
                            <span>抵扣金额</span>
                            <span class="price">-￥{{ actualDeduct?.toFixed(2) || '0.00' }}</span>
                        </div>
                        <div>
                            <span>实付金额</span>
                            <span class="price">
                                ￥{{ actualPay?.toFixed(2) || '0.00' }}
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="remark">
                <van-field label="买家留言" autosize type="textarea" v-model="remark" placeholder="请输入买家留言" />
            </div>
        </div>

        <van-submit-bar class="b_l_w" placeholder :price="actualPay * 100" :tip="`商品总数:${totalQuantity}件`"
            tip-icon="info-o" safe-area-inset-bottom :currency="product.mallstate === 5 ? '' : '¥'">
            <template #button>
                <van-button round color="rgb(227, 83, 33)" :loading="isloading" @click="submitOrder"
                    style="height: 10vw;">
                    提交订单
                </van-button>
            </template>
        </van-submit-bar>

        <AddressSelector ref="ad_selector" @confirm="onAddressConfirm" />

    </BasePage>
</template>

<script>
export default {
    name: 'TradeConfirm',
    mounted() {
        this.loadProduct();
        this.loadUserInfo();
        this.loadDefaultAddress();
    },
    data() {
        return {
            product: {},
            remark: "",
            address: {},
            coupon: 0,
            useCoupon: 0,
            fruit: 0,
            fruitData: {},
            isloading: false,
            checked: '',
            userInfo: {},
            _lastChecked: '',
        };
    },
    computed: {
        totalQuantity() {
            return this.product.buynums || 1;
        },
        totalPrice() {
            return ((this.product.saleprice || 0) * (this.product.buynums || 1)).toFixed(2);
        },
        // 商品金额（不含运费）
        goodsAmount() {
            return (this.product.saleprice || 0) * (this.product.buynums || 1);
        },
        // 运费
        freight() {
            return this.product.expressprice || 0;
        },
        // 积分可抵扣金额（接口返回的最高抵扣金额，乘以数量）
        maxJifenDeduct() {
            return (this.product.deductjifen || 0) * (this.product.buynums || 1);
        },
        // 会员卡可抵扣金额（接口返回的最高抵扣金额，乘以数量）
        maxQuanDeduct() {
            return (this.product.deducthuiyuanka || 0) * (this.product.buynums || 1);
        },
        // 实际积分可抵扣金额（余额够时抵接口返回金额，不够时抵余额）
        actualJifenDeduct() {
            const max = this.maxJifenDeduct;
            const available = this.userInfo.xiaofeijifen || 0;
            return Math.min(max, available, this.goodsAmount);
        },
        // 实际会员卡可抵扣金额（余额够时抵接口返回金额，不够时抵余额）
        actualQuanDeduct() {
            const max = this.maxQuanDeduct;
            const available = this.userInfo.xiaofeiquan || 0;
            return Math.min(max, available, this.goodsAmount);
        },
        // 当前选中的抵扣方式实际可抵扣金额
        actualDeduct() {
            if (!this.checked) return 0;
            return this.checked === '1' ? this.actualJifenDeduct : this.actualQuanDeduct;
        },
        // 实付金额 = 商品金额 + 运费 - 抵扣金额
        actualPay() {
            return this.goodsAmount + this.freight - this.actualDeduct;
        },
        useFruitPrice() {
            return this.actualPay;
        },
    },
    methods: {
        loadProduct() {
            const id = this.$route.query.id;
            const skuid = this.$route.query.skuid;
            this.$get(`/v1/client/EProsClient/${id}`).then(res => {
                const data = res.data;
                // 从规格组合中找到匹配的SKU
                let sku = null;
                if (skuid && data.specCombinations) {
                    sku = data.specCombinations.find(s => String(s.skuid) === String(skuid));
                }
                if (!sku && data.specCombinations?.length) {
                    sku = data.specCombinations[0];
                }
                this.product = {
                    id: data.id,
                    name: data.name,
                    img: sku?.img || data.img,
                    saleprice: sku?.saleprice || data.saleprice,
                    originalprice: sku?.originalprice || data.originalprice,
                    skuid: sku?.skuid,
                    skuname: sku?.skuname || '默认规格',
                    buynums: parseInt(this.$route.query.buynums) || 1,
                    typename: data.typename || '商品',
                    expressprice: data.expressprice || 0,
                    deductjifen: data.deductjifen || 0,
                    deducthuiyuanka: data.deducthuiyuanka || 0,
                    mallstate: data.mallstate || 0,
                };
            });
        },
        loadUserInfo() {
            this.$get('/v1/client/DUsersClient').then(res => {
                this.userInfo = res.data;
            }).catch(() => { });
        },
        loadDefaultAddress() {
            this.$get('/v1/client/DUseraddressClient').then(res => {
                const list = res.data || [];
                const defaultAddr = list.find(item => item.defaulted);
                if (defaultAddr) {
                    this.address = {
                        ReceiveName: defaultAddr.name,
                        ReceivePhone: defaultAddr.phone,
                        ReceiveRegionName: defaultAddr.province + defaultAddr.city + defaultAddr.county,
                        ReceiveAddress: defaultAddr.address,
                        province: defaultAddr.province,
                        city: defaultAddr.city,
                        county: defaultAddr.county,
                    };
                }
            }).catch(() => { });
        },
        onAddressConfirm(addr) {
            this.address = addr;
        },
        toggleRadio(name) {
            if (this.checked === name) {
                this.checked = '';
            } else {
                this.checked = name;
            }
        },
        onRadioChange(val) {
            if (this._lastChecked === val) {
                this.checked = '';
                this._lastChecked = '';
            } else {
                this._lastChecked = val;
            }
        },
        submitOrder() {
            if (!this.address.ReceiveName) {
                this.$showFailToast("请选择收货地址！");
                return;
            }
            this.isloading = true;
            const form = {
                info: [{
                    proid: this.product.id,
                    skuid: this.product.skuid,
                    skuname: this.product.skuname,
                    buynums: this.product.buynums || 1
                }],
                expresstype: true,
                name: this.address.ReceiveName,
                phone: this.address.ReceivePhone,
                province: this.address.province,
                city: this.address.city,
                county: this.address.county,
                address: this.address.ReceiveAddress,
                ishuiyuanka: this.checked === '2',
                isjifen: this.checked === '1'
            };
            this.$post('/v1/client/FOrdersClient', form).then(data => {
                this.$showSuccessToast('提交成功');
                this.$navigate('/Pay?ordernum=' + data.data);
            }).catch(err => {
                this.$showFailToast(err.message);
            }).finally(() => {
                this.isloading = false;
            });
        },
    },
};
</script>

<style scoped>
.radio-group {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.way {
    display: flex;
    align-items: flex-start;
    padding: 2.53vw;
    /* border: 1px solid #eee; */
    border-radius: 8px;
    flex-direction: row !important;
    align-items: center;
}

/* .way.active {
    border-color: #ca2904;
    background: #fef8f7;
} */

.radio-icon {
    width: 20px;
    height: 20px;
    border: 1px solid #ccc;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
    color: #ca2904;
    font-size: 4.2vw;
}

.way.active .radio-icon {
    border-color: #ca2904;
}

.radio-content {
    flex: 1;
}

.line {
    display: flex;
    align-items: center;
    gap: 8px;
}

.line img {
    width: 3.33vw;
    height: 3.33vw;
}
</style>
