<template>
  <div class="login">
    <el-row type="flex">
      <el-col :span="12">
        <div class="login-form-left"> 
          <!-- <span class="copyright">Copyright © 2021 quanshu123.com All Rights Reserved.</span> -->
        </div>
      </el-col>
      <el-col :span="12">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" :inline='false'>
          <!-- <h3 class="title">{{title}}</h3> -->
          <div class="title-container">
            <div class="login_header" >
              <a @click="changeTab('actpwd')" class="a50" :class="{active:type=='actpwd'}" >密码登录</a>
              <a @click="changeTab('phonesms')" class="a50" :class="{active:type=='phonesms' }" >短信登录</a>
            </div>
          </div>
          
          <div v-if="type=='actpwd'" class="cbody_item">
            <el-form-item prop="username" label="手机号" id="selectForm" class=".login-form">
              <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
              </el-input>
            </el-form-item>
            <el-form-item prop="password" label="密码" class=".login-form">
              <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码" @keyup.enter.native="handleLogin" >
              </el-input>
            </el-form-item>
            <el-row style="height:120px">
              <el-col :span="15" >
            <el-form-item prop="code" v-if="captchaOnOff" label="验证码" class=".login-form">
              <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码"  @keyup.enter.native="handleLogin">
              </el-input>
            </el-form-item>
              </el-col>

              <el-col class="identifying-code">
                <div class="login-code">
                <img :src="codeUrl" @click="getCode" style="height:48px;width:128px;"/>
              </div>
              </el-col>
            </el-row>
            <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 8px 0px;">记住密码</el-checkbox>
          </div>
          <div v-if="type=='phonesms'" class="cbody_item" style="margin-bottom:88px">
            <el-form-item prop="mobile" label="手机号" class="mobile-item" >
              <el-input ref="mobile" v-model="loginForm.mobile" placeholder="请输入手机号" name="mobile" type="text"
                tabindex="1" auto-complete="on">
              </el-input>
            </el-form-item>

            <el-form-item prop="status">
              <JcRange ref="jcr" status="status" :successFun="onMpanelSuccess" :errorFun="onMpanelError" :is-lock="status"></JcRange>
            </el-form-item>

            <el-row class="yzcode">
              <el-col :span="15">
            <el-form-item prop="verifyCode" label="验证码" class="yz-code">               
                  <el-input ref="verifyCode" v-model="loginForm.verifyCode" type="text" placeholder="请输入验证码" name="verifyCode" abindex="2"
                    maxlength="6" auto-complete="off" @keyup.enter.native="handleLogin">
                  </el-input>
            </el-form-item>
              </el-col>

              <el-col :span="9" class="yzcode-btn">
                  <span style="float: right;">
                    <el-button :loading="sending" :disabled="sendDisabled" size="medium" @click="onSendSms" class="yzcode-send" type="primary">
                      {{ sendButtonText }}
                    </el-button>
                  </span>
                </el-col>
              </el-row>
          </div>
          <el-form-item  class="login-bottom">
            <el-button :loading="loading" size="medium" type="primary" class="login-btn"
              @click.native.prevent="handleLogin">
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div style="float: right;" v-if="register">
              <router-link class="link-type" :to="'/register'">立即注册</router-link>
            </div>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {
    getCodeImg,sendSms
  } from "@/api/login";
  import Cookies from "js-cookie";
  import {
    encrypt,
    decrypt
  } from '@/utils/jsencrypt'
  //import logoImg from '@/assets/logo/quick-logo.png'

  import {
    isBoolean
  } from "@/utils/validate"

  import JcRange from "@/components/JcRange/index.vue";
  import AuthImg from "@/components/AuthImg/index.vue"

  export default {
    name: "Login",
    components: {
      JcRange,AuthImg
    },
    data() {
      return {
        title: "系统登录",
        type: "actpwd",   // 账号密码 actpwd，手机短信验证码登录 phonesms，微信登录 wechatcode
        sending: false,
        sendDisabled: false,
        loading: false,
        timer: 0,
        logo:"",
        codeUrl: "",
        cookiePassword: "",
        loginForm: {
          username: "admin",
          password: "admin123",
          rememberMe: false,
          code: "",
          uuid: "",
          mobile: "",
          verifyCode: "",
          status: false
        },
        status: false,
        loginRules: {
          username: [{
            required:true,
            trigger: "blur",
            message: "请输入您的账号"
          }],
          password: [{
            required:true,
            trigger: "blur",
            message: "请输入您的密码"
          }],
          code: [{
            required:true,
            trigger: "change",
            message: "请输入验证码"
          }]
        },
        loading: false,
        // 验证码开关
        captchaOnOff: true,
        // 注册开关
        register: false,
        redirect: undefined
      };
    },
    computed: {
      sendButtonText() {
        if (this.timer === 0) {
          this.sendDisabled = false
          return "发送验证码";
        } else {
          return `${this.timer}秒后重发`;
        }
      }
    },
    watch: {
      $route: {
        handler: function(route) {
          this.redirect = route.query && route.query.redirect;
        },
        immediate: true
      },
      timer(num) {
        if (num > 0) {
          setTimeout(() => {
            this.timer = --num;
          }, 1000);
        }
      }
    },
    created() {
      this.getCode();
      this.getCookie();
    },
    methods: {
      changeTab(tab){
        // console.log("changeTab====="+ tab)
        this.$refs["loginForm"].clearValidate();
        this.loginRules = {}
        this.type = tab
        if(this.type=='actpwd'){
          this.loginRules ={
            username: [{
              required:true,
              trigger: "blur",
              message: "请输入您的账号"
            }],
            password: [{
              required:true,
              trigger: "blur",
              message: "请输入您的密码"
            }],
            code: [{
              required:true,
              trigger: "change",
              message: "请输入验证码"
            }]
          }
        }else if(this.type=='phonesms'){
          this.loginRules ={
            mobile: [
              {required:true, trigger: "blur",message: "请输入您的手机号码"},
              {pattern: /^((\+?86)|(\(\+86\)))?1\d{10}$/, message: "请输入正确的手机号码", trigger: "blur" }
           ],
            verifyCode: [{
              required:true,
              trigger: "change",
              message: "请输入您的短信验证码"
            }],
            // status: [{
            //    validator:isBoolean,
            //    trigger: "change",
            //    message: "请拖住滑块，拖动到最右边"
            // }]
          }
          if(this.timer == 0){
            this.$nextTick(() => {
              this.$refs.jcr.init()
            }) 
            this.status = false;
          }
        }
      },

      getCode() {
        getCodeImg().then(res => {
          this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff;
          if (this.captchaOnOff) {
            this.codeUrl = "data:image/gif;base64," + res.img;
            this.loginForm.uuid = res.uuid;
          }
        });
      },
      // 发送短信
      onSendSms() {
        this.$refs.loginForm.validateField("mobile", err => {
          if (!err) {
            if(!this.status){
              this.$message.warning("请拖住滑块，拖动到最右边");
              return false;
            }
            this.sending = true;
            this.sendDisabled = true
            const mobile = this.loginForm.mobile;
            sendSms(mobile)
              .then(res => {
                this.timer = 60;
                this.loginForm.uuid = res.data;
                this.$message.success("短信发送成功，请注意查收");
                Cookies.set("last-send-time", new Date());
              })
              .catch(e => {
                this.$message.error("网络异常");
                this.timer = 0;
                this.sendDisabled = false;
                // console.log(e);
              })
              .finally(() => (this.sending = false));
          }
        });
      },
      onMpanelSuccess(){
        // console.log("onMpanelSuccess 验证成功 =====")
        this.status = true
      },
      onMpanelError(){
         // console.log("onMpanelError 验证失败 =====")
         this.status = false
      },
      getCookie() {
        const username = Cookies.get("username");
        const password = Cookies.get("password");
        const rememberMe = Cookies.get('rememberMe')
        this.loginForm = {
          username: username === undefined ? this.loginForm.username : username,
          password: password === undefined ? this.loginForm.password : decrypt(password),
          rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
        };
      },

      handleLogin() {
         // console.log("this.handleLogin == "+JSON.stringify(this.loginForm))
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true;
            if(this.type == 'actpwd'){
              if (this.loginForm.rememberMe) {
                Cookies.set("username", this.loginForm.username, {
                  expires: 30
                });
                Cookies.set("password", encrypt(this.loginForm.password), {
                  expires: 30
                });
                Cookies.set('rememberMe', this.loginForm.rememberMe, {
                  expires: 30
                });
              } else {
                Cookies.remove("username");
                Cookies.remove("password");
                Cookies.remove('rememberMe');
              }
            }
            var patch = "PwdLogin";
            var loginParams = {
               uuid: this.loginForm.uuid
            }
            // console.log("this.loginForm == "+JSON.stringify(this.loginForm))
            if(this.type == 'phonesms'){
              patch = "SmsLogin";
              loginParams.mobile = this.loginForm.mobile
              loginParams.verifyCode = this.loginForm.verifyCode
            }else{
              loginParams.username = this.loginForm.username
              loginParams.password = this.loginForm.password
              loginParams.code = this.loginForm.code
            }
            // console.log("loginParams == "+JSON.stringify(loginParams))
            this.$store.dispatch(patch, loginParams).then(() => {
              // console.log("登录成功=================== this.redirect = " + this.redirect)
              this.$router.push({
                path: this.redirect || "/"
              }).catch(() => {
                // console.log("404=================== ")
              });
            }).catch(() => {
              this.loading = false;
              if (this.captchaOnOff) {
                this.getCode();
              }
            });
          }
        });
      }
    }
  };
</script>

<style rel="stylesheet/scss" lang="scss">
  .login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-image: url("../assets/images/login-background.png");
    background-size: cover;
  }

  .login{
    // 去除el-form-item默认效验前面的红*号
  .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap>.el-form-item__label:before, .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before { 
    content: ''; 
    }
  }
  .title {
    margin: 0px auto 30px auto;
    text-align: center;
    color: #707070;
  }

  .title-container{
    border-bottom: 1px solid  #ebebeb;
    height:36px;
    margin-bottom:24px
  }

  .login-form-left {
    border-radius: 6px 0 0 6px;
    background-image: url("../assets/images/login-left.png");
    width: 439px;
    text-align: center;
    padding: 15px;
    height: 100%;
  }

  .login-form {
    border-radius: 0 16px 16px 0;
    background: #ffffff;
    width: 440px;
    padding: 24px 40px 6px 40px;

    .el-input {
      height: 48px;

      input {
        height: 48px;
        border-radius: 8px;
        background-color:  rgba(242, 242, 242, 1);
      }
    }

    .input-icon {
      height: 39px;
      width: 14px;
      margin-left: 2px;
    }
  }

  .login-code {
    float: right;
    position: relative;
    top: -64px;
    img {
      cursor: pointer;
      vertical-align: middle;
    }
  }

  .el-form-item__content{
    margin-bottom: -6px;
  }

  .mobile-item{
    margin-bottom:29px
  }

  .a50 {
    font-family: SourceHanSansCN-Medium;
    font-size: 20px;
    color: #000;
    margin: 50px;
  }

  .login_header {
    margin-bottom: 20px;
    text-align: center;
  }

  .login_header span {
    margin-right: 20px;
    cursor: pointer;
  }

  .cbody_item {
    border: 0px solid #999;
    overflow: hidden;
  }

  .active {
    color: #00aaff;
    padding-bottom: 6px;
    border-bottom: 4px solid #00aaff;
    
  }

  .yzcode{
    display: flex;
    height: 120px;
  }

  .yz-code{
    height: 76px;
  }

  .yzcode-btn{
    position:relative;
    top:40px;
  }

  .yzcode-send{
    height:48px;
    width:128px;
    border-radius: 8px;
    color: rgba(255, 255, 255, 100);
    font-size: 16px;
    font-family: SourceHanSansCN-Medium;
  }

  .login-form {
    .el-form-item__label{
      font-size: 20px;
      color: #000;
      font-family: SourceHanSansCN-Medium;
      margin-bottom: 4px;
    }
}

// .el-input--medium {
//     font-size: 16px;
//     font-family: SourceHanSansCN-Medium
// }

.el-col-24{
  height: 36.0%;
}

.login-bottom{
  width:100%;
  margin-bottom: 30px;
}

.login-btn{
  font-size: 16px;
  color: rgba(255, 255, 255, 100);
  font-family: SourceHanSansCN-Bold;
  width:100%;
  height:48px;
  border-radius: 8px
}

.copyright{
  color: #fff;
  opacity: 40%;
  font-size: 12px;
  position: relative;
  top: 490px;
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
    .el-input--medium {
    font-size: 16px;
    font-family: SourceHanSansCN-Medium
}
</style>