<template>
    <div id="register" class="fotgetPassword">
        <div class="fs-29 c-333 tl pl30 pt30 pb20">轻松找回你的<br>密码</div>
        <div class="plr30 pt20  bgc-fff" id="inpForm">
            <van-cell-group>
                <van-field type="tel" placeholder="请输入手机号码" v-model="data.mobile" maxlength="11" clearable class="mobile right-line">
                    <van-svg-icon slot="left-icon" icon-class="svg-shoujihao"/>
                </van-field>
                <van-field v-model="data.msgCode" class="codeInp right-line" clearable @click-icon="msgCode=''" maxlength="10"  placeholder="短信验证码">
                    <van-svg-icon slot="left-icon" icon-class="svg-yanzhengma" style="margin-top:2px;"/>
                    <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="passwordView.type" v-model="data.password" maxlength="16" placeholder="请输入新的登录密码"  @click-right-icon="passwordViewSet()">
                    <div slot="left-icon" class="left-icon-wrap">
                        <img class="left-icon"  src="@/assets/images/mima_icon.png" alt="">
                    </div>
                    <van-svg-icon slot="right-icon" :icon-class="passwordView.icon"/>
                </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="passwordAgainView.type" v-model="data.againPassword" maxlength="16" placeholder="请确认新的登录密码"  @click-right-icon="passwordViewSet(2)">
                    <div slot="left-icon" class="left-icon-wrap">
                        <img class="left-icon"  src="@/assets/images/mimasuo_icon.png" alt="">
                    </div>
                    <van-svg-icon slot="right-icon" :icon-class="passwordAgainView.icon"/>
                </van-field>
            </van-cell-group>
            <div class="mt32">
                <van-button block round type="primary" @click="submit" class="">
                   确 认
                </van-button>
            </div>
        </div>
    </div>
</template>

<script>
import { getPublicKey, login, imgCaptcha, sendCaptcha, findPatientPw } from "@/api/login";
import ValidatorUtils from '@/utils/validator'
import {isIdcard} from '@/utils/validator'
import { setTimeout } from 'timers';

export default {
    name: "fotgetPassword",
    data() {
        return {
            countdown: 0,
            data: {
                userName: "",
                idCard: "",
                mobile: "",
                sbk: "",
                msgCode: "",
                password: "",
                againPassword: ""
            },
            rules: {
                mobile: [
                    { required: true, message: '请输入手机号码' },
                    { pattern: /^[1][0-9]{10}$/, message: '请输入正确的手机号码' }
                ]
            }, 
            passwordView: {},
            passwordAgainView: {},
            passwordNotView: {type: "password",icon: "svg-biyan", value: false}, //闭眼
            password_view: { type: "text", icon: "svg-kaiyan", value: true }, //睁眼

            testReq: /((?=[\x21-\x7e]+)[^A-Za-z0-9])/,
            testNumber: /[0-9]/,
            testLetter: /[A-Za-z]/,
            s1: -1,
            s2: -1,
            s3: -1,
        };
    },
    created() {
        this.validator = new ValidatorUtils({
            rules: this.rules,
            data: this.data 
        })
        this.passwordView = this.passwordNotView
        this.passwordAgainView = this.passwordNotView
        this.initPage();
    },
    methods: {
        passwordViewSet(type) {
            //设置密码显示
            var vm = this;
            if(type){
                if (vm.passwordAgainView.value) {
                    vm.passwordAgainView = vm.passwordNotView;
                } else {
                    vm.passwordAgainView = vm.password_view;
                }
            } else {
                if (vm.passwordView.value) {
                    vm.passwordView = vm.passwordNotView;
                } else {
                    vm.passwordView = vm.password_view;
                }
            }
        },
        changeLogin(){
            this.$router.push({path: "/login", query: this.$route.query})
        },
        initPage() {
            
        },
        countdownSubtract() {
            //验证码
            if (this.countdown > 0) {
                setTimeout(() => {
                    this.countdown -= 1;
                    this.countdownSubtract();
                }, 1000);
            }
        },
        goPage(url){
            this.$router.push({
                path:url
            });
        },
        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
            }
        },
        sendMobileCode() {
            this.validator.validate("mobile").then(() => {
                this.countdown = 60;
                this.countdownSubtract();
                sendCaptcha({
                    type: 2, // 2 找回密码
                    username: this.data.mobile,
                    client_id: this.$root.clientId?this.$root.clientId:process.env.VUE_APP_CLIENTID,
                    wxId: process.env.VUE_APP_WXID
                }).then((res) => {
                    if(res.status == 200) {
                        this.$toast("发送成功");
                    } else {
                        this.$toast("发送失败");
                    }
                })     
            }, (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)
        },
        validate() {
            return new Promise((resolve, reject)=>{
                if(!this.validateMobile()){
                    reject("请输入正确的手机号码") 
                } else if(!this.data.msgCode || !this.data.msgCode.trim()){
                    reject("请输入短信验证码") 
                } else if(this.s1!=1 || this.s2!=1 || this.s3!=1 ){
                    reject("密码设置不符合要求") 
                } else if(this.data.againPassword != this.data.password){
                    reject("两次密码不一致") 
                }
                resolve()
            }).then(() => {
                // 校验成功
                this.findPatientPw()
            }, 
            (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 findPatientPw() {
            var that = this
            var p = {
                mobile: this.data.mobile,
                login_type: 3,
                captcha: this.data.msgCode,
                pw: this.data.password,
                client_id: this.$root.clientId,
            }

            findPatientPw(p).then(res1 => {
                this.$toast.clear()
                if (res1.status == 200) {
                    this.$toast('重置成功');
                    this.$router.push("/login")
                } else {
                    this.$toast(res1.message);
                }
            })
            .catch(e => {
                this.$toast.clear()
                // this.$toast('重置失败');
            })
        }
    }
};
</script>

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