<template>
    <ion-page ref="page">
        <ion-header>
            <ion-toolbar>
                <ion-buttons slot="start">
                    <ion-back-button text="" default-href="#" @click="$router.back(-1)"></ion-back-button>
                </ion-buttons>
                <ion-title>{{ $t('order.detail') }}</ion-title>
            </ion-toolbar>
        </ion-header>
        <ion-content :fullscreen="true">
            <div class="top-bg">
                <div class="mask"></div>
            </div>
            <div class="top">
                <div class="status">
                    <ion-icon :icon="icons.walletOutline" v-if="orderInfo.status == 'NOT_PAID'"></ion-icon>
                    <ion-icon :icon="icons.closeCircleOutline" v-if="orderInfo.status == 'CANCELED'"></ion-icon>
                    <ion-icon :icon="icons.albumsOutline" v-if="orderInfo.status == 'CONFIRMED'"></ion-icon>
                    <ion-icon :icon="icons.timeOutline" v-if="orderInfo.status == 'SELLING'"></ion-icon>
                    <ion-icon :icon="icons.walletOutline" v-if="orderInfo.status == 'SOLD_NOT_PAID'"></ion-icon>
                    <ion-icon :icon="icons.checkmarkCircleOutline" v-if="orderInfo.status == 'SOLD'"></ion-icon>
                    <div class="status" v-if="orderInfo.status">
                        {{ $t('order.status.' + orderInfo.status) }}
                    </div>
                </div>
                <div class="status-desc" v-if="orderInfo.status">
                    {{ $t('order.statusDesc.' + orderInfo.status) }}
                </div>
            </div>

            <div class="product">
                <div class="product-content">
                    <van-image class="suk-img" style="min-width: 80px" width="80" height="80" fit="fill" :src="pic" />

                    <div class="order-text">
                        <div class="van-ellipsis text1">{{ productInfo.name }}</div>

                        <div class="text2" v-if="productInfo.user">当前所有人为：{{ productInfo.user.nickname }}</div>

                        <div class="text3">
                            <div class="price">¥{{ orderInfo.totalPrice }}</div>
                            <div class="num">×1</div>
                        </div>
                    </div>
                </div>
                <div class="divider"></div>
                <div class="order-info">
                    <div class="name">{{ $t('product.dailyEarning') }}</div>
                    <div class="val">3%</div>
                </div>
                <div class="order-info">
                    <div class="name">{{ $t('product.dailyEarning') }}</div>
                    <div class="val">0.3</div>
                </div>
                <!-- <div class="order-info">
        <div class="name">订单留言</div>
        <div class="val">麻烦尽快发货，谢谢</div>
      </div> -->
            </div>

            <div class="order-detail">
                <div class="detail-item">
                    <div class="name">{{ $t('order.payMethod') }}</div>
                    <div class="val">
                        {{
                            orderInfo.status === 'NOT_PAID'
                                ? $t('order.status.' + orderInfo.status)
                                : $t('order.payMethodName.balance')
                        }}
                    </div>
                </div>

                <div class="time-content">
                    <div class="detail-item">
                        <div class="name">订单编号</div>
                        <div class="val">{{ orderInfo.id }}</div>
                    </div>
                    <div class="detail-item">
                        <div class="name">创建时间</div>
                        <div class="val">{{ orderInfo.createdAt }}</div>
                    </div>
                    <div class="detail-item" v-if="orderInfo.paidTime">
                        <div class="name">付款时间</div>
                        <div class="val">{{ orderInfo.paidTime }}</div>
                    </div>
                </div>
            </div>
            <ion-modal id="delegate" ref="modal" :is-open="show" @didDismiss="show = false">
                <div v-if="show" class="getsold">
                    <div class="title">{{ $t('delegate.title') }}</div>
                    <div class="sold-list">
                        <div class="sold-item">
                            <div class="name">原价</div>
                            <div class="val">¥{{ orderInfo.totalPrice }}</div>
                        </div>
                        <div class="sold-item">
                            <div class="name">加价</div>
                            <van-stepper
                                v-model="value"
                                input-width="60px"
                                step="1"
                                integer
                                min="1"
                                :max="maxRiseRate"
                            />
                        </div>
                        <div class="sold-item">
                            <div class="name">卖价</div>
                            <div class="val bold">¥{{ soldValue }}</div>
                        </div>
                    </div>
                    <div class="tips">
                        注：委托平台代卖服务，每次最高可将商品价格提高{{ maxRiseRate }}%，平台会收取{{
                            serviceValue
                        }}%的托管服务费用
                    </div>

                    <van-button class="button" :disabled="loading" block type="primary" @click="sale">
                        支付手续费 ¥{{ serviceCharge }}
                    </van-button>
                </div>
            </ion-modal>
        </ion-content>
        <ion-footer v-if="orderInfo.status == 'NOT_PAID' || orderInfo.status == 'CONFIRMED'">
            <div class="bottom">
                <div>
                    <div class="order-button" v-if="orderInfo.status == 'NOT_PAID'">
                        <span class="price">
                            <span class="label">{{ $t('order.totalPayment') }}</span>
                            <span class="gt sym"> {{ $t('balance.symbol') }}</span>
                            <span class="gt num">
                                {{ orderInfo.totalPrice ? orderInfo.totalPrice.toFixed(2) : '' }}</span
                            >
                        </span>
                        <van-button class="btn-pay" type="primary" @click="pay" style="width: 150px">{{
                            $t('order.payNow')
                        }}</van-button>
                    </div>

                    <div class="order-button" v-else-if="orderInfo.status == 'CONFIRMED'">
                        <!-- <van-button color="#AAACAD" round plain @click="applyShip">申请发货</van-button> -->
                        <van-button type="primary" class="full" @click="show = true" v-if="delegationActive">
                            {{ $t('delegate.title') }}
                        </van-button>
                        <van-button color="#aaacad" class="full" @click="showTip" v-else
                            >{{ $t('delegate.title') }}
                        </van-button>
                    </div>
                </div>
            </div>
        </ion-footer>
    </ion-page>
</template>
<script>
import { mapState } from 'pinia'
import { useUserStore } from '@/stores/user'
import { orderStatus } from '../status'
import { parse } from 'date-fns'
import { timeOutline, walletOutline, albumsOutline, closeCircleOutline, checkmarkCircleOutline } from 'ionicons/icons'
export default {
    name: 'orderDetail',
    data() {
        return {
            orderStatus,
            orderInfo: {},
            productInfo: {},
            fromUser: {},
            show: false,
            value: 6,
            platformCommission: 0.02,
            delegationActive: '',
            delegationTime: '',
            maxRiseRate: 6,
            loading: false,
            payType: 'balance',
            icons: {
                timeOutline,
                walletOutline,
                albumsOutline,
                closeCircleOutline,
                checkmarkCircleOutline
            },
            presentingElement: null
        }
    },
    mounted() {
        this.presentingElement = this.$refs.page.$el
    },
    computed: {
        ...mapState(useUserStore, ['user']),
        pic() {
            if (this.productInfo.pic && this.productInfo.pic.length > 0) {
                return this.productInfo.pic[0]
            } else {
                return null
            }
        },
        soldValue() {
            var price = Number(this.orderInfo.totalPrice)
            if (this.value) {
                var more = this.mul(this.value, price)
                more = this.mul(more, 0.01)
                price = this.addNum(more, price)
            }
            return price.toFixed(2)
        },
        serviceCharge() {
            let totalPrice = this.orderInfo ? this.orderInfo.totalPrice || 0 : 0
            return (totalPrice * this.platformCommission).toFixed(2)
        },
        serviceValue() {
            return this.platformCommission * 100
        }
    },
    created() {
        this.$http
            .get('/order/get/' + this.$route.query.id)
            .then(res => {
                this.orderInfo = { ...res }
                if (res.productId) {
                    return this.$http.get('/product/get/' + res.productId)
                }
            })
            .then(res => {
                this.productInfo = res
                if (this.orderInfo.fromUserId) {
                    return this.$http.get('/user/get/' + this.orderInfo.fromUserId)
                }
            })
            .then(res => {
                this.fromUser = res
            })
        this.$http.get('/sysConfig/get/platform_commission').then(res => {
            this.platformCommission = res.value
        })
        this.$http.get('/sysConfig/get/max_rise_rate').then(res => {
            this.maxRiseRate = res.value * 100
            this.value = this.maxRiseRate
        })
        this.$http.get('/sysConfig/get/delegation_time').then(res => {
            var date = parse(res.value, 'HH:mm', new Date())
            this.$http.get('/sysConfig/get/sell_time').then(res => {
                var date2 = parse(res.value, 'HH:mm', new Date())
                if (new Date().getTime() >= date.getTime() || new Date().getTime() <= date2.getTime()) {
                    this.delegationActive = true
                    this.delegationTime = res.value
                }
            })
        })
        // this.$http.get('/sysConfig/get/pay_type').then(res => {
        //     if (res.value == '0') {
        //         if (this.isWeixin) {
        //             this.payType = 'weixin';
        //         } else {
        //             this.payType = 'alipay';
        //         }
        //     } else {
        //         this.payType = 'third';
        //     }
        // });
    },
    methods: {
        showTip() {
            this.$dialog.alert({
                title: '提示',
                message: '委托代卖暂未开始，将在今天' + this.delegationTime + '开始'
            })
        },
        getInfo() {
            this.$http.get('/order/get/' + this.$route.query.id).then(res => {
                this.orderInfo = res
            })
        },
        addNum(a, b) {
            var c, d, e
            try {
                c = a.toString().split('.')[1].length
            } catch (f) {
                c = 0
            }
            try {
                d = b.toString().split('.')[1].length
            } catch (f) {
                d = 0
            }
            return (e = Math.pow(10, Math.max(c, d))), (this.mul(a, e) + this.mul(b, e)) / e
        },
        mul(a, b) {
            var c = 0,
                d = a.toString(),
                e = b.toString()
            try {
                c += d.split('.')[1].length
            } catch (f) {
                /* empty */
            }
            try {
                c += e.split('.')[1].length
            } catch (f) {
                /* empty */
            }
            return (Number(d.replace('.', '')) * Number(e.replace('.', ''))) / Math.pow(10, c)
        },
        confirmPayment() {
            this.$toast.loading({
                mask: false,
                message: '加载中...',
                duration: 0,
                forbidClick: true
            })
            this.$http
                .post('/order/confirmPayment', {
                    orderId: this.orderInfo.id
                })
                .then(res => {
                    this.$toast.success('确认成功')
                    setTimeout(() => {
                        this.getInfo()
                    }, 1000)
                })
                .catch(e => {
                    return this.$toast.error(e.error)
                })
        },
        confirmReceipt() {
            this.$toast.loading({
                mask: false,
                message: '加载中...',
                duration: 0,
                forbidClick: true
            })
            this.$http
                .post('/order/confirmReceipt', {
                    orderId: this.orderInfo.id
                })
                .then(res => {
                    this.$toast.success('确认成功')
                    setTimeout(() => {
                        this.getInfo()
                    }, 1000)
                })
                .catch(e => {
                    return this.$toast.error(e.error)
                })
        },
        sale() {
            this.show = false
            if (this.payType === 'alipay') {
                window.open(
                    this.$baseUrl +
                        `/payDelegation/alipay?userId=${this.user.id}&orderId=${this.orderInfo.id}&riseRate=${
                            this.value / 100
                        }&returnUrl=${encodeURIComponent(location.href)}`
                )
            } else if (this.payType === 'third') {
                console.log(
                    this.$baseUrl +
                        `/payDelegation/third?userId=${this.user.id}&orderId=${this.orderInfo.id}&riseRate=${
                            this.value / 100
                        }&&payType=` +
                        (this.isWeixin ? 'WXGZH' : 'ZFBH5')
                )
                window.open(
                    this.$baseUrl +
                        `/payDelegation/third?userId=${this.user.id}&orderId=${this.orderInfo.id}&riseRate=${
                            this.value / 100
                        }&&payType=` +
                        (this.isWeixin ? 'WXGZH' : 'ZFBH5')
                )
            } else if (this.payType === 'weixin') {
                this.loading = true
                this.$toast.loading({
                    mask: false,
                    message: '加载中...',
                    duration: 0,
                    forbidClick: true
                })
                this.$http
                    .get('/payDelegation/wx', {
                        userId: this.user.id,
                        orderId: this.orderInfo.id,
                        riseRate: this.value / 100
                    })
                    .then(res => {
                        this.$toast.dismiss()
                        this.loading = false
                        wx.chooseWXPay({
                            appId: res.appId,
                            timestamp: res.timeStamp,
                            nonceStr: res.nonceStr,
                            package: res.packageValue,
                            signType: res.signType,
                            paySign: res.paySign,
                            success(res) {
                                this.$toast.success('支付成功')
                            }
                        })
                    })
                    .catch(e => {
                        this.$toast.dismiss()
                        this.loading = false
                        return this.$toast.error(e.error)
                    })
            } else if (this.payType === 'balance') {
                this.$toast.loading('支付中')
                this.$http
                    .post('/payDelegation/balance', {
                        userId: this.user.id,
                        orderId: this.orderInfo.id,
                        riseRate: this.value / 100
                    })
                    .then(res => {
                        this.$toast.success('支付成功')
                        this.getInfo()
                    })
                    .catch(e => {
                        this.$toast.error(e.error)
                    })
            }
        },
        applyShip() {
            this.$dialog
                .confirm({
                    title: '提示',
                    message: '确认申请发货？'
                })
                .then(() => {
                    this.$toast.loading({
                        mask: false,
                        message: '加载中...',
                        duration: 0,
                        forbidClick: true
                    })
                    this.$http
                        .post('/order/applyShip', {
                            orderId: this.orderInfo.id
                        })
                        .then(res => {
                            this.$toast.success('申请成功')
                            setTimeout(() => {
                                this.getInfo()
                            }, 1000)
                        })
                        .catch(e => {
                            return this.$toast.error(e.error)
                        })
                })
                .catch(() => {})
        },
        receive() {
            this.$toast.loading({
                mask: false,
                message: '加载中...',
                duration: 0,
                forbidClick: true
            })
            this.$http
                .post('/order/receive', {
                    orderId: this.orderInfo.id
                })
                .then(res => {
                    this.$toast.success('确认成功')
                    setTimeout(() => {
                        this.getInfo()
                    }, 1000)
                })
                .catch(e => {
                    return this.$toast.error(e.error)
                })
        },
        pay() {
            this.$toast.loading('支付中')
            this.$http
                .post('/order/balancePay', { orderId: this.orderInfo.id })
                .then(res => {
                    this.$toast.success('支付成功')
                    setTimeout(() => {
                        this.getInfo()
                    }, 1000)
                })
                .catch(e => {
                    this.$toast.error(e.error)
                })
        }
    }
}
</script>
<style lang="less" scoped>
.top-bg {
    height: 206px;
    background: linear-gradient(135deg, #d700ff 0%, #3e22ff 100%);
    z-index: 0;
    position: absolute;
    left: 0;
    right: 0;
    .mask {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 110px;
        background: linear-gradient(360deg, var(--ion-background-color) 0%, rgba(var(--ion-color-light-contrast-rgb), 0) 100%);
    }
}
.top {
    position: relative;
    z-index: 1;
    padding: 22px 16px 0 16px;
    color: var(--ion-color-dark-contrast);
    min-height: 76px;
    .status {
        .f();
        height: 24px;
        line-height: 24px;
        font-size: 18px;
        ion-icon {
            font-size: 24px;
            margin-right: 6px;
        }
    }
    .status-desc {
        margin-top: 6px;
        font-size: 14px;
        height: 24px;
        line-height: 24px;
    }
}
.addresss {
    background: rgba(255, 255, 255, 1);
    border-radius: 2px;
    margin: 15px 15px 0;
    display: flex;
    padding: 15px;
    img {
        width: 22px;
        height: 22px;
        margin-top: 5px;
    }

    .addresss-content {
        font-size: 14px;
        color: rgba(var(--ion-color-light-contrast-rgb), 1);
        line-height: 20px;
        margin-left: 10px;
    }
}

.product {
    position: relative;
    z-index: 1;
    background: rgba(255, 255, 255, 1);
    border-radius: 2px;
    margin: 20px 15px 0;
    padding: 15px;

    .product-content {
        display: flex;

        .order-text {
            margin-left: 10px;
            flex-grow: 1;
            flex-basis: 0;
            min-width: 0;
            .text1 {
                font-size: 14px;
                color: rgba(var(--ion-color-light-contrast-rgb), 1);
                line-height: 20px;
                text-overflow: ellipsis;
                white-space: nowrap;
                overflow: hidden;
            }

            .text2 {
                font-size: 12px;
                line-height: 22px;
                height: 22px;
                background: var(--ion-color-step-50);
                border-radius: 2px 100px 100px 100px;
                padding: 0 8px;
                margin-top: 5px;
                display: inline-block;
            }

            .text3 {
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-top: 13px;

                .price {
                    font-size: 14px;
                    font-weight: bold;
                    color: rgba(var(--ion-color-light-contrast-rgb), 1);
                    line-height: 20px;
                }

                .num {
                    font-size: 14px;
                    color: rgba(170, 172, 173, 1);
                    line-height: 20px;
                }
            }
        }
    }
    .divider {
        height: 1px;
        margin-top: 15px;
        background: #f2f4f5;
    }
    .order-info {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 15px;

        .name {
            font-size: 13px;
            color: rgba(170, 172, 173, 1);
            line-height: 18px;
        }

        .val {
            font-size: 13px;
            color: rgba(var(--ion-color-light-contrast-rgb), 1);
            line-height: 18px;
        }
    }
}

.order-detail {
    background: rgba(255, 255, 255, 1);
    border-radius: 2px;
    margin: 15px;
    padding: 15px;

    .detail-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .name {
            font-size: 13px;
            color: rgba(170, 172, 173, 1);
            line-height: 18px;
        }
        .val {
            font-size: 13px;
            color: rgba(var(--ion-color-light-contrast-rgb), 1);
            line-height: 18px;

            &.price {
                color: #ff3b30;
                font-weight: bold;
            }
        }
        &:not(:last-child) {
            margin-bottom: 10px;
        }
    }

    .time-content {
        padding-top: 10px;
        border-top: 1px solid #f2f4f5;
        .val {
            color: rgba(102, 102, 102, 1);
        }
    }

    .pay-content {
        padding-top: 10px;
        border-top: 1px solid #f2f4f5;
        padding-bottom: 10px;
    }
}

.order-button {
    height: 50px;
    display: flex;
    .f();
    padding: 0 15px;
    width: 100%;
    .price {
        .f();
        align-items: baseline;
        flex-grow: 1;
        .label {
            font-size: 14px;
            color: var(--ion-color-step-400);
            margin-right: 4px;
        }
        .sym {
            font-weight: bold;
            font-size: 14px;
        }
        .num {
            font-weight: bold;
            font-size: 24px;
        }
    }
    .van-button {
        width: 110px;
        height: 39px;
        line-height: 39px;
        margin-left: 10px;
    }
    .full {
        flex-grow: 1;
        margin-left: 12px;
        margin-right: 12px;
    }
}
.bottom {
    width: 100%;
    background-color: var(--ion-color-dark-contrast);
}
ion-backdrop {
    opacity: 0.3;
    background: var(--ion-color-step-950);
}
.getsold {
    width: calc(100vw - 60px);
    background: var(--ion-background-color);
    border-radius: 4px;
    padding: 15px 20px;
    box-sizing: border-box;
    .title {
        font-size: 16px;
        font-weight: bold;
        text-align: center;
        color: rgba(var(--ion-color-light-contrast-rgb), 1);
        line-height: 22px;
    }

    .sold-item {
        display: flex;
        align-items: center;
        padding: 22px 0 10px;
        border-bottom: 1px solid #f2f4f5;
        .name {
            font-size: 14px;
            font-weight: bold;
            color: rgba(var(--ion-color-light-contrast-rgb), 1);
            line-height: 25px;
            min-width: 82px;
        }

        .val {
            font-size: 14px;
            font-weight: bold;
            color: rgba(var(--ion-color-light-contrast-rgb), 1);
            line-height: 20px;

            &.bold {
                font-size: 16px;
                color: rgba(255, 59, 48, 1);
                line-height: 22px;
            }
        }
    }
    .sold-list {
        margin-top: 10px;
    }
    .tips {
        font-size: 13px;
        color: rgba(170, 172, 173, 1);
        line-height: 18px;
        margin-top: 20px;
    }

    .button {
        width: 200px;
        display: block;
        margin: 50px auto 0;
    }
}
ion-modal#delegate {
    --width: fit-content;
    --min-width: 250px;
    --height: fit-content;
    --border-radius: 6px;
    --box-shadow: 0 28px 48px rgba(var(--ion-color-light-contrast-rgb), 0.4);
}
</style>
