<template>
    <div class="forget-pass-model">
        <div class="header-nav" @click="changeModel">
            <span><i class="el-icon-back"></i></span>
            <span v-if="!isMobile">忘记密码</span>
            <span v-else>{{ forgetPassTextMobile }}</span>
        </div>
        <div class="step-container model-wrap" v-show="currentStep===0">
            <el-form 
                ref="modelForm" 
                label-position="right" 
                label-width="0px"
                :model="form"
                :rules="rules">
                <el-form-item prop="account">
                    <el-input
                        type="text"
                        v-model="form.account"
                        auto-complete="off"
                        placeholder="请输入账号">
                    </el-input>
                </el-form-item>
                <el-form-item prop="picCode">
                    <el-input
                        class="input-with-slot"
                        type="text"
                        v-model="form.picCode"
                        auto-complete="off"
                        placeholder="请输入图形验证码"
                    >
                        <div class="pic-box" slot="append" @click="getCodePic">
                            <img :src="picSrc" alt="图形验证码"/>
                        </div>
                    </el-input>
                </el-form-item>
            </el-form>
            <el-button class="submit_btn" @click="getUserInfo">下一步</el-button>
        </div>
        <div class="step-container" v-show="currentStep>0">
            <div class="container-header">
                <p>您正在找回账号{{form.account}}的密码</p>
                <ModelSteps :active-step="currentStep"/>
            </div>
            <div class="container-inner model-wrap" v-show="currentStep===1 && (!isMobile)">
                <VerificationBox
                    verifies-type="mobile"
                    :info-text="userMobile||'暂未绑定'"
                    :hideBtn="!userMobile"
                    @goNext="getCode"
                />
                <VerificationBox
                    verifies-type="email"
                    :info-text="userEmail||'暂未绑定'"
                    :hideBtn="!userEmail"
                    @goNext="getCode"
                />
            </div>
            <div v-show="currentStep===1 && isMobile">
                <div class="verification-item" 
                    :class="{'active':choosedWay==='mobile','disabled':!userMobile.length}" @click="choosedWay = 'mobile'">
                    <!-- <div class="icon"> -->
                        <img src="~@/assets/img/icons/phone-login-type.png" />
                    <!-- </div> -->
                    <div class="text">{{userMobile||'暂未绑定'}}</div>
                </div>
                <div class="verification-item"
                    :class="{'active':choosedWay==='email','disabled':!userEmail.length}" @click="choosedWay = 'email'">
                    <!-- <div class="icon"> -->
                        <img src="~@/assets/img/icons/email-login-type.png" />
                    <!-- </div> -->
                    <div class="text">{{userEmail||'暂未绑定'}}</div>
                </div>
                <el-button class="verification-button" type="primary" round @click="getCode(choosedWay)"
                v-show="userMobile.length || userEmail.length">获取验证码</el-button>
            </div>
            <div class="container-inner" v-show="currentStep===2">
                <CaptchaInput 
                    ref="captInput"
                />
                <div class="btn-wrap">
                    <el-button type="primary" plain @click="changeModel">上一步</el-button>
                    <el-button type="primary" @click="checkInput">下一步</el-button>
                </div>
            </div>
            <div class="container-inner model-wrap" v-show="currentStep===3">
                <el-form 
                    ref="passForm" 
                    label-position="right" 
                    label-width="0px"
                    :model="passForm"
                    :rules="passRules">
                    <el-form-item prop="pass1">
                        <el-input
                            type="password" show-password
                            v-model.trim="passForm.pass1"
                            auto-complete="off"
                            @copy.native.capture.prevent="()=>{return false}"
                            @cut.native.capture.prevent="()=>{return false}"
                            @paste.native.capture.prevent="()=>{return false}"
                            placeholder="请输入新密码">
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="pass2">
                        <el-input
                            type="password" show-password
                            v-model.trim="passForm.pass2"
                            auto-complete="off"
                            @copy.native.capture.prevent="()=>{return false}"
                            @cut.native.capture.prevent="()=>{return false}"
                            @paste.native.capture.prevent="()=>{return false}"
                            placeholder="请确认新密码">
                        </el-input>
                    </el-form-item>
                </el-form>
                <el-button class="submit_btn" @click="handleResetPass">{{checkPassStr}}</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import CaptchaInput from './components/CaptchaInput.vue';
import ModelSteps from './components/ModelSteps.vue';
import VerificationBox from './components/VerificationBox.vue';
import modelMixins from './modelMixins';
import{checkPassWord} from '@/utils/commonOptions';
import http from '@/api/http.js';
import {departInterence } from "@/api/api.js";
export default {
    mixins:[modelMixins],
    props:{
        autoAccount:{//自动填写的账号,如果有,作为form.accout的初始值
            type:String,
            default:''
        },
        isMobile:{
            type:Boolean,
            default:false
        }
    },
    components: { VerificationBox, ModelSteps, CaptchaInput },
    data() {
        const validatePass = (rule,value,callback)=>{
            if(value===''){
                callback(new Error('请输入新密码'))
            }
            if(this.passForm.pass2!==''){
                this.$refs.passForm.validateField('pass2')
            }
            if(!checkPassWord(value)){
                callback(new Error('密码要求8位及以上，包含数字、大写字母、小写字母、特殊字符中的三个类型'))
            }else{
                callback()
            }
        }
        const validateCheck = (rule,value,callback)=>{
            if(value===''){
                callback(new Error('请输入确认密码'))
            }else if(value!==this.passForm.pass1){
                callback(new Error('两次输入的密码不一致，请检查'))
            }else{
                callback()
            }
        }
        return {
            currentStep:0,
            /* form */
            form:{//步骤0的表单
                account:this.autoAccount,
                picCode:''
            },
            picSrc:'',
            picId:'',
            passForm:{//设置新密码的表单
                pass1:'',
                pass2:''
            },
            /* form rule */
            rules:{},
            passRules:{
                pass1:[{validator: validatePass,trigger: 'blur'}],
                pass2:[{validator: validateCheck,trigger: 'blur'}]
            },
            /*user info */
            userMobile:'',//用户的手机号
            TelAreaCode:'',//用户手机号的区号
            userEmail:'',//用户的邮箱
            /* check way */
            checkWay:'',//选择的验证方式
            authCode:'',//手机/邮箱验证码，从CaptchaInput组件中取
            mobileCountDown:0,//手机获取验证码倒计时
            emailCountDown:0,//邮箱验证码倒计时
            checkPassStr:'确定',//重置密码按钮
            countDownNum:5,
            resetPassTimer:0,
            choosedWay:'mobile',
        };
    },
    computed:{
        forgetPassTextMobile(){
            switch (this.currentStep) {
                case 0:
                    return "忘记密码"
                case 1:
                    return "安全验证"
                case 2:
                    return "请输入验证码"
                case 3:
                    return "设置密码"
                default:
                    break;
            }
        }
    },
    created(){
        this.getCodePic()
    },
    methods: {
        //获取用户账号信息
        getUserInfo(){
            //检查form是否填写完整
            const {account,picCode} = this.form
            if(!account){
                this.$message.warning('请输入账号')
                return
            }
            if(!picCode){
                this.$message.warning('请输入图形验证码')
                return
            }
            //请求接口获取账号数据，赋值userMobile,userEmail
            departInterence.accountCheck({
                CaptchaId:this.picId,
                CaptchaCode:picCode,
                UserName:account
            }).then(res=>{
                if(res.Ret!==200){
                    //刷新图形验证码
                    this.getCodePic()
                    this.form.picCode=''
                    return
                }
                if(res.Data){
                    this.userMobile = res.Data.Mobile||''
                    this.userEmail = res.Data.Email||''
                    this.TelAreaCode = res.Data.TelAreaCode||''
                    this.goSteps()
                }
                
            })
        },
        //获取对应验证方式的验证码
        getCode(way){
            this.checkWay = way
            departInterence.getCodeVerify({
                VerifyType:way==='mobile'?1:2,
                CaptchaId:this.picId,
                CaptchaCode:this.form.picCode,
                Mobile:way==='mobile'?this.userMobile:'',
                TelAreaCode:way==='mobile'?this.TelAreaCode:'',
                Email:way==='email'?this.userEmail:'',
                Source:3
            }).then(res=>{
                if(res.Ret!==200) return
                /* //60秒倒计时
                this.countDown()
                this.timer = setInterval(()=>{
                    this.countDown()
                },1000)
                this.goSteps() */
                this.goSteps()
            })
        },
        //检查输入的验证码
        checkInput(){
            const code = this.$refs.captInput.captchas.map((x) => x.num).join("");
            if(code.length!==6){
                this.$message.warning('请输入完整的验证码')
                return
            }
            departInterence.checkCodeVerify({
                FindType:this.checkWay==='mobile'?1:2,
                VerifyCode:code,
                UserName:this.form.account,
                Mobile:this.checkWay==='mobile'?this.userMobile:'',
                Email:this.checkWay==='email'?this.userEmail:''
            }).then(res=>{
                if(res.Ret!==200) return
                this.goSteps()
            })

        },
        goSteps(){
            this.currentStep++
        },
        changeModel(){
            if(this.currentStep>0){
                this.currentStep--
                if(this.currentStep===0){
                    this.getCodePic()
                    this.form.picCode = ''
                }
            }else{
                this.$emit('changeModel')
            }
            
        },
        handleResetPass(){
            if(this.checkPassStr.includes('去登陆')){
                this.$emit('changeModel')
                return
            }
            this.$refs.passForm.validate((valid)=>{
                if(valid){
                    //重置密码
                    departInterence.resetPass({
                        UserName:this.form.account,
                        Password:new http.Base64().encode(this.passForm.pass1),
                        RePassword:new http.Base64().encode(this.passForm.pass2)
                    }).then(res=>{
                        if(res.Ret!==200) return
                        this.$message.success('重置密码成功，请登陆')
                        localStorage.setItem('timeKey',Date.now())
                        localStorage.setItem("account", new http.Base64().encode(this.form.account));
                        localStorage.setItem("checkPass", new http.Base64().encode(this.passForm.pass1));
                        this.resetPassCountDown()
                        this.resetPassTimer = setInterval(()=>{
                            this.resetPassCountDown()
                        },1000)
                    })
                }
            })
        },
        resetPassCountDown(){
            this.countDownNum--
            this.checkPassStr = `去登陆（${this.countDownNum}s）`
            if(this.countDownNum<=0){
                clearInterval(this.resetPassTimer)
                this.$emit('changeModel')
                return
            }
        }
    },
};
</script>

<style lang="scss">
@import "./css/formStyle.scss";
</style>
<style scoped lang="scss">
.forget-pass-model{
    .header-nav{
        font-size: 38px;
        margin-bottom: 60px;
        cursor: pointer;
    }
    .step-container{
        .container-header{
            margin-bottom: 60px;
            p{
               font-size: 18px;
               padding-bottom: 20px;
               border-bottom: 1px solid #DCDFE6; 
               margin-bottom: 60px;
            }
            .el-steps{
                margin-top: 60px;
            }
        }
        .container-inner{
            .btn-wrap{
                margin-top: 100px;
                text-align: center;
                .el-button{
                    width:200px;
                }
            }
        }
    }
    .verification-item{
        display: flex;
        align-items: center;
        width:100%;
        box-sizing: border-box;
        padding:10px 15px;
        margin-bottom: 30px;
        border: 1px solid #DCDFE6;
        border-radius: 8px;
        background-color: #fff;
        &.active{
            border: 1px solid #0052D9;
            background-color: #F2F3FF;
        }
        &.disabled{
            user-select: none;
            pointer-events: none;
        }
        img{
            width: 40px;
            margin-right: 10px;
        }
    }
    .verification-button{
        width: 100%;
        margin-top: 20px;
    }
    @media screen and (max-width:650px) {
        .header-nav{
            font-size: 24px;
        }
        .submit_btn{
            border-radius: 50px;
        }
        .step-container{
            .container-header{
                display: none;
            }
            .container-inner{
                .btn-wrap{
                    .el-button{
                        width:100%;
                        margin-left: 0;
                        border-radius: 42px;
                        &:first-child{
                            margin-bottom: 30px;
                        }
                    }
                }
            }
        }
    }
}
</style>
