<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm"  class="login-form" autocomplete="on" label-position="left">

      <div class="title-container">
        <img class="title" src="../../assets/images/login_title.png" alt="">
        <!-- <h3 class="title">
          {{ $t('login.title') }}
        </h3>
        <lang-select class="set-language" /> -->
      </div>

      <el-form-item prop="username">
        <span class="login_span">
          用户名
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          :placeholder="$t('login.username')"
          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="login_span">
            密码
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            :placeholder="$t('login.password')"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
        </el-form-item>
        <div class="chepwd">
          <el-checkbox v-model="checked"></el-checkbox>
          <span class="text">记住当前密码</span>
        </div>

      <el-button :loading="loading" type="primary" style="width:100%;height: 44px;font-size: 16px;
font-family: PingFang SC;
font-weight: bold;
color: #FFFFFF;
border:none;
margin-top:40px;
background: linear-gradient(90deg, #4472C4 0%, #3366C1 100%);
border-radius: 4px;" @click.native.prevent="handleLogin">
        {{ $t('login.logIn') }}
      </el-button>

      <!-- <div style="position:relative">
        <div class="tips">
          <span>{{ $t('login.username') }} : admin</span>
          <span>{{ $t('login.password') }} : {{ $t('login.any') }}</span>
        </div>
        <div class="tips">
          <span style="margin-right:18px;">
            {{ $t('login.username') }} : editor
          </span>
          <span>{{ $t('login.password') }} : {{ $t('login.any') }}</span>
        </div>

        <el-button class="thirdparty-button" type="primary" @click="showDialog=true">
          {{ $t('login.thirdparty') }}
        </el-button>
      </div> -->
    </el-form>

    <!-- <el-dialog :title="$t('login.thirdparty')" :visible.sync="showDialog">
      {{ $t('login.thirdpartyTips') }}
      <br>
      <br>
      <br>
      <social-sign />
    </el-dialog> -->
  </div>
</template>

<script>
// import { validUsername } from '@/utils/validate'
import Vue from 'vue'
import LangSelect from '@/components/LangSelect'
import SocialSign from './components/SocialSignin'
import md5 from 'js-md5';
export default {
  name: 'Login',
  components: { LangSelect, SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: ''
      },
      // loginRules: {
      //   username: [{ required: true, trigger: 'blur', validator: validateUsername }],
      //   password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      // },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      checked: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // typeof localStorage.getItem("isRemember") 为string
    if (localStorage.getItem("isRemember") == 'true'
    && localStorage.getItem("username")
    && localStorage.getItem("password")) {
      this.checked = true
      this.loginForm.username = localStorage.getItem("username")
      this.loginForm.password = localStorage.getItem("password")
    }
    // enter 按键登录
    let _that = this
    document.onkeydown = function() {
      let key = window.event.keyCode
      if (key == 13 || key == 100) {
        _that.handleLogin()
      }
    }
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // 离开登录页面消除按键监听 避免影响其他页面
    document.onkeydown = ''
  },
  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() {
      if(!this.loginForm.username){
        this.$message.error('请输入用户名')
        return false
      }
      if(!this.loginForm.password){
        this.$message.error('请输入密码')
        return false
      }
      this.loading = true
      let login = {
        username:this.loginForm.username,
        password:md5(this.loginForm.password)
      }

      this.$store.dispatch('user/login', login).then(() => {
        console.log('22222222222222222');
        window.localStorage.setItem("isRemember", this.checked)
        window.localStorage.setItem("username", this.loginForm.username)
        window.localStorage.setItem("password", this.loginForm.password)
        this.$store.dispatch('user/getMenus').then((mns) => { // 获取路由
          // const { id, account, employeeNumber, name, orgName } = res.data
          // localStorage.setItem('userInfo', JSON.stringify(data))
          const USER_INFO = JSON.parse(window.localStorage.getItem('USER_INFO'))
          this.loading = false
          let {
            modifyPassword, // 1提示修改密码 0 不提示修改
            remainLoginTimes, // 剩余登陆次数
            status, // ("状态(1：启用  2：冻结  0：删除)")
            firstLogin // ("是否首次登陆1是0否，修改密码成功后修改状态为0(重置密码也要修改为1)")
          } = USER_INFO.value
          // console.log('status,firstLogin,modifyPassword,remainLoginTimes',status,firstLogin,modifyPassword,remainLoginTimes);
          /**
           * 1、判断用户状态
           * 启用：
           *   判断用户是否第一次登录
           *   是：弹出修改密码弹窗，并且在密码未修改过程中，不允许执行系统操作
           *   否：判断是否修改密码
           *      是：提示密码修改并展示剩余登录次数
           */
          // let status = 1
          // let firstLogin = 0
          // let modifyPassword = 1
          // let remainLoginTimes = 3
          if (status === 1) { // 1：启用
            if (firstLogin === 1) { // ("是否首次登陆1是0否，修改密码成功后修改状态为0(重置密码也要修改为1)")
              this.$router.push({ path:'/pwdmodify'})
            } else {
              if (modifyPassword === 1) { // 1提示修改密码 0 不提示修改
                const mesStr = remainLoginTimes === 0 ? '请修改密码，已是最后一次登录' : `密码已过期, 是否修改密码? 剩余登录次数：${remainLoginTimes}次`
                this.$confirm(mesStr, '提示', {
                  confirmButtonText: '是',
                  cancelButtonText: '否',
                  type: 'info'
                }).then(() => {
                  this.$router.push({ path:'/usercenter'})
                }).catch(() => {
                  this.$router.push({ path:'/'})
                });
              } else {
                this.$router.push({ path:'/'})
              }
            }
          }
        }).catch(() => { this.loading = false })
      }).catch(() => { this.loading = false })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
  }
}
</script>



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

.login-container {
  min-height: 100%;
  width: 100%;
  background:url('../../assets/images/login.png') no-repeat;
  background-size: 100% 100%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;

  .login-form {
    position: relative;
    width: 380px;
    height: 466px;
    background: #FFFFFF;
    box-shadow: 0px 7px 8px 0px rgba(0, 0, 0, 0.04);
    border-radius: 0px 4px 4px 0px;
    max-width: 100%;
    padding: 40px;
    margin: 0 auto;
    overflow: hidden;
  }
  .login_span{
    width: 100%;
    height: 13px;
    font-size: 13px;
    font-family: "SourceHanSansCN";
    font-weight: 500;
    color: #707070;
    line-height: 16px;
    display: inline-block;
  }
  .el-form-item{
    margin-bottom: 14px !important;
  }
  .el-input {
    border: 1px solid #E5E5E5 !important;
    border-radius: 4px !important;
    .el-input__inner{
      width: 294px !important;
      height: 34px !important;
    }
  }

  .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;
    display: flex;
    justify-content: center;
    margin-bottom: 38px;
    .title {
      width: 193px;
      height: 98px;
    }

    .set-language {
      color: #fff;
      position: absolute;
      top: 3px;
      font-size: 18px;
      right: 0px;
      cursor: pointer;
    }
  }
  .chepwd{
    display: flex;
    .text{
      font-size: 13px;
      font-family: "SourceHanSansCN";
      font-weight: 500;
      color: #707070;
      margin-left: 6px;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

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

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