<template>
  <div class="login-container">
    <div class="login-form-wrapper">
      <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">
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="用户名"
            name="username"
            type="text"
            tabindex="1"
            autocomplete="on"
          />
        </el-form-item>

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

        <el-button
          class="loginButton"
          :loading="loading"
          type="primary"
          @click.native.prevent="handleLogin"
          >登 录</el-button
        >
      </el-form>
    </div>
  </div>
</template>
<script>
import { login,getUsersByUserName } from "@/api/wms-auth"
export default {
  name: 'Login',
  data () {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能少于6位'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username:"",
        password:"",
        rememberMe:true,
        grant_type: 'password',
        client_id: 'Auth_App',
        // warehouseCode: localStorage.getItem("warehouseCode"),
        // company: localStorage.getItem("company"),
        // username: '',
        // password: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: 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)
    // 禁止缩放
    document.addEventListener('mousewheel', function (e) {
      e = e || window.event;
      if ((e.wheelDelta && event.ctrlKey) || e.detail) {
        event.preventDefault();
      }
    }, {
      capture: false,
      passive: false
    });
  },
  mounted () {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed () {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    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 () {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // todo-new:自动登录跳转处理
          this.$store.dispatch('user/getUserInfo',this.loginForm.username).then(()=>{
            localStorage.setItem('isLoginName',this.loginForm.username)
            this.$router.push({
              path:'/',
              query:{
                isSinglePage:this.$route.query.isSinglePage
              },
              replace: true
            })
          }).catch(()=>{
            this.$message.error('获取用户信息失败，请重试!')
          })
          return
          this.loading = true
          this.loginForm.userNameOrEmailAddress = this.loginForm.username
          // todo-new:与permission文件的登录统一封装
          let _zh = localStorage.getItem('columnsApiNamesZh')
          login(this.loginForm).then(()=>{
          // this.$store.dispatch('user/login', this.loginForm).then(() => {
              // 提前获取接口监控看板表头数据并存储
              // getUsersByUserName(localStorage.getItem("userNameOrEmailAddress")).then(res=>{
              //   // store.dispatch('user/setName',res)
              //   localStorage.setItem("currentUserInfo", JSON.stringify(res));
              // })
              // this.$router.push({ path: '/'})
              // this.loading = false
            })
            .catch((error) => {
              this.$message.error('用户名或密码错误！')
              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 */

$bg: #283443;
$bg_gray: #ececec;
$light_gray: #fff;
$cursor: #fff;
$dark_gray: #889aa4;


/* reset element-ui css */
.login-container {
  .el-select {
    display: inline-block;
    height: 47px;
    width: calc(100% - 30px);
    .el-input {
      width: 100%;
    }
  }
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

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

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

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background-color: $bg_gray;
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  background: url('../../../public/img_login_bg.jpg') no-repeat;
  background-size: cover;
  background-position: center;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  
  .login-form-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
  }
  .login-form {
    position: fixed;
    left: calc(50% + 100px);
    background: #fff;
    width: 520px;
    max-width: 100%;
    padding: 60px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

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

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

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 30px;
      letter-spacing:19px;
      // color: $light_gray;
      color: $bg;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .loginButton{
    width: 100%; 
    margin-top: 100px;
    height:50px;
    font-size:18px
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
