<template>
    <div class="contentBo">
        <div class="find-container">
            <Banner></Banner>
            <div class="login-img fl"><img src="../../images/loginImg.png"/></div>
            <div :class="['box', { 'box2': flag == 2 ||  flag == 3}]">
                <!-- <h3>
                  <img v-show="showText=='修改密码'" src="../../images/return.png" height="18" width="18" @click="back">
                  {{showText}}
                </h3> -->
                <div v-if="flag==1" class="title-box clearfix"> <h3 class="login-title fl">找回密码</h3> <h4 class="num fr num2">1/2</h4></div>
                <div v-if="flag==2" class="title-box clearfix"> <h3 class="login-title fl">输入新密码</h3> <h4 class="num fr num2">2/2</h4></div>
                <div class="main">
                    <!-- <div class="progress">
                        <p class="progress-info">
                            <span class="finished">输入验证信息</span>
                            <span :class="['unfinished',{'finished':newPawComplete}]">输入新密码</span>
                            <span :class="['unfinished',{'finished':complete}]">完成设置</span>
                        </p>
                        <p :class="['progress-pic',{'progress-new':newPawComplete,'progress-fin':complete}]"></p>
                    </div> -->
                    <form>
                        <div class="first" v-if="flag==1">
                            <div class="phoneBox">
                                <input type="tel" :class="{error: phoneErrText}" name="" v-model="phone" maxlength="11" @input="handleTelInput"
                                    placeholder="手机号" @blur="checkPhone">
                                <span class="tips" v-show="phoneErrText" >{{phoneErrText}}</span>
                            </div>
                            
                            <div class="yanzm" maxlength="11">
                                <input type="text" :class="{error: imgErrText}" name="" v-model="picCode" @blur="checkImgCode" maxlength="4"
                                       placeholder="图形验证码">
                                <img :src='"data:image/png;base64,"+imgCode' @click="refreshCode">
                                <span class="tips" >{{imgErrText}}</span>
                            </div>
                            <div class="yanzm">
                                <input type="text" name="" :class="{error: SMSErrText}" v-model="msgCode" maxlength="6" placeholder="短信验证码" @blur="checkMsgCode">
                                <div v-if="timerFlag" type="primary" class="getMsg disabled">{{'再次发送(' + time + ')'}}</div>
                                <div v-else class="getMsg" @click="getMsgCode">获取验证码</div>
                                 <span class="tips" v-show="SMSErrText">{{SMSErrText}}</span>
                            </div>
                           
                        </div>
                        <div class="second" v-if="flag == 2">
                          <div class="phoneBox">
                              <input type="password" :class="{error: newPswErrText}" name="" placeholder="新密码（6-16位字母、数字组合）" v-model="newPsw"
                                   @blur="checkPsw" maxlength="16">
                              <span class="tips" v-show="newPswErrText">{{newPswErrText}}</span>
                          </div>
                          <div class="phoneBox">
                            <input type="password" name="" placeholder="确认新密码（6-16位字母、数字组合）" v-model="newPswAgain"  maxlength="16">

                          </div>
                        </div>
                        <div class="third" v-if="flag == 3">
                            <img class="modifyImg" src="../../images/success.png" alt="">
                            <p class="modifyInfo">修改成功</p>
                            <p class="suc">恭喜，您的密码已修改成功！</p>
                        </div>
                        <div class="next" v-if="changCor">{{nextText}}</div>
                        <div :class="['next nextCor',{'goLogin':flag == 3}]" @click="toNext(flag)" v-else>{{nextText}}
                        </div>

                    </form>
                </div>
            </div>
            <copy-right-info></copy-right-info>
        </div>
    </div>
</template>
<script type="text/javascript">
  import api from '../../api/index.js';
  import utils from '@api/utils.js';
  import '@components/forgetPassword/findPassword.less';
  import copyRightInfo from '../common/CopyRightInfo.vue';
  import Banner from '@components/common/Banner.vue';
  import md5 from 'js-md5'

  export default {
    name: 'FindPassword',
    data() {
      return {
        showText:'找回密码',
        phone: '',
        picCode: '',//用户输入
        msgCode: '',
        imgCode: '',//流
        imgId: '',
        flag: 1,//切换下一页
        nextText: '下一步',
        changCor: true,
        imgCodeErr: false,
        time: 180,
        timer: null,
        timerFlag: false,//倒计时标识
        newPawComplete: false,//进度条1
        complete: false, //进度条2
        newPsw: '',
        newPswAgain: '',
        picTimer: null,//图形验证码时限
        picTime: 600,
        msgCodeTimer:null,//短信验证码
        msgCodeTime:180,
        codeErrText:'',
        modifiPsw:'',//修改密码
        phoneErrText: '', //用户名错误信息
        imgErrText: '', //图片验证码错误信息
        SMSErrText: '',  //短信验证码错误信息
        newPswErrText: '' //新密码错误信息

      }
    },
    created() {
      //localStorage.removeItem('token');
      this.getPicCode();
      const type = document.URL;
      if(type.indexOf('?')>=0){
        this.showText = "修改密码";
        this.modifiPsw = "Y";
      }else{
        this.showText = "忘记密码";
        this.modifiPsw = "";
      }
    },
    beforeDestroy() {
      window.clearInterval(this.picTimer);
      window.clearInterval(this.msgCodeTimer);
    },
    methods: {
      back(){
        this.$router.go(-1);
      },
      CalcuMD5(password){
        // password = password.toUpperCase();
        password = md5(password);
        return password;
      },
      handleTelInput(e) {//手机号输入验证
        this.phone = e.target.value.replace(/[^\d]/g, ''); //限制只能输入数字
        let firstNum = this.phone.substring(0, 1);//第一位1
        if (firstNum != 1) {
          this.phone = "";
        }
      },
      getPicCode() {//获取图形验证码
        api.getImgCode().then((res) => {
          if (+res.data.code == 0) {
            const imgCodeInfo = res.data.data;
            this.imgCode = imgCodeInfo.imgByte;
            this.imgId = imgCodeInfo.imgId;

            let that = this;
            this.picTimer = window.setInterval(() => {
              if ((that.picTime--) <= 0) {
                this.$message({
                  message: '图形验证码已过期',
                  type: 'warning',
                  showClose: true
                });
                that.picCode = '';
                that.picTime = 600//图形验证码过期时间10分钟;
                window.clearInterval(that.picTimer);
                that.picTimer = null
                that.getPicCode();//过期刷新验证码
              }
            }, 1000);

          } else {
            this.$message({
              message: res.data.msg,
              type: 'warning',
              showClose: true
            });

          }
        }).catch((err) => {
          console.log(err);
        })
      },
      refreshCode() {//刷新图形验证码
        window.clearInterval(this.picTimer);
        this.picTime = 600;//图形验证码过期时间10分钟;
        this.getPicCode();
      },
      checkImgCode() {//验证图片验证码
        if (this.picCode.trim()) {//定义参数
          const params = {
            imgCode: this.picCode,
            imgId: this.imgId
          }
          api.vertifyImgCode(params).then((res) => {
            if (+res.data.code != 0) {//验证失败
              // this.imgCodeErr = true
              this.imgErrText = "图形验证码错误";
            } else {
              // this.imgCodeErr = false
              /*window.clearInterval(this.picTimer);
              this.picTime = 600*/
              this.imgErrText = "";
            }
          }).catch((err) => {
            console.log(err);
          })
        }

      },
      checkPhone() {//验证手机号
        // const reg = new RegExp(/^((13|14|15|16|17|18|19)\d{9})$/);
        const reg = utils.phoneReg;
        if(this.phone.trim()){
          if (!reg.test(this.phone)) {
            /*this.$message({
              message: '手机格式不正确',
              type: 'warning',
              showClose: true
            });*/
            // this.imgCodeErr = true;
            this.phoneErrText = "手机号格式有误";
            this.phone = "";
          }else{//验证手机号是否注册
            // this.imgCodeErr = false;
            api.checkForgetTel(this.phone).then((res)=>{
              if(+res.data.code == 0){
                 this.phoneErrText = ''
              }else{
                this.phoneErrText = ''
                this.$message({
                  message: res.data.msg,
                  type: 'warning',
                  showClose: true
                });
                this.phone = "";
              }
            })
          }
        }
      },
      getMsgCode() {//获取短信验证码
        if(!this.phone){
          /*this.$message({
            message: '手机号不能为空',
            type: 'warning',
            showClose: true
          });*/
          // this.imgCodeErr = true;
          this.phoneErrText = "手机号不能为空";
        }else if(!this.picCode){
          // this.imgCodeErr = true
          this.imgErrText = "图形验证码不能为空";
        }else{
          //调请求接口
          // if(!this.imgCodeErr){
            this.imgCodeErr = false;
            const params = {
              imgCode: this.picCode,
              imgId: this.imgId,
              mobile: this.phone
            }
            api.forgetPswGetMobileCode(params).then((res) => {
              if (+res.data.code == 0) {
                this.$message({
                  message: '验证码发送成功',
                  type: 'success',
                  showClose: true
                });
                //按钮倒计时
                this.timerFlag = true;
                let that = this;
                this.timer = window.setInterval(() => {
                  if ((that.time--) <= 0) {
                    that.time = 180;
                    that.timerFlag = false;
                    window.clearInterval(that.timer);
                  }
                }, 1000)

                //短信验证码180s过期时间
                this.msgCodeTimer = window.setInterval(() => {
                  if ((that.msgCodeTime--) <= 0) {
                    this.$message({
                      message: '短信验证码已过期，请重新获取',
                      type: 'warning',
                      showClose: true
                    });
                    that.msgCode = '';
                    that.msgCodeTime = 180;
                    window.clearInterval(that.msgCodeTimer);
                    that.msgCodeTimer = null;
                  }
                }, 1000);

              } else {
                console.log(res.data);
                this.$message({
                  message: res.data.msg,
                  type: 'warning',
                  showClose: true
                });
                // return
              }
            }).catch((err) => {
              console.log(err);
            })
          // }
        }

      },
      checkPsw() {//校验密码
        // const pswlReg = /^(?![0-9]+$)(?![a-zA-Z]+$)/;
        const pswlReg = utils.pswReg;
        const psw = this.newPsw;
        if (psw) {
          if (psw.trim().length < 6 || psw.trim().length > 16) {
            this.imgCodeErr = true;
            this.newPswErrText = "密码长度为6-16位";
            this.psw = "";
          }
          else if (!pswlReg.test(psw)) {
            this.imgCodeErr = true;
            this.newPswErrText = "密码过于简单";
            this.psw = "";
          }else{
            this.newPswErrText = ''
            this.imgCodeErr = false;
          }
        }

      },
      checkMsgCode(){
        const params = {
            imgCode: this.picCode,
            imgId: this.imgId,
            mobile: this.phone,
            smsCode: this.msgCode
          }
          if(!this.msgCode.trim()) {
            return
          }
          api.vertifyMobileCode(params).then((res) => {
            // 验证成功，切换下一页
            if (+res.data.code == 0) {
              // this.flag = 2;//切换下一页
              // this.newPawComplete = true;
              this.imgCodeErr = false;
            } else {
              // this.$message.error('短信验证码错误');
              // this.imgCodeErr = true;
              this.SMSErrText = "短信验证码错误";
              this.msgCode = "";
            }
          }).catch((err) => {
            console.log(err);
          })
      },
      toNext(flag) {//点下一步验证短信验证码
        //掉验证接口
        if (flag == 1) {//验证第一页数据
          const params = {
            imgCode: this.picCode,
            imgId: this.imgId,
            mobile: this.phone,
            smsCode: this.msgCode
          }
          api.vertifyMobileCode(params).then((res) => {
            // 验证成功，切换下一页
            if (+res.data.code == 0) {
              clearInterval(this.msgCodeTimer);
              clearInterval(this.picTimer);
              this.picTimer = null;
              this.msgCodeTimer = null;
              this.flag = 2;//切换下一页
              this.newPawComplete = true;
              this.imgCodeErr = false;
            } else {
              // this.$message.error('短信验证码错误');
              this.imgCodeErr = true;
              this.SMSErrText = "短信验证码错误";
              this.msgCode = "";
            }
          }).catch((err) => {
            console.log(err);
          })

        }

        if (flag == 2) {//验证两次输入是否一致
          if (this.newPsw && this.newPswAgain) {
            if (this.newPsw.trim() == this.newPswAgain.trim()) {
              const mdPsw = this.CalcuMD5(this.newPsw);
              //调接口
              const params = {
                password: mdPsw,
                username: this.phone,
                diffPassword:this.modifiPsw
              }
              api.resetPsw(params).then((res) => {
                if (+res.data.code == 0) {
                  this.flag = 3;
                  this.complete = true;
                  //修改成功清除定时器
                  // window.clearInterval(this.picTimer);
                }else {
                  this.$message({
                    message: res.data.msg,
                    type: 'warning',
                    showClose: true
                  });
                  this.newPsw = "";
                  this.newPswAgain = "";
                }
              }).catch((err) => {
                console.log(err);
              })

            } else {
              this.$message({
                message: '两次密码不一致',
                type: 'warning'
              });
            }
          }

        }
        if (flag == 3) {
          this.$router.push({path: '/'})
        }


      },
    },
    computed: {
      nextButton() {
        const {phone, picCode, msgCode, flag, newPsw, newPswAgain,imgCodeErr} = this;
        return {
          phone,
          picCode,
          msgCode,
          flag,
          newPsw,
          newPswAgain,
          imgCodeErr
        }
      }
    },
    watch: {
      nextButton: {
        handler: function (val) {//所有数据不为空，且手机格式正确、图形验证码正确
          if (val.flag == 3) {
            this.nextText = "去登录";
          }
          if (val.phone.trim() && val.picCode.trim() && val.msgCode.trim()  && val.flag == 1) {
          // if (val.phone.trim() && val.picCode.trim() && val.msgCode.trim() && val.flag == 1) {
            this.changCor = false;
          } else {
            this.changCor = true;
          }

          if (val.newPsw.trim() && val.newPswAgain.trim()) {
            this.changCor = false;

          } else {
            // this.changCor = true;
          }
        },
        deep: true
      }
    },
    components: {
      Banner,
      copyRightInfo
    },
  }
</script>