<template>
    <view v-if="orderInfo">
        <scroll-view :scroll-y="true" @scroll="handleContentScroll">
            <!-- <u-navbar :placeholder="true" autoBack @click="autoBackFun">
                <view slot="center">
                    <view class="centerTitle" style="background-color: #fff;">{{ title }}</view>
                </view>
            </u-navbar> -->

            <view class="contentBox">
                <view class="remainingTime">
                    {{ orderStatus }}
                    <text v-if="orderInfo.orderStatus == 0 && countdownText != '00:00'">{{ countdownText }}</text>
                </view>
                <view class="content">
                    <view class="addressBox">
                        <image style="width: 40rpx;height: 40rpx;" src="@/static/points/addressIcon.png" mode="">
                        </image>
                        <view style="margin-left: 16rpx;">
                            <view class="name">
                                {{ orderInfo.receiverName }} <text>{{ orderInfo.receiverPhone }}</text>
                            </view>
                            <view class="address">
                                {{ orderInfo.addressName }}
                            </view>
                        </view>

                    </view>

                    <view class="productPrice">
                        <view style="display:flex;">
                            <view>
                                <image style="width: 120rpx;height: 120rpx;"
                                    :src="$globalData.publicUrl + productInfo.skuImage" mode="">
                                </image>
                            </view>
                            <view
                                style="margin-left: 24rpx;display: flex;flex-direction: column;justify-content: space-between;">
                                <view class="productName">{{ productInfo.productName }} </view>
                                <view class="spec">已选:{{ skuSpecFun(productInfo.skuSpec) }} </view>
                                <view class="price">{{ productInfo.paymentType == 1 ? orderInfo.pointsUsed + '积分' :
                                    productInfo.paymentType == 2 ? '￥' + orderInfo.payAmount + '元' :
                                        productInfo.paymentType == 3 ? '￥' + orderInfo.payAmount + '元' + '+' +
                                            orderInfo.pointsUsed + '积分' : null }}</view>

                            </view>
                        </view>
                        <view class="productPrice1">
                            <view class="text">商品金额</view>
                            <view class="price">{{ productInfo.paymentType == 1 ? orderInfo.pointsUsed + '积分' :
                                productInfo.paymentType == 2 ? '￥' + orderInfo.payAmount + '元' :
                                    productInfo.paymentType == 3 ? '￥' + orderInfo.payAmount + '元' + '+' +
                                        orderInfo.pointsUsed + '积分' : null }}</view>
                        </view>
                        <view class="shippingFee">
                            <view class="text">运费</view>
                            <view class="text">￥{{ orderInfo.freightAmount }}</view>
                        </view>
                        <view style="height: 2rpx;background-color: #f0f0f0;margin-top: 20rpx;"> </view>
                        <view class="total">
                            <text class="text">合计：</text>
                            <text class="price">¥ {{
                                (orderInfo.payAmount + (orderInfo.freightAmount > 0 ? orderInfo.freightAmount : 0))
                                }}</text>
                        </view>
                    </view>
                    <view class="weiChect" v-if="productInfo.paymentType !== 1 || orderInfo.freightAmount>0">
                        <view style="display: flex;">
                            <image v-if="orderInfo.payType == '1'" style="width: 40rpx;height: 40rpx;"
                                src="@/static/points/weiXin.png" mode="">
                            </image>
                            <image v-if="orderInfo.payType == '2'" style="width: 40rpx;height: 40rpx;"
                                src="@/static/points/yue.png" mode="">
                            </image>
                            <view class="text" style="color: #333;margin-left: 16rpx;">{{ orderInfo.payType == '1' ?
                                '微信支付' :
                                '余额支付' }}
                            </view>

                        </view>
                        <view>
                            <u-radio-group v-model="orderInfo.payType">
                                <u-radio activeColor="#03C1B8 " :name=orderInfo.payType style="margin: 0;"></u-radio>
                            </u-radio-group>
                        </view>
                    </view>
                    <view class="orderInfo">
                        <view class="item">
                            <view class="text">订单编号</view>
                            <view class="text1">{{ orderInfo.orderNo }}</view>
                        </view>
                        <view class="item">
                            <view class="text">下单时间</view>
                            <view class="text1">{{ orderInfo.createTime }}</view>
                        </view>
                        <view class="item">
                            <view class="text">支付方式</view>
                            <view class="text1">{{ orderInfo.payType == 1 ? '微信' : '余额' }}</view>
                        </view>
                        <view class="item">
                            <view class="text">订单备注</view>
                            <view class="text1">{{ orderInfo.buyerRemark ? orderInfo.buyerRemark : '无' }}</view>
                        </view>

                    </view>


                </view>
            </view>
            <view class="buttonClass">

                <u-button v-if="orderInfo.orderStatus == 0" :customStyle="{
                    color: '#999',
                    background: '',
                    height:'52rpx',
                    lineHeight: '52rpx',
                    border: '2rpx solid rgba(153, 153, 153, 1)'
                }" @click="cancelOrderFun">取消支付</u-button>

                <u-button :disabled="goPayBtnDisable" v-if="orderInfo.orderStatus == 0" :customStyle="{
                    color: '#fff ',
                    background: '#03C1B8'
                }" @click="goPay">去付款</u-button>
                <u-button v-if="orderInfo.orderStatus == 11" :customStyle="{
                    color: '#fff ',
                    background: '#03C1B8'
                }" @click="buyAgain">再次购买</u-button>


            </view>

        </scroll-view>


        <!-- 取消订单 <u-line></u-line>-->
        <u-popup :show="cancelOrderShowPopup" mode="bottom" round="10">
            <view class="popup-con">
                <!-- 标题 -->
                <view class="popup-text">
                    <text class="title">取消订单</text>
                    <text @click="cancelOrderShowPopup = false">取消</text>
                </view>
                <!-- 项目列表 -->
                <view class="refund-items">
                    <view class="reason">请选择退款原因</view>
                    <u-radio-group v-model="selectReason">
                        <view style="padding: 0 20rpx 24rpx 20rpx;width: 100%;">
                            <view class="radioBox" v-for="(item,index) in selectReasonList" :key="index" @click="groupChange(item.value)">
                                <u-radio activeColor="#03C1B8 " :name=item.value></u-radio>{{ item.text }}
                            </view>
                        </view>
                    </u-radio-group>

                </view>
                <view class="popupButtonClass">
                    <u-button :customStyle="{
                        color: selectReason ? '#fff' : '#999',
                        background: selectReason ? '#03C1B8' : '#eee'
                    }" @click="cancelOrderSubmit">{{ selectReason ? '提交' : '请先选择原因' }}</u-button>

                </view>
            </view>



        </u-popup>

    </view>

</template>

<script>
import wx from 'weixin-js-sdk';
import { h5Url } from '@/common/config.js';
import { getPointOrderInfo, productOrderCancel, productOrderPay } from '@/api/pointOrder'
import { getInfo, getSignature } from '@/api/index.js';

//paymentType 商品的付款类型 付款类型（1：积分 2：金额 3：积分+金额）

//订单状态(0：待付款 1：待发货 2：待收货 3：已收货 4：售后中  11：取消订单)

//售后状态(0:待审核 1：退款完成 2:等待用户寄回  3:等待商家收货 4:等待商家寄出  5:订单完成 6:取消售后)

export default {
    components: {},
    data() {
        return {
            selectReason: '',
            selectReasonValue: '',
            cancelOrderShowPopup: false,
            countdownText: '',
            orderStatus: '', //超时未支付
            selectReasonList: [
                { value: '1', text: '买错了/不想要' },
                { value: '2', text: '商品无货' },
                { value: '3', text: '商品信息填写错误' },
                { value: '4', text: '地址信息填写错误' },
                { value: '5', text: '其他原因' },
            ],
            dBalance: 0.00,
            timer: null, // 定时器
            orderNo: '',
            orderInfo: null,
            productInfo: null,
            wxconfig: {},
            goPayBtnDisable: false
        }
    },
    onLoad(data) {
        if (data.orderNo) {
            this.orderNo = data.orderNo
        }
    },
    onShow() {
        this.getOrderInfo();
    },
    onPageScroll() {
    },
    async mounted() {

    },

    methods: {
        //规则组装
        skuSpecFun(skuSpec) {
            if (!skuSpec) return ''
            return JSON.parse(skuSpec).map(e => e.specValue).join(',')

        },
        //获取订单详情
        async getOrderInfo() {
            const res = await getPointOrderInfo({
                orderNo: this.orderNo,
                //openId: uni.getStorageSync('wx_copenid')
            })
            this.orderInfo = res.data.data.orderInfo
            this.productInfo = res.data.data.productInfo
            //this.orderInfo.remainSeconds = 30
            if (this.orderInfo.remainSeconds > 0 && this.orderInfo.orderStatus == 0) {
                this.orderCountdownFun(this.orderInfo.remainSeconds)
                this.orderStatus = '剩余时间'
                uni.setNavigationBarTitle({
                    title: '待支付'
                });
            } else if (this.orderInfo.remainSeconds < 0 && this.orderInfo.orderStatus == 0) {
                this.orderStatus = '超时未支付'
                uni.setNavigationBarTitle({
                    title: '订单取消'
                });
            } else if (this.orderInfo.orderStatus == 11) {
                this.orderStatus = '您已取消支付'
                uni.setNavigationBarTitle({
                    title: '订单取消'
                });
            }

        },
        //订单倒计时
        orderCountdownFun(remain) {
            this.timer = setInterval(() => {
                remain--;
                this.countdownText = this.formatTime(remain);
                if (remain <= 0) {
                    clearInterval(this.timer);
                    this.getOrderInfo()
                    this.cancelOrderShowPopup = false
                }
            }, 1000);
        },
        // 时间格式化：秒 → mm:ss（00:00）
        formatTime(seconds) {
            if (seconds <= 0) return '00:00';
            const m = Math.floor(seconds / 60).toString().padStart(2, '0');
            const s = (seconds % 60).toString().padStart(2, '0');
            return `${m}:${s}`;
        },

        //去付款
        goPay() {
            this.goPayBtnDisable = true
            if (this.productInfo.paymentType == 1 && this.orderInfo.freightAmount==0) {//只有积分兑换
                this.productOrderCreateFun()
                return
            }
            if (this.orderInfo.payType == 1) {
                //微信支付
                this.weixinPay()
            } else if (this.orderInfo.payType == 2) {
                //余额支付
                this.nowYuyue()
            }

        },
        //支付api
        async productOrderPayFun() {
            let res1 = await productOrderPay({
                orderNo: this.orderInfo.orderNo, //订单编号
                payType: this.productInfo.paymentType == 1 ? 3 : this.orderInfo.payType, //支付方式:1微信支付 2:余额支付
                totalPrice: this.orderInfo.totalAmount //订单总金额，单位：元
            })
            if (res1.data.code == 200) {
                return res1.data
            } else {
                this.goPayBtnDisable = false
                uni.showToast({
                    title: res1.data.msg,
                    icon: 'none'
                })
            }

        },
        //微信支付
        async weixinPay() {
            let data = await this.productOrderPayFun()
            if (!data) return
            let payConfig = JSON.parse(data.data)
            getSignature(h5Url).then(res => {
                this.wxconfig = res.data
                wx.config({
                    beta: true,
                    debug: false,
                    appId: this.wxconfig.appId, // 公众号ID
                    // appId: uni.getAppBaseInfo().host.appId, // 公众号ID
                    timestamp: this.wxconfig.timestamp, // 时间戳，自1970年以来的秒数
                    nonceStr: this.wxconfig.nonceStr, // 随机串
                    signature: this.wxconfig.signature, // 微信签名方式
                    jsApiList: ['getBrandWCPayRequest']
                });
                var vm = this
                wx.invoke('getBrandWCPayRequest',
                    // 下面参数内容都是后台返回的
                    {
                        'appId': payConfig.appId, // 公众号名称，由商户传入
                        'timeStamp': payConfig.timeStamp, // 时间戳
                        'nonceStr': payConfig.nonceStr, // 随机串
                        'package': payConfig.package, // 预支付id
                        'signType': payConfig.signType, // 微信签名方式
                        'paySign': payConfig.paySign, // 微信签名
                    },
                    function (res) {
                        // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                        vm.goPayBtnDisable = false
                        // JSON.stringify(res);
                        if (res.err_msg == "get_brand_wcpay_request:ok") {

                            uni.navigateTo({
                                url: '/points/productDetails/paymentSuccessful?orderNo=' + vm.orderNo
                            });
                        } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                            uni.showToast({
                                title: '已取消支付',
                                icon: 'none'
                            })

                        } else {
                            alert('付款失败');
                        }
                    }
                )

            }).catch(err => {
                this.goPayBtnDisable = false
                uni.showToast({
                    title: err,
                    icon: 'none'
                })
            })
        },
        //账号余额支付
        async nowYuyue() {
            if (parseFloat(this.dBalance) < parseFloat(this.orderInfo.totalAmount)) {
                uni.showModal({
                    title: '账户余额不足',
                    content: '请充值',
                    success: function (res) {
                        if (res.confirm) {
                            uni.navigateTo({
                                url: '../../pages/my/pay?name=充值'
                            })
                        } else if (res.cancel) { }
                    }
                });
                this.goPayBtnDisable = false
            } else {
                let data = await this.productOrderPayFun()
                if (!data) return
                this.goPayBtnDisable = false
                uni.navigateTo({
                    url: '/points/productDetails/paymentSuccessful?orderNo=' + this.orderNo
                });

            }
        },
        //查询账户余额
        getinfo() {
            getInfo().then(res => {
                if (res.data.code == 200) {
                    this.dBalance = res.data.data.dBalance.toFixed(2)
                }
            })
        },
        //取消订单提交按钮
        cancelOrderSubmit() {
            let params = {
                //openId: uni.getStorageSync('wx_copenid'),
                orderNo: this.orderNo,
                cancelReason: this.selectReasonValue,
            }
            productOrderCancel(params).then(res => {
                if (res.data.code == 200) {
                    clearInterval(this.timer);
                    this.cancelOrderShowPopup = false
                    this.getOrderInfo();
                } else {
                    //alert(res.data.msg)
                    uni.showToast({
                        title: res.data.msg,
                        icon: 'none'
                    })
                }

            })
        },
        //点击单选按钮
        groupChange(val) {
            this.selectReason = val
            this.selectReasonList.forEach(item => {
                if (item.value == val) {
                    this.selectReasonValue = item.text
                }

            });
        },
        //关闭取消订单选择页
        closeCancelOrderFun() {
            this.cancelOrderShowPopup = false
        },
        //取消订单按钮
        cancelOrderFun() {
            this.cancelOrderShowPopup = true
        },
        //再次购买
        buyAgain() {
            uni.navigateTo({
                url: `/points/productDetails/index?id=${this.productInfo.productId}`
            });
        }

    }
}
</script>

<style lang="scss" scoped>
.centerTitle {
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 34rpx;
    color: #060606;
    text-align: center;
    font-style: normal;
    text-transform: none;
}



.buttonClass {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    font-family: PingFang SC, PingFang SC;
    margin-top: 20rpx;

    button {
        width: 168rpx;
        display: flex;
        align-items: center;
        height: 56rpx;
        line-height: 56rpx;
        border-radius: 98rpx 98rpx 98rpx 98rpx;
        font-size: 26rpx;
        //padding: 5rpx 0 5rpx 0;
        margin: 0 32rpx 0 0;
    }
}

.contentBox {
    background-image: url("@/static/points/orderBg.png");
    background-size: 100%;
    background-repeat: no-repeat;
    background-color: #F5F8F8;
    padding-top: 54rpx;

    .remainingTime {
        font-weight: 500;
        font-size: 32rpx;
        color: #FFFFFF;
        line-height: 40rpx;
        text-align: left;
        font-style: normal;
        text-transform: none;
        text-align: center;
    }

}

.content {
    padding: 24rpx 32rpx 30rpx 32rpx;
    font-family: PingFang SC, PingFang SC;
    border-radius: 20rpx 20rpx 0 0;

    .addressBox {
        margin-top: 30rpx;
        padding: 24rpx 32rpx;
        display: flex;
        align-items: flex-start;
        background: #FFFFFF;
        border-radius: 20rpx 20rpx 20rpx 20rpx;

        .name {
            font-weight: 500;
            font-size: 32rpx;
            color: #333333;
            line-height: 40rpx;
            text-align: left;
            font-style: normal;
            text-transform: none;

        }

        .address {
            margin-top: 8rpx;
            font-weight: 500;
            font-size: 28rpx;
            color: #666666;
            line-height: 40rpx;
            text-align: left;
            font-style: normal;
            text-transform: none;
        }

    }

    .productPrice {
        background-color: #fff;
        margin-top: 24rpx;
        padding: 24rpx;
        border-radius: 20rpx 20rpx 20rpx 20rpx;

        .productName {
            font-weight: bold;
            font-size: 28rpx;
            color: #333333;
            text-align: left;
            font-style: normal;
            text-transform: none;
        }

        .price {
            font-weight: bold;
            font-size: 26rpx;
            color: #333333;
            text-align: left;
            font-style: normal;
            text-transform: none;
        }

        .spec {
            font-weight: 500;
            font-size: 26rpx;
            color: #999999;
            text-align: left;
            font-style: normal;
            text-transform: none;

        }

        .shippingFee {
            margin-top: 22rpx;
            display: flex;
            justify-content: space-between;

            .text {
                font-weight: 500;
                font-size: 26rpx;
                color: #666666;
                text-align: left;
                font-style: normal;
                text-transform: none;

            }

            .price {
                font-weight: 500;
                font-size: 28rpx;
                color: #03C1B8;
                text-align: left;
                font-style: normal;
                text-transform: none;
            }
        }

        .productPrice1 {
            margin-top: 16rpx;
            display: flex;
            justify-content: space-between;

            .text {
                font-weight: 500;
                font-size: 26rpx;
                color: #666666;
                text-align: left;
                font-style: normal;
                text-transform: none;

            }

            .price {
                font-weight: 500;
                font-size: 28rpx;
                color: #03C1B8;
                text-align: left;
                font-style: normal;
                text-transform: none;
            }
        }

        .total {
            text-align: right;

            .text {
                font-weight: 400;
                font-size: 28rpx;
                color: #2F3437;
                text-align: left;
                font-style: normal;
                text-transform: none;

            }

            .price {
                font-weight: 800;
                font-size: 28rpx;
                color: #03C1B8;
                text-align: left;
                font-style: normal;
                text-transform: none;
            }

        }
    }

    .weiChect {
        height: 94rpx;
        background: #FFFFFF;
        border-radius: 20rpx 20rpx 20rpx 20rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: 500;
        font-size: 28rpx;
        color: #333333;
        line-height: 40rpx;
        text-align: left;
        font-style: normal;
        text-transform: none;
        margin: 24rpx 0;
        padding: 0 24rpx;

    }

    .orderInfo {
        height: 268rpx;
        background: #FFFFFF;
        border-radius: 16rpx 16rpx 16rpx 16rpx;
        padding: 26rpx 24rpx 0 24rpx;

        .item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 24rpx;
        }

        .text {
            font-weight: 400;
            font-size: 26rpx;
            color: #666666;
            text-align: left;
            font-style: normal;
            text-transform: none;

        }

        .text1 {
            font-weight: 500;
            font-size: 28rpx;
            color: #2F3437;
            text-align: left;
            font-style: normal;
            text-transform: none;

        }

    }


}

.popup-con {
    font-size: 27rpx;
    color: #666666;
    background: #F5F8F8;
    padding: 40rpx;
    border-radius: 20rpx 20rpx 0 0;

    .popup-text {
        font-weight: bold;
        font-size: 40rpx;
        color: #333333;
        text-align: center;
        font-style: normal;
        text-transform: none;
        display: flex;
        justify-content: space-between;
        position: relative;

        .title {
            padding-bottom: 10rpx;
            background-image: url("@/static/points/cancelOrderBg.png");
            background-size: 100%;
            background-repeat: no-repeat;
            background-position: center bottom;
            /* 水平居中、垂直靠下 */
        }

        text:last-of-type {
            font-weight: 400;
            font-size: 28rpx;
            color: #999999;
            text-align: center;
            font-style: normal;
            text-transform: none;
            // width: 38rpx;
            // height: 38rpx;
            // text-align: center;
            // line-height: 38rpx;
            // color: #6D728B;
            // background: #DEDEDE;
            // border-radius: 50%;
            // position: absolute;
            // right: 24rpx;
            // font-size: 28rpx;
        }
    }

    .refund-items {
        margin-top: 32rpx;
        font-size: 26rpx;
        color: #333333;
        padding-bottom: 70rpx;
        background: #FFFFFF;
        border-radius: 20rpx 20rpx 20rpx 20rpx;

        height: 400rpx;
        background: #FFFFFF;
        border-radius: 20rpx 20rpx 20rpx 20rpx;

        .reason {
            background: #E8FFFD;
            border-radius: 20rpx 20rpx 0rpx 0rpx;
            font-weight: bold;
            font-size: 28rpx;
            color: #333333;
            text-align: left;
            font-style: normal;
            text-transform: none;
            padding: 16rpx 20rpx;
        }

        .radioBox {
            display: flex;
            width: 100%;
            margin-top: 24rpx;
        }


    }

    .popupButtonClass {
        margin-top: 32rpx;
        height: 84rpx;
        border-radius: 98rpx 98rpx 98rpx 98rpx;

        button {
            align-items: center;
            border-radius: 98rpx 98rpx 98rpx 98rpx;
            font-size: 32rpx;
            font-weight: 500;
        }
    }
}
</style>
