<template>
  <el-form ref="loginForm" class="login-form" status-icon :rules="loginRules" :model="loginForm" label-width="0">
    <el-form-item v-if="enableTenant" prop="tenantId">
      <el-input v-model="loginForm.tenantId" size="small" auto-complete="off">
        <i slot="prefix" class="el-icon-key" />
      </el-input>
    </el-form-item>
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" size="small" auto-complete="off" :placeholder="$t('ec.login.username')">
        <i slot="prefix" class="fa fa-user-o" />
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" size="small" :type="passwordType" auto-complete="off" :placeholder="$t('ec.login.password')" @keyup.enter.native="handleLogin">
        <i slot="suffix" class="el-icon-view el-input__icon" @click="showPassword" />
        <i slot="prefix" class="el-icon-lock" />
      </el-input>
    </el-form-item>
    <el-form-item v-if="loginCaptcha" prop="captcha">
      <el-row :span="24">
        <el-col :span="16">
          <el-input v-model="loginForm.captcha" size="small" auto-complete="off" maxlength="20" :placeholder="$t('ec.login.code')" @keyup.enter.native="handleLogin">
            <i slot="prefix" class="fa fa-shield" />
          </el-input>
        </el-col>
        <el-col :span="8">
          <div class="login-code">
            <img :src="loginForm.image" class="login-code-img" @click="refreshCode">
          </div>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item v-if="needSms" prop="smsCode">
      <el-input
        v-model="loginForm.smsCode"
        size="small"
        auto-complete="off"
        :placeholder="$t('ec.login.code')"
        @keyup.enter.native="handleLogin"
      >
        <i
          slot="prefix"
          class="el-icon-chat-line-square"
          style="margin-top:2px;"
        />
        <template slot="append">
          <span
            class="msg-text"
            :class="[{display:msgKey}]"
            @click="handleSend"
          >{{ msgText }}</span>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button :style="`background:${defaultTheme}`" type="primary" size="small" class="login-submit" :loading="loading" @click.native.prevent="handleLogin">{{ $t('ec.login.logIn') }}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import config from '@/settings'
import { getCaptcha, sendLoginSmsCode } from 'ecip-web/api/user'
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min';

const needSms = typeof window._CONFIG['needSms'] === 'undefined' ? false : window._CONFIG['needSms']
const loginEncrypt = typeof window._CONFIG['loginEncrypt'] === 'undefined' ? false : window._CONFIG['loginEncrypt']

export default {
  name: 'Userlogin',
  props: [],
  data() {
    return {
      loading: false,
      needSms,
      loginEncrypt,
      enableTenant: config.enableTenant,
      loginCaptcha: !needSms && config.loginCaptcha,
      msgText: '',
      msgTime: '',
      msgKey: false,
      loginForm: {
        // 租户ID
        tenantId: '000000',
        // 用户名
        username: '',
        // 密码
        password: '',
        // 账户类型
        type: 'account',
        // 验证码的值
        captcha: '',
        // 验证码的索引
        key: '',
        smsCode: '',
        // 预加载白色背景
        image:
          'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
      },
      loginRules: {
        tenantId: [
          {
            required: false,
            message: this.$t('ec.login.tenantId'),
            trigger: 'blur'
          }
        ],
        username: [
          {
            required: true,
            message: this.$t('ec.login.usernameEmpty'),
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: this.$t('ec.login.pwd.empty'),
            trigger: 'blur'
          },
          {
            min: 1,
            message: this.$t('ec.login.pwd.lengthError'),
            trigger: 'blur'
          }
        ]
      },
      passwordType: 'password',
      redirect: undefined,
      otherQuery: {}
    }
  },
  computed: {
    defaultTheme() {
      return this.$store.state.settings.defaultTheme
    },
    config() {
      return {
        MSGINIT: this.$t('ec.login.getPhoneCode'),
        MSGSCUCCESS: this.$t('ec.login.resendCodeAfter'),
        MSGTIME: 60
      }
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    this.msgText = this.config.MSGINIT
    this.msgTime = this.config.MSGTIME
    if (this.loginCaptcha) {
      this.loginRules.captcha = [
        {
          required: true,
          message: this.$t('ec.login.codeEmpty'),
          trigger: 'blur'
        }
      ]
      this.refreshCode()
    }
    if (this.needSms) {
      this.loginRules.smsCode = [{ required: true, trigger: 'blur', validator: this.validateCode }]
    }
    if (config.demo) {
      this.username = 'admin'
      this.password = '123456'
    }
  },
  mounted() {},
  methods: {
    validateCode(rule, value, callback) {
      if (value.length !== 6) {
        callback(new Error(this.$t('ec.login.codeError')))
      } else {
        callback()
      }
    },
    async handleSend() {
      if (this.msgKey) return
      if (!this.loginForm.username) {
        this.$message.warning(this.$t('ec.login.requireUsername'))
        return
      }
      if (!this.loginForm.password) {
        this.$message.warning(this.$t('ec.login.requirePassword'))
        return
      }
      let enPassword = this.loginForm.password
      if (config.loginEncrypt || loginEncrypt) {
        // const JSEncrypt = require('jsencrypt')
        // const crypt = new JSEncrypt.JSEncrypt()
        const crypt = new JSEncrypt()
        crypt.setPublicKey(config.loginPublicKey)
        enPassword = crypt.encrypt(this.loginForm.password)
      }
      const { data } = await sendLoginSmsCode(Object.assign({}, this.loginForm, { password: enPassword }))
      this.loginForm.key = data.key
      this.msgText = this.msgTime + this.config.MSGSCUCCESS
      this.msgKey = true
      const time = setInterval(() => {
        this.msgTime--
        this.msgText = this.msgTime + this.config.MSGSCUCCESS
        if (this.msgTime === 0) {
          this.msgTime = this.config.MSGTIME
          this.msgText = this.config.MSGINIT
          this.msgKey = false
          clearInterval(time)
        }
      }, 1000)
    },
    refreshCode() {
      return new Promise((resolve) => {
        getCaptcha().then((res) => {
          const data = res.data
          this.loginForm.key = data.key
          this.loginForm.image = data.captcha
          resolve(res)
        })
      })
    },
    showPassword() {
      this.passwordType === ''
        ? (this.passwordType = 'password')
        : (this.passwordType = '')
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true
          const loading = this.$loading({
            lock: true,
            text: this.$t('ec.login.wait'),
            spinner: 'el-icon-loading'
          })
          const loginForm = Object.assign(
            { enableTenant: config.enableTenant, code: this.loginForm.captcha }, // code 为了兼容旧的src/store/modules/user.js
            this.loginForm
          )
          let enPassword = loginForm.password
          if (config.loginEncrypt || loginEncrypt) {
            // const JSEncrypt = require('jsencrypt')
            // const crypt = new JSEncrypt.JSEncrypt()
            const crypt = new JSEncrypt()
            crypt.setPublicKey(config.loginPublicKey)
            enPassword = crypt.encrypt(loginForm.password)
          }
          this.$store
            .dispatch('user/login', Object.assign({}, loginForm, { password: enPassword }))
            .then(() => {
              this.$router.push({
                path: this.redirect || '/',
                query: this.otherQuery
              })
              this.loading = false
              loading.close()
            })
            .catch(async(err) => {
              if (this.loginCaptcha) {
                if (err &&  err.message && err.message == '验证码错误') {
                  this.loginForm.captcha = ''
                } else {
                  this.loginForm.captcha = ''
                  this.loginForm.password = ''
                }
                
                await this.refreshCode()
              }
              this.loading = false
              loading.close()
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.msg-text {
  display: block;
  width: 100px;
  font-size: 12px;
  text-align: center;
  cursor: pointer;
}
.msg-text.display {
  color: #ccc;
}
</style>

