<template>
  <div class="login-container">
    <!-- <video class="bg-video" autoplay loop muted>
      <source src="@public/static/video/bg.mp4" />
    </video>-->
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">登录</h3>
      </div>

      <el-form-item prop="username">
        <div class="form-item__wrap">
          <span class="svg-container">
            <!-- <svg-icon icon-class="user" /> -->
            <i class="ri-user-line"></i>
          </span>
          <el-input
            ref="username"
            class="username"
            v-model="loginForm.username"
            placeholder="请输入用户名"
            name="username"
            type="text"
            tabindex="1"
            autocomplete="on"
          />
        </div>
      </el-form-item>

      <el-tooltip
        v-model="capsTooltip"
        content="Caps lock is On"
        placement="right"
        manual
      >
        <el-form-item prop="password">
          <div class="form-item__wrap">
            <span class="svg-container">
              <!-- <svg-icon icon-class="password" /> -->
              <i class="ri-lock-line"></i>
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              class="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="请输入用户密码"
              name="password"
              tabindex="2"
              autocomplete="on"
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleLogin"
            />
          </div>
          <span class="show-pwd" @click="showPwd">
            <i
              :class="
                passwordType === 'password' ? 'ri-eye-line' : 'ri-eye-off-line'
              "
            ></i>
          </span>
        </el-form-item>
      </el-tooltip>

      <el-button
        class="login-btn"
        :loading="loading"
        type="primary"
        round
        @click.native.prevent="handleLogin"
        >登 录</el-button
      >
    </el-form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { setToken } from '@/utils/auth'

export default {
  name: 'Login',
  // components: { SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      // if (!validUsername(value)) {
      //   callback(new Error("请输入正确的用户名"));
      // } else {
      //   callback();
      // }
      callback()
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不少于6位字符'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
      },
      loginRules: {
        username: [
          { required: true, trigger: 'blur', validator: validateUsername },
        ],
        password: [
          // { required: true, trigger: 'blur', validator: validatePassword }
          { required: true, trigger: 'blur', message: '请输入密码' },
        ],
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true,
    },
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
    let that = this
    window.addEventListener(
      'message',
      function (event) {
        if (event.origin === window.config.messageSource) {
          setToken(event.data)
          // console.log('收到消息', event.data)
          that.$router.push({
            path: '/',
          })
        }
      },
      false
    )
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    ...mapMutations('user', ['SET_TOKEN']),
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z'
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      console.log(1)
      this.$refs.loginForm.validate((valid) => {
        console.log(2)
        if (valid) {
          this.loading = true
          console.log(3)
          this.$store
            .dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({
                path: this.redirect || '/',
                query: this.otherQuery,
              })
              window.localStorage.setItem('menusChose', '1')
              console.log(this.$router, 'this.$router')
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  },
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
@import '~@/styles/variables.scss';

$bg: #000b0d;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    // height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 48px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba($--color-primary, 0.2);
    background: $bg;
    border-radius: 24px;
    color: #454545;

    .el-form-item__content {
      line-height: 34px;
    }
  }

  .login-btn {
    width: 100%;
    border-radius: 24px;

    span {
      font-size: 20px;
      font-weight: bold;
    }
  }
}
</style>

<style lang="scss" scoped>
@import '~@/styles/variables.scss';

$bg: #000b0d;
$dark_gray: #889aa4;
$light_gray: #eee;

@keyframes dynamic {
  from {
    background-position: 0 0;
  }
  to {
    background-position: 200% 0;
  }
}

.login-container {
  min-height: 100%;
  width: 100%;
  // background-color: var(--body-background-color);
  // background-image: linear-gradient(
  //   to right,
  //   #1cb5e0 1%,
  //   #2e66ce 50%,
  //   #1cb5e0 99%
  // );
  background: url('~@/assets/img/login/bg.gif') no-repeat center center / cover;
  // background-color: #000;
  // animation: dynamic 20s linear infinite;
  overflow: hidden;

  .bg-video {
    position: absolute;
    left: -15vw;
    // top: 20vh;
    // left: 5vw;
    height: 100%;
  }

  .login-form {
    position: absolute;
    top: 30vh;
    right: 15vw;
    width: 500px;
    padding: 30px 80px 60px;
    box-sizing: border-box;
    background: url('~@/assets/img/login/form-bg.png') no-repeat center center /
      100% 100%;
    border-radius: 4px;

    .form-item__wrap {
      display: flex;
      align-items: center;
      box-sizing: border-box;
      padding: 0 10px 0 0;
    }
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    font-size: 20px;
    padding: 6px 5px 6px 20px;
    vertical-align: middle;
    // width: 30px;
    display: inline-block;
    i {
      color: var(--side-bar-text-color);
    }
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 30px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 20px;
    top: 7px;
    font-size: 16px;
    cursor: pointer;
    user-select: none;

    i {
      color: rgba($--color-primary, 0.5) !important;
    }
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
