<!-- eslint-disable no-undef -->
<template>
  <!--登录块-->
  <div class="login-container">
    <!--表单区域-->
    <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="$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="svg-container">
            <svg-icon icon-class="password" />
          </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"
          />
          <!-- 显示密码 -->
          <span class="show-pwd" @click="showPwd">
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>
      </el-tooltip>

      <!-- <el-form-item prop="code">
        <el-input
          v-model="loginForm.code"
          class="code"
          prefix-icon="el-icon-info"
          placeholder=""
          style="margin-left:5px;fill: currentColor"
        />
        <img
          id="code"
          style="float: right;margin-top: 4px; margin-left: ;cursor: pointer"
          title="看不清,点击刷新"
          alt="验证码"
          @click="changeCode"
        >
      </el-form-item> -->

      <!-- 验证码 -->
      <el-form-item>
        <el-row :gutter="24">
          <el-col :span="16" :offset="0">
            <el-input
              v-model="loginForm.code"
              placeholder="请输入验证码"
            />
            <!-- 引入图标 -->
            <!-- <el-input
              v-model="loginForm.code"
              prefix-icon="el-icon-info"
              style="margin-left: 5px; fill: currentColor"
            /> -->
          </el-col>

          <el-col :span="8" :offset="0">
            <vue-image @getIdentifyCode="getIdentifyCodes" />
          </el-col>
        </el-row>
      </el-form-item>

      <!-- 记住密码 -->
      <el-checkbox
        v-model="loginForm.rememberMe"
        style="margin-left: 8px"
      >记住密码</el-checkbox>

      <!-- 按钮 -->
      <el-button
        :loading="loading"
        type="info"
        icon="el-icon el-icon-delete"
        style="width: 30%; margin-bottom: 20px; margin-left: 20px"
        @click="resetLoginForm()"
      >
        重置
        <!-- {{ $t("login.logIn") }} -->
      </el-button>
      <el-button
        :loading="loading"
        type="info"
        icon="el-icon el-icon-circle-plus"
        style="width: 35%; margin-bottom: 20px; margin-left: 20px"
        @click="registerForm()"
      >
        注册
        <!-- {{ $t("login.logIn") }} -->
      </el-button>
      <el-button
        :loading="loading"
        icon="el-icon el-icon-s-promotion"
        type="primary"
        style="width: 100%; margin-bottom: 30px; margin-left: 0px"
        @click.native.prevent="handleLogin"
      >
        {{ $t("login.logIn") }}
      </el-button>
    </el-form>

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

<script>
// eslint-disable-next-line no-unused-vars
import { validUsername } from '@/utils/validate'
import LangSelect from '@/components/LangSelect'
import SocialSign from './components/SocialSignin'
import VueImage from './components/vueImageVerify.vue'
// import LoginFunc from '@/function-namespace/auth/LoginFunc'

export default {
  name: 'Login',
  // eslint-disable-next-line vue/no-unused-components
  components: { LangSelect, SocialSign, VueImage },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      // 表单数据
      loginForm: {
        username: 'adminult',
        password: '123456'
      },
      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: {}
    }
  },
  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)
    // this.getCode()
    // this.getCookie()
  },
  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: {
    getIdentifyCodes(value) {
      console.log('------', value)
      // 判断验证码输入是否有误 和输入的文本框
      // if (this.verify.toLowerCase() != value.toLowerCase()) {
      // Toast.fail('验证码有误')
      // return
      // }
      this.valiatecode = value.toLowerCase()
    },

    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()
      })
    },
    registerForm() {
      this.$router.push({ path: '/Register' })
    },
    handleLogin() {
      // 验证码判断
      // eslint-disable-next-line eqeqeq
      if (this.valiatecode.toLowerCase() != this.loginForm.code.toLowerCase()) {
        console.log(this.valiatecode, this.loginForm.code)
        this.$notify({
          title: 'warning',
          message: '验证码错误',
          type: 'warning',
          duration: 2000
        })
        return
      }
      // 登陆判断
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$notify({
            title: 'Success',
            message: '登录成功',
            type: 'success',
            duration: 2000
          })

          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    handleLogin_second() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    resetLoginForm() {
      // vue中刷新页面
      this.$router.go(0)
      // windows强制刷新：window.location.reload()
    },
    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;
$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: 47px;
      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(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

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

.el-button--info {
  background: #1890ff;
}

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .verifyCodeImg {
    margin-top: 5px;
    margin-left: 10px;
    height: 30px;
    width: "60%";
  }
  .login-form {
    position: relative;
    width: 450px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

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

  .warning{
    border-color: #48D1CC;
    color: #fff;
    background: #48D1CC;
  }
  .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: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }

    .set-language {
      color: #fff;
      position: absolute;
      top: 3px;
      font-size: 18px;
      right: 0px;
      cursor: pointer;
    }
  }

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

  .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;
  }

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

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

