<template>
    <div class="page">
        <div class="submit">
            <div class="pageTitle">{{ info.minter }}</div>
            <div class="product">
                <van-image width="80" height="80" :radius="6" :src="getImg(changeImgs(info.pic))" fit="cover" />
                <div class="product-content">
                    <div class="text1">
                        {{ info.name }}
                    </div>
                    <div class="no">{{ info.number }}</div>
                    <div class="price">¥{{ info.price }}</div>
                </div>
            </div>

            <div class="list">
                <div class="info">
                    <div class="text1">作品费用</div>
                    <div class="text2">¥{{ info.price }}</div>
                </div>
                <div class="info" v-if="!($store.state.review && inIos)">
                    <div class="text1">GAS费用</div>
                    <div class="text2">¥{{ gas }}</div>
                </div>
                <div v-if="couponList.length > 0" class="info" :class="{ not: !couponInfo }" @click="goCoupon">
                    <div class="text1">藏品兑换券</div>
                    <div class="text2">{{ couponInfo ? '已选择兑换券' : '请选择' }}</div>
                    <img class="inter" src="@assets/icon_inter.png" alt="" />
                </div>

                <!-- <van-field type="text" label="订单留言" placeholder="选填" v-model="message" /> -->

                <pay-method-pick v-model="payType"></pay-method-pick>
            </div>
        </div>

        <div class="bottom van-safe-area-bottom" ref="bottom">
            <div class="bottom-content">
                <span class="text">总计</span>
                <span class="price">
                    <van-icon class-prefix="font_family" name="icon-icon_jiage" />
                    {{ money }}
                </span>
                <div class="btn">
                    <van-button type="primary" round @click="submit"> 立即支付 </van-button>
                </div>
                <a id="pay" :href="payUrlScheme"></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
            @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 product from '../mixins/product';
import coupon from '../mixins/coupon';
import { mapState } from 'vuex';
import resolveUrl from 'resolve-url';
import qs from 'qs';
import encryptUtil from '../utils/encryptUtil';
import PayMethodPick from '../components/PayMethodPick';
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 {
    name: 'Submit',
    mixins: [product, coupon],
    components: { PayMethodPick },
    data() {
        return {
            info: {},
            message: '',
            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'),
                require('@assets/icon_gouxuan_huise1.png')
            ],
            bottom: null,
            orderId: 0,
            gas: 1,
            inWeixin,
            inApp,
            inIos,
            couponList: [],
            collectionId: 0,
            timer: null,
            payUrlScheme: '',
            launchName: '',
            launchPath: '',
            createOrderTimer: null,
            timerNum: 0,
            weixinOptions: {},
            showPwdDialog: false,
            showKeyboard: false,
            tradeCode: ''
        };
    },
    computed: {
        money() {
            let money = 0;
            if (this.info.price && !this.couponInfo) {
                money = this.accAdd(this.info.price, money);
            }
            if (this.gas && (!this.couponInfo || this.couponInfo.needGas)) {
                money = this.accAdd(money, this.gas);
            }
            return money;
        },
        ...mapState(['couponInfo', 'companyId']),
        couponPayment() {
            return this.info.couponPayment || false;
        }
    },
    beforeRouteLeave(to, from, next) {
        if (this.createOrderTimer) {
            clearInterval(this.createOrderTimer);
        }
        if (to.path !== '/couponList') {
            this.$store.commit('setCouponInfo', null);
        }
        next();
    },
    mounted() {
        this.$http.get('/sysConfig/get/gas_fee').then(res => {
            this.gas = res.value;
            if (window.cordova && window.cordova.platformId === 'ios' && this.$store.state.review) {
                this.gas = 0;
            }
            return Promise.resolve();
        });

        this.$toast.loading({
            message: '加载中...',
            forbidClick: true
        });
        if (this.$route.query.id) {
            this.collectionId = Number(this.$route.query.id);
            this.$http.get('/collection/get/' + this.collectionId).then(res => {
                this.info = res;
                setTimeout(() => {
                    this.$toast.clear();
                }, 100);

                // this.$http('/sysConfig/get/gas_fee')
            });
            this.getCouponList();
        } else {
            this.orderId = this.$route.query.orderId;
            this.getOrder();
        }

        this.bottom = this.$refs.bottom;
        this.emitter.on('iapEvent', this.iapEvent);
    },
    beforeUnmount() {
        this.emitter.off('iapEvent', this.iapEvent);
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
        }
    },
    methods: {
        getOrder(next = false) {
            this.$http.get('/order/get/' + this.orderId).then(res => {
                this.info = 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.pay(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(() => {
                            if (res.status === 'CANCELLED') {
                                this.$router.back();
                            } else {
                                this.$router.replace('/' + this.$route.params.companyId + '/orderDetail?id=' + res.id);
                            }
                            // on close
                        });
                } else if (next) {
                    this.timerNum += 1;
                    this.timer = setTimeout(() => {
                        this.getOrder(next);
                    }, 1500);
                }
            });
        },
        getCouponList() {
            this.$http
                .post(
                    '/userCoupon/all',
                    {
                        query: { userId: this.$store.state.userInfo.id, used: false },
                        size: 999
                    },
                    { body: 'json' }
                )
                .then(res => {
                    this.couponList = [...res.content].filter(item => {
                        return this.checkTime(item) && this.checkUse(item, this.collectionId);
                    });
                });
        },
        createOrder() {
            if (this.orderId) {
                return Promise.resolve({ id: this.orderId });
            }
            if (!this.payType) {
                this.$toast('请选择支付方式');
                return;
            }
            this.$toast.loading('请不要离开当前页面');

            let params = {
                collectionId: this.collectionId,
                qty: 1,
                couponId: (this.couponInfo || {}).id || '',
                invitor: this.$store.state.invitor || '',
                vip: this.$store.state.userInfo.vipPurchase > 0 ? true : false
            };
            params.sign = encryptUtil.encrypt(qs.stringify({ ...params, ts: new Date().getTime() }));
            return this.$http.post('/order/mqCreate', params).then(res => {
                return new Promise((resolve, reject) => {
                    let checkOrder = () => {
                        this.$http
                            .get('/order/createResult', { id: res.id })
                            .then(res => {
                                if (res) {
                                    clearInterval(this.createOrderTimer);
                                    this.createOrderTimer = null;
                                    if (res.success) {
                                        resolve(res.data);
                                    } else {
                                        reject({ error: res.data });
                                    }
                                }
                            })
                            .catch(e => {
                                clearInterval(this.createOrderTimer);
                                this.createOrderTimer = null;
                                reject(e);
                            });
                    };
                    setTimeout(checkOrder, 500);
                    this.createOrderTimer = setInterval(checkOrder, 2000);
                });
            });
        },
        submit(e) {
            if (!this.payType) {
                this.$toast('请选择支付方式');
                return;
            }

            if (this.couponPayment && !this.couponInfo) {
                this.$dialog
                    .alert({
                        title: '提示',
                        message: '该藏品为特殊藏品，需要使用优惠券才能兑换'
                    })
                    .then(() => {});
                return;
            }
            if (!this.checkWebDriver(e)) {
                return;
            }
            this.createOrder()
                .then(res => {
                    this.orderId = res.id;
                    this.pay();
                })
                .catch(e => {
                    if (e) {
                        this.$toast.clear();
                        this.$dialog
                            .alert({
                                title: '提示',
                                message: this.backReson(e.error)
                            })
                            .then(res => {
                                this.$router.back();
                            });
                    }
                });
        },
        pay(saveOrder = true) {
            console.log('pay saveOrder=' + saveOrder);
            if (this.money === 0) {
                this.$toast.success('支付成功');
                setTimeout(() => {
                    this.$router.replace('/' + this.$route.params.companyId + '/orderDetail?id=' + this.orderId);
                }, 1000);
                return;
            }
            if (this.payType === 'SYXPAY') {
                this.$toast.clear();
                this.$router.replace({ name: 'bankPay', query: { id: this.orderId } });
            } else if (this.payType === 'IAP') {
                window.store.order('358');
                this.getOrder(true);
            } else if (this.payType === 'ALIPAY_BRIDGE') {
                document.location.replace(
                    resolveUrl(
                        this.$baseUrl,
                        '/payOrder/v2/alipay_wx?id=' + this.orderId + '&companyId' + this.companyId
                    )
                );
            } else if (this.payType === 'ALIPAY') {
                this.$toast.loading({
                    message: '支付中',
                    forbidClick: true
                });
                (this.payUrlScheme
                    ? Promise.resolve()
                    : this.$http.get(`/payOrder/v2/alipay?id=${this.orderId}&companyId=${this.companyId}`).then(res => {
                          this.payUrlScheme = res;
                      })
                )
                    .then(() => {
                        this.$nextTick(() => {
                            document.getElementById('pay').click();
                        });

                        this.getOrder(true);
                    })
                    .catch(e => {
                        this.$toast.clear();
                        e = e || {};
                        e.error = e.error || '支付失败';
                        this.$dialog
                            .alert({
                                title: '提示',
                                message: this.backReson(e.error)
                            })
                            .then(res => {
                                this.$router.back();
                            });
                    });
            } else if (this.payType === 'UNION') {
                const url = resolveUrl(
                    this.$baseUrl,
                    '/payOrder/v2/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/');
                console.log(url);
                document.location.href = url;
                this.getOrder(true);
            } else if (this.payType === 'QUICK_BIND') {
                this.$http
                    .get('/payOrder/v2/sandQuickBind?id=' + this.orderId + '&companyId=' + this.companyId)
                    .then(res => {
                        document.location.href = res;
                        this.getOrder(true);
                    })
                    .catch(e => {
                        this.$toast.clear();
                        e = e || {};
                        e.error = e.error || '支付失败';
                        this.$dialog
                            .alert({
                                title: '提示',
                                message: this.backReson(e.error)
                            })
                            .then(res => {
                                this.$router.back();
                            });
                    });
            } 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/balance', {
                        id: this.orderId,
                        tradeCode: this.tradeCode,
                        companyId: this.companyId
                    })
                    .then(res => {
                        this.$toast.success('支付成功');
                        setTimeout(() => {
                            this.$router.replace(
                                '/' + this.$route.params.companyId + '/orderDetail?id=' + this.orderId
                            );
                        }, 1000);
                    })
                    .catch(e => {
                        this.tradeCode = '';
                        this.$toast(e.error || '支付失败');
                    });
            } else if (this.payType === 'ALI') {
                this.$toast.loading({
                    message: '支付中',
                    forbidClick: true
                });
                (this.payUrlScheme
                    ? Promise.resolve()
                    : this.$http.get('/payOrder/v2/ali', { id: this.orderId, companyId: this.companyId }).then(res => {
                          this.payUrlScheme = res;
                      })
                )
                    .then(() => {
                        this.$nextTick(() => {
                            document.getElementById('pay').click();
                        });

                        this.getOrder(true);
                    })
                    .catch(e => {
                        this.$toast.clear();
                        e = e || {};
                        e.error = e.error || '支付失败';
                        this.$dialog
                            .alert({
                                title: '提示',
                                message: this.backReson(e.error)
                            })
                            .then(res => {
                                this.$router.back();
                            });
                    });
            }
        },
        goCoupon() {
            if (!this.orderId) {
                this.$router.push('/' + this.$route.params.companyId + '/couponList?collectionId=' + this.info.id);
            }
        },
        iapEvent(e) {
            console.log(e);
            switch (e.event) {
                case 'initiated':
                    this.$toast.loading({
                        duration: 0,
                        forbidClick: true,
                        message: '加载中'
                    });
                    break;
                case 'finished':
                    //this.$toast.clear();
                    this.$http.post('/notify/order/iap', {
                        receiptData: e.product.transaction.appStoreReceipt,
                        orderId: this.orderId
                    });
                    console.log(e.product.transaction.appStoreReceipt);
                    break;
                case 'cancelled':
                    this.$toast.clear();
                    this.orderId = null;
                    break;
            }
        }
    }
};
</script>

<style lang="less" scoped>
.page {
    background-color: @bg3;
}
.submit {
    padding: 20px 16px;
    background-color: @bg;
}

.pageTitle {
    font-size: 14px;
    color: @text0;
    line-height: 22px;
}

.info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 60px;
    border-bottom: 1px solid @tabBorder;
    .text1 {
        font-size: 14px;
        color: @text0;
        line-height: 24px;
        flex-grow: 1;
    }

    .text2 {
        font-size: @font2;
        font-weight: bold;
        color: var(--primlight);
        line-height: 24px;
    }

    .text3 {
        font-size: 14px;
        color: @text3;
        line-height: 20px;
    }

    .inter {
        width: 24px;
        height: 24px;
    }

    &.not {
        .text2 {
            font-size: @font2;
            color: @text3;
        }
    }
}

.product {
    display: flex;
    padding: 12px 0 20px;
    border-bottom: 1px solid @tabBorder;
    .product-content {
        flex-grow: 1;
        margin-left: 10px;
        display: flex;
        flex-direction: column;
        .no {
            flex-grow: 1;
            padding: 4px 0 8px;
            font-size: 14px;
            color: @text3;
            line-height: 24px;
        }

        .text1 {
            font-size: @font2;
            font-weight: bold;
            color: @text0;
            line-height: 24px;
        }

        .price {
            font-size: @font2;
            font-weight: bold;
            color: @text0;
            line-height: 24px;
        }
    }
}

/deep/.van-field {
    padding: 20px 0;
    .van-field__label {
        font-size: 14px;
        color: @text0;
        line-height: 24px;
    }
    .van-field__control {
        text-align: right;
        color: @text3;
    }
}

.pay-item {
    display: flex;
    align-items: center;
    height: 60px;
    border-bottom: 1px solid @tabBorder;
    .icon {
        height: 24px;
        display: block;
    }
    .img-icon {
        width: 45px;
        .flex();
        justify-content: center;
    }
    span {
        font-size: 14px;
        font-weight: bold;
        color: @text0;
        line-height: 24px;
        flex-grow: 1;
        padding: 0 10px;
    }
    .choose-icon {
        width: 24px;
        height: 24px;
    }

    &.not {
        span {
            color: @text3;
        }
    }
}

.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;
            --van-button-primary-background-color: var(--primlight);
            --van-button-primary-border-color: var(--primlight);
        }
        .text {
            font-size: 14px;
            color: @text3;
            line-height: 20px;
            word-break: keep-all;
        }

        .price {
            font-size: 34px;
            font-family: OSP;
            font-weight: normal;
            color: var(--primlight);
            line-height: 30px;
            display: flex;
            align-items: flex-end;

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

            img {
                width: 10px;
                height: 11px;
                display: block;
                margin-top: 8px;
            }
        }
    }
}
.van-number-keyboard {
    z-index: 9999;
}
:deep(.van-password-input__item) {
    background: @bg3;
}
</style>
