<template>
  <div class="login">
    <div class="login-total-title">安全生产管理平台</div>
    <div class="login-form-login">
      <!-- 左上角用户登录 -->
      <div class="login-left-top-title">用户登录</div>
      <!-- 请输入用户名 -->
      <div class="login-user-wrapper">
        <div class="login-user-icon" />
        <div ref="userRef" class="login-user-input" contenteditable="true" spellcheck="false" @keydown.stop="keydownUserName" @input="inputUserName" @blur="checkNoUserName" />
      </div>
      <div v-show="noUserName" class="noUser inputError">用户名不能为空</div>
      <!-- 请输入密码 -->
      <div class="login-password-wrapper">
        <div class="login-password-icon" />
        <input ref="inputPass" placeholder="请输入密码" class="login-password-input" type="password" @input="inputPassWord" @keydown="keydownPassWord" @blur="checkNoPassWord">
      </div>
      <div v-show="noPassWord" class="noPass inputError">密码能为空</div>
      <!-- 请输入验证码 -->
      <div class="login-verification-code-wrapper">
        <div class="login-vertification-code-icon" />
        <div ref="inputCode" class="login-vertification-code-input" contenteditable="true" spellcheck="false" @keydown.stop="keydownCode" @input="inputCode" @blur="checkNoCode" />
      </div>
      <div class="login-vertification-img-wrapper">
        <img style="width: 100%; height: 100%;" :src="codeUrl" alt="error" @click="getCode">
      </div>
      <div v-show="noCode" class="noCode inputError">验证码不能为空</div>
      <!-- 登录 -->
      <button class="login-login-btn" @click="logintoyulu">登录</button>
    </div>
  </div>
</template>

<script>
import { encrypt } from '@/utils/rsaEncrypt'
import Config from '@/settings'
import { getCodeImg } from '@/api/login'
import Cookies from 'js-cookie'
import qs from 'qs'
// import Background from '@/assets/images/background.jpg'
import Background from '@/assets/images/bg.png'
export default {
  name: 'Login',
  data() {
    return {
      Background: Background,
      noUserName: false,
      noPassWord: false,
      noCode: false,
      codeUrl: '',
      cookiePass: '',
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '用户名不能为空' }],
        password: [{ required: true, trigger: 'blur', message: '密码不能为空' }],
        code: [{ required: true, trigger: 'change', message: '验证码不能为空' }]
      },
      loading: false,
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const data = route.query
        if (data && data.redirect) {
          this.redirect = data.redirect
          delete data.redirect
          if (JSON.stringify(data) !== '{}') {
            this.redirect = this.redirect + '&' + qs.stringify(data, { indices: false })
          }
        }
      },
      immediate: true
    },
    'loginForm.password': {
      handler: function(hehe) {
        console.log(hehe, 'fhhfhfhfhfhhf')
      }
    }
  },
  created() {
    // 获取验证码
    this.getCode()
    // 获取用户名密码等Cookie
    this.getCookie()
    // token 过期提示
    this.point()
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = res.img
        this.loginForm.uuid = res.uuid
      })
    },
    getCookie() {
      const username = Cookies.get('username')
      let password = Cookies.get('password')
      const rememberMe = Cookies.get('rememberMe')
      // 保存cookie里面的加密后的密码
      this.cookiePass = password === undefined ? '' : password
      password = password === undefined ? this.loginForm.password : password
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password,
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
        code: ''
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        const user = {
          username: this.loginForm.username,
          password: this.loginForm.password,
          rememberMe: this.loginForm.rememberMe,
          code: this.loginForm.code,
          uuid: this.loginForm.uuid
        }
        if (user.password !== this.cookiePass) {
          user.password = encrypt(user.password)
        }
        if (valid) {
          this.loading = true
          if (user.rememberMe) {
            Cookies.set('username', user.username, { expires: Config.passCookieExpires })
            Cookies.set('password', user.password, { expires: Config.passCookieExpires })
            Cookies.set('rememberMe', user.rememberMe, { expires: Config.passCookieExpires })
          } else {
            Cookies.remove('username')
            Cookies.remove('password')
            Cookies.remove('rememberMe')
          }
          this.$store.dispatch('Login', user).then(() => {
            this.loading = false
            // this.$router.push({ path: this.redirect || '/home' })
            this.$router.push({ path: '/home/index' })
          }).catch(() => {
            this.loading = false
            this.getCode()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    point() {
      const point = Cookies.get('point') !== undefined
      if (point) {
        this.$notify({
          title: '提示',
          message: '当前登录状态已过期，请重新登录！',
          type: 'warning',
          duration: 5000
        })
        Cookies.remove('point')
      }
    },
    inputUserName($event) {
      this.loginForm.username = $event.target.innerText
      this.noUserName = false
    },
    inputPassWord($event) {
      // this.loginForm.password = $event.target.innerText
      console.log($event.target.value, '$event.target.value')
      this.loginForm.password = $event.target.value
      this.noPassWord = false
    },
    keydownUserName($event) {
      if ($event.key === 'Enter') {
        $event.preventDefault()
        this.$refs['inputPass'].focus()
      }
    },
    keydownPassWord($event) {
      if ($event.key === 'Enter') {
        $event.preventDefault()
        this.$refs['inputCode'].focus()
      }
    },
    keydownCode($event) {
      if ($event.key === 'Enter') {
        $event.preventDefault()
        this.loginForm.code = $event.target.innerText
        const user = {
          username: this.loginForm.username,
          password: this.loginForm.password,
          rememberMe: this.loginForm.rememberMe,
          code: this.loginForm.code,
          uuid: this.loginForm.uuid
        }
        if (user.password !== this.cookiePass) {
          user.password = encrypt(user.password)
        }
        this.loading = true
        this.$store.dispatch('Login', user).then(() => {
          this.loading = false
          // this.$router.push({ path: this.redirect || '/home' })
          this.$router.push({ path: '/yulu/index' })
        }).catch(() => {
          this.loading = false
          this.getCode()
        })
      }
    },
    inputCode($event) {
      this.loginForm.code = $event.target.innerText
      this.noCode = false
    },
    logintoyulu() {
      // document.querySelector('.login-password-input').style['-webkit-text-security'] = 'none'
      // console.log(document.querySelector('.login-password-input'))
      // this.loginForm.password = '123456'
      this.checkNoUserName()
      this.checkNoPassWord()
      this.checkNoCode()
      if (this.checkNoUserName() || this.checkNoPassWord() || this.checkNoCode()) {
        return
      }
      const user = {
        username: this.loginForm.username,
        password: this.loginForm.password,
        rememberMe: this.loginForm.rememberMe,
        code: this.loginForm.code,
        uuid: this.loginForm.uuid
      }
      if (user.password !== this.cookiePass) {
        user.password = encrypt(user.password)
      }
      this.loading = true
      this.$store.dispatch('Login', user).then(() => {
        this.loading = false
        // this.$router.push({ path: this.redirect || '/home' })
        this.$router.push({ path: '/yulu/index' })
      }).catch((err) => {
        console.log(err, 'loginErr')
        this.loading = false
        if (err === '企业员工') {
          this.$notify.error({
            title: '错误',
            message: '非政府、运营商用户不得进入'
          })
          return
        }
        this.getCode()
      })
    },
    checkNoUserName() {
      if (this.$refs['userRef'].innerText === '') {
        this.noUserName = true
      }
      return this.noUserName
    },
    checkNoPassWord() {
      if (this.$refs.inputPass.value === '') {
        this.noPassWord = true
      }
      return this.noPassWord
    },
    checkNoCode() {
      if (this.$refs.inputCode.innerText === '') {
        this.noCode = true
      }
      return this.noCode
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-size: cover;
    position: relative;
    background-image: url('../assets/images/bg.png');
    .login-total-title {
      position: absolute;
      top: 226px;
      left: 50%;
      transform: translateX(-50%);
      font-family: 'SourceHanSansCN-Bold';
      font-weight: bold;
      color: #DFEEF3;
      font-size: 68px;
      text-shadow: 0px 1px 2px rgba(9, 74, 154, 0.35);
      background: linear-gradient(1deg, #D3E7FF 0%, #6FB0FF 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
    /* 登录框 */
    .login-form-login {
      position: absolute;
      top: 374px;
      left: 50%;
      transform: translateX(-50%);
      width: 723px;
      height: 388px;
      background: #FFFFFF;
      border-radius: 8px;
      /* 左上角用户登录 */
      .login-left-top-title {
        position: absolute;
        left: -25px;
        top: -24px;
        width: 215px;
        height: 52px;
        background: linear-gradient(90deg, #051F4B, #0A50A6);
        text-align: center;
        font-family: 'SourceHanSansCN-Bold';
        font-weight: bold;
        color: #fff;
        font-size: 24px;
        line-height: 52px;
      }
      /* 输入用户名 */
      .login-user-wrapper {
        margin-top: 73px;
        position: relative;
        left: 50%;
        transform: translateX(-50%);
        display: flex;
        width: 356px;
        height: 41px;
        background: #fff;
        border: 1px solid rgba(0, 0, 0, 0.12);
        border-radius: 8px;
        line-height: 41px;
        .login-user-icon {
          width: 53px;
          height: 41px;
          border-radius: 8px;
          background-image: url('../assets/home/姓名用户名昵称.png');
          background-position: center;
          background-repeat: no-repeat;
          background-color: #F5F7FA;
        }
        .login-user-input {
          flex: 1;
          cursor: text;
          padding-left: 3px;
          &:empty::after {
            content: '请输入用户名';
            font-family: 'SourceHanSansCN-Regular';
            color: #0098CE;
            font-size: 16px;
            line-height: 41px;
          }
        }
      }
      /* 输入密码 */
      .login-password-wrapper {
        margin-top: 22px;
        position: relative;
        left: 50%;
        transform: translateX(-50%);
        display: flex;
        width: 356px;
        height: 41px;
        background: #fff;
        border: 1px solid rgba(0, 0, 0, 0.12);
        border-radius: 8px;
        line-height: 41px;
        .login-password-icon {
          width: 53px;
          height: 41px;
          border-radius: 8px;
          background-image: url('../assets/home/密码.png');
          background-position: center;
          background-repeat: no-repeat;
          background-color: #F5F7FA;
        }
        .login-password-input {
          /* -webkit-text-security: disc;
          -webkit-appearance: textfield;
          -webkit-user-select: text;
          user-select: text; */
          /* cursor: text; */
          flex: 1;
          padding-left: 3px;
          /* position: relative; */
          outline: none;
          border: none;
          display: block;
          /* &.emp {
            color: #0098CE;
            font-size: 16px;
            line-height: 41px;
          } */
          /* &:empty:after {
            -webkit-text-security: none;
            content: '请输入密码';
            font-family: 'SourceHanSansCN-Regular';
            color: #0098CE;
            font-size: 16px;
            line-height: 41px;
          } */
          &::-webkit-input-placeholder,textarea::-webkit-input-placeholder {
            color: #0098CE;
            font-size: 16px;
            line-height: 41px;
          }
        }
      }
      /* 验证码 */
      .login-verification-code-wrapper {
        margin-top: 21px;
        display: flex;
        width: 246px;
        height: 41px;
        position: relative;
        left: 50%;
        transform: translateX(calc(-50% - 55px));
        line-height: 41px;
        border: 1px solid rgba(0, 0, 0, 0.12);
        border-radius: 8px;
        .login-vertification-code-icon {
          width: 53px;
          height: 41px;
          border-radius: 8px;
          background-image: url('../assets/home/验证码.png');
          background-repeat: no-repeat;
          background-position: center;
          background-color: #F5F7FA;
        }
        .login-vertification-code-input {
          flex: 1;
          cursor: text;
          padding-left: 3px;
          &:empty::after {
            content: '请输入验证码';
            font-family: 'SourceHanSansCN-Regular';
            color: #0098CE;
            font-size: 16px;
          }
        }
      }
      /* 验证码图片 */
      .login-vertification-img-wrapper {
        position: absolute;
        left: 438px;
        top: 199px;
        width: 104px;
        height: 40px;
      }
      /* 登录 */
      .login-login-btn {
        margin-top: 51px;
        width: 357px;
        height: 47px;
        position: relative;
        left: 50%;
        transform: translateX(-50%);
        background: linear-gradient(90deg, #051F4B, #0A50A6);
        border-radius: 8px;
        font-size: 20px;
        font-family: Source Han Sans CN;
        font-weight: bold;
        color: #FFFFFF;
        line-height: 36px;
        cursor: pointer;
      }
    }
  }
  .title {
    margin: 0 auto 30px auto;
    text-align: center;
    color: #707070;
  }

  .login-form {
    border-radius: 6px;
    background: #ffffff;
    width: 385px;
    padding: 25px 25px 5px 25px;
    .el-input {
      height: 38px;
      input {
        height: 38px;
      }
    }
    .input-icon{
      height: 39px;width: 14px;margin-left: 2px;
    }
  }
  .login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
  }
  .login-code {
    width: 33%;
    display: inline-block;
    height: 38px;
    float: right;
    img{
      cursor: pointer;
      vertical-align:middle
    }
  }
  .inputError {
    width: 356px;
    position: relative;
    left: 50%;
    transform: translateX(-175px);
    color: red;
    font-size: 14px;
  }
</style>
