<template>
  <div class="login" :style="'background-image:url('+ Background +');'">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-position="left" label-width="0px" class="login-form">
      <h3 class="title">
        {{ title }}</h3>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" auto-complete="off" :placeholder="$t('common.account')">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" auto-complete="off" :placeholder="$t('common.password')" @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 prop="code">
        <el-input v-model="loginForm.code" auto-complete="off" :placeholder="$t('common.verification_code')" style="width: 63%" @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-row :gutter="20">
        <el-col :span="12">
          <el-checkbox v-model="loginForm.rememberMe" style="margin:0 0 25px 0;">
            {{ $t('common.login_rm') }}
          </el-checkbox>
        </el-col>
        <el-col :span="12">
          <!-- <el-dropdown style="display: flex; justify-content: right; color: #409EFF;" trigger="click" @command="langChange"> -->
          <el-dropdown style="display: flex; justify-content: right; color: #409EFF;" trigger="click" @command="changeLanguage">
            <span class="el-dropdown-link">
              {{ language }}
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item divided command="zh">简体中文</el-dropdown-item>
              <el-dropdown-item divided command="en">English</el-dropdown-item>
              <el-dropdown-item divided command="in">Indonesian</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
      <el-form-item style="width:100%;">
        <el-button :loading="loading" size="medium" type="primary" style="width:100%;" @click.native.prevent="handleLogin">
          <span v-if="!loading">{{ $t('common.login') }}</span>
          <span v-else>{{ $t('common.login_ing') }}</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div v-if="$store.state.settings.showFooter" id="el-login-footer">
      <span v-html="$store.state.settings.footerTxt" />
      <span> ⋅ </span>
      <a href="https://beian.miit.gov.cn/#/Integrated/index" target="_blank">{{ $store.state.settings.caseNumber }}</a>
    </div>
  </div>
</template>

<script>
import { encrypt } from '@/utils/rsaEncrypt'
import Config from '@/settings'
import { getCodeImg } from '@/api/login'
import Cookies from 'js-cookie'
import Background from '@/assets/images/background.jpg'
import i18n from '@/i18n'
import { fetchMessages } from '@/api/i18n'
export default {
  name: 'Login',
  data() {
    return {
      language: '简体中文',
      title: i18n.t('platform.title'),
      title_param: 'platform',
      Background: Background,
      codeUrl: '',
      cookiePass: '',
      loginForm: {
        username: 'admin',
        password: '123456',
        rememberMe: false,
        code: '',
        uuid: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: i18n.t('platform.tip1') }],
        password: [{ required: true, trigger: 'blur', message: i18n.t('platform.tip2') }],
        code: [{ required: true, trigger: 'change', message: i18n.t('platform.tip3') }]
      },
      loading: false,
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.setLang(localStorage.getItem('lang'))
    // 获取验证码
    this.getCode()
    // 获取用户名密码等Cookie
    this.getCookie()
    // token 过期提示
    this.point()
  },
  methods: {
    // 语言切换-x
    async changeLanguage(locale) {
      // 如果已经加载过该语言，可以直接设置，避免重复请求
      if (!this.$i18n.getLocaleMessage(locale)) {
        const messages = await fetchMessages(locale)
        this.$i18n.setLocaleMessage(locale, messages.content)
      }
      this.$i18n.locale = locale
      // 可以将当前语言保存到本地存储，以便下次使用
      localStorage.setItem('lang', locale)
      this.setLang(locale)
      location.reload()
    },
    // 中英文切换
    langChange(command) {
      this.$i18n.locale = command
      localStorage.setItem('lang', command)
      this.setLang(command)
      location.reload()
    },
    setLang(command) {
      if (command === 'en') {
        this.language = 'English'
      } else if (command === 'zh') {
        this.language = '简体中文'
      } else if (command === 'in') {
        this.language = 'Indonesian'
      }
    },
    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),
        device_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
        }
        user.password = encrypt(user.password)
        if (valid) {
          this.loading = true
          if (user.rememberMe) {
            Cookies.set('username', user.username, { expires: Config.passCookieExpires })
            Cookies.set('password', this.loginForm.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
            window.location.href = this.redirect
            // if (this.redirect === 'http://localhost:8013/dashboard'){
            //   window.location.href = this.redirect
            // }
            // this.$router.push({ path: this.redirect || '/' })
          }).catch(() => {
            this.loading = false
            this.getCode()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    point() {
      const point = Cookies.get('point') !== undefined
      console.log(point)
      if (point) {
        this.$notify({
          title: i18n.t('common.Tips'),
          message: i18n.t('common.Tip20'),
          type: 'warning',
          duration: 5000
        })
        Cookies.remove('point')
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-size: cover;
  }
  .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
    }
  }
</style>
