<template>
  <div class="login-container" id="particles-js">
    <div class="bg-logo anim"></div>
    <div class="login-form">
      <div class="title-container">
        <!-- <h3 class="title">{{appName}}</h3> -->
        <img class="csms-logo" src="../../icons/logo.png"/>
        <p class="title" v-if="showOTP">Please enter 6-digit OTP sent to your email</p>
        <p class="title" v-else-if="passwordTitle">{{passwordTitle}}</p>
        <p class="title" v-else>{{showSetPassword ? "Reset Password" : "CSMS LOGIN"}}</p>
        <p class="sub-title" v-if="passwordSubTitle">{{passwordSubTitle}}</p>
      </div>
      <div v-if="showResetSuccess">
        <div style="height: 200px;"></div>
        <el-button
          :loading="loading"
          type="primary"
          class="login-button"
          @click="handleShowLogin">
          GO TO LOGIN
        </el-button>
      </div>
      <OtpView
        v-else-if="showOTP"
        :loginInfo="loginForm"
        :resetInfo="newPasswordInfo"
        :isReset="showSetPassword"
        @onLogin="handleLogin"
        @onReset="handleResetSuccess"/>
      <el-form
        v-else-if="!showSetPassword"
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        autocomplete="on"
        label-position="left">
        <el-form-item prop="email">
          <div class="form-login-input">
            <span class="svg-container">
              <svg-icon icon-class="email" />
            </span>
            <el-input
              ref="username"
              v-model="loginForm.email"
              name="email"
              type="text"
              tabindex="1"
              autocomplete="on"
              clearable
              maxlength="50"
              @focus="() => focusFiled.email = true"
              @blur="() => focusFiled.email = false"/>
            <label :class='isNameValid ? "focus" : ""'>Email</label>
          </div>
        </el-form-item>
        <el-form-item prop="password">
          <div class="form-login-input">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              name="password"
              tabindex="2"
              autocomplete="off"
              clearable
              maxlength="32"
              @keyup.enter.native="onPreLogin"
              @focus="() => focusFiled.password = true"
              @blur="() => focusFiled.password = false"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
            <label :class='isPsdValid ? "focus" : ""'>Password</label>
          </div>
        </el-form-item>
        
        <div>
          <el-button
            :loading="loading"
            type="primary"
            class="login-button"
            @click.native.prevent="onPreLogin">
            LOGIN
          </el-button>
          <el-button
            type="content"
            class="forgot-button"
            @click="handleForgotPassword">
            FORGET PASSWORD
          </el-button>
        </div>
      </el-form>
      <Password
        v-else
        :email="expireEmail"
        @back="handleShowLogin"
        @confirm="onResetPasswordConfirm"/>
    </div>
    <div class="copyinfo">©{{copyYear}}&nbsp; {{company}}</div>
  </div>
</template>

<script>
import VueRouter from 'vue-router'
import { Message } from 'element-ui'
import settings from '../../settings.js'
import {getEmail} from '../../utils/auth.js'
import particles from 'particles.js'
import animateJson from './animate.json'
import Password from './Password.vue'
import OtpView from './otp.vue'
import api from '@/http/api/user'
import {parseTime} from '@/utils/index'
import permission from '@/utils/permission.js'
const { isNavigationFailure, NavigationFailureType } = VueRouter

export default {
  name: 'Login',
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      year: 2023,
      appName: settings.title,
      company: settings.company,
      loginForm: {
        otp: '',
        email: '',
        password: ''
      },
      loginRules: {
        email: [{
          required: true,
          trigger: 'blur',
          message: "Please type email"
        }, {
          pattern: /^[a-zA-Z0-9]+[\S]+@[a-zA-Z0-9_-]+[\.][\Sa-zA-Z]+$/,
          trigger: 'blur',
          message: 'Please type a correct email'
        }],
        password: [{
          required: true,
          trigger: 'blur',
          message: "Please type password"
          //validator: validatePassword
        }]
      },
      passwordType: 'password',
      loading: false,
      redirect: undefined,
      otherQuery: {},
      focusFiled: {
        email: false,
        password: false
      },
      showOTP: false,
      expireEmail: "",
      showSetPassword: false,
      showResetSuccess: false,
      passwordTitle: "",
      passwordSubTitle: "",
      newPasswordInfo: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  computed: {
    copyYear() {
      const year = new Date().getFullYear();
      if (year > this.year) {
        return this.year + "-" + year;
      } else {
        return this.year;
      }
    },
    isNameValid() {
      return (this.loginForm.email !== "" || this.focusFiled.email)
    },
    isPsdValid() {
      return (this.loginForm.password !== "" || this.focusFiled.password)
    }
  },
  components: {Password, OtpView},
  created() {
    // window.addEventListener('storage', this.afterQRScan)
    const user = getEmail()
    if (user) {
      this.loginForm.email = user;
    }
    //console.log(animateJson);
    //
  },
  beforeMount() {
    this.$nextTick(() => {
      //const sss = document.getElementById("particles-js");
      particlesJS('particles-js', animateJson);
    })
  },
  mounted() {
    if (this.loginForm.email === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = 'text'
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleShowLogin() {
      this.showOTP = false;
      this.showSetPassword = false;
      this.showResetSuccess = false;
      this.expireEmail = "";
      this.passwordTitle = "";
      this.passwordSubTitle = "";
      this.newPasswordInfo = {};
    },
    handleResetSuccess() {
      this.handleShowLogin();
      this.showResetSuccess = true;
      this.passwordTitle = "Successful. Your password has been changed.";
      this.passwordSubTitle = parseTime(new Date(), "{d}/{m}/{y}");
    },
    handleForgotPassword() {
      this.handleShowLogin();
      this.showSetPassword = true;
    },
    handleResetPassword(isFirst) {
      this.handleShowLogin();
      this.passwordTitle = isFirst ? "Please set your password." : "Password Expired.";
      this.passwordSubTitle = isFirst ? "" : "Please create new password";
      this.expireEmail = this.loginForm.email;
      this.showSetPassword = true;
    },
    onResetPasswordConfirm(info) {
      //reset 忘记密码
      //create 首次登录、密码过期
      this.loginForm.password = "";
      this.newPasswordInfo = info;
      this.showOTP = true;
    },
    onPreLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          api.preLogin(this.loginForm).then(res => {
            if (res.code) {
              switch(res.code) {
                case 2016: //未启用二次登录验证
                  this.handleLogin("");
                  break;
                case 2017: //首次登录流程
                  this.handleResetPassword(true);
                  break;
                case 2018: //密码过期流程
                  this.handleResetPassword(false);
                  break;
                case 2019: //OTP 登录流程
                  this.showOTP = true;
                  break;
                default:
                  this.handleLogin("");
                  break;
              }
            }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: err
            })
          }).finally(() => {
            this.loading = false;
          })
        } else {
          console.log('error submit!!')
        }
      })
    },
    handleLogin(otp) {
      if (otp) {
        this.loginForm.otp = otp;
      }
      this.$store.dispatch('user/login', this.loginForm).then((response) => {
        let path = this.redirect || '/'
        if (response.data.roleName === "MCST") {
          path = '/site-management'
        } else if (response.data.resources.length > 0) {
          this.$store.commit('permission/SET_ROUTES', response.data.resources);
          let validPath = false;
          for (let _route of response.data.resources) {
            if (path.indexOf(_route[permission.RESOURCE_KEY]) >= 0) {
              validPath = true;
              break
            }
          }
          if (!validPath) {
            path =  response.data.resources[0][permission.RESOURCE_KEY];
          }
        }
        this.$router.push({
          path: path,
          query: this.otherQuery,
        }).catch((failure) => {
          if (!isNavigationFailure(failure, NavigationFailureType.redirected)) {
            throw failure
          }
        })
        this.loading = false
      }).catch((error) => {
        Message.error(error.message)
        this.loading = false
        this.handleShowLogin();
      });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss" scoped>
/* reset element-ui css */
.login-container {
  width: 100%;
  display: flex;
  overflow: hidden;
  min-height: 100%;
  user-select: none;
  align-items: center;
  justify-content: center;
  background: linear-gradient(0deg, #333333 0%, #A1A1A1 100%);
  
  .login-form {
    width: 100%;
    z-index: 2;
    margin: 0 auto;
    max-width: 450px;
    overflow: hidden;
    background: #fff;
    position: relative;
    border-radius: 3px;
    padding: 30px 40px 50px;
    transition: all .3s;
    box-shadow: 1px 1px 5px 3px rgba(0,0,0,.2);
  }
  .title-container {
    text-align: center;
    position: relative;
    padding: 20px 0 0;
  
    .title {
      font-size: 16px;
      color: #333;
      margin: 20px 0;
      text-align: center;
      font-weight: bold;
    }
    .sub-title {
      font-size: 16px;
      color: #333;
      margin-top: -10px;
      padding-bottom: 5px;
      text-align: center;
    }
    .csms-logo {
      max-width: 200px;
      height: 70px;
      object-fit: contain;
    }
  }
  
  .form-login-input {
    width: 100%;
    display: flex;
    padding: 0 10px;
    margin-top: 20px;
    position: relative;
    align-items: center;
    border-bottom: 1px solid #999;
    label {
      top: 0;
      left: 0;
      color: #aaa;
      font-size: 14px;
      position:absolute;
      padding-top: 7px;
      padding-left: 45px;
      font-weight: normal;
      pointer-events: none;
      transition: all 0.3s;
    }
    label.focus {
    	top: -30px;
    	color: #333;
    	font-size: 15px;
      font-weight: bold;
      padding-left: 5px;
    }
    .svg-container {
      width: 30px;
      color: #333;
      font-size: 16px;
      padding: 6px 6px 6px 5px;
    }
    .el-input {
      flex: 1;
      height: 42px;
    
      &::v-deep input {
        color: #333;
        height: 42px;
        border: none;
        font-size: 14px;
        padding: 0 5px;
        border-radius: 0px;
        -webkit-appearance: none;
        background: transparent;
      }
    }
  }
  
  .show-pwd {
    color: #666;
    cursor: pointer;
    font-size: 16px;
    user-select: none;
  }
  
  .login-button {
    width:100%;
    color: #fff;
    padding: 15px;
    margin-top: 40px;
    margin-bottom: 20px;
    font-weight: bold;
  }
  
  .forgot-button {
    width:100%;
    padding: 15px;
    margin: 0 0 20px;
    font-weight: bold;
  }
  
  .copyinfo {
    left: 0;
    right: 0;
    bottom: 10px;
    color: #e0e0e0;
    font-size: 12px;
    user-select: none;
    text-align: center;
    position: absolute;
    transform: scale(.8);
  }
  
  .bg-logo {
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    opacity: .3;
    position: fixed;
    filter: blur(30px);
    pointer-events: none;
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
    background-image: url(../../assets/logo.png);
  }
  .bg-logo.anim {
    animation: moveBg 10s infinite;
    background-origin: content-box;
  }
}
@keyframes moveBg {
  0% {
    padding: 0;
    filter: blur(30px);
  }
  50% {
    padding: 0 200px;
    filter: blur(20px);
  }
  100% {
    padding: 0;
    filter: blur(30px);
  }
}
</style>
<style>
  .particles-js-canvas-el {
    z-index: 1;
    position: fixed;
  }
</style>