<template>
    <div class="submit">
        <div class="address" v-if="!info.airDrop">
            <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-title">
                <div class="text1">{{ info.name }}</div>
                <div class="text2" v-if="info.airDrop">商品的铸造将会销毁对应藏品，请谨慎选择</div>
            </div>

            <div class="assets-product" v-for="item in list" :key="item.id">
                <van-image width="60" height="60" radius="6" :src="getImg(changeImgs(item.pic))" fit="cover" />
                <div class="assets-info">
                    <div class="text1">{{ item.name }}</div>
                    <div class="flex1"></div>
                    <div class="text2" v-if="item.category">类型：{{ item.category }}</div>
                    <div class="text2" v-if="item.number">编号：{{ item.number }}</div>
                </div>
            </div>
        </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 :src="item.icon" alt="" />
                <span>{{ item.name }}</span>
                <img class="choose-icon" :src="payType === item.type ? icons[1] : icons[0]" alt="" />
            </div>
        </div>

        <div class="bottom van-safe-area-bottom" ref="bottom">
            <div class="bottom-content">
                <span class="text">GAS费</span>
                <span class="price"> <img src="@assets/jiage_huang.png" alt="" />{{ gas }} </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 asset from '../../mixins/asset';
import product from '../../mixins/product';
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: 'activitySubmit',
    inject: ['setKeeps'],
    mixins: [asset, product],
    data() {
        return {
            addressInfo: {},
            list: [],
            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')],
            inWeixin,
            inApp,
            inIos,
            gas: 1,
            enable_wx_lite: false,
            enable_wx_pub: false,
            assets: '',
            activityId: 0,
            orderId: 0,
            hrefUrl: '',
            timer: null,
            info: {}
        };
    },
    computed: {
        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() {
        this.emitter.on('updateChoose', info => {
            // console.log(id);
            this.addressInfo = info;
        });
        if (this.$route.query.assets) {
            this.assets = this.$route.query.assets;
            this.activityId = this.$route.query.activityId;
            this.getProduct(this.$route.query.assets.split(','));
            this.$http.get('/mintActivity/get/' + this.activityId).then(res => {
                this.info = res;

                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];
                        }
                    });
            });
        }

        Promise.all([
            this.$http.get('/sysConfig/get/gas_fee').then(res => {
                this.gas = res.value;
                if (this.$store.state.review) {
                    this.gas = 0;
                }
                return Promise.resolve();
            }),
            inWeixin
                ? this.$http.get('/sysConfig/get/enable_wx_pub').then(res => {
                      this.enable_wx_pub = res.value.split(',').findIndex(i => i === this.$route.query.id) > -1;
                      return Promise.resolve();
                  })
                : Promise.resolve(),
            this.$http.get('/sysConfig/get/enable_wx_lite').then(res => {
                this.enable_wx_lite =
                    res.value.split(',').findIndex(i => i === this.$route.query.id) > -1 &&
                    !/AliApp/i.test(navigator.userAgent);
                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';
            }
        });
    },
    methods: {
        onAdd() {
            this.$router.push('/mineAddress?page=submit&chooseId=' + this.addressInfo.id);
        },
        getOrder(next = false) {
            this.$http.get('/notify/adapay/mintOrder/' + this.orderId).then(res => {
                this.info = res;
                if (this.timer) {
                    clearTimeout(this.timer);
                }
                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('/activityOrderDetail?id=' + res.id);
                            }
                            // on close
                        });
                } else if (next) {
                    this.timer = setTimeout(() => {
                        this.getOrder(next);
                    }, 1000);
                }
            });
        },
        getProduct(list = [], index = 0) {
            if (index >= list.length) {
                return;
            }
            this.$http.get('/asset/get/' + list[index]).then(res => {
                this.list.push(res);
                this.getProduct(list, index + 1);
            });
        },
        createOrder() {
            if (!this.addressInfo.id && !this.info.airDrop) {
                this.$toast('请选择收货地址');
                return;
            }
            if (!this.payType) {
                this.$toast('请选择支付方式');
                return;
            }
            this.$toast.loading('请不要离开当前页面');

            return this.$http
                .post('/mintOrder/create', {
                    assets: this.assets,
                    mintActivityId: this.activityId,
                    addressId: this.addressInfo.id,
                    invitor: sessionStorage.getItem('invitor')
                })
                .then(res => {
                    return Promise.resolve(res);
                })
                .catch(e => {
                    return Promise.reject(e);
                });
        },
        submit() {
            if (!this.payType) {
                this.$toast('请选择支付方式');
                return;
            }
            this.createOrder()
                .then(res => {
                    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/mint/alipay_wx?id=' + res.id)
                                );
                            } else {
                                this.$http
                                    .get(`/payOrder/mint/${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/mint/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 || '支付失败请稍后再试');
                                });
                        }
                    });
                })
                .catch(e => {
                    if (e) {
                        this.$toast(e.error);
                    }
                });
        }
    },
    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: 12px;
            color: #000000;
            line-height: 24px;
        }

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

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

.pay-item {
    display: flex;
    align-items: center;
    height: 48px;
    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;
    }
}
.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;
            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;
            }
        }
    }
}
</style>
