<template>
  <div class="ibps-login">
    <div class="login-bg">
      <div class="login-top">
        <van-icon  name="comment-circle-o" class="logo-icon"/>
        <div class="logo-text">{{ $t('common.platform') }}</div>
        <br>
        <div class="logo-text">(移动端)</div>
      </div>
    </div>
    <div class="ibps-p">
      <van-form ref="form" @submit="handleLogin" @failed="onFailed">
        <van-field
          v-model="loginForm.username"
          :placeholder="$t('system.login.usernamePlaceholder')"
          :rules="usernameRules"
          name="username"
          icon-prefix="ibps-icon"
          left-icon="user-circle-o"
          clearable
        />
        <van-field
          v-model="loginForm.password"
          :type="passwordType"
          :placeholder="$t('system.login.passwordPlaceholder')"
          :rules="[{ required: true, message: ' ' }]"
          :right-icon="passwordType==='password'?'eye-slash':'eye'"
          name="password"
          icon-prefix="ibps-icon"
          left-icon="lock"
          clearable
          @click-right-icon="showPassword"
        />
        <van-field
          v-if="enabledValidCode"
          v-model="loginForm.captcha"
          :placeholder="$t('system.login.codePlaceholder')"
          :rules="[{ required: true, message: ' ' }]"
          name="captcha"
          icon-prefix="ibps-icon"
          left-icon="qrcode"
          clearable
        >
          <template #button>
            <img :src="code.src" class="login-code-img" @click="refreshCode">
          </template>
        </van-field>
        <div class="ibps-mt">
          <van-button round block type="info" native-type="submit">
            {{ $t('system.login.logIn') }}
          </van-button>
        </div>
      </van-form>

      <switch-environment v-if="$nodeEnv === 'development'" class="ibps-mt ibps-text-center" type="link" />
    </div>
    <div class="copyright">
     {{ $t('common.company') }}©{{ $t('common.copyright') }}
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import Utils from '@/utils/util'
import '@/assets/styles/pages/login.scss'
import SwitchEnvironment from '@/views/system/switch-environment'

const loginForm = process.env.NODE_ENV === 'development'
  ? {
    username: 'admin',
    password: '1'
  } : {
    username: '',
    password: ''
  }
export default {
  components: {
    SwitchEnvironment
  },
  data() {
    return {
      passwordType: 'password',
      loginForm: {
        username: loginForm.username,
        password: loginForm.password,
        requestId: '',
        captcha: ''
      },
      redirect: undefined,
      isRegOpen: false,
      enabledValidCode: false,
      code: {
        src: '',
        value: '',
        len: 5,
        type: 'src'
      },
      usernameRules: [{ required: true, message: ' ' }]
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.isRegisterOpen()
    this.loadValidCode(true)
  },
  mounted() {
    // 注销退出清空验证码
    this.loginForm.captcha = ''
    // 注销退出清空请求ID
    this.loginForm.requestId = ''
  },
  methods: {
    ...mapActions('ibps/account', [
      'login',
      'getCaptcha',
      'getRegisterOpen'
    ]),
    isRegisterOpen() {
      this.getRegisterOpen().then((data) => {
        this.isRegOpen = data.data
        if (this.isRegOpen) {
          this.usernameRules = [
            { required: true, message: ' ' },
            { validator: this.validateMobile, message: ' ' }
          ]
        } else {
          this.usernameRules = [{ required: true, message: ' ' }]
        }
      }).catch((e) => {})
    },
    validateMobile(value) {
      if (Utils.isEmpty(value)) {
        return false
      } else {
        const isPhone = /^1(3|4|5|6|7|8|9)\d{9}$/
        if (value.length === 11) {
          if (!isPhone.test(value)) {
            return false
          } else {
            return true
          }
        } else {
          if (!isPhone.test(value)) {
            return false
          } else {
            return false
          }
        }
      }
    },
    // 获取验证码
    loadValidCode(isBackfill) {
      this.getCaptcha({ params: { requestId: this.loginForm.requestId }}).then((data) => {
        // 返回状态501，说明系统没有开启验证码
        if (data.state === 501) {
          this.enabledValidCode = false
        } else {
          this.enabledValidCode = true
          this.code.src = data.data
          this.loginForm.requestId = data.variables.requestId
        }
        this.initValidCode()
        if (isBackfill) {
          this.loginForm.code = this.code.value
        }
      }).catch((e) => {

      })
    },
    refreshCode() {
      this.loadValidCode()
    },
    showPassword() {
      this.passwordType === 'text'
        ? (this.passwordType = 'password')
        : (this.passwordType = 'text')
    },
    onFailed({ values }) {
      if (this.enabledValidCode && this.$utils.isEmpty(values.captcha)) {
        this.$toast(this.$t('system.login.codeCorrect'))
        return
      }

      if (this.$utils.isNotEmpty(values.username) && this.isRegOpen) {
        this.$toast(this.$t('system.login.mobileCorrect'))
      } else {
        this.$toast(this.$t('system.login.usernamePasswordCorrect'))
      }
    },
    handleLogin() {
      this.login({
        form: this.loginForm
      }).then(() => {
        let path = '/'
        if (this.redirect) {
          path = '/dashboard'
        }
        this.$router.push({ path: path })
      }).catch((err) => {
        // 验证码错误自动清空&密码输入错误3次后触发验证码填写模块
        if (err && err.state === 6020104) {
          this.loginForm.captcha = ''
          this.enabledValidCode = true
          this.refreshCode()
        }
        if (err && err.state && this.enabledValidCode) {
          this.loginForm.captcha = ''
          this.refreshCode()
        }
      })
    }
  }
}
</script>
