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

        <div class="title-container">
          <h3 class="title">
            {{ $t('login.register') }}
          </h3>
        </div>

        <el-form-item prop="username" :label="$t('login.username') + ':'" label-width="152px" label-position="right">
          <el-input
            ref="username"
            v-model="loginForm.username"
            :placeholder="$t('login.username')"
            name="username"
            type="text"
            tabindex="1"
            autocomplete="on"
            @keyup.enter.native="registerSubmit"
          />
        </el-form-item>

        <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
          <el-form-item prop="password" :label="$t('login.password') + ':'" label-width="152px" label-position="right">
            <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="registerSubmit"
            />
            <span class="show-pwd" @click="showPwd(1)">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
        </el-tooltip>

        <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
          <el-form-item prop="password" :label="$t('profile.confirmPassword') + ':'" label-width="152px" label-position="right">
            <el-input
              :key="passwordType2"
              ref="password2"
              v-model="loginForm.password2"
              :type="passwordType2"
              :placeholder="$t('login.password')"
              name="password2"
              tabindex="2"
              autocomplete="on"
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="registerSubmit"
            />
            <span class="show-pwd" @click="showPwd(2)">
              <svg-icon :icon-class="passwordType2 === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
        </el-tooltip>

        <el-button
          :loading="loading"
          type="primary"
          style="width:20%;margin-bottom:30px;margin-left: calc(25% + 78px);"
          @click.native.prevent="registerSubmit"
        >
          {{ $t('login.register') }}
        </el-button>
        <el-button type="default" style="width:20%;margin-bottom:30px;" @click.native.prevent="cancelLogin">
          {{ $t('login.logCancel') }}
        </el-button>
        <lang-select class="set-language" />
      </el-form>
    </div>
  </div>
</template>

<script>
import { addInfo, queryInfo } from '@/api/user.js'
import LangSelect from '@/components/LangSelect'

export default {
  name: 'Register',
  components: {
    LangSelect
  },
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        password2: ''
      },
      loginRules: {
        username: [{
          required: true,
          trigger: 'blur'
        }],
        password: [{
          required: true,
          trigger: 'blur'
        }]
      },
      passwordType: 'password',
      passwordType2: '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
    }
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    } else if (this.loginForm.password2 === '') {
      this.$refs.password2.focus()
    }
  },
  methods: {
    checkCapslock(e) {
      const {
        key
      } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd(type) {
      if (type === 1) {
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
      }
      if (type === 2) {
        if (this.passwordType2 === 'password') {
          this.passwordType2 = ''
        } else {
          this.passwordType2 = 'password'
        }
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
        this.$refs.password2.focus()
      })
    },
    // 取消
    cancelLogin() {
      this.$router.push('/login')
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    registerSubmit() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          if (!this.loginForm.username) {
            this.$message({
              message: this.$i18n.t('profile.inputusername'),
              type: 'warning'
            })
            return
          }
          if (!this.loginForm.password) {
            this.$message({
              message: this.$i18n.t('profile.inputpassword'),
              type: 'warning'
            })
            return
          }
          if (!this.loginForm.password2) {
            this.$message({
              message: this.$i18n.t('profile.inputpassword2'),
              type: 'warning'
            })
            return
          }
          if (this.loginForm.password !== this.loginForm.password2) {
            this.$message({
              message: this.$i18n.t('profile.passwordDifferent'),
              type: 'warning'
            })
            return
          }
          // 大写小写数字特殊符号四选三
          const reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,16}$/
          // 大写小写数字特殊符号四种都有
          // const reg = /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,16}$/
          if (this.loginForm.password.length < 8) {
            this.$message({
              message: this.$i18n.t('profile.passwordLengthError'),
              type: 'warning'
            })
            return
          }
          if (!reg.test(this.loginForm.password)) {
            this.$message({
              message: this.$i18n.t('profile.passwordStrongError'),
              type: 'warning'
            })
            return
          }
          const param = {
            ...this.loginForm
          }
          addInfo(param).then(res => {
            if (res.code === 200) {
              queryInfo({}).then(mes => {
                this.$store.commit('user/SET_INITSTATE', mes.userHasBeenInit || true)
              }).catch(() => {
                this.$store.commit('user/SET_INITSTATE', true)
              })
              this.$nextTick(() => {
                this.$confirm(this.$i18n.t('profile.registerSuccess') + this.$i18n.t('profile.gologin'), this.$i18n.t('table.tips'), {
                  confirmButtonText: this.$i18n.t('table.submit'),
                  cancelButtonText: this.$i18n.t('table.cancel'),
                  center: true
                }).then(() => {
                  this.$router.push('/login')
                }).catch(() => {
                  this.loginForm.username = ''
                  this.loginForm.password = ''
                  this.loginForm.password2 = ''
                })
              })
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              })
            }
          }).catch(() => {
            this.$confirm(this.$i18n.t('profile.registerSuccess') + this.$i18n.t('profile.gologin'), this.$i18n.t('table.tips'), {
              confirmButtonText: this.$i18n.t('table.submit'),
              cancelButtonText: this.$i18n.t('table.cancel'),
              center: true
            }).then(() => {
              this.$router.push('/login')
            }).catch(() => {
              this.loginForm.username = ''
              this.loginForm.password = ''
              this.loginForm.password2 = ''
            })
          })
        } else {
          return false
        }
      })
    }
  }
}
</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: 44px;
      width: 80%;

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

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

    .el-form-item {
      padding-left: 15%;
      margin-bottom: 20px;

      .el-input {
        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:#373737;
  $dark_gray:#889aa4;
  $light_gray:#eee;

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

    .middlebgcard {
      width: 100%;
      height: 20%;
      background: linear-gradient(180deg, #828182 0%, #484848 100%);
      position: absolute;
      top: 40%;
      left: 0;
    }

    .formbox {
      width: 100%;
      height: 40%;
      position: absolute;
      top: 20%;
      left: 0;
    }

    .login-form {
      width: 640px;
      max-width: 100%;
      padding-bottom: 12px;
      margin: 0 auto;
      background: linear-gradient(180deg, #EBEBEB 0%, #AAAAAA 100%);
      border-radius: 8px;
      position: relative;
      overflow: hidden;

      .set-language {
        color: #fff;
        position: absolute;
        bottom: 12px;
        font-size: 18px;
        right: 16px;
        cursor: pointer;
      }
    }

    .title-container {
      width: 96%;
      height: 64px;
      line-height: 64px;
      padding: 0 24px;
      margin: 0 auto;
      margin-top: 20px;
      margin-bottom: 32px;
      background: #727272;
      display: flex;
      align-items: center;
      justify-content: space-between;

      img {
        width: 128px;
      }

      .title {
        font-size: 18px;
        color: $light_gray;
        text-align: center;
        font-weight: bold;
      }
    }

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

  .tips{
      font-size: 14px;
      margin-bottom: 16px;
      color: #FF1D1C;
      text-align: center;
  }
</style>
