<template>
  <div class="login-wrap">
    <div class="login-panel">
      <img src="../../assets/png/login-left.png" alt="" class="login-panel-left">
      <div class="login-panel-right login-container2">
        <el-form
          ref="loginForm"
          auto-complete="on"
          :model="loginForm"
          :rules="loginRules"
          label-position="left"
          label-width="0px"
          class="card-box login-form"
        >
          <!--          <div id="wx_reg" />-->
          <!--          <div v-if="showToast" class="wx_reg_failed">-->
          <!--            <div style="margin-top: 140px;color: #0082ef">登录中,请稍后......</div>-->
          <!--          </div>-->

          <img src="../../assets/png/login-title.png" alt="" class="login-form-title">
          <el-form-item class="cus-efi" prop="username">
                      <span class="svg-container" style="color: #666666">
                        <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 class="cus-efi" prop="password">
                        <span class="svg-container" style="color: #666666">
                          <svg-icon icon-class="password"/>
                        </span>
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                style="width: 80% !important;"
                :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>
          <div v-if="showCaptcha" style="height: 50px;">
            <el-form-item class="cus-efi cus-captcha fl" prop="code">
                        <span class="svg-container" style="color: #666666">
                          <i class="el-icon-picture"/>
                        </span>
              <el-input
                ref="code"
                v-model="loginForm.code"
                :placeholder="$t('login.captcha')"
                name="code"
                type="text"
                tabindex="1"
                autocomplete="on"
              />
            </el-form-item>
            <img style="margin-left: 20px;cursor: pointer;" :src="captchaUrl" class="fl" @click="refresh">
          </div>
          <div class="clearfix"/>
          <el-form-item style="margin-bottom: 10px">
            <el-button type="primary" style="width:100%;" class="login-form-btn" size="large" :loading="loading"
                       @click.native.prevent="handleLogin">
              {{ $t('login.logIn') }}
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button style="color: orangered" type="text" @click="toInnerLoginPage">飞书员工账号登录(仅限飞书员工使用)</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>

</template>

<script>
import {delCookie, getCookie, setCookie} from "@/utils/cookie";

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value === undefined || value === null || value.trim() === '') {
        callback(new Error(this.$t('login.usernameValid')))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value === undefined || value === null || value.trim() === '') {
        callback(new Error(this.$t('login.passwordValid')))
      } else {
        callback()
      }
    }
    const validateCaptcha = (rule, value, callback) => {
      if (value === undefined || value === null || value.trim() === '') {
        callback(new Error(this.$t('login.captchaValid')))
      } else {
        callback()
      }
    }
    return {
      showCaptcha: false,
      loginForm: {
        username: '',
        password: '',
        codeKey: this.randomString(32),
        code: null
      },
      loginRules: {
        username: [{required: true, trigger: 'blur', validator: validateUsername}],
        password: [{required: true, trigger: 'blur', validator: validatePassword}],
        code: [{required: true, trigger: 'blur', validator: validateCaptcha}]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      showToast: false,
      showScanError: false
    }
  },
  computed: {
    captchaUrl: function () {
      return `${process.env.VUE_APP_BASE_API}/captcha?key=` + this.loginForm.codeKey
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.initLogin()
      },
      immediate: true
    }
  },
  mounted() {
    this.initLogin()
  },
  destroyed() {
  },
  methods: {
    initLogin() {
      // 获取code
      if (this.$route.query && this.$route.query.code) {
        // 用户登录
        this.showToast = true
        this.$store.dispatch('user/qyWxLogin', {code: this.$route.query.code}).then(() => {
          this.$router.push({path: this.redirect || '/', query: this.otherQuery})
          localStorage.removeItem('qa.sino.integral')
        }).catch((res) => {
          this.showToast = false
          this.$router.push({path: '/login', query: {}})
        })
      }
    },
    getDomain() {
      let domain = ''
      // 获取环境域名
      if (process.env.VUE_APP_ENV === 'production') {
        domain = ''
      } else if (process.env.VUE_APP_ENV === 'testing') {
        domain = 'http://jfadmin.stratageman.com'
      } else {
        domain = 'http://jfadmin.stratageman.com'
      }
      return domain
    },
    // 去空格
    trim(text) {
      const rTrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g
      return text == null ? '' : (text + '').replace(rTrim, '')
    },
    // 是否为空
    isEmpty(text) {
      return this.trim(text) === ''
    },
    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) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm).then(() => {
            this.$router.push({path: this.redirect || '/', query: this.otherQuery})
            this.loading = false
          }).catch((res) => {
            this.loginForm.codeKey = this.randomString(32)
            if (res.errCode === 999) {
              this.showCaptcha = true
            }
            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
      }, {})
    },
    randomString(len) {
      len = len || 32
      const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      const maxPos = $chars.length
      let pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    refresh() {
      this.loginForm.codeKey = this.randomString(32)
    },
    //跳转到内部员工登录页面
    toInnerLoginPage(){
      window.open(process.env.VUE_APP_LOGIN_PAGE, '_self')
      // this.$router.push({path: '/inner-login'})
    },
    //登录成功回调
    loginBack(){
      console.log('loginBack')
      let key = process.env.VUE_APP_TOKEN_KEY
      //内部登录成功,回跳的当前页面,从cookie中获取token,校验是否登录成功
      let token = getCookie(key)
      if (token!=null&&token!==''){
      console.log('token')
        let loginForm = {
          token:token,
          userSource:16
        }
        this.$store.dispatch('user/innerLogin', loginForm).then(() => {
          this.$router.push({path: this.redirect || '/', query: this.otherQuery})
          this.loading = false
        }).catch((res) => {
          this.loginForm.codeKey = this.randomString(32)
          if (res.errCode === 999) {
            this.showCaptcha = true
          }
          this.loading = 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-container2 {
  position: relative;

  .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;
      color: #283443;
      //height: 47px;
      caret-color: #283443;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #FAFAFA inset !important;
        -webkit-text-fill-color: #283443 !important;
      }
    }
  }

  .cus-efi {
    border: 1px solid #F0F0F0;
    background: #FAFAFA;
    border-radius: 5px;
    color: #454545;
  }

  .cus-captcha {
    width: 180px;

    .el-input {
      width: 76%;
    }
  }
}
</style>

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

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

  .login-form {
    position: relative;
    width: 520px;
    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;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: #666666;
    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;
  }

  .show-pwd2 {
    position: absolute;
    font-size: 16px;
    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>
<style lang="scss" scoped>
.wx_reg_failed {
  position: absolute;
  width: 280px;
  height: 280px;
  top: 96px;
  right: 50%;
  transform: translateX(50%);
  background: #fff;
  opacity: 0.95;
  color: red;
}
</style>
<style rel="stylesheet/scss" lang="scss">
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-wrap {
  position: fixed;
  height: 100%;
  width: 100%;
  background: url("../../assets/png/bj.png") no-repeat center/cover;
  display: flex;
  align-items: center;
  justify-content: center;

  .login-panel {
    display: flex;
    justify-content: center;

    .login-panel-left {
      width: 430px;
    }

    .login-panel-right {
      width: 620px;
      min-width: 620px;
      background: #fff;
      display: flex;
      justify-content: center;
      text-align: center;
      flex: 1;
      align-self: stretch;

      .login-form {
        width: 520px;
        margin-top: 75px;

        .login-form-title {
          margin-bottom: 70px;
          //width: 300px;
        }

        .login-form-btn {
          margin-top: 60px;
        }

        .el-form-item {
          margin-bottom: 30px;
        }

        .el-input__inner {
          height: 50px;
          line-height: 50px;
        }
      }
    }

    .el-input__prefix {
      display: flex;
      align-items: center;
    }
  }

  .bottom-tip {
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: #999999;
    letter-spacing: 0;
    text-align: center;
    margin-top: 40px;
  }
}

@media screen and (max-width: 2000px) {
  .login-wrap {
    position: fixed;
    height: 100%;
    width: 100%;
    background: url("../../assets/png/bj.png") no-repeat center/cover;
    display: flex;
    align-items: center;
    justify-content: center;

    .login-panel {
      display: flex;
      justify-content: center;

      .login-panel-left {
        width: 350px;
        height: 472px;
      }

      .login-panel-right {
        width: 420px;
        min-width: 420px;
        background: #fff;
        display: flex;
        justify-content: center;
        text-align: center;
        flex: 1;
        align-self: stretch;

        .login-form {
          width: 300px;
          margin-top: 58px;

          .login-form-title {
            margin-bottom: 44px;
            //width: 200px;
          }

          .login-form-btn {
            margin-top: 30px;
          }

          .el-form-item {
            margin-bottom: 20px;
          }

          .el-input__inner {
            height: 40px;
            line-height: 40px;
          }
        }
      }

      .el-input__prefix {
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>
