<template>
    <van-action-sheet v-model:show="show" title="参拍详情">
        <div class="content">
            <div class="collection">
                <van-image width="80" height="80" radius="8" :src="getImg(changeImgs(info.pic, 600))" fit="cover" />
                <div class="collection-info">
                    <div class="name">{{ info.name }}</div>
                    <div class="time">
                        <img src="../../assets/info_icon_time.png" alt="" />
                        <span>{{ timeText }}：<van-count-down :time="time" format="HH 时 mm 分 ss 秒" /></span>
                    </div>
                </div>
            </div>

            <div class="price">
                <div class="text1">保证金</div>
                <img src="../../assets/jiage_huang.png" alt="" />
                <div class="text2">{{ info.deposit }}</div>
            </div>
            <div class="tips">若竞拍不成功,保证金将原路退回</div>

            <div v-if="!isNFT" class="address" @click="onAdd">
                <div class="address-info" v-if="addressInfo.id">
                    <div class="text1">
                        <span>收货人</span>
                        <span>{{ addressInfo.name }} {{ addressInfo.phone }}</span>
                    </div>

                    <div class="text1">
                        <span>收货地址</span>
                        <span
                            >{{ addressInfo.provinceName }} {{ addressInfo.cityName }} {{ addressInfo.districtName }}
                            {{ addressInfo.address }}</span
                        >
                    </div>
                </div>
                <span class="address-info address-info-text" v-else> 选择收货地址 </span>
                <img src="../../assets/icon_inter.png" alt="" />
            </div>

            <div class="pay">
                <!-- <div class="pay-item" @click="payType = item.type" v-for="(item, index) in payInfos" :key="index">
                    <img class="icon" :src="item.icon" alt="" />
                    <span>{{ item.name }}</span>
                    <img class="choose-icon" :src="payType === item.type ? icons[1] : icons[0]" alt="" />
                </div> -->

                <pay-method-pick v-model="payType"></pay-method-pick>
            </div>
        </div>
        <div class="bottom">
            <div class="agreement" @click="showRule">竞拍需要同意协议<span>《拍卖服务协议》</span></div>
            <div class="btn">
                <a id="pay" :href="hrefUrl"></a>
                <van-button type="primary" block round @click="submit">同意协议并支付</van-button>
            </div>
        </div>
    </van-action-sheet>

    <van-number-keyboard v-model="tradeCode" :show="showKeyboard" @blur="showKeyboard = false" />

    <van-dialog
        v-model:show="showPwdDialog"
        title="请输入支付密码"
        confirmButtonText="立即支付"
        show-cancel-button
        confirmButtonColor="#3ab200"
        @cancel="(showPwdDialog = false), $toast.clear()"
        @confirm="pay"
    >
        <div style="padding: 20px 0">
            <van-password-input :value="tradeCode" :focused="showKeyboard" @focus="showKeyboard = true" gutter="4px" />
        </div>
    </van-dialog>
</template>

<script>
import auction from '../../mixins/auction';
import resolveUrl from 'resolve-url';
import PayMethodPick from '../PayMethodPick.vue';
let inWeixin = /micromessenger/i.test(navigator.userAgent);
let inApp = /#cordova#/i.test(navigator.userAgent);
let inIos = /iPhone|iPad|iPod/i.test(navigator.userAgent);
export default {
    components: { PayMethodPick },
    props: {
        info: {
            type: Object,
            default: () => {
                return {};
            }
        }
    },
    mixins: [auction],
    data() {
        return {
            show: false,
            time: 30 * 60 * 60 * 1000,
            addressInfo: {},
            payType: null,
            icons: [require('@assets/svgs/icon_gouxuan_huise.svg'), require('@assets/icon_gouxuan_pre.png')],
            payInfos: [
                {
                    icon: require('@assets/svgs/zhifubao.svg'),
                    name: '支付宝',
                    type: 'ALIPAY'
                },
                {
                    icon: require('@assets/svgs/wechat.svg'),
                    name: '微信',
                    type: 'WEIXIN'
                }
                // {
                //   icon: require("@assets/svgs/png-decp.svg"),
                //   name: "DCEP",
                // },
            ],
            enable_wx_lite: false,
            enable_wx_pub: false,
            hrefUrl: '',
            orderId: 0,
            timer: null,
            showPwdDialog: false,
            showKeyboard: false,
            tradeCode: '',
            money: 0
        };
    },
    mounted() {
        if (this.isLogin) {
            this.emitter.on('updateChoose', info => {
                console.log(info);
                this.addressInfo = info;
            });
            this.$http
                .post(
                    '/userAddress/all',
                    {
                        query: {
                            userId: this.$store.state.userInfo.id,
                            del: false,
                            def: true
                        },
                        size: 99
                    },
                    { body: 'json' }
                )
                .then(res => {
                    if (!res.empty) {
                        this.addressInfo = res.content[0];
                    }
                });
        }
    },
    methods: {
        getOrder(next = false) {
            this.$http.get('/auctionOrder/get/' + this.orderId).then(res => {
                if (this.timer) {
                    clearTimeout(this.timer);
                }
                if (this.timerNum >= 20) {
                    this.$toast.clear();
                    this.$dialog
                        .confirm({
                            title: '提示',
                            message: '订单是否已经支付',
                            confirmButtonText: '已经支付',
                            cancelButtonText: '未支付'
                        })
                        .then(() => {
                            this.$dialog
                                .alert({
                                    title: '正在排队中...',
                                    message: '您的铸造订单正在排队，下单的藏品后续会直接出现在藏品室哦～'
                                })
                                .then(res => {
                                    this.$router.back();
                                });
                        })
                        .catch(e => {
                            this.$dialog
                                .confirm({
                                    title: '提示',
                                    message: '订单未支付是否重新支付？',
                                    confirmButtonText: '重新支付',
                                    cancelButtonText: '取消订单'
                                })
                                .then(() => {
                                    this.timerNum = 0;
                                    this.payEvent(false);
                                })
                                .catch(() => {
                                    this.$router.back();
                                });
                        });
                } else if (res.status === 'PROCESSING' || res.status === 'FINISH' || res.status === 'CANCELLED') {
                    this.$toast.clear();
                    this.$dialog
                        .alert({
                            title: '提示',
                            message:
                                res.status === 'CANCELLED' ? '订单支付失败,点击重新下单' : '订单已支付,点击查看订单详情'
                        })
                        .then(() => {
                            this.$emit('refreash');
                            // on close
                        });
                } else if (next) {
                    this.timerNum += 1;
                    this.timer = setTimeout(() => {
                        this.getOrder(next);
                    }, 1500);
                }
            });
        },
        onAdd() {
            this.$router.push(
                '/' + this.$route.params.companyId + '/mineAddress?page=submit&chooseId=' + this.addressInfo.id
            );
        },
        init(money = 0) {
            this.money = money;
            this.time = this.getTime(this.info.endTime);
            this.show = true;
        },
        showRule() {
            this.$emit('showRule');
        },
        paySubmit(saveOrder = true) {
            return new Promise((resolve, reject) => {
                if (this.info.deposit && saveOrder) {
                    this.$toast.clear();
                    this.$nextTick(() => {
                        if (window.cordova && window.cordova.platformId === 'ios' && this.$store.state.review) {
                            resolve();
                        } else if (this.payType === 'ALIPAY') {
                            if (this.inWeixin) {
                                resolve();
                            } else {
                                this.$http
                                    .get(`/payOrder/v2/auction/alipay?id=${this.orderId}`)
                                    .then(res => {
                                        this.$toast.clear();
                                        this.hrefUrl = res;
                                        resolve();
                                    })
                                    .catch(e => {
                                        if (e && e.error) {
                                            this.$toast.clear();
                                            this.$dialog
                                                .alert({
                                                    title: '提示',
                                                    message: this.backReson(e.error)
                                                })
                                                .then(res => {
                                                    this.$router.back();
                                                });
                                            reject();
                                        }
                                    });
                            }
                        } else if (this.payType === 'WEIXIN') {
                            this.$toast.loading('加载中');
                            this.$http
                                .post('/payOrder/weixin', {
                                    id: this.orderId,
                                    channel: this.payChannel,
                                    openId: localStorage.getItem('openId') || 'oWJG55wLnwdVzXoKka1-DzQKOd_Y'
                                })
                                .then(res => {
                                    if ('wx_pub' === this.payChannel) {
                                        this.weixinOptions = res;
                                        resolve();
                                    } else {
                                        this.$toast.clear();
                                        this.hrefUrl = res.scheme_code;
                                        resolve();
                                    }
                                    // console.log({
                                    //     ...res,
                                    //     package: res.package || res.packageValue
                                    // });
                                    // let _this = this;
                                    // wx.chooseWXPay({
                                    //     ...res,
                                    //     package: res.package || res.packageValue,
                                    //     timestamp: res.timeStamp,
                                    //     success(res) {
                                    //         _this.$toast.success('支付成功');
                                    //         setTimeout(() => {
                                    //             _this.$router.replace('/orders');
                                    //         }, 1000);
                                    //     },
                                    //     fail(e) {
                                    //         console.log(e);
                                    //         _this.$toast('支付失败，请稍后再试');
                                    //     }
                                    // });
                                })
                                .catch(e => {
                                    this.$toast.clear();
                                    this.$dialog
                                        .alert({
                                            title: '提示',
                                            message: this.backReson(e.error || '支付失败请稍后再试')
                                        })
                                        .then(res => {
                                            this.$router.back();
                                        });
                                    reject();
                                });
                        } else if (this.payType === 'H5PAY') {
                            resolve();
                        }
                    });
                } else {
                    resolve();
                }
            });
        },
        createOrder() {
            let form = {
                userId: this.$store.state.userInfo.id,
                auctionId: this.info.id,
                type: 'DEPOSIT',
                amount: this.money
            };
            if (!this.isNFT) {
                form.addressId = this.addressInfo.id;
            }
            return this.$http
                .post('/auctionOrder/createDeposit', form)
                .then(res => {
                    return Promise.resolve(res);
                })
                .catch(e => {
                    return Promise.reject(e);
                });
        },
        submit() {
            if (!this.isNFT && !this.addressInfo.id) {
                this.$toast('请选择收货地址');
                return;
            }

            this.$toast.loading({
                message: '加载中...',
                forbidClick: true
            });
            this.createOrder()
                .then(res => {
                    this.$toast.clear();
                    this.orderId = res.id;
                    this.pay();
                })
                .catch(e => {
                    if (e) {
                        this.$toast(e.error);
                    }
                });
        },
        pay() {
            if (Number(this.info.deposit) != 0) {
                this.$router.replace({ query: { ...this.$route.query, orderId: this.orderId } });

                this.$nextTick(() => {
                    if (this.payType === 'SYXPAY') {
                        this.$toast.clear();
                        this.$router.push(
                            '/' +
                                this.$route.params.companyId +
                                '/bankPay?id=' +
                                this.orderId +
                                '&type=auction&paymentType=DEPOSIT'
                        );
                    } else if (this.$store.state.review) {
                        window.store.order('358');
                        this.getOrder(true);
                    } else if (this.payType === 'ALIPAY') {
                        if (this.inWeixin) {
                            document.location.replace(
                                resolveUrl(this.$baseUrl, '/payOrder/v2/auction/alipay_wx?id=' + this.orderId)
                            );
                        } else {
                            this.$http
                                .get(`/payOrder/v2/auction/alipay?id=${this.orderId}`)
                                .then(res => {
                                    this.$toast.clear();
                                    this.hrefUrl = res;
                                    this.$nextTick(() => {
                                        document.getElementById('pay').click();
                                    });

                                    this.$toast.loading({
                                        message: '加载中...',
                                        forbidClick: true
                                    });
                                    this.getOrder(true);
                                })
                                .catch(e => {
                                    if (e.error) {
                                        this.$toast(e.error);
                                    }
                                });
                        }
                    } else if (this.payType === 'WEIXIN') {
                        this.$toast.loading('加载中');
                        this.$http
                            .post('/payOrder/auction/weixin', {
                                id: this.orderId,
                                channel: this.payChannel,
                                openId: localStorage.getItem('openId') || 'oWJG55wLnwdVzXoKka1-DzQKOd_Y'
                            })
                            .then(res => {
                                if ('wx_pub' === this.payChannel) {
                                    console.log('wxPayParams', res);
                                    wx.chooseWXPay({
                                        ...res,
                                        success(res) {
                                            this.$toast.success('支付成功');
                                            setTimeout(() => {
                                                this.$router.replace('/orders');
                                            }, 1000);
                                        },
                                        fail(e) {
                                            console.log(e);
                                            this.$toast('支付失败，请稍后再试');
                                        }
                                    });
                                } else {
                                    this.$toast.clear();
                                    this.hrefUrl = res.scheme_code;
                                    this.$nextTick(() => {
                                        document.getElementById('pay').click();
                                    });

                                    this.$toast.loading({
                                        message: '加载中...',
                                        forbidClick: true
                                    });
                                    this.getOrder(true);
                                }
                            })
                            .catch(e => {
                                this.$toast(e.error || '支付失败请稍后再试');
                            });
                    } else if (this.payType === 'UNION') {
                        document.location.href = resolveUrl(
                            this.$baseUrl,
                            '/payOrder/v2/auction/sandQuick?id=' + this.orderId
                        )
                            .replace('www.raex.vip', 'jump.raex.vip')
                            .replace('test.raex.vip', 'jumptest.raex.vip')
                            .replace(/http:\/\/192\.168.*?\//, 'https://jumptest.raex.vip/');
                    } else if (this.payType === 'QUICK_BIND') {
                        this.$http
                            .get('/payOrder/v2/auction/sandQuickBind?id=' + this.orderId)
                            .then(res => {
                                document.location.href = res;
                                this.getOrder(true);
                            })
                            .catch(e => {
                                this.$toast.clear();
                                this.$dialog
                                    .alert({
                                        title: '提示',
                                        message: e.error || '支付失败'
                                    })
                                    .then(res => {
                                        this.$router.go(-2);
                                    });
                            });
                    } else if (this.payType === 'BALANCE') {
                        if (!this.tradeCode) {
                            this.$toast.clear();
                            this.showPwdDialog = true;
                            return;
                        }
                        this.$toast.loading({
                            message: '支付中',
                            forbidClick: true
                        });
                        this.$http
                            .post('/payOrder/v2/auction/balance', {
                                id: this.orderId,
                                tradeCode: this.tradeCode
                            })
                            .then(res => {
                                this.$toast.success('出价成功');
                                setTimeout(() => {
                                    setTimeout(() => {
                                        this.$emit('refreash');
                                    }, 1000);
                                }, 1000);
                            })
                            .catch(e => {
                                this.tradeCode = '';
                                this.$toast(e.error || '支付失败');
                            });
                    }
                });
            } else {
                this.$toast.success('出价成功');
                setTimeout(() => {
                    this.$emit('refreash');
                }, 1000);
            }
        },
        payEvent(saveOrder = true) {
            this.paySubmit(saveOrder).then(() => {
                if (this.info.deposit) {
                    this.$nextTick(() => {
                        if (this.payType === 'SYXPAY') {
                            this.$toast.clear();
                            this.$router.replace(
                                '/' + this.$route.params.companyId + '/bankPay?id=' + this.orderId + '&type=auction'
                            );
                        } else if (this.$store.state.review) {
                            window.store.order('358');
                            this.getOrder(true);
                        } else if (this.payType === 'ALIPAY') {
                            if (this.inWeixin) {
                                document.location.replace(
                                    resolveUrl(this.$baseUrl, '/payOrder/v2/auction/alipay_wx?id=' + this.orderId)
                                );
                            } else {
                                this.$http
                                    .get(`/payOrder/v2/auction/alipay?id=${this.orderId}`)
                                    .then(res => {
                                        this.$toast.clear();
                                        this.hrefUrl = res;
                                        this.$nextTick(() => {
                                            document.getElementById('pay').click();
                                        });

                                        this.$toast.loading({
                                            message: '加载中...',
                                            forbidClick: true
                                        });
                                        this.getOrder(true);
                                    })
                                    .catch(e => {
                                        if (e.error) {
                                            this.$toast(e.error);
                                        }
                                    });
                            }
                        } else if (this.payType === 'WEIXIN') {
                            this.$toast.loading('加载中');
                            this.$http
                                .post('/payOrder/auction/weixin', {
                                    id: this.orderId,
                                    channel: this.payChannel,
                                    openId: localStorage.getItem('openId') || 'oWJG55wLnwdVzXoKka1-DzQKOd_Y'
                                })
                                .then(res => {
                                    if ('wx_pub' === this.payChannel) {
                                        console.log('wxPayParams', res);
                                        wx.chooseWXPay({
                                            ...res,
                                            success(res) {
                                                this.$toast.success('支付成功');
                                                setTimeout(() => {
                                                    this.$router.replace(
                                                        '/' + this.$route.params.companyId + '/orders'
                                                    );
                                                }, 1000);
                                            },
                                            fail(e) {
                                                console.log(e);
                                                this.$toast('支付失败，请稍后再试');
                                            }
                                        });
                                    } else {
                                        this.$toast.clear();
                                        this.hrefUrl = res.scheme_code;
                                        this.$nextTick(() => {
                                            document.getElementById('pay').click();
                                        });

                                        this.$toast.loading({
                                            message: '加载中...',
                                            forbidClick: true
                                        });
                                        this.getOrder(true);
                                    }
                                    // console.log({
                                    //     ...res,
                                    //     package: res.package || res.packageValue
                                    // });
                                    // let _this = this;
                                    // wx.chooseWXPay({
                                    //     ...res,
                                    //     package: res.package || res.packageValue,
                                    //     timestamp: res.timeStamp,
                                    //     success(res) {
                                    //         _this.$toast.success('支付成功');
                                    //         setTimeout(() => {
                                    //             _this.$router.replace('/orders');
                                    //         }, 1000);
                                    //     },
                                    //     fail(e) {
                                    //         console.log(e);
                                    //         _this.$toast('支付失败，请稍后再试');
                                    //     }
                                    // });
                                })
                                .catch(e => {
                                    this.$toast(e.error || '支付失败请稍后再试');
                                });
                        } else if (this.payType === 'UNION') {
                            document.location.href = resolveUrl(
                                this.$baseUrl,
                                '/payOrder/v2/auction/sandQuick?id=' + this.orderId
                            )
                                .replace('www.raex.vip', 'jump.raex.vip')
                                .replace('test.raex.vip', 'jumptest.raex.vip')
                                .replace(/http:\/\/192\.168.*?\//, 'https://jumptest.raex.vip/');
                        } else if (this.payType === 'QUICK_BIND') {
                            this.$http
                                .get('/payOrder/v2/auction/sandQuickBind?id=' + this.orderId)
                                .then(res => {
                                    document.location.href = res;
                                    this.getOrder(true);
                                })
                                .catch(e => {
                                    this.$toast.clear();
                                    this.$dialog
                                        .alert({
                                            title: '提示',
                                            message: e.error || '支付失败'
                                        })
                                        .then(res => {
                                            this.$router.go(-2);
                                        });
                                });
                        }
                    });
                } else {
                    this.$toast.success('出价成功');
                    setTimeout(() => {
                        this.$emit('refreash');
                    }, 1000);
                }
            });
        }
    }
};
</script>

<style lang="less" scoped>
.content {
    padding: 16px;
    .bottom(120px);
}

.collection {
    .flex();
    .van-image {
        flex-shrink: 0;
    }
    .collection-info {
        flex-grow: 1;
        .flex-col();
        margin-left: 10px;
        align-self: stretch;

        .name {
            font-size: 14px;
            font-weight: bold;
            color: #000000;
            line-height: 20px;
        }

        .time {
            .flex();
            background: #fff7f2;
            border-radius: 4px;
            align-self: flex-start;
            padding: 0 2px;
            margin-top: 10px;
            img {
                width: 18px;
                height: 18px;
            }
            span {
                margin-left: 2px;
                .flex();
                font-size: 12px;
                color: #ff7f1f;
                line-height: 22px;
                .van-count-down {
                    font-size: 12px;
                    color: #ff7f1f;
                    line-height: 22px;
                }
            }
        }
    }
}

.price {
    .flex();
    align-items: flex-end;
    padding-top: 16px;
    .text1 {
        font-size: 14px;
        color: #000000;
        line-height: 14px;
        font-weight: bold;
    }

    img {
        width: 10px;
        height: 11px;
        margin-left: 10px;
    }
    .text2 {
        font-size: 32px;
        font-family: OSP-DIN, OSP;
        font-weight: normal;
        color: #3ab200;
        line-height: 20px;
    }
}
.tips {
    font-size: 12px;
    color: #c8c9cc;
    line-height: 17px;
    margin-top: 6px;
}

.address {
    background-color: #f5f7fa;
    padding: 16px 10px;
    border-radius: 12px;
    margin-top: 16px;
    .flex();

    .text1 {
        .flex();
        align-items: flex-start;
        span {
            font-size: 14px;
            color: #000000;
            line-height: 24px;

            &:first-child {
                color: #939599;
                min-width: 56px;
                margin-right: 12px;
                display: inline-block;
            }
        }
    }

    .address-info {
        flex-grow: 1;

        &.address-info-text {
            font-size: 14px;
            color: @text3;
            line-height: 52px;
        }
    }

    .text1 + .text1 {
        margin-top: 6px;
    }

    img {
        width: 24px;
        height: 24px;
    }
}

.agreement {
    font-size: 12px;
    color: #939599;
    line-height: 24px;
    margin-top: 26px;
    text-align: center;
    background-color: #f5f7fa;
    padding: 7px 0;
    span {
        color: #3ab200;
    }
}
.btn {
    padding: 9px 48px;
}
.pay {
    padding-top: 10px;
}
.pay-item {
    display: flex;
    align-items: center;
    height: 48px;
    border-top: 1px solid @tabBorder;
    .icon {
        height: 24px;
        display: block;
    }
    span {
        font-size: 14px;
        font-weight: bold;
        color: @text0;
        line-height: 24px;
        flex-grow: 1;
        padding: 0 10px;
    }
    .choose-icon {
        width: 24px;
        height: 24px;
    }
}
.van-number-keyboard {
    z-index: 9999;
}
:deep(.van-password-input__item) {
    background: @bg3;
}

.bottom {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    .fixedBottom(0px);
}
</style>
