<template>
  <div class="aui-wrapper aui-page__login">
    <div class="aui-content__wrapper">
      <main class="aui-content">
        <div class="login-header">
          <h2 class="login-brand"
              style="text-transform: none;color:red;">{{ $t('brand.lg') }}</h2>
        </div>
        <div class="login-body">
          <h3 class="login-title">{{ $t('login.title') }}</h3>
          <el-form :model="dataForm"
                   :rules="dataRule"
                   ref="dataForm"
                   @keyup.enter.native="dataFormSubmitHandle()"
                   status-icon>
            <!-- <el-form-item>
              <el-select v-model="$i18n.locale" class="w-percent-100">
                <el-option v-for="(val, key) in i18nMessages" :key="key" :label="val._lang" :value="key"></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item prop="username">
              <el-input v-model="dataForm.username"
                        :placeholder="$t('login.username')"
                        @blur="onInputBlur">
                <span slot="prefix"
                      class="el-input__icon">
                  <svg class="icon-svg"
                       aria-hidden="true">
                    <use xlink:href="#icon-user"></use>
                  </svg>
                </span>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="dataForm.password"
                        type="password"
                        :placeholder="$t('login.password')">
                <span slot="prefix"
                      class="el-input__icon">
                  <svg class="icon-svg"
                       aria-hidden="true">
                    <use xlink:href="#icon-lock"></use>
                  </svg>
                </span>
              </el-input>
            </el-form-item>
            <el-form-item prop="captcha"
                          v-if='!getMobileType'>
              <el-row :gutter="20">
                <el-col :span="14">
                  <el-input v-model="dataForm.captcha"
                            :placeholder="$t('login.captcha')">
                    <span slot="prefix"
                          class="el-input__icon">
                      <svg class="icon-svg"
                           aria-hidden="true">
                        <use xlink:href="#icon-safetycertificate"></use>
                      </svg>
                    </span>
                  </el-input>
                </el-col>
                <el-col :span="10"
                        class="login-captcha">
                  <img :src="captchaPath"
                       @click="getCaptcha()">
                </el-col>
              </el-row>
            </el-form-item>
            <div class="login-mobile"
                 v-if='getMobileType'>手机号：{{loginMobile.mobile}}</div>
            <el-form-item prop="smsCode"
                          v-if='getMobileType'>
              <el-row :gutter="20">
                <el-col :span="10">
                  <el-input v-model="dataForm.smsCode"
                            :placeholder="$t('login.smsCode')">
                    <span slot="prefix"
                          class="el-input__icon">
                      <svg class="icon-svg"
                           aria-hidden="true">
                        <use xlink:href="#icon-safetycertificate"></use>
                      </svg>
                    </span>
                  </el-input>
                </el-col>
                <el-col :span="10"
                        class="login-captcha">
                  <el-button @click="getSmsCode()"
                             :disabled="smsCodeText !== '获取验证码'"
                             type="primary">{{smsCodeText}}</el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="dataFormSubmitHandle()"
                         class="w-percent-100">{{ $t('login.title') }}</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div v-if="isHidden">
          <p><a href="https://dl.google.com/tag/s/appguid%3D%7B8A69D345-D564-463C-AFF1-A69D9E530F96%7D%26iid%3D%7B0EBBEC46-30F5-946B-A54E-5628DFF12914%7D%26lang%3Den%26browser%3D4%26usagestats%3D1%26appname%3DGoogle%2520Chrome%26needsadmin%3Dprefers%26ap%3Dx64-stable-statsdef_1%26installdataindex%3Ddefaultbrowser/update2/installers/ChromeSetup.exe"
               target="_blank">点击此处下载谷歌浏览器</a></p>
        </div>
        <!-- <div class="login-footer">
          <p><a href="http://www.elinkit.com.cn/"
               target="_blank">{{ $t('login.copyright') }}</a>2020 © www.elinkit.com.cn</p>
        </div> -->
      </main>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import debounce from 'lodash/debounce'
import { messages } from '@/i18n'
import { getUUID } from '@/utils'
export default {
  data () {
    return {
      i18nMessages: messages,
      captchaPath: '',
      isHidden: false,
      dataForm: {
        username: '',
        password: '',
        uuid: '',
        captcha: '',
        smsCode: ''
      },
      loginMobile: {
        mobile: '',
        keyword: ''
      },
      getMobileType: false, // 用于判断显示验证码还是短信验证码登录
      smsCodeText: '获取验证码' // 获取验证码button内容
    }
  },
  computed: {
    dataRule () {
      return {
        username: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        password: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        smsCode: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCaptcha()
    this.myBrowser()
  },
  methods: {
    myBrowser () {
      var userAgent = navigator.userAgent
      if (userAgent.indexOf('Chrome') > -1) {
        this.isHidden = false
      } else {
        this.isHidden = true
      }
    },
    // 获取验证码
    getCaptcha () {
      this.dataForm.uuid = getUUID()
      this.captchaPath = `${window.SITE_CONFIG['apiURL']}/auth/captcha?uuid=${this.dataForm.uuid}`
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        // getMobileType false 按原流程登录
        const loginUrl = this.getMobileType ? '/auth/loginBySms' : '/auth/login'
        this.$http.post(loginUrl, this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            this.getCaptcha()
            return this.$message.error(res.msg)
          }
          Cookies.set('token', res.data.token)
          this.$router.replace({ name: 'home' })
          // 登陆之后从localStorage获取党委为空则从网络上拉取
          this.checkLocakStorage()
        }).catch(() => { })
        this.$http.get(`/api/plugins/workLog/getCustomId`)
          .then(res => {
            if (res.data.code !== 0) {
              return this.$message.error(res.data.msg)
            }
            Cookies.set('customerId', res.data.data)
          })
          .catch((err) => {
            console.log(err)
          })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    checkLocakStorage () {
      var street = localStorage.getItem('street')
      if (street === null) {
        this.getIdByCode('shibei')
      }
    },
    // 获取党委
    getIdByCode (partyCode) {
      this.$http.get(`/sys/dept/getIdByCode/` + partyCode).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        localStorage.setItem('street', res.data.id)
      }).catch(() => { })
    },
    // 用户名失去焦点方法
    onInputBlur () {
      this.$http.get(`/sys/user/getLoginMobile/?username=${this.dataForm.username}`).then(({ data: res }) => {
        if (res.code !== 0) {
          this.getMobileType = false
          return this.$message.error(res.msg)
        }
        // mobile 不为空：
        // 登录页面隐藏验证码，采用短信验证码的方式登录(/auth/loginBySms)
        // phone 为空
        // 原登录流程不变
        this.getMobileType = res.data.mobile ? true : false
        this.loginMobile = {
          mobile: res.data.mobile,
          keyword: res.data.keyword
        }
      }).catch(() => { })
    },
    // 获取验证码
    getSmsCode () {
      this.smsCodeText = '获取中...'
      this.$http.post(`/message/sms/send/byMobileAndKeyword?mobile=${this.loginMobile.mobile}&keyword=${this.loginMobile.keyword}`).then(({ data: res }) => {
        if (res.code !== 0) {
          this.smsCodeText = '获取验证码'
          return this.$message.error(res.msg)
        }
        this.$message({
          message: '验证码发送成功',
          type: 'success'
        })
        let num = 60
        this.smsCodeText = '60s后重新获取'
        const timer = setInterval(() => {
          if (num >= 1) {
            this.smsCodeText = `${num}s后重新获取`
            --num
          } else {
            clearInterval(timer)
            this.smsCodeText = '获取验证码'
          }
        }, 1000)
      }).catch(() => {
        this.smsCodeText = '获取验证码'
      })
    }
  }
}
</script>
