<template>
    <div class="app-container">
        <!--        <van-tabs :swipeable="true" style="margin-top:0.5rem;padding:0 10px;">-->
        <van-form style="margin:50px 0;">
            <!--        <van-field-->
            <!--          v-model="formData.memberName"-->
            <!--          name="请输入姓名"-->
            <!--          placeholder="请输入姓名"-->
            <!--          :rules="[{ required: true, message: '' }]"-->
            <!--        />-->
            <!--        <van-field-->
            <!--          v-model="formData.idcard"-->
            <!--          name="请输入身份证号"-->
            <!--          style="margin-top: 20px"-->
            <!--          placeholder="请输入身份证号"-->
            <!--          :rules="[{ required: true, message: '' }]"-->
            <!--        />-->
            <van-field
                v-model="formData.mobile"
                name="请输入手机号"
                style="margin-top: 20px"
                placeholder="请输入手机号"
                :rules="[{ required: true, message: '' }]"
            />
            <!--            <van-field-->
            <!--                v-model="formData.code"-->
            <!--                center-->
            <!--                clearable-->
            <!--                label="验证码"-->
            <!--                placeholder="图形验证码"-->
            <!--            >-->
            <!--                <template #button>-->
            <!--                    <img style="width: 100px" :src="codeUrl" @click="getCode"/>-->
            <!--                </template>-->
            <!--            </van-field>-->
            <van-field
                v-model="formData.smsCode"
                style="margin-top: 20px"
                placeholder="请输入验证码"
                :rules="[{ required: true, message: '' }]"
            >
                <template #button>
                    <!-- <van-button size="mini" type="info" @click="getRegisterSmsCode" >获取验证码</van-button> -->
                    <div class="registerSmsBtn" @click="getRegisterSmsCode">{{
                        computeTime > 0 ? `(${computeTime}s)已发送` : "获取短信码"
                        }}
                    </div>
                </template>
            </van-field>
            <div style="margin: 50px 16px 16px;">
                <van-button block type="info" native-type="submit" @click="registerSubmit">绑定</van-button>
            </div>
        </van-form>
        <!--        </van-tabs>-->
    </div>
</template>
<style scoped>
    .app-container {
        background: #fff;
        height: 100vh;
    }

    .title {
        padding-top: 20%;
        width: 88%;
        margin: 0 auto;
    }

    .van-tab--active {
        font-size: .6rem;
        font-weight: bold;
    }

    .van-tabs__line {
        background: #1D6FE9;
        width: 0.15rem;
        height: 0.15rem;
        border-radius: 0.07rem;
        bottom: 0.3rem;
    }

    .van-tabs__nav {
        padding: 0
    }

    .van-tab {
        display: inline-block;
        flex: inherit;
        margin-left: 30px;
        line-height: .8rem;
    }

    .van-tab__text--ellipsis {
        overflow: auto;
    }

    .van-password-input {
        width: 50%;
        margin: 0 auto;
    }

    [class*=van-hairline]::after {
        border: none;
    }

    .van-password-input__security li {
        margin: 0 10px;
        border-bottom: 3px solid black;
    }

    .registerSmsBtn {
        color: rgb(29, 111, 233);
        font-size: 1rem;

    }
</style>
<script>
    import {getUUID} from '@/utils'

    const APPID = "wx7135dd84735bc392";
    // 静默授权：scope=snsapi_base
    // const WX_AUTH_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID
    //     + '&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=0#wechat_redirect';

    // 非静默授权：scope=snsapi_userinfo
    const WX_AUTH_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID
        + '&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect';

    export default {
        data() {
            return {
                showMessage: false,
                smsCodeValue: "",
                showKeyboard: false,
                formData: {
                    // username: "", //账号
                    // password: "", //密码
                    code: null, //图片验证码
                    uuid: null, //识别uuid
                    mobile: null, //手机号
                    smsCode: null, //短信验证码
                    codeTime: null, //短信验证码发送时间
                    openId: null, // openId
                    // memberName: null, //身份信息
                    // idcard: null, //身份号码
                    // rememberMe: false
                },
                loading: false,
                codeUrl: "", //验证码
                isSmsLogin: false, //是否手机验证码
                computeTime: 0,
                headimgurl: "",
                nickname: "",
            };
        },
        created() {
            // this.getCode();
            this.wxAuth();
        },
        methods: {
            showPopup() {
                this.showKeyboard = !this.showKeyboard
            },
            showMessagePop() {
                this.showMessage = !this.showMessage
            },
            wxAuth() {
                // 非静默授权：snsapi_userinfo，有弹框弹出需要用户手动点击确认授权。可以获取openId，用户的头像、昵称等
                return new Promise((resolve, reject) => {
                    let openid = this.$cookie.get('openid');
                    if (openid) {
                        resolve(openid);
                        return;
                    }
                    let code = this.getUrlParam('code');
                    if (!code) {//未经过微信授权
                        /**
                         * 获取网页授权登录code
                         * 如果有直接返回，如果没有重定向到腾讯授权页面，腾讯会再次重定向回来并带有code参数
                         **/
                        let code = this.getUrlParam('code');//获取URL中的code参数
                        if (code) return code;
                        let currentUrl = encodeURIComponent(window.location.href);
                        window.location.replace(WX_AUTH_URL.replace('REDIRECT_URI', currentUrl));
                    } else {
                        this.$cookie.set('appid', APPID); //接口服务端从cookie中读取openid
                        this.$http({
                            url: this.$http.adornUrl('/wxAuth/codeToUserInfo'),
                            method: 'post',
                            data: this.$http.adornParams({
                                'code': code
                            })
                        }).then(res => {
                            if (res.data.code == 200) {
                                console.log("微信授权完成");
                                this.headimgurl = res.data.headimgurl;
                                this.nickname = res.data.nickname;
                                console.log(this.headimgurl);
                                console.log(this.nickname);
                            } else {
                                console.log("换取openid失败");
                            }
                        });
                    }
                });

                // 静默授权：snsapi_base，没有弹窗，只能获取用户的openId。
                // return new Promise((resolve, reject) => {
                //     let openid = this.$cookie.get('openid');
                //     if (openid) {
                //         resolve(openid);
                //         return;
                //     }
                //     let code = this.getUrlParam('code');
                //     if (!code) {//未经过微信授权
                //         let currentUrl = encodeURIComponent(window.location.href);
                //         window.location.replace(WX_AUTH_URL.replace('REDIRECT_URI', currentUrl));
                //     } else {
                //         this.$cookie.set('appid', APPID); //接口服务端从cookie中读取openid
                //         this.$http({
                //             url: this.$http.adornUrl('/wxAuth/codeToOpenid'),
                //             method: 'post',
                //             data: this.$http.adornParams({
                //                 'code': code
                //             })
                //         }).then(res => {
                //             if (res.code == 200) {
                //                 console.log("微信授权完成" + res.data);
                //                 resolve(res.data);
                //             } else {
                //                 console.log("换取openid失败");
                //             }
                //         });
                //     }
                // });
            },
            getUrlParam(key) {//获取当前页面url中的参数
                var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
                var result = window.location.search.substr(1).match(reg);
                return result ? decodeURIComponent(result[2]) : '';
            },
            getCode() {
                this.formData.uuid = getUUID()
                this.codeUrl = this.$http.adornUrl(`/captcha?uuid=${this.formData.uuid}`)
            },
            getRegisterSmsCode() {
                if (!this.computeTime) {
                    let myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
                    if (!myreg.test(this.formData.mobile)) {
                        this.$dialog.alert({
                            message: '手机号格式不正确',
                        });
                        return false;
                    }
                    // else if (this.formData.code == "") {
                    //     this.$dialog.alert({
                    //         message: '图片验证码不能为空',
                    //     });
                    //     return false;
                    // }
                    this.$http({
                        url: this.$http.adornUrl('/sms/code'),
                        method: 'post',
                        data: this.$http.adornParams({
                            'mobile': this.formData.mobile
                        })
                    }).then((res) => {
                        if (res.data.code == 200) {
                            this.$dialog.alert({
                                message: '验证码已发送',
                            });
                            this.formData.codeTime = res.data.smsCode;
                            this.computeTime = 60;
                            this.timer = setInterval(() => {
                                this.computeTime--;
                                if (this.computeTime <= 0) {
                                    clearInterval(this.timer);
                                }
                            }, 1000);
                        } else {
                            this.$dialog.alert({
                                message: res.data.msg,
                            });
                        }
                    }).catch((res) => {
                        this.$dialog.alert({
                            message: '验证码发送失败' + res.data.msg,
                        });
                    });
                }
            },
            registerSubmit() {
                //绑定
                if (this.formData.mobile == "") {
                    this.$dialog.alert({
                        message: '手机号码不能为空',
                    });
                    return false;
                } else if (this.formData.smsCode == "") {
                    this.$dialog.alert({
                        message: '短信验证码不能为空',
                    });
                    return false;
                }
                this.$http({
                    url: this.$http.adornUrl('/sms/verifyCode'),
                    method: 'post',
                    data: this.$http.adornParams({
                        'openId': this.$cookie.get('openid'),
                        'headimgurl': this.headimgurl,
                        'nickname': this.nickname,
                        'mobile': this.formData.mobile,
                        'code': this.formData.smsCode,
                        'codeTime': this.formData.codeTime
                    })
                }).then((res) => {
                    if (res.data.code == 200) {
                        this.$dialog.alert({
                            message: '手机号绑定成功',
                        });
                    } else {
                        this.$dialog.alert({
                            message: res.data.msg,
                        });
                    }
                }).catch((res) => {
                    this.$dialog.alert({
                        message: '手机号绑定失败' + res.data.msg,
                    });
                });
            }
        },
    };
</script>