<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 priceColor">¥{{ iosPrice || info.price }}</div>
                </div>
                <div class="info">
                    <div class="text1">GAS费用</div>
                    <div class="text2 priceColor">¥{{ iosPrice ? 0 : 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" /> -->

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

<script>
import product from '../mixins/product';
import coupon from '../mixins/coupon';
import { mapState } from 'vuex';
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);
export default {
    name: 'Submit',
    mixins: [product, coupon],
    data() {
        return {
            info: {},
            message: '',
            payType: inWeixin ? 'WEIXIN' : 'ALIPAY',
            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')],
            bottom: null,
            orderId: 0,
            gas: 1,
            inWeixin,
            inApp,
            inIos,
            couponList: [],
            collectionId: 0,
            timer: null,
            hrefUrl: '',
            enable_wx_lite: false,
            enable_wx_pub: false,
            launchName: '',
            launchPath: '',
            iosPrice: 0
        };
    },
    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);
            }

            if (this.iosPrice) {
                money = this.iosPrice;
            }

            return money;
        },
        ...mapState(['couponInfo'])
    },
    beforeRouteLeave(to, from, next) {
        console.log(to);
        if (to.path !== '/couponList') {
            this.$store.commit('setCouponInfo', null);
        }
        next();
    },
    mounted() {
        if (this.inApp && this.inIos) {
            this.$http.get(`/appVersion/checkIosReview?version=${navigator.appInfo.version}`).then(res => {
                if (res.review === true) {
                    this.iosPrice = 328;
                }
            });
        }
        console.log(navigator.appInfo);

        Promise.all([
            this.$http.get('/sysConfig/get/gas_fee').then(res => {
                this.gas = res.value;
                return Promise.resolve();
            }),
            inWeixin
                ? this.$http.get('/sysConfig/get/enable_wx_pub').then(res => {
                      this.enable_wx_pub = res.value === '1';
                      return Promise.resolve();
                  })
                : Promise.resolve(),
            this.$http.get('/sysConfig/get/enable_wx_lite').then(res => {
                this.enable_wx_lite = res.value === '1';
                return Promise.resolve();
            })
        ]).then(() => {
            if (!(this.enable_wx_lite || this.enable_wx_pub)) {
                this.payInfos.splice(1, 1);
                this.payType = 'ALIPAY';
            } else if (this.enable_wx_pub) {
                this.payChannel = 'wx_pub';
            } else {
                this.payChannel = 'wx_lite';
            }
        });
        this.$toast.loading({
            message: '加载中...',
            forbidClick: true
        });
        if (this.$route.query.id) {
            this.collectionId = Number(this.$route.query.id);
            this.$http.get('/collection/get/' + this.$route.query.id).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 (res.status === 'PROCESSING' || res.status === 'FINISH' || res.status === 'CANCELLED') {
                    this.$dialog
                        .alert({
                            title: '提示',
                            message:
                                res.status === 'CANCELLED' ? '订单支付失败,点击重新下单' : '订单已支付,点击查看订单详情'
                        })
                        .then(() => {
                            if (res.status === 'CANCELLED') {
                                this.$router.back();
                            } else {
                                this.$router.replace('/orderDetail?id=' + res.id);
                            }
                            // on close
                        });
                } else if (next) {
                    this.timer = setTimeout(() => {
                        this.getOrder(next);
                    }, 1000);
                }
            });
        },
        getCouponList() {
            this.$http
                .post(
                    '/userCoupon/all',
                    {
                        query: {
                            userId: this.$store.state.userInfo.id,
                            used: false,
                            projectId: this.$store.state.projectId
                        }
                    },
                    { body: 'json' }
                )
                .then(res => {
                    this.couponList = [...res.content].filter(item => {
                        return this.checkTime(item) && this.checkUse(item, this.collectionId);
                    });
                });
        },
        submit() {
            if (!this.payType) {
                this.$toast('请选择支付方式');
                return;
            }
            this.$toast.loading('加载中');
            let url = '/order/create?collectionId=' + this.$route.query.id + '&qty=1';
            if (this.couponInfo) {
                url += '&couponId=' + this.couponInfo.id;
            }
            let invitor = sessionStorage.getItem('invitor');
            if (invitor) {
                url += '&invitor=' + invitor;
            }
            this.$http
                .post(url)
                .then(res => {
                    if (this.money) {
                        this.$toast.clear();
                        this.orderId = res.id;
                        this.$router.replace({ query: { ...this.$route.query, orderId: res.id } });
                        this.$nextTick(() => {
                            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/alipay_wx?id=' + res.id)
                                    );
                                } else {
                                    this.$http
                                        .get(`/payOrder/${this.inApp ? 'alipay_app' : 'alipay_h5'}?id=${res.id}`)
                                        .then(res => {
                                            this.$toast.clear();
                                            this.hrefUrl = 'alipays://platformapi/startapp?saId=10000007&qrcode=' + res;
                                            // window.open(
                                            //     'alipays://platformapi/startapp?saId=10000007&qrcode=' + res,
                                            //     '_blank'
                                            // );
                                            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/weixin', {
                                        id: res.id,
                                        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);
                                        }
                                        // 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 {
                        this.$toast.success('支付成功');
                        setTimeout(() => {
                            this.$router.replace('/orderDetail?id=' + res.id);
                        }, 1000);
                    }
                })
                .catch(e => {
                    if (e) {
                        this.$toast(e.error);
                    }
                });
        },
        goCoupon() {
            if (!this.orderId) {
                this.$router.push('/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: @prim;
        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;
    span {
        font-size: 14px;
        font-weight: bold;
        color: @text0;
        line-height: 24px;
        flex-grow: 1;
        padding: 0 10px;
    }
    .choose-icon {
        width: 24px;
        height: 24px;
    }
}

.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;
            word-break: keep-all;
        }

        .price {
            font-size: 34px;
            font-family: OSP;
            font-weight: normal;
            color: @priceColor;
            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;
            }
        }
    }
}
</style>
