<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">
            IP Speaker
          </h3>
          <!--           <img src="@/assets/login/logo_white.svg" alt="">-->
          <h3 class="title">
            {{ $t('login.title') }}
          </h3>
        </div>

        <el-form-item prop="username" :label="$t('login.username') + ':'" label-width="92px" 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="handleLogin"
          />
        </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="92px" 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="handleLogin"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === '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="handleLogin"
        >
          {{ $t('login.logIn') }}
        </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>

    <el-dialog :visible.sync="dialogVisible" :title="$t('login.changePassword')" width="600px">
      <el-form>
        <div class="tips">{{ $t('table.tips') }}: {{ $t('login.changePasswordTip') }}</div>
        <el-form-item :label="$t('profile.password0')" label-width="120px">
          <el-input v-model.trim="formData.old" type="password" maxlength="16" />
        </el-form-item>
        <el-form-item :label="$t('profile.password1')" label-width="120px">
          <el-input v-model.trim="formData.new" type="password" maxlength="16" />
        </el-form-item>
        <el-form-item :label="$t('profile.password2')" label-width="120px">
          <el-input v-model.trim="formData.new2" type="password" maxlength="16" />
        </el-form-item>
        <div style="display: flex;justify-content: center;">
          <el-button type="primary" style="width: 120px;" @click="submit">
            {{ $t("profile.update") }}
          </el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import LangSelect from '@/components/LangSelect'
import { userInfoChange } from '@/api/index.js'
import { getKeyInfo } from '@/api/user.js'
import { encryptData } from '@/utils/encryption/entrypt'

// import { encryptData } from '@/utils/encryption/entrypt.js'
export default {
  name: 'Login',
  components: {
    LangSelect
  },
  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('Please enter the correct password'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        ip: ''
      },
      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: {},

      dialogVisible: false,
      formData: {
        old: '',
        new: '',
        new2: ''
      }
    }
  },
  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() {
    this.loginForm.ip = window.location.host
    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()
      })
    },
    getKeyInfo() {
      getKeyInfo({}).then(res => {
        const reslut = {
          rsaPublicKey: res.rsaPublicKey || '', // RSA公钥（2048位）
          aesKey: res.aesKey || '' // AES密钥（256位）
        }
        this.$store.commit('user/SET_KEY', reslut)
      }).catch(() => {
        const reslut = {
          rsaPublicKey: '', // RSA公钥（2048位）
          aesKey: '' // AES密钥（256位）
        }
        this.$store.commit('user/SET_KEY', reslut)
      })
    },
    handleLogin() {
      // debugger
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          var param = {
            ...this.loginForm
          }
          debugger
          console.log(param)
          param.password = encryptData(param.password)
          console.log('0-0--0', param)
          // const password = encryptData(this.loginForm.password + this.loginForm.password)
          // this.loginForm.password = password
          this.$store.dispatch('user/login', param)
            .then(() => {
              this.$router.push({
                path: this.redirect || '/',
                query: this.otherQuery
              })
              this.loading = false
            })
            .catch(err => {
              console.log(err)
              this.getKeyInfo()
              this.loading = false
              if (err.code === 600) {
                this.$message({
                  type: 'warning',
                  message: err.message
                })
                this.dialogVisible = true
              }
              if (err.code === 601) {
                this.$confirm(err.message, this.$i18n.t('table.tips'), {
                  confirmButtonText: this.$i18n.t('table.confirm'),
                  cancelButtonText: this.$i18n.t('table.cancel'),
                  center: true
                }).then(() => {

                }).catch(() => {
                })
              }
              if (err.code === 602 || err.code === 603) {
                this.$message({
                  type: 'warning',
                  message: err.message
                })
              }
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 取消登录
    cancelLogin() {

    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    submit() {
      if (!this.formData.old) {
        this.$message({
          message: this.$i18n.t('profile.oldPassword'),
          type: 'warning'
        })
        return
      }
      if (!this.formData.new) {
        this.$message({
          message: this.$i18n.t('profile.newPassword'),
          type: 'warning'
        })
        return
      }
      if (!this.formData.new2) {
        this.$message({
          message: this.$i18n.t('profile.newPassword2'),
          type: 'warning'
        })
        return
      }
      if (this.formData.new !== this.formData.new2) {
        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.formData.new.length < 8) {
        this.$message({
          message: this.$i18n.t('profile.passwordLengthError'),
          type: 'warning'
        })
        return
      }
      if (!reg.test(this.formData.new)) {
        this.$message({
          message: this.$i18n.t('profile.passwordStrongError'),
          type: 'warning'
        })
        return
      }
      var param = {
        old: this.formData.old,
        new: this.formData.new
        // username: this.name
      }
      param.old = encryptData(param.old)
      param.new = encryptData(param.new)
      userInfoChange(param).then(res => {
        if (res.code === 200) {
          this.$message({
            message: this.$i18n.t('profile.updatePasswordSuccess'),
            type: 'success'
          })
          this.dialogVisible = false
        } else {
          console.log('Error')
          this.$message({
            message: res.message,
            type: 'error'
          })
        }
      })
    }
    // 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: 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: 30%;
      left: 0;
    }

    .login-form {
      width: 480px;
      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>
