<template>
    <view class="container">
        <view class="header" :style="{ paddingTop: top + 'px', height: localHeight + 'px' }">
            <u-icon bold color="#000" size="40" name="arrow-left" @click="back"></u-icon>
        </view>

        <swiper class="swiper" autoplay>
            <swiper-item v-for="(item, pageIndex) in info.bigImg" :key="pageIndex">
                <image class="pic" :src="picUrl + item" mode="aspectFill" />
            </swiper-item>
        </swiper>

        <view class="swiper_boxshadow"></view>

        <view class="Tit">
            向 <span>{{ info.merchant_name }}</span> 付款
        </view>

        <view class="Msg">
            <view class="payMony">
                ￥<input type="digit" v-model="Money" placeholder="付款金额" placeholder-style="font-size: 50rpx;"
                    @blur="handleMoneyInput" step="0.01" min="0.01">
            </view>
            <view class="payRemark">
                <input type="text" v-model="remarks" placeholder="付款备注">
            </view>
        </view>

        <view class="Msg2">
            <view class="Msg2_tit">
                <view class="Msg2_tit_left">获得岁银</view>
                <!-- <view class="Msg2_tit_right" @click="choseComminty">
                    绑定房源
                    <u-icon name="arrow-right" color="#999999" size="28"></u-icon>
                </view> -->
            </view>

            <view class="Msg2_con">
                <view class="Msg2_con_left">
                    ￥ <span>
                        {{ homeMoney }}
                    </span>
                </view>
                <!-- <view class="Msg2_con_right">
                    {{ room_name }}
                </view> -->
            </view>
        </view>

        <view class="Msg3">
            <view class="Msg3_tit">获得积分</view>
            <view class="Msg3_con">
                {{ integral }}
            </view>
        </view>

        <view class="btn" @click="pay">确认支付</view>

        <view class="btnList">
            <view class="btnItem" @click="payList">付款记录</view>
            <!-- <view class="btnItem" @click="homeMoneList">岁银</view> -->
            <view class="line"></view>
            <view class="btnItem" @click="home">首页</view>
            <view class="line"></view>
            <view class="btnItem2" @click="changeBoxshadow">
                <image src="https://static.hshuishang.com/property-img-file/local_qrcode.png"
                    mode="aspectFill"></image>
                本页二维码
            </view>
        </view>


        <u-picker :show="show" :columns="[commintyList]" keyName="label" @confirm='confirm' @close='onClose'
            @cancel='onClose' closeOnClickOverlay></u-picker>

        <view class="boxshadow" @click="changeBoxshadow2" v-if="boxShow">
            <view class="boxshadow_con">
                <image :src="myCode" mode="aspectFill"></image>

            </view>
        </view>

    </view>
</template>

<script>
import {
    request,
    picUrl,
    uniqueByField,
    menuButtonInfo,
    NavgateTo
} from '../../../utils';

import {
    apiArr
} from '../../../api/v2local';

import { apiPay } from '../../../api/pay'

export default {
    data() {
        return {
            picUrl,
            top: "",
            localHeight: "",
            info: "",
            integral: 0,
            homeMoney: 0,
            Money: "",
            show: false,
            remarks: "",
            room_id: "",
            room_name: "",
            boxShow: false,
            commintyList: [],
            OrderMsg: "",
            payId: "",
            myCode: ""
        }
    },
    watch: {
        Money(newVal) {
            const homeMoney1 = newVal * (this.info.refund_property_fee_ratio || 0)
            this.homeMoney = homeMoney1.toFixed(2);
            const integral1 = newVal * (this.info.refund_user_points_ratio || 0)
            this.integral = integral1.toFixed(2);
        },

    },

    onLoad(options) {
        const meun = menuButtonInfo();
        this.top = meun.top;
        this.localHeight = meun.height;
        this.info = uni.getStorageSync("merchantInfo")
        this.getUserCommunityList()
    },


    methods: {

        handleMoneyInput() {
            // 清除非数字和非小数点的字符
            let value = this.Money.toString().replace(/[^\d.]/g, '');

            // 限制只能有一个小数点
            value = value.replace(/\.{2,}/g, '.');

            // 确保小数点后最多两位
            value = value.replace(/^(\d+)\.(\d{2}).*$/, '$1.$2');

            // 处理开头是小数点的情况
            if (value.startsWith('.')) {
                value = '0' + value;
            }

            // 处理大于0的验证
            const num = parseFloat(value);
            if (isNaN(num) || num <= 0) {
                value = '';
            }

            this.Money = value;
        },


        changeBoxshadow2() {
            this.boxShow = !this.boxShow
        },
        changeBoxshadow() {
            uni.showLoading({
                title: '加载中',
                mask: true
            });
            const params = {
                merchant_id: this.info.id,
            }
            request(apiPay.qrcode, "POST", params).then(res => {
                uni.hideLoading();
                if (res && res.qrcode_image_url) {
                    this.myCode = picUrl + res.qrcode_image_url;
                    this.boxShow = !this.boxShow;
                } else {
                    uni.showToast({
                        title: '获取二维码失败，请重试',
                        icon: 'none'
                    });
                }
            }).catch(err => {
                console.error('获取二维码失败:', err);
                uni.hideLoading();
                uni.showToast({
                    title: '获取二维码失败，请重试',
                    icon: 'none'
                });
            });
        },

        confirm(e) {
            console.log(e);
            this.room_id = e.value[0].room_id
            this.room_name = e.value[0].label
            this.show = false
        },
        onClose() {
            this.show = false
        },
        //选择房源
        choseComminty() {
            this.show = true
        },
        back() {
            NavgateTo("1")
        },
        getUserCommunityList() {
            request(apiArr.getUserCommunityList, "POST", {
                page_num: 1,
                page_size: 30,
            }).then(res => {
                res.rows.forEach(item => {
                    item.label = item.name
                })
                this.commintyList = res.rows
                if (res.rows.length) {
                    this.room_id = res.rows[0].room_id
                    this.room_name = res.rows[0].name
                }
            })
        },
        pay() {
            let that = this
            if (!that.Money) {
                return uni.showToast({
                    title: "请输入金额",
                    icon: "none"
                })
            }
            request(apiArr.createPay, "POST", {
                merchant_id: that.info.id,
                order_amount: Number((that.Money)), //金额
                refund_property_fee: that.homeMoney, //岁银
                refund_member_points: that.integral, //积分
                remark: that.remarks,
                room_id: that.room_id
            }).then(res => {
                that.payId = res.id
                that.getPayInfo(res.id)
            })
        },

        payList() {
            NavgateTo("../payInfo/index?id=" + this.info.id)
        },
        homeMoneList() {
            NavgateTo("../houseProvident/index")
        },
        home() {
            NavgateTo("/pages/index/index")
        },

        async getPayInfo(e) {
            let that = this
            await request(apiArr.getPayInfo, "POST", {
                id: e
            }).then(res => {
                console.log(res);
                this.OrderMsg = res
                that.LakaLaPrePay()
            })
        },

        async LakaLaPrePay() {
            let that = this
            request(apiArr.getPreOrderInfo, "POST", {
                id: that.payId,
            }).then(res => {
                if (res && res.timeStamp && res.nonceStr && res.package && res.signType && res.paySign) {
                    // 调用微信支付
                    uni.requestPayment({
                        timeStamp: res.timeStamp,
                        nonceStr: res.nonceStr,
                        package: res.package,
                        signType: res.signType,
                        paySign: res.paySign,
                        success: (payRes) => {
                            const params = {
                                id: this.OrderMsg.id,
                                back_wygjj: this.homeMoney,
                                back_points: this.integral,
                            }
                            request(apiArr.tradeQuery, "POST", params).then(res => {
                            })
                        },
                        fail: (payErr) => {
                            uni.showToast({
                                title: payErr.errMsg == 'requestPayment:fail cancel' ? '已取消支付' : '支付失败',
                                icon: 'none'
                            })
                            const params = {
                                order_ids: orderId,
                            }
                        },
                        complete: () => {
                            // 支付完成后的回调，无论成功失败都会执行
                        }
                    })
                } else {
                    console.error("获取支付参数失败，缺少必要参数")
                    uni.showToast({
                        title: '获取支付信息失败',
                        icon: 'none'
                    })
                }
            })
        },

        async queryPay(e) {
            await request(apiPay.queryPay, "POST", {
                merchant_no: e.merchant_no,
                term_no: e.trade_no,
                out_trade_no: e.out_trade_no
            }).then(res => {
                console.log(res);
            })
        },

    },


}
</script>

<style>
@import url("./index.css");
</style>
