<template>
    <div>
        <div class="loginframe">      
          <el-tabs v-if='newregistration==1' v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="密码登录" name="passwordlog">
              <el-form ref="loginForm" :rules="loginRules" :model="loginForm"
                       status-icon label-width="0">
                <el-form-item prop="account" style="margin:20px 0">
                  <el-input v-model="loginForm.account"
                            auto-complete="off"
                            placeholder="请输入账号"
                            @keyup.enter.native="doLogin">                
                    <img slot="prefix" src="/assets/loginreg/account.png"  alt="" style="margin-top:12px">
                  </el-input>
                </el-form-item>
                <el-form-item prop="password" style="margin:21px 0" >
                  <el-input :type="passwordType" 
                            v-model="loginForm.password"
                            auto-complete="off"
                            placeholder="请输入密码"
                            @keyup.enter.native="doLogin">
                    <img slot="prefix" src="/assets/loginreg/password.png" alt="" style="margin-top:12px">
                    <i  slot="suffix" style="cursor:pointer" class="el-icon-view el-input__icon" @click="showPassword"/>
                  </el-input>
                </el-form-item>
                
                <el-form-item class="logbtn">
                  <el-button  :loading="doloading" type="primary" @click.native.prevent="doLogin">登录</el-button>
                </el-form-item>           
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="短信登录" name="smslogin">
              <el-form ref="smsloginForm" :rules="smsloginnRules" :model="smsloginForm"
                       status-icon label-width="0">
                <el-form-item prop="phone" style="margin:20px 0">
                  <el-input v-model="smsloginForm.phone"
                            auto-complete="off"
                            placeholder="请输入手机号"
                            @keyup.enter.native="dosmsloginLogin">
                        <img slot="prefix" src="/assets/loginreg/shoujihao.png" alt="" style="margin-top:12px">
                  </el-input>
                </el-form-item>
                <el-form-item prop="verify" class="verifybtn">
                  <!-- <el-row :span="24">
                    <el-col :span="12"> -->
                      <el-input
                          maxlength="6"
                          v-model="smsloginForm.verify"
                          auto-complete="off"
                          placeholder="请输入验证码"
                          @keyup.enter.native="dosmsloginLogin">
                          <img slot="prefix" src="/assets/loginreg/yanzhengma.png" alt="" style="margin-top:12px">
                          <el-button slot="suffix" 
                                     @click="getVerify"
                                   
                                     :disabled="codeVerify.disabled">
                              <span v-show="codeVerify.show">获取验证码</span>
                              <span v-show="!codeVerify.show" class="count">{{codeVerify.count}} s</span>
                          </el-button>
                          <!-- <span slot="prefix">获取验证码</span> -->
                      </el-input>
                    <!-- </el-col>
                  </el-row> -->
                </el-form-item>
                <el-form-item class="logbtn">
                  <el-button :loading="smsloading"  type="primary" @click.native.prevent="dosmsloginLogin">登录</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <div style="display:flex;justify-content:space-between;font-size:16px;margin-top:10px"> 
              <div style="color: #0066EB;cursor:pointer" @click="regnewuser">注册新用户</div>
              <div style="color: #999999;cursor:pointer" @click='goretrieve'>找回密码？</div>
            </div>
          </el-tabs>
          <!-- 新用户注册 -->
          <el-tabs v-if='newregistration==2' v-model="regactiveName" style="width: 420px;height:500px;margin-top:70px;"> 
            <el-tab-pane label="新用户注册" name="newreg">
              <el-form ref="regForm" :rules="regFormRules" :model="regForm"
                       status-icon label-width="0">
                <el-form-item prop="regphone">
                  <el-input v-model="regForm.regphone"
                            auto-complete="off"
                            
                            placeholder="请输入手机号"
                            @keyup.enter.native="doregistration">
                        <img slot="prefix" src="/assets/loginreg/shoujihao.png" alt="" style="margin-top:12px">
                  </el-input>
                </el-form-item>
                <el-form-item prop="regsterverify" class="verifybtn">
                    <el-input
                        maxlength="6"
                        v-model="regForm.regsterverify"
                        auto-complete="off"
                        placeholder="请输入验证码"
                        @keyup.enter.native="doregistration">
                        <img slot="prefix" src="/assets/loginreg/yanzhengma.png" alt="" style="margin-top:12px">
                        <el-button slot="suffix" 
                                   @click="getVerify"
                                   :disabled="regVerify.disabled">
                            <span v-show="regVerify.show">获取验证码</span>
                            <span v-show="!regVerify.show" class="count">{{regVerify.count}} s</span>
                        </el-button>
                    </el-input>
                </el-form-item>
                <div>
                  <el-form-item prop="regaccount" style="margin:20px 0" >
                      <el-input v-model="regForm.regaccount"
                                auto-complete="off"
                                placeholder="请输入用户名"
                                @keyup.enter.native="doregistration">                
                        <img slot="prefix" src="/assets/loginreg/account.png"  alt="" style="margin-top:12px">
                      </el-input>
                  </el-form-item>
                </div>
                <div>
                  <el-form-item prop="regpassword" style="margin:20px 0" >
                    <el-input :type="passwordType"
                              v-model="regForm.regpassword"
                              auto-complete="off"
                              placeholder="请设置6-20位密码"
                              @keyup.enter.native="doregistration">
                      <img slot="prefix" src="/assets/loginreg/password.png" alt="" style="margin-top:12px">
                      <i  slot="suffix" style="cursor:pointer" class="el-icon-view el-input__icon" @click="showPassword"/>
                    </el-input>
                  </el-form-item>
                </div>
                <div>
                  <el-form-item prop="newpassword" style="margin:20px 0" >
                    <el-input :type="newpasswordType"
                              v-model="regForm.newpassword"
                              auto-complete="off"
                              placeholder="请输入确认密码"
                              @keyup.enter.native="doregistration">
                      <img slot="prefix" src="/assets/loginreg/password.png" alt="" style="margin-top:12px">
                      <i  slot="suffix" style="cursor:pointer"  class="el-icon-view el-input__icon" @click="shownewPassword"/>
                    </el-input>
                  </el-form-item>
                </div>
                <el-form-item class="logbtn">
                  <el-button :loading="regloading" type="primary" @click.native.prevent="doregistration">注册并登录</el-button>
                </el-form-item>
                <p style='color:#0066EB;text-align:center;cursor:pointer' @click='gologin'>使用已用账号登录</p>
              </el-form>
            </el-tab-pane> 
          </el-tabs>
          <!-- 找回密码 -->
          <el-tabs v-if='newregistration==3' v-model="regactiveName" style="width: 400px;height:460px;margin-top:70px;"> 
            <el-tab-pane label="找回密码" name="newreg">
              <el-form ref="retrieveForm" :rules="retrieveFormRules" :model="retrieveForm"
                       status-icon label-width="0">
                <el-form-item prop="retrievephone">
                  <el-input v-model="retrieveForm.retrievephone"
                            auto-complete="off"
                            placeholder="请输入手机号"
                            @keyup.enter.native="doretrieve">
                        <img slot="prefix" src="/assets/loginreg/shoujihao.png" alt="" style="margin-top:12px">
                  </el-input>
                </el-form-item>
                <el-form-item prop="retrieveverify" class="verifybtn">
                    <el-input
                        maxlength="6"
                        v-model="retrieveForm.retrieveverify"
                        auto-complete="off"
                        placeholder="请输入验证码"
                        @keyup.enter.native="doretrieve">
                        <img slot="prefix" src="/assets/loginreg/yanzhengma.png" alt="" style="margin-top:12px">
                        <el-button slot="suffix" 
                                   @click="getVerify"
                                   :disabled="zhpasswordVerify.disabled">
                            <span v-show="zhpasswordVerify.show">获取验证码</span>
                            <span v-show="!zhpasswordVerify.show" class="count">{{zhpasswordVerify.count}} s</span>
                        </el-button>
                    </el-input>
                </el-form-item>
                <el-form-item prop="retrievepassword" style="margin:20px 0" >
                  <el-input :type="passwordType"
                            v-model="retrieveForm.retrievepassword"
                            auto-complete="off"
                            placeholder="请输入新密码"
                            @keyup.enter.native="doretrieve">
                    <img slot="prefix" src="/assets/loginreg/password.png" alt="" style="margin-top:12px">
                    <i  slot="suffix" style="cursor:pointer"  class="el-icon-view el-input__icon" @click="showPassword"/>
                  </el-input>
                </el-form-item>
                <el-form-item prop="newretrievepassword" style="margin:20px 0" >
                  <el-input :type="newpasswordType"
                            v-model="retrieveForm.newretrievepassword"
                            auto-complete="off"
                            placeholder="请确认新密码"
                            @keyup.enter.native="doretrieve">
                    <img slot="prefix" src="/assets/loginreg/password.png" alt="" style="margin-top:12px">
                    <i  slot="suffix" style="cursor:pointer"  class="el-icon-view el-input__icon" @click="shownewPassword"/>
                  </el-input>
                </el-form-item>
                <el-form-item class="logbtn">
                  <el-button :loading="retriloading"  type="primary" @click.native.prevent="doretrieve">提交</el-button>
                </el-form-item>
                <p style='color:#0066EB;text-align:center;cursor:pointer' @click='gologin'>使用已用账号登录</p>
              </el-form>
            </el-tab-pane> 
          </el-tabs>
        </div>
    </div>
</template>

<script>
  import {isMobile} from "@/util/validate";
  import {getCodeUserLogin,getCodeUserRegister,getCodeChangePasswd} from "@/api/system/login";
  import {addTester,changePasswd,listUser,getUser,delUser,updateUser,exportUser,resetUserPwd,changeUserStatus,importTemplate} from "@/api/system/user";
  import { encrypt, decrypt } from '@/util/encrypt'
  export default {
    data(){
      const validatephone=(rule, value, callback) => {
          if (value === '') {
              return callback(new Error('请输入手机号'));
          }
          if(!/^1[3456789]\d{9}$/.test(value)){
             return callback(new Error('手机号格式不对')); 
          }
          callback();
      };
      const validateaccount = (rule, value, callback) => {
          if (value === '') {
              return callback(new Error('请输入用户名'));
          }
          if(!/^[A-Za-z0-9]+$/.test(value)){
             return callback(new Error('请输入数字和字母')); 
          }
          callback();
      };
      const validatePass = (rule, value, callback) => {
            if (value === '') {
              return callback(new Error('请输入密码'));
            }
            if(!/^[a-z0-9][a-z0-9A-Z@#%^.*!~?|]{5,19}$/i.test(value)){
              return callback(new Error('密码格式错误'));
            }
            // if (this.getpasswordForm.repassword !== '') {
            //   this.$refs.getpasswordForm.validateField('repassword')
            // }
            return callback();
          };
          //注册的确认密码
      const validatePass2 = (rule, value, callback) => {
          if (value === '') {
              callback(new Error('请再次输入密码'));
          } else if (value !== this.regForm.regpassword) {
            callback(new Error('两次输入密码不一致!'));
          } else {
               callback();
          }
      };
      //找回密码确认密码
      const validatePass3 = (rule, value, callback) => {
          if (value === '') {
              callback(new Error('请再次输入密码'));
          } else if (value !== this.retrieveForm.retrievepassword) {
            callback(new Error('两次输入密码不一致!'));
          } else {
               callback();
          }
      };
      return {
        doloading:false,//账号登录
        smsloading:false,//验证码登录
        regloading:false,//注册
        retriloading:false,//找回密码
        newregistration:1,
        activeName:'passwordlog',
        regactiveName:'newreg',
        loginForm: {account: '', password: ''},//密码登录
        checked: false,
        loginRules: {
          account: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
          password: [{ required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, message: '密码长度最少为6位', trigger: 'blur' }],      
        },
        passwordType: 'password',
        newpasswordType: 'password',
        smsloginForm: {phone: '',  verify: '',uuid:''},//验证码登录
        smsloginnRules: {
          phone: [{ required: true,validator:validatephone, trigger: 'change' }],       
          verify: [{ required: true, message: '请输入验证码', trigger: 'change' },
            { min: 6, max: 6, message: '验证码长度为6位', trigger: 'change' }
        ]
        },
        codeVerify:{ show: true, count: 0, timer: null, disabled: false},//登录验证码
        regVerify:{ show: true, count: 0, timer: null, disabled: false},//注册验证码
        zhpasswordVerify:{ show: true, count: 0, timer: null, disabled: false},//找回密码验证码
        //注册
        regForm:{regphone: '',  regsterverify: '',regaccount: '', regpassword: '',newpassword:'',uuid:''},
        regFormRules:{
          regphone: [{ required: true,validator:validatephone, trigger: 'change' }],  
          regsterverify: [{ required: true, message: '请输入验证码', trigger: 'change' },
            { min: 6, max: 6, message: '验证码长度为6位', trigger: 'change' }],
          regaccount: [{ required: true, validator:validateaccount,trigger: 'blur' }],
          regpassword: [ { max: 20, message: '密码长度最多为20位', trigger: 'blur' },{ required: true, validator:validatePass, trigger: 'blur' },
            { min: 6, message: '密码长度最少为6位', trigger: 'blur' },],
          newpassword: [{ required: true, validator:validatePass2, trigger: 'blur' },
            { min: 6, message: '密码长度最少为6位', trigger: 'blur' }],
        },
        //找回密码
        retrieveForm:{retrievephone: '',  retrieveverify: '',retrievepassword: '',newretrievepassword:'',uuid:''},
        retrieveFormRules:{
          retrievephone: [{ required: true,validator:validatephone, trigger: 'blur' }],  
          retrieveverify: [{ required: true, message: '请输入验证码', trigger: 'change' },
            { min: 6, max: 6, message: '验证码长度为6位', trigger: 'change' }],
          retrievepassword: [ { max: 20, message: '密码长度最多为20位', trigger: 'blur' },{ required: true, validator:validatePass, trigger: 'blur' },
            { min: 6, message: '密码长度最少为6位', trigger: 'blur' },],
          newretrievepassword: [{ required: true, validator:validatePass3, trigger: 'blur' },
            { min: 6, message: '密码长度最少为6位', trigger: 'blur' }],
        },
      }
    },
    created() {  

    },
    watch:{

    },
    mounted(){
        let type=this.$route.query.type;
        if(type=='log'){
          this.newregistration=1;
        }else if(type=='reg'){
          this.newregistration=2;
        }
        this.getlocal()
    },
    methods:{
       getlocal() {
        const account =  localStorage.getItem('account');
        const password =  localStorage.getItem("password");
        // const rememberMe =  localStorage.getItem('rememberMe')
        this.loginForm = {
          account: account === undefined ? this.loginForm.account : account,
          password: password === undefined ? this.loginForm.password : password,
          // rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
        };
      },
      showPassword() {this.passwordType == ''? (this.passwordType = 'password'): (this.passwordType = '')  },
      shownewPassword() {this.newpasswordType == ''? (this.newpasswordType = 'password'): (this.newpasswordType = '')  },
      // tab切换按钮
      handleClick(tab, event){
      },
      //获取验证码
      getVerify() {
          let phone = '';
          if(this.newregistration==2){       
            phone =this.regForm.regphone;
            if (!phone || !isMobile(phone)) {
              this.$message.warning('手机格式不对');
              return;
            }
            this.regVerify.disabled = true;
            // 获取注册验证码的接口
            getCodeUserRegister(phone).then((res)=> {
                if(res.code==200){
                  this.regForm.uuid=res.uuid;
                  this.$message.success('短信发送成功，请注意查收')             
                  const TIME_COUNT = 60; //更改倒计时时间
                  if (!this.timer) {
                      this.regVerify.count = TIME_COUNT;
                      this.regVerify.show = false;
                      this.regVerify.timer =
                      setInterval(() => {
                          if (this.regVerify.count > 0 && this.regVerify.count <= TIME_COUNT) {
                              this.regVerify.count--;
                          } else {
                              this.regVerify.disabled = false;
                              this.regVerify.show = true;
                              clearInterval(this.regVerify.timer); // 清除定时器
                              this.regVerify.timer = null;
                          }
                      }, 1000);
                  }
                }           
            }).catch((err) => {
            });   
          }else if(this.newregistration==1){
            phone =this.smsloginForm.phone;
            if (!phone || !isMobile(phone)) {
              this.$message.warning('手机格式不对');
              return;
            }
            this.codeVerify.disabled = true;
             // 获取登录验证码的接口
            getCodeUserLogin(phone).then((res)=> {
                if(res.code==200){
                  this.smsloginForm.uuid=res.uuid;
                  this.$message.success('短信发送成功，请注意查收')   
                  const TIME_COUNT = 60; //更改倒计时时间
                  if (!this.timer) {
                      this.codeVerify.count = TIME_COUNT;
                      this.codeVerify.show = false;
                      this.codeVerify.timer =
                      setInterval(() => {
                          if (this.codeVerify.count > 0 && this.codeVerify.count <= TIME_COUNT) {
                              this.codeVerify.count--;
                          } else {
                              this.codeVerify.disabled = false;
                              this.codeVerify.show = true;
                              clearInterval(this.codeVerify.timer); // 清除定时器
                              this.codeVerify.timer = null;
                          }
                      }, 1000);
                  }        
                }
            });
            
          }else if(this.newregistration==3){
            phone =this.retrieveForm.retrievephone;
            if (!phone || !isMobile(phone)) {
              this.$message.warning('手机格式不对');
              return;
            }
            this.zhpasswordVerify.disabled = true;
             // 获取找回密码验证码的接口
              getCodeChangePasswd(phone).then((res)=> {
                if(res.code==200){
                  this.retrieveForm.uuid=res.uuid;
                  this.$message.success('短信发送成功，请注意查收')              
                  const TIME_COUNT = 60; //更改倒计时时间
                  if (!this.timer) {
                      this.zhpasswordVerify.count = TIME_COUNT;
                      this.zhpasswordVerify.show = false;
                      this.zhpasswordVerify.timer =
                      setInterval(() => {
                          if (this.zhpasswordVerify.count > 0 && this.zhpasswordVerify.count <= TIME_COUNT) {
                              this.zhpasswordVerify.count--;
                          } else {
                              this.zhpasswordVerify.disabled = false;
                              this.zhpasswordVerify.show = true;
                              clearInterval(this.zhpasswordVerify.timer); // 清除定时器
                              this.zhpasswordVerify.timer = null;
                          }
                      }, 1000);
                  }
                }    
              }).catch((err) => {
            });   
          }         
      },
      //密码登录
      doLogin(){
         this.$refs.loginForm.validate((valid) => {
            if(valid) {       
              this.doloading = true;
              let data={
                username: this.loginForm.account,
                // password: this.loginForm.password
                password: encrypt(this.loginForm.password)
              };
              this.$store.dispatch("NameLogin", data).then((res) => {
                // if (this.loginForm.rememberMe) {
                 localStorage.setItem("account", this.loginForm.account,);
                //  localStorage.setItem("password", this.loginForm.password);
                  // Cookie.set('rememberMe', this.loginForm.rememberMe, {expires: 30});
                // } else {
                //   localStorage.remove("username");
                //   localStorage.remove("password");
                //   localStorage.remove('rememberMe');
                // }
                 this.$store.dispatch("GetInfo").then((userInfo)=>{
                   if(userInfo){
                     this.$router.push('/')
                   }
                 })
                
              }).catch(() => {
                this.doloading = false;
              });
              // localStorage.setItem('access_token',this.token)  
              // let data=Date.parse(new Date());        
              // localStorage.setItem('logindate',data)        
              // this.$router.push('/')
            }
        })
      },
      // 手机号登录
      dosmsloginLogin(){
        this.$refs.smsloginForm.validate((valid) => {
          if(valid) {      
            // smsloginForm: {phone: '',  verify: '',uuid:''},
            this.smsloading = true;
            let data={
              mobile:this.smsloginForm.phone,
              code:this.smsloginForm.verify,
              uuid:this.smsloginForm.uuid,
            };
            this.$store.dispatch("PhoneLogin", data).then(() => {
              this.$store.dispatch("GetInfo").then((userInfo)=>{
                if(userInfo){
                  this.$router.push('/')
                }
              })
            }).catch(() => {
              this.smsloading = false;
            });
            // localStorage.setItem('access_token',this.token)
            // let data=Date.parse(new Date());        
            // localStorage.setItem('logindate',data)
            // this.$router.push('/')
          }
        })
      },
      //注册新用户
      regnewuser(){
        this.newregistration=2;
      },
      //注册并登录
      doregistration(){
        this.$refs.regForm.validate((valid) => {
          if(valid) {        
            // regForm:{regphone: '',  regsterverify: '',regaccount: '', regpassword: '',newpassword:'',uuid:''},
            this.regloading = true;
            let data={
              phonenumber:this.regForm.regphone,
              remark:this.regForm.regsterverify,
              sex:this.regForm.uuid,
              userName:this.regForm.regaccount,
              // password:this.regForm.regpassword,
              password:encrypt(this.regForm.regpassword),
              checkPass:this.regForm.newpassword,
            }
            // return;
            addTester(data).then((response) => {
              if(response.code==200){
                this.$message.success("注册成功");
                this.newregistration=1;
              }           
            }).catch(() => {
              this.regloading = false;
            });   
          }
        })
      },
      //找回密码
      goretrieve(){
        this.newregistration=3;
      },
      //找回密码提交
      doretrieve(){
        this.$refs.retrieveForm.validate((valid) => {
          if(valid) {             
              //  retrieveForm:{retrievephone: '',  retrieveverify: '',retrievepassword: '',newretrievepassword:'',uuid:''},
              // this.form.userName = this.form.phonenumber;
              // this.form.nickName = this.form.userName;//基本信息里的
              let data={
                // userName,remark,password,checkPass
                phonenumber:this.retrieveForm.retrievephone,
                nickName:this.retrieveForm.retrievephone,
                userName:this.retrieveForm.retrievephone,
                password: encrypt(this.retrieveForm.retrievepassword),
                checkPass: encrypt(this.retrieveForm.newretrievepassword),
                remark:this.retrieveForm.retrieveverify,
                sex:this.retrieveForm.uuid,
              }
              changePasswd(data).then((response) => {
                this.$message.success("修改成功，请重新登录");              
                setTimeout(()=>{
                  this.newregistration=1;
                },1000)
              });
            
          }
        })
      },
      gologin(){
        this.newregistration=1;
      }
    },
  }
</script>

<style scoped>
  .loginframe{
    height:650px;
    width:100%;
    background-image: url('/assets/loginreg/bg.png');
    background-size:100% 650px;
    background-repeat:no-repeat;
    /* padding-top:130px; */
  }
  .loginframe>>>.el-tabs{
    width: 380px;
    height: 350px;
    background:#FFFFFF;
    margin-left:62%;
    box-shadow: 0px 2px 13px 0px rgba(9, 39, 77, 0.28);
    border-radius: 8px;
    padding:20px;
    margin-top:130px;
    display:inline-block;
  }
  .loginframe>>>.el-tabs__nav-scroll{
    display:flex;
    justify-content:center;
  }
  .loginframe>>>.el-input__inner{
    height:44px;
  }
  .loginframe>>>.el-tabs__item{
    font-weight: bold;
    color: #737373;
    font-size:20px;
    padding: 0 52px;
    margin-bottom:10px
  }
  .loginframe>>>.el-tabs__item:hover,.loginframe>>>.el-tabs__item.is-active{
    font-weight: bold;
    color: #0066EB;
    font-size:20px
  }
  .loginframe>>>.el-tabs__active-bar{
    background-color: #0066EB;
  }
  .logbtn>>>.el-button{
    margin-top:20px;
    /* margin-left:57px; */
    width:100%;
    height:50px;
    font-size:20px;
    color:rgba(255,255,255,1);
    background: linear-gradient(45deg, #2978EE, #0066EB);
    border:none;
    border-radius:6px;
  }
  .verifybtn>>>.el-button{
    margin-top:-3px;
    margin-left: -28px;
    width:100%;
    height:50px;
    font-size:17px;
    color:#0066EB;
    background: transparent;
    border:none;
    border-radius:6px;
    z-index:-1
    /* 18798569999 */
  }
  .verifybtn>>>.el-button.is-disabled:hover{
    background: transparent;
  }
</style>
