<template>
    <div id="register" class="register">
        <div class="fs-29 c-333 tl pl30 pt30 pb20">注册账户</div>
        <div class="plr30 bgc-fff" id="inpForm">
            <van-cell-group>
                <!-- <van-field v-if="alias!='zs'" placeholder="请输入姓名" v-model="data.userName" clearable class="right-line">
                    <div slot="left-icon" class="left-icon-wrap">
                        <img class="left-icon"  src="@/assets/images/xingming_icon.png" alt="">
                    </div>
                </van-field>
                <van-field  placeholder="请输入身份证号码" v-model="data.idCard" clearable class="right-line">
                    <div slot="left-icon" class="left-icon-wrap">
                        <img class="left-icon"  src="@/assets/images/shenfenzheng_icon.png" alt="">
                    </div>
                </van-field> -->
                <van-field type="tel" placeholder="请输入手机号码" v-model="data.mobile" maxlength="11" clearable class="mobile right-line">
                    <div slot="left-icon" class="left-icon-wrap">
                        <img class="left-icon"  src="@/assets/images/shouji_icoon.png" alt="">
                    </div>
                </van-field>
                <van-field v-model="data.msgCode" class="codeInp right-line" clearable @click-icon="msgCode=''" maxlength="10"  placeholder="短信验证码">
                    <div slot="left-icon" class="left-icon-wrap">
                        <img class="left-icon"  src="@/assets/images/yanzhengma_icon.png" alt="">
                    </div>
                    <van-button round slot="button" size="small" :disabled="countdown > 0" @click="sendMobileCode" type="primary">
                        {{ countdown ? countdown + 's' +' 后重发': '发送验证码'}}
                    </van-button>
                </van-field>
                <van-field @input="validPwd" class="mima right-line" type="password" v-model="data.password" maxlength="16" placeholder="请输入登录密码">
                    <div slot="left-icon" class="left-icon-wrap">
                        <img class="left-icon"  src="@/assets/images/mima_icon.png" alt="">
                    </div>
                </van-field>
                <!-- <div class="tips">
                    <div><van-icon name="success" class="v-middle" color="#14b914" v-if="s1==1"/><van-icon color="#ff0000" v-else-if="s1==2" name="cross" />8-20个字符</div>
                    <div><van-icon name="success" class="v-middle" color="#14b914" v-if="s2==1"/><van-icon color="#ff0000" v-else-if="s2==2" name="cross" />只能设置大小写字母、数字及标点符号(不允许输入#：")。</div>
                    <div><van-icon name="success" class="v-middle" color="#14b914" v-if="s3==1"/><van-icon color="#ff0000" v-else-if="s3==2" name="cross" />必须包含大小写字母、数字及标点符号其中三种。</div>
                </div> -->
                <van-field class="mima right-line" type="password" v-model="data.againPassword" maxlength="16" placeholder="请再次输入登录密码">
                    <div slot="left-icon" class="left-icon-wrap">
                        <img class="left-icon"  src="@/assets/images/mimasuo_icon.png" alt="">
                    </div>
                </van-field>
            </van-cell-group>
            <div class="mt32 pb20">
                <van-button v-if="!loading" block round type="primary" @click="submit" class="">
                   注  册
                </van-button>
                <van-button v-else block round type="primary" class=""><van-loading class="login-loading" color="#ffffff"/>
                </van-button>
            </div>
        </div>
    </div>
</template>

<script>
import { getPublicKey, login, imgCaptcha, sendCaptcha, registerPatientAndLogin, captcha } from "@/api/login";
import ValidatorUtils from '@/utils/validator'
import {isIdcard} from '@/utils/validator'
import { setTimeout } from 'timers';
import { getSign, getOpenidByCode} from "@/api/wx"
export default {
    name: "register",
    data() {
        return {
            openid: this.$route.query.openid||"",
            countdown: 0,
            // 验证对象
            validator: undefined,
            data: {
                userName: "",
                idCard: "",
                mobile: "",
                sbk: "",
                msgCode: "",
                password: "",
                againPassword: ""
            },
            rules: {
                mobile: [
                    { required: true, message: '请输入手机号码' },
                    { pattern: /^[1][0-9]{10}$/, message: '请输入正确的手机号码' }
                ],
            },
            redirect: undefined,
            loading: false,

            testReq: /((?=[\x21-\x7e]+)[^A-Za-z0-9])/,
            testNumber: /[0-9]/,
            testLetter: /[A-Za-z]/,
            s1: -1,
            s2: -1,
            s3: -1,
        };
    },
    watch: {
        $route: {
            handler(route) {
                this.redirect = route.query && route.query.redirect;
                this.openid = route.query && route.query.openid;
            },
            immediate: true
        }
    },
    async created() {
        // this.$store.dispatch("SetLoading",true)
        this.validator = new ValidatorUtils({
            rules: this.rules,
            data: this.data 
        })
        //await this.fetchOpenid()
        this.initPage();
    },
    methods: {
        // fetchOpenid(code) {
        //     //微信授权过来的  取得到code
        //     if(code){
        //         return getOpenidByCode({
        //             code: code
        //         }).then((res)=>{
        //             if(res.status==200){
        //                 store.dispatch('SetLoginUser', {openid: res.obj})
        //                 return Promise.resolve(res.obj)
        //             } else {
        //                 vant.Toast('获取openid失败');
        //                 return Promise.reject()
        //             }
        //         }).catch((err)=>{
        //             vant.Toast('获取openid失败');
        //             console.error(err)
        //             return Promise.reject()
        //         })
        //     }
            
        // },
        changeLogin(){
            this.$router.push({path: "/login", query: this.$route.query})
        },
        initPage() {
            // this.$store.dispatch("SetLoading",false)
        },
        countdownSubtract() {
            //验证码
            if (this.countdown > 0) {
                setTimeout(() => {
                    if(this.countdown>0){
                        this.countdown -= 1;
                        this.countdownSubtract();
                    }
                }, 1000);
            }
        },
        goPage(url){
            this.$router.push({
                path:url
            });
        },
        sendMobileCode() {
            this.validator.validate("mobile").then(() => {
                this.countdown = 60;
                this.countdownSubtract();
                sendCaptcha({
                    username: this.data.mobile,
                    client_id: this.$store.getters.clientId,
                    wxId: process.env.VUE_APP_WXID
                }).then((res) => {
                    if(res.status == 200) {
                        this.$toast("发送成功");
                    } else {
                        this.countdown = 0;
                        this.$toast("发送失败");
                    }
                }).catch(err=>{
                    console.error(err)
                    this.countdown = 0;
                })
            }, (err) => {
                this.$toast(err[0].message)
            })
        },
        validateIdCard(){
            if(!this.data.idCard || !this.data.idCard.trim()){
                return false
            }
            var idcard = this.data.idCard
            var idcardLen = idcard.length,
                xchar = idcard.charAt(idcardLen-1);
            if (xchar === 'x') {
                idcard = idcard.substr(0, idcardLen-1) + 'X';
            }
            return isIdcard(idcard)
        },
        validateMobile(){
            if(!this.data.mobile || !this.data.mobile.trim()){
                return false
            }
            return /^[1][0-9]{10}$/.test(this.data.mobile)
        },
        validPwd(){
            if(this.data.password.length>=8&&this.data.password.length<=20){
                this.s1 = 1
            } else {
                this.s1 = 2
            }
            if(/^[A-Za-z0-9\x21-\x7e]{1,}$/.test(this.data.password) && /^((?!#|：|"|").)*$/.test(this.data.password)){
                this.s2 = 1
            } else {
                this.s2 = 2
            }
            if( (/[A-Z]/.test(this.data.password) && /[a-z]/.test(this.data.password) && (this.testReq.test(this.data.password) || this.testNumber.test(this.data.password)))
                ||
                (this.testReq.test(this.data.password) && this.testNumber.test(this.data.password) && this.testLetter.test(this.data.password))
                ){
                this.s3 = 1
            } else {
                this.s3 = 2
            }
        },
        validate() {
            return new Promise((resolve, reject)=>{
                // if((!this.data.userName || !this.data.userName.trim()) && this.alias!='zs'){
                //     reject("请输入您的姓名") 
                // } else if(!this.validateIdCard()){
                //     reject("请输入正确身份证号码") 
                // } else 
                if(!this.validateMobile()){
                    reject("请输入正确的手机号码") 
                } else if(!this.data.msgCode || !this.data.msgCode.trim()){
                    reject("请输入短信验证码") 
                } 
                else if(this.data.password.length<6 ){
                    reject("密码不能小于6个字符") 
                } 
                // else if(this.s1!=1 || this.s2!=1 || this.s3!=1 ){
                //     reject("密码设置不符合要求") 
                // } 
                else if(this.data.againPassword != this.data.password){
                    reject("两次密码不一致") 
                }

                resolve()
            }).then(() => {
                // 校验成功
                this.register()
            }, 
            (err) => {
                // 校验失败
                this.$toast.clear()
                this.$toast(err)
                return Promise.reject(err)
            })
        },
        submit(){
            this.$toast.loading({
                duration: 0,
                forbidClick: true, // 禁用背景点击
                loadingType: 'loading',
                message: "提交中..."
            })
            this.validate()
        },
        async register() {
            var that = this
            var p = {
                name: this.data.userName,
                mobile: this.data.mobile,
                pw: this.data.password,
                captcha: this.data.msgCode,
                openid: this.user.openid,
                wxId: process.env.VUE_APP_WXID,
                client_id: this.$store.getters.clientId,
                login_type: 3, // 1-平台管理员  2-医生登录  3-患者登录

                idcard: this.data.idCard,
                ssc: this.data.sbk,
            }
            
            registerPatientAndLogin(p).then(async result => {
                
                if (result.status == 200) {
                  this.$toast.clear()
                  localStorage.removeItem("Medical-Care-Wx-Logined-User-Agent")
                  localStorage.removeItem("Medical-Care-Wx-Logined-User")
                  var userAgent = {
                      id: result.obj.id,
                      uid: result.obj.id,
                    }
                  localStorage.setItem("Medical-Care-Wx-Logined-User-Agent", JSON.stringify(userAgent))
                  this.$store.dispatch('SetLoginUser', result.obj)
                //   let userInfo = await this.getPatientById(result.obj)
                    // var userAgent = {
                    //     id: result.obj.id,
                    //     uid: result.obj.user,
                    // }
                    // this.$store.dispatch('SET_HLW_USER_AGENT', userAgent)
                    // localStorage.setItem("token", result.obj.accessToken)
                    // localStorage.setItem("hlwUserAgent", JSON.stringify(userAgent))
                    this.$router.push("/setRole")
                } else {
                    this.$toast.clear()
                    this.$toast(result.status==1300? "验证码错误" : result.message);
                }
            }).catch(err=>{
                this.reponseMsg(err.message)
            })
        },
        async getPatientById(userInfo){
            var res = await residentApi.getPatientById({
                id: userInfo.id
            }).catch(err=>{
                console.error(err)
            })
            userInfo = _.assignIn(userInfo, res.obj.patient)
            this.$store.dispatch('SetLoginUser', userInfo)

            return userInfo
        },
        reponseMsg(text){
            if(text=='该手机号已经注册过'){
                this.$toast.clear()
                this.$dialog.confirm({
                    title: '提示',
                    message: '该手机号码已注册，请直接使用短信验证码进行登录。',
                    cancelButtonText: '取消',
					confirmButtonText: '去登陆'
                }).then(() => {
                    this.$router.push({
                        path: "/login",
                        query: {
                            loginType: 2,
                            mobile: this.data.mobile
                        }
                    })
                });
            }
        },
    }
};
</script>

<style lang="scss">
@import "./css/register.scss";
</style>
