<template>
  <div class="page-body">
    <div class="head-box-login">
      <div class="head-box-top">
        <div class="top-call" />
        <div class="top-call"><img src="@/assets/home_images/gemho_logo.png" alt="gemho-logo"></div>
        <div class="top-call"><title-menus ref="titleMenus" menu-index="99" /></div>
        <div class="top-call"><user-login ref="userLogin" /></div>
        <div class="top-call"><language-setting ref="languageSetting" /></div>
      </div>
    </div>
    <div class="content-box-login">
      <div class="login-panel" style="width: 64%;text-align: center"><img src="@/assets/home_images/login_title.png"></div>
      <div class="login-panel" style="width: 36%">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-position="left" label-width="0px" class="login-form">
          <h3>{{ title }}</h3>
          <div class="login-remember" style="padding-bottom: 10px">
            <span v-if="mode===1" class="touch" @click="changeMode(2)"><i class="el-icon-s-unfold el-icon--left" />短信快捷登录</span>
            <span v-if="mode===2" class="touch" @click="changeMode(1)"><i class="el-icon-s-fold el-icon--left" />使用密码登录</span>
          </div>
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" size="medium" type="text" auto-complete="off" placeholder="请输入11位手机号码">
              <template slot="prepend">+86</template>
              <svg-icon slot="prefix" icon-class="z_phone" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item v-show="mode!==2" prop="password">
            <el-input v-model="loginForm.password" size="medium" type="password" auto-complete="off" placeholder="请输入登录密码" @keyup.enter.native="handleLogin">
              <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item v-show="mode===1" prop="code">
            <el-input v-model="loginForm.code" size="medium" auto-complete="off" placeholder="图像验证码" style="width: 70%" @keyup.enter.native="handleLogin">
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode">
            </div>
          </el-form-item>
          <el-form-item v-show="mode!==1" prop="sms">
            <el-input v-model="loginForm.sms" size="medium" auto-complete="off" placeholder="短信验证码" style="width: 70%" @keyup.enter.native="handleLogin">
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>
            <div class="login-code">
              <div class="sms-btn touch" @click="getSmsCode">{{ smsBtn }} {{ smsTime?smsTime+'s':'' }}</div>
            </div>
          </el-form-item>
          <el-form-item v-show="mode!==3" style="width:100%;">
            <div class="login-remember">
              <el-checkbox v-model="loginForm.rememberMe" style="margin:0 0 25px 0;opacity: 0.8">下次自动登录</el-checkbox>
            </div>
            <el-button :loading="loading" size="medium" type="primary" style="width:100%;font-size:17px;padding:13px" @click.native.prevent="handleLogin">
              <span v-if="!loading">{{ title }}</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div class="login-remember" style="margin: 10px 0">
              <span class="underline touch" @click="changeMode(3)">去注册</span>
            </div>
          </el-form-item>
          <el-form-item v-show="mode===3" style="width:100%;">
            <el-button :loading="loading" size="medium" type="primary" style="width:70%;font-size:17px;padding:13px" @click.native.prevent="handleRegister">
              <span v-if="!loading">注册</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div class="login-account">
              <span class="underline touch" @click="changeMode(1)">使用已有账号登录</span>
            </div>
            <div style="padding: 10px 0;">
              <el-checkbox v-model="loginForm.rememberMe" style="margin:0;opacity:0.8" />
              <div class="login-agreement"><span class="touch">阅读并接受《中国基建传感器网用户协议》及《中国基建传感器网隐私权保护声明》</span></div>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <home-footer ref="homeFooter" />
  </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 titleMenus from './components/titleMenus'
import userLogin from './components/userLogin'
import languageSetting from './components/languageSetting'
import homeFooter from './components/homeFooter'

export default {
  components: { titleMenus, userLogin, languageSetting, homeFooter },
  data() {
    const validateMobile = (rule, value, callback) => {
      if (value === 'admin') {
        return callback()
      }
      const newValue = value.replace(/[^0-9]/gi, '')
      if (value !== newValue) {
        callback(new Error('请输入正确的手机号'))
      } else if (newValue.length !== 11) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (this.mode !== 2 && !value) {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    const validateCode = (rule, value, callback) => {
      if (this.mode === 1 && !value) {
        callback(new Error('图像验证码不能为空'))
      } else {
        callback()
      }
    }
    const validateSms = (rule, value, callback) => {
      if (this.mode !== 1 && !value) {
        callback(new Error('短信验证码不能为空'))
      } else {
        callback()
      }
    }
    return {
      mode: 1,
      title: '登录',
      smsBtn: '短信获取验证码',
      smsTime: 0,
      smsTimer: null,
      codeUrl: '',
      cookiePass: '',
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        sms: '',
        uuid: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '手机号不能为空' }, { validator: validateMobile, trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }],
        code: [{ validator: validateCode, trigger: 'change' }],
        sms: [{ validator: validateSms, trigger: 'change' }]
      },
      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
    }
  },
  created() {
    // 获取验证码
    this.getCode()
    // 获取用户名密码等Cookie
    this.getCookie()
    // token 过期提示
    this.point()
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
  },
  methods: {
    changeMode(mode) {
      this.mode = mode
      if (mode === 1) {
        this.title = '登录'
      } else if (mode === 2) {
        this.title = '快捷登录'
      } else {
        this.title = '注册'
      }
    },
    getSmsCode() {
      if (this.timer && this.smsTime) {
        return
      }
      this.smsBtn = '短信已发送'
      this.smsTime = 30
      this.timer = setInterval(() => {
        this.smsTime--
        if (this.smsTime === 0) {
          clearInterval(this.timer)
          this.timer = null
          this.smsBtn = '短信获取验证码'
        }
      }, 1000)
    },
    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: ''
      }
    },
    handleRegister() {
      this.$refs.loginForm.validate(valid => {
        const user = {
          username: this.loginForm.username,
          password: this.loginForm.password,
          rememberMe: this.loginForm.rememberMe,
          code: this.loginForm.code,
          sms: this.loginForm.sms,
          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: '/console/registerInfo' })
          }).catch(() => {
            this.loading = false
            this.getCode()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        const user = {
          username: this.loginForm.username,
          password: this.loginForm.password,
          rememberMe: this.loginForm.rememberMe,
          code: this.loginForm.code,
          sms: this.loginForm.sms,
          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: '/console' })
          }).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')
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
::-webkit-scrollbar {
  width : 0;
  height: 0;
}
.touch {
  cursor:pointer;
}
.underline {
  text-decoration: underline; //下划线
  text-underline-offset: 5px; //下划线和文字间距
}
.head-box-login {
  width: 100vw;
  background: #1961C5;
  position: fixed;
  z-index: 999;
  .head-box-top {
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    padding: 15px 15px 0;
    .top-call {
      height: 50px;
    }
  }
  .head-title {
    width: 100%;
    margin-top: 92px;
    text-align: center;
    user-select: none;
  }
}
.content-box-login {
  width: 100vw;
  height: 100vh;
  display: table;
  background: #1961C5;
  font-family: Source Han Sans CN;
  font-weight: 400;
  user-select: none;
  .login-panel {
    height: 100vh;
    display: table-cell;
    vertical-align: middle;
  }
  .login-form {
    border-radius: 6px;
    width: 520px;
    padding: 25px;
    h3 {
      margin: 10px 0;
      color: white;
    }
    .login-remember {
      text-align: right;
      color: white;
    }
    .el-checkbox {
      .el-checkbox__inner {
        background-color: transparent;
        border-color: white;
      }
      .el-checkbox__label {
        padding-top: 2px;
        color: white;
      }
    }
    .el-input {
      height: 42px;
      input {
        height: 42px;
      }
    }
    .input-icon{
      height: 42px;width: 16px;margin-left: 2px;
    }
  }
  .login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
  }
  .login-account {
    width: 30%;
    display: inline-block;
    padding-top: 16px;
    text-align: center;
    float: right;
    color: white;
  }
  .login-agreement {
    width: 440px;
    float: right;
    color: white;
    span {
      opacity: 0.8;
    }
    span:hover {
      opacity: 1;
    }
  }
  .login-code {
    width: 26%;
    display: inline-block;
    height: 38px;
    float: right;
    img{
      margin: 2px 0;
      cursor: pointer;
      vertical-align:middle
    }
    .sms-btn {
      width: 100%;
      background-color: #7FBAF5;
      color: white;
      text-align: center;
      padding: 7px;
    }
  }
}
</style>
