<template>
  <div class="login" :class="processClass">
    <div class="login-box">
      <div class="login-from-bgm">
        <img :src="require('@/assets/login/from_left.png')" alt="">
      </div>
      <div class="login-from-box">
        <div class="login-from-title">
          <img :src="require('@/assets/login/from_title.png')" alt="">
          <span> {{loginTitle}}</span>
        </div>
        
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
          <div class="login-from-tab">
            <div 
            v-for="(item,index) in loginTypeList"
            :key="index"
            @click="setLoginType(item)"
            :class="[ item.type == loginForm.loginType ? 'login-from-tab-action' : '' ]"
            >
              <span>{{ item.name }}</span>
              <span></span>
            </div>
          </div>
          <!--  账号登录  -->
          <div style="min-height: calc( 100% - 200px );width: 100%;" v-if="loginForm.loginType == 1">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                type="text"
                auto-complete="off"
                placeholder="账号"
              >
                <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                auto-complete="off"
                placeholder="密码"
                @keyup.enter.native="handleLogin"
              >
                <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
            <el-form-item prop="code" v-if="captchaEnabled">
              <el-input
                v-model="loginForm.code"
                auto-complete="off"
                placeholder="验证码"
                style="width: 63%"
                @keyup.enter.native="handleLogin"
              >
                <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
              </el-input>
              <div class="login-code">
                <img :src="codeUrl" @click="getCode" class="login-code-img"/>
              </div>
            </el-form-item>
            <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
          </div>
          <!--  验证码登录  -->
          <div style="min-height: calc( 100% - 200px );width: 100%;" v-if="loginForm.loginType == 2">
            <el-form-item prop="phone">
              <el-input
                v-model="loginForm.phone"
                type="text"
                auto-complete="off"
                placeholder="手机号"
                @keyup.enter.native="getCode()"
              >
                <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
            <el-form-item prop="code" v-if="captchaEnabled">
              <el-input
                v-model="loginForm.code"
                auto-complete="off"
                placeholder="验证码"
                style="width: 63%"
                @keyup.enter.native="handleLogin"
              >
                <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
              </el-input>
              <div class="login-code">
                <el-button
                  :loading="codeLoading"
                  size="medium"
                  type="primary"
                  style="width:100%;background: linear-gradient( 90deg, #34F8F3 0%, #1AA0F2 100%);"
                  @click="getCode"
                  round
                >
                  <span v-if="!codeLoading && !codeType">获取验证码</span>
                  <span v-if="!codeLoading && codeType == 2">重新获取</span>
                  <span v-if="codeLoading">重新获取</span>
                  <span v-if="!codeLoading && codeType == 1">{{ codeEffectiveTime }}s后重新获取</span>
                </el-button>
              </div>
            </el-form-item>
          </div> 
          <el-form-item style="width:100%;">
              <el-button
                :loading="loading"
                size="medium"
                type="primary"
                style="width:100%;background: linear-gradient( 90deg, #34F8F3 0%, #1AA0F2 100%);"
                @click.native.prevent="handleLogin"
                round
              >
                <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>
      </div>
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2023 达泽科技 All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg,getCodeNum } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
  name: "Login",
  data() {
    return {
      codeUrl: "",
      loginTitle: '',
      loginForm: {
        username: "admin",
        password: "admin123",
        rememberMe: false,
        code: "",
        uuid: "",

        loginType: 1,
        phone: null,
        smsToken: null, // 短信验证token，由短信发送接口获取
      },
      loginRules: {
        username: [
          { required: true, trigger: ["change","blur"], message: "请输入您的账号" }
        ],
        phone: [
          { required: true, trigger: ["change","blur"], message: "请输入您的账号" },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: ["change","blur"] }
        ],
        password: [
          { required: true, trigger: ["change","blur"], message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
      processClass: '',

      // 登录类型
      loginTypeList: [
        { name: '密码登录', type: 1 },
        { name: '验证码登录', type: 2 },
      ],
      codeLoading: false,// 加载获取验证码
      codeTime: false, // 验证码失效时间
      codeType: null, // 获取验证码是否成功的标识 0: 失败  1： 成功
      codeEffectiveTime: 60,
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    this.getCookie();

    // 根据环境切换名称和背景图
    this.loginTitle = process.env.VUE_APP_TITLE;
    if(process.env.NODE_ENV == 'development') { // 开发环境
      this.processClass = 'login-dev';
    } else if (process.env.NODE_ENV == 'staging') { // 测试环境
      this.processClass = 'login-stage';
    } else if (process.env.NODE_ENV == 'production') { // 生产环境
      this.processClass = 'login-prod';
      this.$set(this.loginForm, 'username', '');
      this.$set(this.loginForm, 'password', '');
    }
  },
  methods: {
    getCode() {
      if(this.loginForm.loginType == 1) { // 密码登录
        getCodeImg().then(res => {
          this.codeUrl =  res.data.captchaImage;
          this.loginForm.uuid = res.data.captchaKey;
        }).catch(()=> {
          this.codeUrl =  null;
          this.loginForm.uuid = null;
        })
      }else if(this.loginForm.loginType == 2) { // 验证码登录
        // 定义手机号格式的正则表达式
        var regExp = /^1[3456789]\d{9}$/;
        if( this.codeType == 1 || !regExp.test(this.loginForm.phone)) {
          if(!regExp.test(this.loginForm.phone)) {
            this.$refs.loginForm.validateField(['phone'])
          }
          return
        }
        if(this.codeLoading || this.codeEffectiveTime != 60 || this.codeType == 1) return
        this.codeEffectiveTime = 60

        if( this.codeTime ) {
          clearInterval(this.codeTime)
        }
        this.codeLoading = true
        getCodeNum({
          "mobile": this.loginForm.phone
        }).then(res => {
          this.loginForm.smsToken = res.data.smsToken
          this.codeType = 1
          this.codeLoading = false
          this.codeEffectiveTime = 60
          this.codeTime = setInterval(()=>{
            this.codeEffectiveTime = this.codeEffectiveTime - 1
            if( this.codeEffectiveTime <= 0 ) {
              this.codeType = null
              clearInterval(this.codeTime)
              this.codeEffectiveTime = 60
            }
          },1000)
        }).catch(()=> {
          this.codeType = 2
          this.codeLoading = 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),
        loginType: 1,
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if(this.loginForm.loginType == 1){
            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');
            }
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            if( this.codeTime ) {
              clearInterval(this.codeTime)
            }
            this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    },
    /**  选择登录方式  */
    setLoginType(item) {
      this.$set( this.loginForm, 'loginType', item.type)
      this.$set( this.loginForm, 'code', null)
      this.$nextTick(()=>{
        this.$refs.loginForm.clearValidate()
      })
    }
  }
};
</script>

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

.login-box {
  display: flex;
  height: 602px;
  .login-from-bgm {
    width: 872px;
    height: 100%;
    box-sizing: border-box;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .login-from-box {
    width: 602px;
    height: 100%;
    box-sizing: border-box;
    background-image: url(../assets/login/from_right.png);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    display: flex;
    flex-direction: column;
    .login-from-title {
      display: flex;
      align-items: center;
      padding: 34px 0 0 48px;
      img {
        width: 46px;
        height: 42px;
      }
      span {
        font-family: SourceHanSansCN, SourceHanSansCN;
        font-weight: 500;
        font-size: 30px;
        color: #FFFFFF;
        margin-left: 15px;
      }
    }

    .login-from-tab {
      width: 100%;
      display: flex;
      padding: 10px 20px 30px;
      >div {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;
        cursor: pointer;
        >span:first-child {
          color: #fff;
          font-family: SourceHanSansCN, SourceHanSansCN;
          font-weight: 400;
          font-size: 22px;
          color: #FFFFFF;
        }
        >span:last-child {
          color: #fff;
          width: 40px;
          height: 4px;
          margin-top: 5px;
        }
        
      }

      >div:first-child {
        padding-right: 20px;
      }

      >div:last-child {
        padding-left: 20px;
      }
      .login-from-tab-action {
        >span:first-child {
          font-family: SourceHanSansCN, SourceHanSansCN;
          font-weight: bold;
          font-size: 22px;
        }
        >span:last-child {
          background: linear-gradient( 225deg, #FFFFFF 0%, #FFFFFF 100%);
          border-radius: 3px;
        }
      }
    }
  }
}

.login-prod{
  background-image: url("../assets/images/login-bg-img.png") !important;
}
.login-stage{
  background-image: url("../assets/images/login-bg-img.png") !important;
}
.login-dev{
  background-image: url("../assets/images/login-bg-img.png") !important;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  //background: rgba(255,255,255,0.62);
  backdrop-filter: blur(5px);
  width: 100%;
  height: calc( 100% - 100px );
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 25px 120px 25px;
  box-sizing: border-box;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
  .el-input__inner {
    border-radius: 29px;
    border: 1px solid #FFFFFF;
    --color-bgm: 'none';
    background-color: var(--color-bgm);
    color: #fff;
  }
  .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #ffffff;
  } 
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
</style>
