<template>
    <div class="submit">
        <van-notice-bar
            :text="getLabelName(paymentType, paymentTypeOptions, 'text')"
            background="#FF7F1F"
            color="#fff"
        />
        <div class="address" v-if="!isNFT">
            <div class="van-address-item van-contact-card" @click="onAdd">
                <div class="van-cell van-cell--borderless">
                    <div class="van-cell__value van-cell__value--alone van-address-item__value">
                        <div role="radio" class="van-radio" tabindex="0" aria-checked="false">
                            <span class="van-radio__label" v-if="addressInfo.id">
                                <div class="van-address-item__name">{{ showAddress.name }} {{ showAddress.tel }}</div>
                                <div class="van-address-item__address">{{ showAddress.address }}</div>
                            </span>
                            <span class="van-radio__label tips" v-else> 选择收货地址 </span>
                        </div>
                    </div>
                    <i class="van-badge__wrapper van-icon van-icon-arrow van-address-item__edit"></i>
                </div>
            </div>
        </div>
        <div class="assets">
            <div class="assets-product" :class="{ isEnd: isEnd }">
                <van-image width="80" height="80" radius="6" :src="getImg(changeImgs(info.pic))" fit="cover" />
                <div class="assets-info">
                    <div class="text1">{{ info.name }}</div>
                    <div class="flex1"></div>

                    <div class="text2">
                        <div class="time" v-if="!isEnd">
                            <img src="../../assets/info_icon_time.png" alt="" />
                            <span>{{ timeText }}：<van-count-down :time="time" format="HH 小时 mm 分 ss 秒" /></span>
                        </div>
                        <div class="time" v-else>{{ timeText }}</div>
                    </div>
                    <!-- <div class="text2" v-if="info.category">类型：{{ info.category }}</div>
                    <div class="text2" v-if="info.number">编号：{{ info.number }}</div> -->
                </div>
            </div>
        </div>

        <div class="text-list">
            <div class="text-info">
                <span class="text1">{{ getLabelName(paymentType, paymentTypeOptions) }}</span>
                <span class="text2">¥{{ preMoney }}</span>
            </div>

            <!-- <div class="text-info">
                <span class="text1">GAS费用</span>
                <span class="text2">¥{{ gas }}</span>
            </div> -->
            <div class="text-info">
                <span class="text1">实际支付</span>
                <span class="text2 prim">¥{{ money }}</span>
            </div>

            <template v-if="paymentType !== 'FIXED_PRICE'">
                <div class="text-cell">
                    <div class="text-top">
                        <span class="text1">保证金</span>
                        <span class="text2 warn">¥{{ info.deposit }}</span>
                    </div>
                    <div class="sub">
                        竞拍成功支付后，送拍机构主动关闭交易，系统会在72小时内释放保证金；若竞拍成功未支付，保证金将不会释放
                    </div>
                </div>
                <div class="text-info">
                    <span class="text1">保证金状态</span>
                    <span class="text2">正常</span>
                </div>
            </template>
        </div>

        <div class="pay" v-if="!$store.state.review">
            <!-- <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 class="bottom van-safe-area-bottom" ref="bottom">
            <div class="bottom-content">
                <span class="text">实际支付</span>
                <span class="price"> <img src="@assets/jiage_huang.png" alt="" />{{ money }} </span>
                <div class="btn">
                    <van-button
                        round
                        :color="`linear-gradient(135deg, ${$colors.prim} 0%, ${$colors.warn} 100%)`"
                        @click="submit"
                        :disabled="!!orderId"
                    >
                        立即支付
                    </van-button>
                </div>
                <a id="pay" :href="hrefUrl"></a>
                <!-- <wx-open-launch-weapp id="launch-btn" :username="launchName" :path="launchPath"> </wx-open-launch-weapp> -->
            </div>
        </div>

        <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>
    </div>
</template>

<script>
import asset from '../../mixins/asset';
import imgInfo from '../../mixins/imgInfo';
import resolveUrl from 'resolve-url';
let inWeixin = /micromessenger/i.test(navigator.userAgent);
let inApp = /#cordova#/i.test(navigator.userAgent);
let inIos = /iPhone|iPad|iPod/i.test(navigator.userAgent);
import auctionOrder from '../../mixins/auctionOrder';
import auction from '../../mixins/auction';
import PayMethodPick from '../../components/PayMethodPick.vue';
import { mapState } from 'vuex';
export default {
    components: { PayMethodPick },
    name: 'activitySubmit',
    inject: ['setKeeps'],
    mixins: [asset, imgInfo, auctionOrder, auction],
    data() {
        return {
            addressInfo: {},
            list: [],
            payType: null,
            payChannel: null,
            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",
                // },
            ],
            icons: [require('@assets/svgs/icon_gouxuan_huise.svg'), require('@assets/icon_gouxuan_pre.png')],
            inWeixin,
            inApp,
            inIos,
            gas: 1,
            enable_wx_lite: false,
            enable_wx_pub: false,
            assets: '',
            auctionId: 0,
            orderId: 0,
            hrefUrl: '',
            timer: null,
            info: {},
            time: '',
            paymentType: 'FIXED_PRICE',
            recordInfo: {},
            showPwdDialog: false,
            showKeyboard: false,
            tradeCode: ''
        };
    },
    computed: {
        ...mapState(['companyId']),
        preMoney() {
            if (this.paymentType === 'PURCHASE_PRICE') {
                return this.info.purchasePrice || 0;
            } else {
                return this.info.fixedPrice || 0;
            }
        },
        money() {
            let money = 0;
            if (this.preMoney) {
                money = this.accAdd(this.preMoney, money);
            }
            // if (this.gas) {
            //     money = this.accAdd(money, this.gas);
            // }

            return money;
        },
        isNFT() {
            return this.info.auctionType === 'NFT';
        },
        showAddress() {
            if (this.addressInfo.id) {
                return {
                    id: this.addressInfo.id,
                    name: this.addressInfo.name,
                    tel: this.addressInfo.phone,
                    address: `${this.addressInfo.provinceName} ${this.addressInfo.cityName} ${this.addressInfo.districtName} ${this.addressInfo.address}`,
                    isDefault: this.addressInfo.def
                };
            } else {
                return {};
            }
        }
    },
    mounted() {
        console.log(this.$route.query.paymentType);
        if (this.$route.query.paymentType) {
            this.paymentType = this.$route.query.paymentType;
        }
        this.emitter.on('updateChoose', info => {
            // console.log(id);
            this.addressInfo = info;
        });
        if (this.$route.query.auctionId) {
            this.auctionId = this.$route.query.auctionId;
            this.$http.get('/auctionRecord/hasPayDeposit?auctionId=' + this.auctionId).then(res => {
                this.recordInfo = res;
            });
            this.$http.get('/auctionActivity/get/' + this.auctionId).then(res => {
                this.info = res;
                this.time = this.getTime(res.endTime);
                // this.gas = res.gasPrice;
                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: {
        onAdd() {
            this.$router.push(
                '/' + this.$route.params.companyId + '/mineAddress?page=submit&chooseId=' + this.addressInfo.id
            );
        },
        getOrder(next = false) {
            this.$http.get('/mintOrder/get/' + this.orderId).then(res => {
                this.info = res;
                if (this.timer) {
                    clearTimeout(this.timer);
                }
                if (res.status && res.status !== 'NOT_PAID') {
                    this.$toast.clear();
                    this.$dialog
                        .alert({
                            title: '提示',
                            message:
                                res.status === 'CANCELLED' ? '订单支付失败,点击重新下单' : '订单已支付,点击查看订单详情'
                        })
                        .then(() => {
                            if (res.status === 'CANCELLED') {
                                this.$router.back();
                            } else {
                                this.$router.replace(
                                    '/' + this.$route.params.companyId + '/activityOrderDetail?id=' + res.id
                                );
                            }
                            // on close
                        });
                } else if (next) {
                    this.timer = setTimeout(() => {
                        this.getOrder(next);
                    }, 1000);
                }
            });
        },
        createOrder() {
            this.$toast.loading('请不要离开当前页面');

            let form = {
                userId: this.$store.state.userInfo.id,
                auctionId: this.auctionId,
                type: this.paymentType
            };

            if (!this.isNFT) {
                form.addressId = this.addressInfo.id;
            }

            if (this.paymentType === 'PURCHASE_PRICE') {
                form.auctionRecordId = this.recordInfo.id;
                return this.$http
                    .post('/auctionOrder/create', form)
                    .then(res => {
                        return Promise.resolve(res);
                    })
                    .catch(e => {
                        return Promise.reject(e);
                    });
            } else {
                return this.$http
                    .post('/auctionOrder/createFixPrice', form)
                    .then(res => {
                        return Promise.resolve(res);
                    })
                    .catch(e => {
                        return Promise.reject(e);
                    });
            }
        },
        submit() {
            if (!this.addressInfo.id && !this.isNFT) {
                this.$toast('请选择收货地址');
                return;
            }
            if (!this.payType) {
                this.$toast('请选择支付方式');
                return;
            }
            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.money) != 0) {
                this.$nextTick(() => {
                    if (this.payType === 'SYXPAY') {
                        this.$toast.clear();
                        this.$router.replace(
                            '/' +
                                this.$route.params.companyId +
                                '/bankPay?id=' +
                                this.orderId +
                                '&type=auction&paymentType=' +
                                this.paymentType +
                                '&companyId=' +
                                this.companyId
                        );
                    } 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 + '&companyId=' + this.companyId
                                )
                            );
                        } else {
                            this.$http
                                .get(`/payOrder/v2/auction/alipay?id=${this.orderId}&companyId=${this.companyId}`)
                                .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',
                                companyId: this.companyId
                            })
                            .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);
                                }
                            })
                            .catch(e => {
                                this.$toast(e.error || '支付失败请稍后再试');
                            });
                    } else if (this.payType === 'UNION') {
                        document.location.href = resolveUrl(
                            this.$baseUrl,
                            '/payOrder/v2/auction/sandQuick?id=' + this.orderId + '&companyId=' + this.companyId
                        )
                            .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 + '&companyId=' + this.companyId
                            )
                            .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(-1);
                                    });
                            });
                    } 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,
                                companyId: this.companyId
                            })
                            .then(res => {
                                this.$toast.success('支付成功');
                                setTimeout(() => {
                                    if (this.paymentType === 'DEPOSIT') {
                                        this.$router.go(-1);
                                    } else {
                                        this.$router.replace(
                                            '/' +
                                                this.$route.params.companyId +
                                                '/auctionOrderDetail?id=' +
                                                this.orderId
                                        );
                                    }
                                }, 1000);
                            })
                            .catch(e => {
                                this.tradeCode = '';
                                this.$toast(e.error || '支付失败');
                            });
                    } else if (this.payType === 'ALI') {
                        this.$http
                            .get('/payOrder/v2/auction/ali', { id: this.orderId, companyId: this.companyId })
                            .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 {
                this.$router.replace('/' + this.$route.params.companyId + '/auctionOrderDetail?id=' + this.orderId);
            }
        }
    },
    beforeRouteLeave(to, from, next) {
        if (to.path === '/mineAddress') {
            this.setKeeps(['activitySubmit']);
        } else {
            this.setKeeps(['activitySubmit'], false);
        }
        next();
    }
};
</script>

<style lang="less" scoped>
.hr {
    width: 100%;
    height: 6px;
    display: block;
}

.address {
    .van-address-item {
        position: relative;
        padding: 20px 16px 26px;
        .van-radio__label {
            margin-left: 0;
        }
        .van-address-item__edit {
            right: 0;
            color: @text3;
            &::before {
                color: @text3;
            }
        }

        &::before {
            height: 6px;
            background-size: 120px;
        }
    }
    .tips {
        color: @text3;
    }
}

.submit {
    background-color: @bg3;
    padding-bottom: 100px;
}
.assets {
    background-color: @bg;
    padding: 16px;
}
.assets-title {
    .text1 {
        font-size: 14px;
        color: #000000;
        line-height: 24px;
    }
    .text2 {
        font-size: 12px;
        color: #ff4f50;
    }
}

.assets-product {
    display: flex;
    margin: 6px 0;

    .assets-info {
        display: flex;
        flex-direction: column;
        flex-grow: 1;
        margin-left: 12px;
        .text1 {
            font-size: 14px;
            color: #000000;
            line-height: 24px;
            font-weight: bold;
        }

        .text2 {
            font-size: 12px;
            color: #939599;
            line-height: 17px;
        }
    }

    &:last-child {
        margin-bottom: 0;
    }

    &.isEnd {
        .text2 {
            .time {
                font-size: 12px;
                color: #939599;
                background-color: #f2f4f5;
            }
        }
    }
}

.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;
    }
}
.pay {
    padding: 0 16px;
    background-color: @bg;
}

.bottom {
    position: fixed;
    bottom: 0px;
    left: 0;
    right: 0;
    background-color: @bg;
    z-index: 20;
    border-top: 1px solid @tabBorder;

    .bottom-content {
        padding: 6px 16px;
        display: flex;
        align-items: flex-end;

        .btn {
            flex-grow: 1;
            display: flex;
            justify-content: flex-end;
        }
        .van-button {
            flex-grow: 1;
            color: @btnText !important;
            max-width: 132px;
        }
        .text {
            font-size: 14px;
            color: @text3;
            line-height: 20px;
            margin-bottom: 2px;
            word-break: keep-all;
        }

        .price {
            font-size: 34px;
            font-family: OSP;
            font-weight: normal;
            color: @prim;
            line-height: 30px;
            display: flex;
            align-items: center;

            // flex-grow: 1;
            margin: 0 6px;
            .font_family {
                font-size: 10px;
            }

            img {
                width: 10px;
                height: 11px;
                display: block;
                margin-top: 8px;
            }
        }
    }
}
.text-list {
    padding: 0 16px;
    background-color: #fff;
}
.text-info {
    .flex();
    height: 48px;
    font-size: 14px;
    color: #000000;
    line-height: 24px;
    justify-content: space-between;

    .text2 {
        font-weight: bold;
    }
    .prim {
        color: @prim;
    }

    border-top: 1px solid #f5f7fa;
}

.text-cell {
    padding: 12px 0 10px;
    border-top: 1px solid #f5f7fa;
    .text-top {
        .flex();
        font-size: 14px;
        color: #000000;
        line-height: 24px;
        justify-content: space-between;
        .text2 {
            font-weight: bold;
        }
        .warn {
            color: #ff7f1f;
        }
    }
    .sub {
        font-size: 12px;
        color: #ff7f1f;
        line-height: 17px;
        margin-top: 4px;
    }
}

.van-notice-bar {
    height: 28px;
    /deep/.van-notice-bar__wrap {
        justify-content: center;
    }
}

.time {
    .flex();
    height: 22px;
    background: #fff7f2;
    border-radius: 4px;
    display: inline-flex;
    padding: 0 4px;
    margin-bottom: 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;
        }
    }
}

.van-number-keyboard {
    z-index: 9999;
}
:deep(.van-password-input__item) {
    background: @bg3;
}
</style>
