<template>
    <div class="contentBo">
        <div class="find-container">
            <Banner></Banner>
            <div class="box">
                <h3>
                  <img v-show="showText=='修改密码'" src="../../images/return.png" height="18" width="18" @click="back">
                  {{showText}}
                </h3>
                <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">
                            <input type="tel" name="" v-model="phone" maxlength="11" @input="handleTelInput"
                                   placeholder="手机号" @blur="checkPhone">
                            <div class="yanzm" maxlength="11">
                                <input type="text" name="" v-model="picCode" @blur="checkImgCode" maxlength="4"
                                       placeholder="图形验证码">

                                <img :src='"data:image/png;base64,"+imgCode' @click="refreshCode">
                            </div>
                            <div class="yanzm">
                                <input type="text" name="" v-model="msgCode" maxlength="6" placeholder="短信验证码" @blur="checkMsgCode">
                                <div v-if="timerFlag" type="primary" class="getMsg disabled">{{time + 's后重新发送'}}</div>
                                <div v-else class="getMsg" @click="getMsgCode">点击获取验证码</div>
                            </div>
                            <span class="tips" v-show="imgCodeErr">{{codeErrText}}</span>
                        </div>
                        <div class="second" v-if="flag == 2">
                            <input type="password" name="" placeholder="新密码（6-16位字母、数字组合）" v-model="newPsw"
                                   @blur="checkPsw" maxlength="16">
                            <input type="password" name="" placeholder="确认新密码（6-16位字母、数字组合）" v-model="newPswAgain"  maxlength="16">
                        </div>
                        <div class="third" v-if="flag == 3">
                            <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>
        </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 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: 60,
        timer: null,
        timerFlag: false,//倒计时标识
        newPawComplete: false,//进度条1
        complete: false, //进度条2
        newPsw: '',
        newPswAgain: '',
        picTimer: null,//图形验证码时限
        picTime: 600,
        msgCodeTimer:null,//短信验证码
        msgCodeTime:180,
        codeErrText:'',
        modifiPsw:'',//修改密码

      }
    },
    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'
                });
                that.picCode = '';
                that.picTime = 600//图形验证码过期时间10分钟;
                window.clearInterval(that.picTimer);
                that.getPicCode();//过期刷新验证码
              }
            }, 1000);

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

          }
        }).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.codeErrText = "图形验证码错误";
            } else {
              this.imgCodeErr = false
              /*window.clearInterval(this.picTimer);
              this.picTime = 600*/
            }
          }).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'
            });*/
            this.imgCodeErr = true;
            this.codeErrText = "手机格式不正确";
            this.phone = "";
          }else{//验证手机号是否注册
            this.imgCodeErr = false;
            api.checkForgetTel(this.phone).then((res)=>{
              if(+res.data.code == 0){
                
              }else{
                this.$message({
                  message: res.data.msg,
                  type: 'warning'
                });
                this.phone = "";
              }
            })
          }
        }
      },
      getMsgCode() {//获取短信验证码
        if(!this.phone){
          /*this.$message({
            message: '手机号不能为空',
            type: 'warning'
          });*/
          this.imgCodeErr = true;
          this.codeErrText = "手机号不能为空";
        }else if(!this.picCode){
          this.imgCodeErr = true
          this.codeErrText = "图形验证码不能为空";
        }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'
                });
                //按钮倒计时
                this.timerFlag = true;
                let that = this;
                this.timer = window.setInterval(() => {
                  if ((that.time--) <= 0) {
                    that.time = 60;
                    that.timerFlag = false;
                    window.clearInterval(that.timer);
                  }
                }, 1000)

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

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

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

      },
      checkMsgCode(){
        const params = {
            imgCode: this.picCode,
            imgId: this.imgId,
            mobile: this.phone,
            smsCode: this.msgCode
          }
          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.codeErrText = "短信验证码错误";
              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) {
              this.flag = 2;//切换下一页
              this.newPawComplete = true;
              this.imgCodeErr = false;
            } else {
              // this.$message.error('短信验证码错误');
              this.imgCodeErr = true;
              this.codeErrText = "短信验证码错误";
              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'
                  });
                  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.imgCodeErr && 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
    },
  }
</script>