<template>
    <div class="content">
        <div class="gift_confirmation">赠送确认</div>
        <div class="gift_confirmation_tip">通过手机号码检索用户信息，确认赠送后该加密作品将会被转移</div>
        <div class="gift_confirmation_information">
            <div class="gift_confirmation_information_title">用户信息</div>
            <van-divider />
            <div class="gift_confirmation_information_con">
                <van-image width="40px" height="40px" radius="65" :src="getImg(infos.avatar)" fit="cover" style="margin-right: 10px"/>
                <div>
                    <div class="gift_confirmation_information_con_name">{{ infos.realName || '保密' }}</div>
                    <div class="gift_confirmation_information_con_phone">手机号码&nbsp;{{ infos.phone }}</div>
                </div>
            </div>
        </div>
        <div class="transaction_password">
            <div class="transaction_password_one">
                <div class="transaction_password_one_title">请输入交易密码</div>
                <div class="transaction_password_forget" @click="$router.push('/tradingPassword')">
                    忘记密码
                    <van-divider />
                </div>
            </div>
            <van-divider />
            <div>
                <!-- v-if="sets" -->
                <!-- 密码输入框 -->
                <van-password-input
                :value="password"
                :gutter="10"
                :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>
            <!-- <div v-else class="text3" @click="$router.push('/tradingPassword')">您当前没有交易密码，点击去设置</div> -->
        </div>
        <div class="additional_costs">
            <div class="additional_costs_left">GAS费用</div>
            <div class="additional_costs_right">¥{{ gas }}</div>
        </div>
        <div class="payment_method">
            <div class="payment_method_con" @click="payType = item.type" v-for="(item, index) in payInfos" :key="index">
                <div class="payment_method_con_left">
                    <img :src="item.icon" alt="" class="payment_method_img">
                    <div class="payment_method_title">{{item.name}}</div>
                </div>
                <van-radio-group v-model="payType">
                    <van-radio :name="item.type" icon-size="24px" checked-color="#28B6FF"></van-radio>
                </van-radio-group>
            </div>
        </div>  
    </div>
    <div class="gift_button">
        <div class="gift_button_cancel" @click="$router.go(-1)">取消</div>
        <div class="gift_button_payment" @click="submit">
            <a id="pay" :href="hrefUrl"></a>
        确认支付</div>
        
    </div>
</template>

<script>
import resolveUrl from 'resolve-url';
import { add, im } from 'mathjs';
import { mapState } from 'vuex';
import product from '../mixins/product';
// import Driver from '../components/Driver.vue';
// import TopNavigation from "../components/TopNavigation.vue"
let inWeixin = /micromessenger/i.test(navigator.userAgent);
let inApp = /#cordova#/i.test(navigator.userAgent);
export default {
    name: 'Submit',
    mixins: [product],
    // components: {
    //     TopNavigation
    // },
    data() {
        return {
            info: {},
            infos:{},
            message: '',
            password: '',
            enable_wx_lite: false,
            enable_wx_pub: false,
            payType: inWeixin ? 'WEIXIN' : 'ALIPAY',
            // 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')],
            bottom: null,
            orderId: 0,
            gas: 1,
            showKeyboard: false,
            hrefUrl: '',
            inWeixin,
            inApp,
            timer: null,
            sets: false
        };
    },
    computed: {
        ...mapState(['userInfo']),
        money() {
            if (this.info.price) {
                return add(this.info.price, this.gas);
            } else {
                return 0;
            }
        }
    },
    mounted() {
        this.getGiverInformation()
        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();
            });
        }

        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.passFn();
        });
    },
    methods: {
        getGiverInformation(){
            this.$http
                .post('/user/searchByPhone', {
                    phone: this.$route.query.phone
                })
                .then(res=>{
                    this.infos = res
                })
        },
        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;
            }

            this.$toast.loading({
                message: '加载中...',
                forbidClick: true
            });
            this.$http
                .post('/user/verifyTradeCode', {
                    tradeCode: this.password
                })
                .then(() => {
                    this.$http
                        .post('/asset/gift', {
                            assetId: this.$route.query.id,
                            toUserId: this.$route.query.toUserId
                        })
                        .then(res => {
                            this.orderId = res.id;
                            this.$nextTick(() => {
                                if (this.payType === 'ALIPAY') {
                                    // document.location.replace(
                                    //     resolveUrl(this.$baseUrl, 'payOrder/gift/alipay?id=' + res.id)
                                    // );
                                    if (this.inWeixin) {
                                        document.location.replace(
                                            resolveUrl(this.$baseUrl, '/payOrder/gift/alipay_wx?id=' + res.id)
                                        );
                                    } else {
                                        this.$http
                                            .get(
                                                `/payOrder/gift/${this.inApp ? 'alipay_app' : 'alipay_h5'}?id=${res.id}`
                                            )
                                            .then(res => {
                                                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') {
                                    if (this.inWeixin) {
                                        this.$toast.loading('加载中');
                                        this.$http
                                            .post('/payOrder/gift/weixin', {
                                                id: res.id,
                                                openId: localStorage.getItem('openId')
                                            })
                                            .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=' + res.id)
                                        );
                                    }
                                }
                            });
                        })
                        .catch(e => {
                            if (e) {
                                this.$toast(e.error);
                            }
                        });
                })
                .catch(e => {
                    if (e) {
                        this.$toast('失败点击忘记密码进行修改');
                    }
                });
        }
    },
    beforeUnmount() {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
        }
    }
};
</script>

<style lang="less" scoped>
    .content{
        width: 100%;
        height: 100%;
        position: absolute;
        background: #0A0A1B;
        padding: 16px;
        box-sizing: border-box;
        .gift_confirmation{
            font-size: 20px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            margin-bottom: 6px;
            color: #FFFFFF;
        }
        .gift_confirmation_tip{
            font-size: 12px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #939599;
            margin-bottom: 20px;
        }
        .gift_confirmation_information{
            width: 100%;
            height: 103px;
            background: #29293F;
            border-radius: 8px;
            padding: 10px;
            box-sizing: border-box;
            .gift_confirmation_information_title{
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #FFFFFF;
                line-height: 24px;
                margin-bottom: 4px;
            }
            .gift_confirmation_information_con{
                margin-top: 8px;
                display: flex;
                // .gift_confirmation_information_con_img{
                //     width: 40px;
                //     height: 40px;
                //     border-radius: 65px;
                //     margin-right: 10px;
                // }
                .gift_confirmation_information_con_name{
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #FFFFFF;
                    line-height: 24px;
                }
                .gift_confirmation_information_con_phone{
                    font-size: 12px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #939599;
                    line-height: 17px;
                }
            }
        }
        .transaction_password{
            width: 100%;
            height: 103px;
            background: #29293F;
            border-radius: 8px;
            padding: 10px;
            box-sizing: border-box;
            margin-top: 10px;
            .transaction_password_one{
                display: flex;
                justify-content: space-between;
                margin-bottom: 4px;
                .transaction_password_one_title{
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #FFFFFF;
                }
                .transaction_password_forget{
                    width: 48px;
                    font-size: 12px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #939599;
                }
            }
            /deep/ .van-password-input{
                margin: 0;
                margin-top: 8px;
                .van-password-input__item{
                    width: 44px;
                    height: 44px;
                    background: rgba(10, 10, 27, 0.3);
                    border-radius: 8px;
                }
            }
        }
        .additional_costs{
            width: 100%;
            margin-top: 10px;
            background: #29293F;
            border-radius: 8px;
            padding: 12px 10px;
            box-sizing: border-box;
            display: flex;
            justify-content: space-between;
            .additional_costs_left{
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #FFFFFF;
            }
            .additional_costs_right{
                font-size: 14px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #28B6FF;
            }
        }
        .payment_method{
            width: 100%;
            background: #29293F;
            border-radius: 8px;
            padding: 12px 10px;
            box-sizing: border-box;
            margin-top: 10px;
            .payment_method_con{
                display: flex;
                justify-content: space-between;
                font-size: 14px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #FFFFFF;
                .payment_method_con_left{
                    display: flex;
                    .payment_method_title{
                        margin-top: 2px;
                    }
                }
                .payment_method_img{
                    width: 24px;
                    height: 24px;
                    margin-right: 6px;
                }
            }
            .payment_method_con:first-child{
            margin-bottom: 10px;
            border-bottom: 1px solid #5F646F;
            padding-bottom: 10px;
            box-sizing: border-box;
        }
        }
        .fee_details_divider{
            margin: 10px 0;
        }
    }
    .gift_button{
        position: fixed;
        bottom: 0;
        width: 100%;
        height: 56px;
        background: #15152D;
        padding: 8px 16px;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        .gift_button_cancel{
            width: 164px;
            height: 40px;
            border-radius: 8px;
            border: 1px solid #28B6FF;
            box-sizing: border-box;
            line-height: 40px;
            text-align: center;
            font-size: 16px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #28B6FF;
        }
        .gift_button_payment{
            width: 164px;
            height: 40px;
            background: #28B6FF;
            border-radius: 8px;
            font-size: 16px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #FFFFFF;
            text-align: center;
            line-height: 40px;
        }
    }
    /deep/ .van-password-input__security i{
        background-color: #fff !important;
    }
</style>
