<template>
    <div class="submit">
        <div class="page-top">
            <div class="pageTitle">赠送作品</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 van-multi-ellipsis--l2">
                        {{ info.name }}
                    </div>
                    <div class="text" v-if="info.number">编号:{{ info.number }}</div>
                    <div class="no"></div>

                    <div class="price">¥{{ info.price }}</div>
                </div>
            </div>
        </div>
        <driver />
        <div class="input">
            <div class="text1">请输入交易密码，验证信息</div>
            <div v-if="sets">
                <van-password-input
                    :gutter="10"
                    :value="password"
                    :focused="showKeyboard"
                    @focus="showKeyboard = true"
                />
                <!-- 数字键盘 -->
                <van-number-keyboard
                    v-model="password"
                    :show="showKeyboard"
                    @blur="showKeyboard = false"
                    maxlength="6"
                    theme="custom"
                    close-button-text="完成"
                    random-key-order
                />
                <div class="text2" @click="$router.push('/' + $route.params.companyId + '/tradingPassword')">
                    忘记密码？
                </div>
            </div>
            <div v-else class="text3" @click="$router.push('/' + $route.params.companyId + '/tradingPassword')">
                您当前没有交易密码，点击去设置
            </div>
        </div>
        <driver />
        <div class="list">
            <div class="info">
                <div class="text1">GAS费用</div>
                <div class="text2">¥{{ gas }}</div>
            </div>

            <div class="pay">
                <pay-method-pick v-model="payType"></pay-method-pick>
                <!-- <div class="pay-item" @click="payType = item.type" v-for="(item, index) in payInfos" :key="index">
                    <div class="img-icon"><img class="icon" :src="item.icon" alt="" /></div>
                    <span>{{ item.name }}</span>
                    <img class="choose" :src="payType === item.type ? icons[1] : icons[0]" alt="" />
                </div>
                <div class="pay-item not" @click="wait">
                    <div class="img-icon">
                        <img class="icon" src="@assets/icon_RMB.png" alt="" />
                    </div>
                    <span>数字人民币</span>
                    <img class="choose-icon" :src="icons[2]" alt="" />
                </div>
                <div class="pay-item not" @click="wait">
                    <div class="img-icon">
                        <img class="icon" src="@assets/icon-jifen1.png" alt="" />
                    </div>
                    <span>积分</span>
                    <img class="choose-icon" :src="icons[2]" alt="" />
                </div>
                <div class="pay-item not" @click="wait">
                    <div class="img-icon">
                        <img class="icon" src="@assets/icon-lvzhoushi.png" alt="" />
                    </div>
                    <span>绿洲石</span>
                    <img class="choose-icon" :src="icons[2]" alt="" />
                </div> -->
            </div>
        </div>

        <div class="bottom van-safe-area-bottom" ref="bottom">
            <div class="bottom-content">
                <div class="btn1" @click="$router.go(-1)">
                    取消
                    <!-- <van-button @click="submit" :disabled="orderId"> 取消 </van-button> -->
                </div>
                <div class="btn2" @click="submit">支付GAS费</div>
                <a id="pay" :href="hrefUrl"></a>
            </div>
        </div>
    </div>
</template>

<script>
import resolveUrl from 'resolve-url';
import { add } from 'mathjs';
import { mapState } from 'vuex';
import product from '../mixins/product';
import PayMethodPick from '../components/PayMethodPick.vue';
// import Driver from '../components/Driver.vue';
let inWeixin = /micromessenger/i.test(navigator.userAgent);
let inApp = /#cordova#/i.test(navigator.userAgent);
export default {
    components: { PayMethodPick },
    name: 'Submit',
    mixins: [product],
    data() {
        return {
            info: {},
            message: '',
            password: '',
            enable_wx_lite: false,
            enable_wx_pub: false,
            payType: null,
            // payType: 'ALIPAY',
            // 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/icon_gouxuan_huise.png'),
                require('@assets/icon_gouxuan_pre.png'),
                require('@assets/icon_gouxuan_huise1.png')
            ],
            bottom: null,
            orderId: 0,
            gas: 1,
            showKeyboard: false,
            hrefUrl: '',
            inWeixin,
            inApp,
            timer: null,
            sets: false
        };
    },
    computed: {
        ...mapState(['userInfo', 'companyId']),
        money() {
            if (this.info.price) {
                return add(this.info.price, this.gas);
            } else {
                return 0;
            }
        }
    },
    mounted() {
        this.$toast.loading({
            message: '加载中...',
            forbidClick: true
        });
        if (this.$route.query.id) {
            this.$http.get('/asset/get/' + this.$route.query.id).then(res => {
                this.info = res;
                this.$toast.clear();
                console.log(this.info);
            });
        }
        this.$http.get('/sysConfig/get/gift_gas_fee').then(res => {
            this.gas = res.value;
            return Promise.resolve();
        });
        this.passFn();
    },
    methods: {
        passFn() {
            this.$http
                .get('/user/tradeCodeStatus', {
                    userId: this.userInfo.id
                })
                .then(res => {
                    console.log(res);
                    this.sets = res.set;
                });
        },
        getOrder(next = false) {
            this.$http.get('/giftOrder/get/' + this.orderId).then(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.go(-2);
                            } else {
                                this.$router.go(-2);
                            }
                            // on close
                        });
                } else if (next) {
                    this.timer = setTimeout(() => {
                        this.getOrder(next);
                    }, 1000);
                }
            });
        },
        submit() {
            if (this.orderId) {
                return;
            }

            if (!this.password) {
                this.$toast('请输入密码');
                return;
            }

            this.$toast.loading({
                message: '加载中...',
                forbidClick: true
            });
            this.$http
                .post('/user/verifyTradeCode', {
                    tradeCode: this.password
                })
                .then(() => {
                    if (Number(this.gas)) {
                        this.$http
                            .post('/asset/gift', {
                                assetId: this.$route.query.id,
                                toUserId: this.$route.query.toUserId,
                                tradeCode: this.password
                            })
                            .then(res => {
                                this.orderId = res.id;
                                console.log(this.payType);
                                this.pay();
                            })
                            .catch(e => {
                                if (e) {
                                    this.$toast(e.error);
                                }
                            });
                    } else {
                        this.$http
                            .post('/asset/giftWithoutGasFee', {
                                assetId: this.$route.query.id,
                                toUserId: this.$route.query.toUserId,
                                tradeCode: this.password
                            })
                            .then(res => {
                                this.$toast.success('转赠成功');
                                setTimeout(() => {
                                    this.$router.go(-2);
                                }, 1500);
                            })
                            .catch(e => {
                                if (e) {
                                    this.$toast(e.error);
                                }
                            });
                    }
                })
                .catch(e => {
                    if (e) {
                        this.$toast(e.error);
                    }
                });
        },
        pay() {
            this.$nextTick(() => {
                if (this.payType === 'SYXPAY') {
                    this.$toast.clear();
                    this.$router.replace(
                        '/' + this.$route.params.companyId + '/bankPay?id=' + this.orderId + '&type=gift'
                    );
                } else if (this.payType === 'ALIPAY') {
                    // document.location.replace(
                    //     resolveUrl(this.$baseUrl, 'payOrder/v2/gift/alipay?id=' + res.id)
                    // );
                    if (this.inWeixin) {
                        document.location.replace(
                            resolveUrl(
                                this.$baseUrl,
                                '/payOrder/v2/gift/alipay_wx?id=' + this.orderId + '&companyId=' + this.companyId
                            )
                        );
                    } else {
                        this.$http
                            .get(`/payOrder/v2/gift/alipay?id=${this.orderId}&companyId=${this.companyId}`)
                            .then(res => {
                                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') {
                    if (this.inWeixin) {
                        this.$toast.loading('加载中');
                        this.$http
                            .post('/payOrder/gift/weixin', {
                                id: this.orderId,
                                openId: localStorage.getItem('openId'),
                                companyId: this.companyId
                            })
                            .then(res => {
                                console.log({
                                    ...res,
                                    package: res.package || res.packageValue,
                                    timestamp: res.timestamp || res.timeStamp
                                });
                                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('支付失败，请稍后再试');
                                    }
                                });
                            });
                    } else {
                        document.location.replace(
                            resolveUrl(
                                this.$baseUrl,
                                'payOrder/gift/weixin_h5?id=' + this.orderId + '&companyId=' + this.companyId
                            )
                        );
                    }
                } else if (this.payType === 'UNION') {
                    document.location.href = resolveUrl(
                        this.$baseUrl,
                        '/payOrder/v2/gift/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/gift/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(-2);
                                });
                        });
                } else if (this.payType === 'BALANCE') {
                    this.$toast.loading({
                        message: '支付中',
                        forbidClick: true
                    });
                    this.$http
                        .post('/payOrder/v2/gift/balance', {
                            id: this.orderId,
                            tradeCode: this.password,
                            companyId: this.companyId
                        })
                        .then(res => {
                            this.$toast.success('支付成功');
                            setTimeout(() => {
                                this.$router.go(-2);
                            }, 1000);
                        })
                        .catch(e => {
                            this.$toast(e.error || '支付失败');
                        });
                } else if (this.payType === 'ALI') {
                    this.$http
                        .get('/payOrder/v2/gift/ali', { id: this.orderId, companyId: this.companyId })
                        .then(res => {
                            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);
                            }
                        });
                }
            });
        }
    },
    beforeUnmount() {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
        }
    }
};
</script>

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

.pageTitle {
    font-size: 14px;
    color: @text0;
    line-height: 22px;
}
.input {
    padding: 20px 16px;
    background-color: @bg;
    .text1 {
        font-size: 14px;
        color: @text0;
        line-height: 24px;
        margin-bottom: 6px;
        text-align: center;
    }
    .text2 {
        font-size: 14px;
        text-align: right;
        font-weight: 400;
        color: @text3;
        line-height: 24px;
        margin-right: 15px;
    }

    .text3 {
        font-size: @font2;
        color: #ff4f50;
        line-height: 24px;
        margin-top: 25px;
        display: flex;
        justify-content: center;
    }
}

/deep/ .van-password-input {
    margin: 0 0;
    .van-password-input__security {
        border: 0px solid @text3!important;
        height: 42px;
        border-radius: 2px;
        li {
            background-color: transparent;
            border: 1px solid @text3;
            border-radius: 2px;
            i {
                color: @text0;
            }
        }
    }
}
/deep/.van-number-keyboard__body {
    background-color: fade(#4a4a4a, 50%);
    .van-key {
        // background-color: @bg;
        &:active {
            background-color: @bg3;
        }
    }
}
.list {
    padding: 0 16px;
    background-color: @bg;
}
.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;
    }

    .text2 {
        font-size: 16px;
        font-weight: bold;
        color: @prim;
        line-height: 24px;
    }

    .text3 {
        font-size: 14px;
        color: @text3;
        line-height: 20px;
    }
}
/deep/ .van-password-input {
    margin: 10px 0;
    padding: 0 15px;
    .van-password-input__security {
        border: 1px solid @text3;
        height: 42px;
        border-radius: 2px;
        li {
            background-color: transparent;
            &:not(:last-child) {
                border-right: 1px solid @text3;
            }
            i {
                color: @text0;
            }
        }
    }
}
.product {
    display: flex;
    padding: 12px 0 20px;
    .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;
        }
        .text {
            font-size: 14px;
            color: @text3;
            line-height: 24px;
            margin-top: 4px;
        }
        .text1 {
            font-size: @font2;
            color: @text0;
            line-height: 24px;
        }
        .text3 {
            font-size: @font2;
            font-weight: 400;
            color: #b81c22;
            line-height: 24px;
            margin-top: 40px;
            display: flex;
            justify-content: center;
        }
        .price {
            font-size: 16px;
            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-top: 1px solid #202122;
    .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 {
        width: 24px;
        height: 24px;
    }
    .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: center;
        justify-content: space-between;

        .btn1 {
            width: 161px;
            height: 44px;
            border-radius: 22px;
            line-height: 44px;
            color: @text3;
            text-align: center;
            border: 1px solid @text3;
        }
        .btn2 {
            width: 162px;
            height: 44px;
            line-height: 44px;
            text-align: center;

            color: @btnText;
            background: linear-gradient(135deg, @prim 0%, @prim 100%);
            border-radius: 22px;
        }
        .van-button {
            flex-grow: 1;
            color: #333230 !important;
            max-width: 210px;
        }
        .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: 34px;
            // flex-grow: 1;
            margin: 0 10px;
            .font_family {
                font-size: 10px;
            }
        }
    }
}
</style>
