<template>
    <div class="order-info">
        <div class="order-top">
            <div class="order-no">{{ $t('order.id') }}:{{ info.id }}</div>
            <div class="order-staus" :class="info.status">
                {{ info.locked && info.status === 'SELLING' ? '暂停出售' : orderStatus[info.status] }}
            </div>
        </div>

        <div class="order-content" @click="goDetail">
            <van-image class="suk-img" 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">¥{{ info.totalPrice }}</div>
                    <div class="num">×1</div>
                </div>
            </div>
        </div>

        <div class="order-price">
            <div class="price">
                <span>{{ $t('order.totalPayment') }}:</span>
                <span>¥{{ info.totalPrice }}</span>
            </div>

            <div class="order-tips" v-if="info.status == 'NOT_PAID'">付款倒计时过期自动取消订单 {{ times }}</div>
        </div>

        <div class="order-button">
            <span class="problem" @click="problem">遇到问题?</span>
            <template v-if="info.status == 'NOT_PAID'">
                <!-- <van-button color="#FF8F00"plain size="small" @click="confirmPayment">我已付款</van-button> -->
                <van-button type="primary" size="small" @click="pay">立即支付</van-button>
            </template>

            <template v-else-if="info.status == 'NOT_CONFIRMED'">
                <van-button color="#AAACAD" plain size="small" @click="goDetail">查看订单</van-button>
            </template>

            <template v-else-if="info.status == 'SOLD_NOT_CONFIRMED'">
                <!-- <van-button color="#AAACAD"plain size="small" @click="confirmPayment">未收到款</van-button> -->
                <!-- <van-button type="primary"size="small" @click="confirmReceipt">确认收款</van-button> -->
            </template>

            <template v-else-if="info.status == 'SELLING'">
                <!-- <van-button color="#AAACAD"plain size="small" @click="confirmPayment">未收到款</van-button> -->
                <!-- <van-button type="primary"size="small" @click="confirmReceipt">确认收款</van-button> -->
                <!-- <van-button color="#AAACAD" plain size="small" @click="applyShip">申请发货</van-button> -->
                <van-button color="#AAACAD" plain size="small" @click="goDetail">查看订单</van-button>
            </template>

            <template v-else-if="info.status == 'CONFIRMED'">
                <van-button color="#AAACAD" plain size="small" @click="applyShip">申请发货</van-button>
                <van-button type="primary" size="small" @click="show = true" v-if="delegationActive">
                    委托代卖</van-button
                >
                <van-button color="#aaacad" @click="showTip" v-else>委托代卖 </van-button>
            </template>

            <template v-else-if="info.status == 'SOLD'">
                <van-button color="#AAACAD" plain size="small" @click="goDetail">查看订单</van-button>
            </template>
            <template v-else-if="info.status == 'NOT_SHIPPED'">
                <van-button color="#AAACAD" plain size="small" @click="goDetail">查看订单</van-button>
            </template>
            <template v-else-if="info.status == 'RECEIVED'">
                <van-button color="#AAACAD" plain size="small" @click="goDetail">查看订单</van-button>
            </template>
            <template v-else-if="info.status == 'SHIPPED'">
                <van-button type="primary" size="small" @click="receive"> 确认收货</van-button>
            </template>
        </div>
        <ion-modal id="delegate" ref="modal" v-model:is-open="show" @didDismiss="show = false">
            <div class="getsold">
                <div class="title">{{ $t('delegate.title') }}</div>
                <div class="sold-list">
                    <div class="sold-item">
                        <div class="name">原价</div>
                        <div class="val">¥{{ info.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" block type="primary" :disabled="loading" @click="sale">
                    支付手续费 ¥{{ serviceCharge }}
                </van-button>
            </div>
        </ion-modal>
    </div>
</template>
<script>
import { mapState } from 'pinia'
import { useUserStore } from '@/stores/user'
import { orderStatus } from '../status'
import { differenceInSeconds, addMinutes, parse } from 'date-fns'
export default {
    name: 'orderInfo',
    props: {
        info: {
            type: Object,
            default: () => {
                return {}
            }
        },
        delegationActive: {
            type: Boolean,
            default: true
        },
        delegationTime: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            orderStatus,
            times: 0,
            show: false,
            value: 6,
            platformCommission: 0.02,
            maxRiseRate: 6,
            loading: false,
            payType: 'balance'
        }
    },
    computed: {
        ...mapState(useUserStore, ['user']),
        productInfo() {
            return this.info.productInfo || {}
        },
        pic() {
            if (this.productInfo.pic && this.productInfo.pic.length > 0) {
                return this.productInfo.pic[0]
            } else {
                return ''
            }
        },
        fromUserInfo() {
            return this.info.fromUserInfo || {}
        },
        soldValue() {
            var price = Number(this.info.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.info ? this.info.totalPrice || 0 : 0
            return (totalPrice * this.platformCommission).toFixed(2)
        },
        serviceValue() {
            return this.platformCommission * 100
        }
    },
    created() {
        if (this.info.status == 'NOT_PAID') {
            this.getTime()
        }
        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/pay_type').then(res => {
        //     if (res.value == '0') {
        //         if (this.isWeixin) {
        //             this.payType = 'weixin';
        //         } else {
        //             this.payType = 'alipay';
        //         }
        //     } else {
        //         this.payType = 'third';
        //     }
        // });
    },
    methods: {
        goDetail() {
            this.$router.push({
                name: 'orderDetail',
                query: {
                    id: this.info.id
                }
            })
        },
        getTime() {
            var times = differenceInSeconds(
                addMinutes(parse(this.info.createdAt, 'yyyy-MM-dd HH:mm:ss', new Date()), 30),
                new Date()
            )
            if (times <= 0) {
                times = 0
            }
            var mint = parseInt(times / 60)
            var seconds = parseInt(times % 60)
            this.times = mint + '分 ' + seconds + '秒'
            if (!times) {
                return
            }
            setTimeout(this.getTime, 1000)
        },
        confirmPayment() {
            this.$http
                .post('/order/confirmPayment', {
                    orderId: this.info.id
                })
                .then(res => {
                    this.$toast.success('确认成功')
                    setTimeout(() => {
                        this.$emit('updateOrder', res)
                    }, 1000)
                })
                .catch(e => {
                    return this.$toast.error(e.error)
                })
        },
        confirmReceipt() {
            this.$http
                .post('/order/confirmReceipt', {
                    orderId: this.info.id
                })
                .then(res => {
                    this.$toast.success('确认成功')
                    setTimeout(() => {
                        this.$emit('updateOrder', res)
                    }, 1000)
                })
                .catch(e => {
                    return this.$toast.error(e.error)
                })
        },
        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) {
                // eslint-disable-next-line no-empty
            }
            try {
                c += e.split('.')[1].length
            } catch (f) {
                // eslint-disable-next-line no-empty
            }
            return (Number(d.replace('.', '')) * Number(e.replace('.', ''))) / Math.pow(10, c)
        },
        sale() {
            this.show = false
            if (this.payType === 'alipay') {
                window.open(
                    this.$baseUrl +
                        `/payDelegation/alipay?userId=${this.user.id}&orderId=${this.info.id}&riseRate=${
                            this.value / 100
                        }&returnUrl=${encodeURIComponent(location.href)}`
                )
            } else if (this.payType === 'third') {
                window.open(
                    this.$baseUrl +
                        `/payDelegation/third?userId=${this.user.id}&orderId=${this.info.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.info.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.info.id,
                        riseRate: this.value / 100
                    })
                    .then(res => {
                        this.$toast.success('支付成功')
                        this.$emit('updateOrder', res)
                    })
                    .catch(e => {
                        this.$toast.error(e.error)
                    })
            }
        },
        applyShip() {
            this.$dialog
                .confirm({
                    title: '提示',
                    message: '确认申请发货？'
                })
                .then(() => {
                    this.$http
                        .post('/order/applyShip', {
                            orderId: this.info.id
                        })
                        .then(res => {
                            this.$toast.success('申请成功')
                            setTimeout(() => {
                                this.$emit('updateOrder', res)
                            }, 1000)
                        })
                        .catch(e => {
                            return this.$toast.error(e.error)
                        })
                })
                .catch(() => {})
        },
        receive() {
            this.$http
                .post('/order/receive', {
                    orderId: this.info.id
                })
                .then(res => {
                    this.$toast.success('确认成功')
                    setTimeout(() => {
                        this.$emit('updateOrder', res)
                    }, 1000)
                })
                .catch(e => {
                    return this.$toast.error(e.error)
                })
        },
        pay() {
            this.$toast.loading('支付中')
            this.$http
                .post('/order/balancePay', { orderId: this.info.id })
                .then(res => {
                    this.$toast.success('支付成功')
                    setTimeout(() => {
                        this.getInfo()
                    }, 1000)
                })
                .catch(e => {
                    this.$toast.error(e.error)
                })
        },
        showTip() {
            this.$dialog.alert({
                title: '提示',
                message: '委托代卖暂未开始，将在今天' + this.delegationTime + '开始'
            })
        },
        problem() {
            this.$router.push({
                name: 'workOrderction',
                query: {
                    orderId: this.info.id
                },
                params: {
                    isNext: true
                }
            })
        }
    }
}
</script>
<style lang="less" scoped>
.order-info {
    padding: 0 15px;
    background: rgba(255, 255, 255, 1);
    border-radius: 2px;
    margin: 12px 16px 0 16px;
}
.order-top {
    display: flex;
    justify-content: space-between;
    height: 43px;
    align-items: center;
    font-size: 13px;
    color: var(--ion-text-color);
    .order-staus {
        color: #ff8f00;
        font-size: 13px;
        font-weight: bold;
        &.NOT_PAID {
            color: var(--ion-color-danger);
        }
        &.CANCELED,
        &.SOLD {
            color: var(--ion-color-step-300);
        }
        &.CONFIRMED,
        &.SELLING {
            .gt();
        }
    }
}

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

.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;
        line-height: 20px;
    }

    .num {
        font-size: 14px;
        color: var(--ion-color-step-300);
        line-height: 20px;
    }
}
.order-content {
    display: flex;
    padding-top: 10px;
    border-top: 1px solid var(--ion-color-step-50);

    .order-text {
        margin-left: 10px;
        flex-grow: 1;
        overflow: hidden;
    }
}

.order-price {
    text-align: right;

    .price {
        font-size: 12px;
        color: var(--ion-color-step-300);
        line-height: 17px;
        margin-top: 18px;
        span {
            &:last-child {
                font-size: 16px;
                font-weight: bold;
                color: var(--ion-color-danger);
                line-height: 22px;
            }
        }
    }
    .order-tips {
        font-size: 12px;
        color: var(--ion-color-danger);
        line-height: 17px;
        margin-top: 8px;
    }
}

.order-button {
    padding: 15px 0;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    border-top: 1px solid var(--ion-color-step-50);
    margin-top: 15px;

    .van-button {
        margin-left: 10px;
        height: 28px;
        border-radius: 4px;
    }
    .problem {
        flex-grow: 1;
        text-align: left;
        font-size: 12px;
        font-weight: 400;
        color: var(--ion-color-step-300);
    }
}
.getsold {
    width: calc(100vw - 60px);
    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 var(--ion-color-step-50);
        .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>
