<template>
    <div class="app-container">
        <div style="padding-top: 100px;"></div>
        
        <p id="loginTitle"> 重置密码 </p>

        <van-form @submit="onSubmit"  @failed="onFailed">
            <van-field
                v-model="phone"
                type="digit"
                name="phone"
                label="手机号"
                placeholder="请输入手机号码"
                maxlength="11"
                :rules="rules.phone"
                clearable
                required
            />
            
            <van-field
                v-model="smsCode"
                type="digit"
                name="smsCode"
                label="验证码"
                maxlength="8"
                placeholder="请输入短信验证码"
                center
                clearable
                required
            >
                <template #button>
                    <van-button size="small" type="info" native-type="button" @click="beforeSendSms" :disabled="disableClick">
                        <span style="display:inline-block;width: 76px;">{{smsText}}</span>
                    </van-button>
                </template>
            </van-field>
            
            <van-field
                v-model="password"
                :type="showPwd ? 'text' : 'password'"
                name="password"
                label="新密码"
                placeholder="请输入新密码"
                :rules="rules.password"
                clearable
                required
            >
                <template #right-icon>
                    <van-icon :name="showPwd ? 'eye-o' : 'closed-eye'" @click="showHidePwd" />
                </template>
            </van-field>

            <van-field
                v-model="confirmPassword"
                :type="showConfirmPwd ? 'text' : 'password'"
                name="confirmPassword"
                label="确认密码"
                placeholder="请再次输入新密码"
                :rules="rules.confirmPassword"
                clearable
                required
            >
                <template #right-icon>
                    <van-icon :name="showConfirmPwd ? 'eye-o' : 'closed-eye'" @click="showHideConfirmPwd" />
                </template>
            </van-field>

            <!-- 图形验证码 -->
            <!-- <div v-show="showCaptcha" ref="captcha" id="captcha"></div> -->

            <div style="margin: 26px;">
                <van-button round block type="info" size="small" native-type="submit">确认重置</van-button>
            </div>
            
            <div style="text-align:center;">
                <router-link to="login">
                    <span style="color:#2196f3;margin-left:5px">前往登录</span>
                </router-link>
            </div>
        </van-form>
    </div>
</template>

<script>

import "../captcha/index.js";
import Vue from 'vue';
import { Icon,Form,Field,Dialog,Button } from 'vant';

Vue.use(Icon);
Vue.use(Form);
Vue.use(Field);
Vue.use(Dialog);
Vue.use(Button);

export default {
    data() {
        return {
            show: false,
            phone: '',
            password: '',
            confirmPassword: '',            
            rules: {
                phone: [
                    { required: true, message: "请输入手机号码" },
                    { trigger: 'onBlur', pattern: /^1[3456789]\d{9}$/, message: "手机号码格式错误" },
                ],
                password: [
                    { required: true, message: '请输入新密码' },
                    { trigger: 'onBlur', pattern: /^[-_a-zA-Z0-9]{6,16}$/, message: '密码应为6-16位，可输入字母、数字、下划线' },
                ],
                confirmPassword: [
                    { required: true, message: '请再次输入新密码' },
                    { trigger: 'onBlur', validator: val => {
                        return this.password === this.confirmPassword;
                    } , message: '两次密码不一致' },
                ]
            },
            smsCode: '',
            smsText: '发送验证码', // 每次发送成功后，倒计时 60s 才能点击
            disableClick: false, // 禁止点击
            intervalIndex: null,
            interval: 60,
            isFirstSend: true, // 第一次发送短信
            // showCaptcha: false, // 显示图片验证
            captchaSuccess: false, // 图片验证成功
            showPwd: false, // 显示密码
            showConfirmPwd: false, // 显示确认密码
            isReset: 1, // 是否重置密码
        }
    },
    mounted() {
        // this.getCaptcha();
    },
    methods: {
        /**
         *  显示隐藏密码 
         */
        showHidePwd() {
            this.showPwd = !this.showPwd;
        },
        /**
         *  显示隐藏确认密码 
         */
        showHideConfirmPwd() {
            this.showConfirmPwd = !this.showConfirmPwd;
        },
        /**
         * 验证码
         */
       /*  getCaptcha() {
            jigsaw.init({
                el: this.$refs.captcha,
                onSuccess: this.onSuccess,
            });
        }, */
        /* onSuccess() {
            // 后台登录认证
            // this.showCaptcha = false;
            // 发送验证码
            this.sendSms();
        }, */
        /**
         * 手机号码验证
         */
        phoneValidator() {
            return /^1[3456789]\d{9}$/.test(this.phone);
        },
        /**
         * 发送短信前
         */
        beforeSendSms() {
            // 检测号码格式
            let result = this.phoneValidator();
            if (!result) {
                this.$notify('请先输入正确的手机号码');
                return false;
            }

            // 暂时每次都提醒，有图形验证码之后可以只在第一次提醒
            this.isFirstSend = true;
            // 第一次弹窗提醒
            if (this.isFirstSend) {
                // this.isFirstSend = false;
                
                Dialog.confirm({
                    title: '确认手机号',
                    message: '我们将发送短信验证码到这个号码：'+ this.phone,
                })
                .then((resp) => {
                    if (resp === 'confirm') {
                        // this.showCaptcha = true;
                        this.sendSms();
                    }
                })
                .catch((resp) => {
                    console.log('cancel', resp);
                });
            } else {
                // this.showCaptcha = true;
                this.sendSms();
            }

        },
        /**
         * 发送验证码
         */
        sendSms() {
            
            let userType = localStorage.getItem('userType');
            let deviceType = localStorage.getItem('deviceType');
            let postData = {
                phone: this.phone,
                userType: userType,
                deviceType: deviceType,
                isReset: this.isReset, // 是否重置密码
            }
            this.$http.post('sendSmsCode', JSON.stringify(postData)).then(resp => {
                this.$notify({
                    type: resp.data.success ? 'success' : 'danger',
                    message: resp.data.message || (resp.data.success ? '发送成功' : '发送失败'),
                })
                
                resp.data.success && this.setWaitInfo();
            }).catch(err=>{
                this.$notify('出错了');
            })
            
        },
        /**
         * 倒计时
         */
        setWaitInfo() {
            if (this.intervalIndex) {
                this.interval = 60;
                clearInterval(this.intervalIndex);
            }

            // 倒计时
            this.disableClick = true;
            
            this.intervalIndex = setInterval(() => {
                this.interval--;
                this.smsText = '重发(' + this.interval + ' s)';
                if (this.interval <= 0) {
                    clearInterval(this.intervalIndex);
                    this.interval = 60;
                    this.disableClick = false;
                    this.smsText = '重发';
                }
            }, 1000);
        },
        /**
         * 重置
         */
        onSubmit(values) {
            
            let userType = localStorage.getItem('userType');
            let deviceType = localStorage.getItem('deviceType');

            let postData = {
                phone: values.phone,
                password: values.password,
                confirmPassword: values.confirmPassword,
                smsCode: values.smsCode,
                userType: userType,
                deviceType: deviceType,
                isReset: this.isReset, // 是否重置密码
            }

            this.$http.post('resetPwd', JSON.stringify(postData))
                .then(resp => {

                    if (!resp.data.success) {
                        this.$notify(resp.data.message);
                        return;
                    }

                    this.$notify({
                        type: 'success',
                        message: resp.data.message || '发送成功',
                    })

                    // 跳转登录
                    Dialog.confirm({
                        title: '提示',
                        message: '重置密码成功，前往登录',
                    })
                    .then((resp) => {
                        this.$router.push('login')
                    })
                    .catch(() => {
                        // on cancel
                        console.log('cancel');
                    });
                }).catch(err => {
                    this.$notify('重置密码失败，请稍后再试');
                })

        },
        /**
         * onFailed
         */
        onFailed(errorInfo) {
            console.log('failed', errorInfo);
            // this.$notify(errorInfo.errors[0].message);
        }
    }
}
</script>

<style lang="scss" scoped>

#loginTitle {
    font-size: 20px;
    text-align: center;
    padding: 20px 0;
}
</style>