<template>
  <!-- 修改后的登录页，简洁版。    更全面功能，参照 OldLogin.vue文件 -->
  <!-- 登录表单 -->
  <a-form :form="form" class="user-layout-login" ref="formLogin" id="formLogin">
    <h6>欢迎登录</h6>
    <!-- 账户名 -->
    <a-form-item>
      <a-input
        size="large"
        v-decorator="['username', validatorRules.username, { validator: this.handleUsernameOrEmail }]"
        type="text"
        placeholder="请输入帐户名 / admin"
      >
        <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
      </a-input>
    </a-form-item>

    <!-- 密码 -->
    <a-form-item>
      <a-input
        v-decorator="['password', validatorRules.password]"
        size="large"
        type="password"
        autocomplete="false"
        placeholder="密码 / 123456"
      >
        <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
      </a-input>
    </a-form-item>

    <!-- 滑块验证-->
    <a-row :gutter="0" id="sliderBox">
      <a-col :span="24">
        <j-slider @onSuccess="sliderSuccess"></j-slider>
        <span style="color: red;">{{ slideredMsg }}</span>
      </a-col>
    </a-row>

    <!-- 自动登录 -->
    <a-form-item style="text-align: left;">
      <a-checkbox style="color:#C1C1C1;" v-decorator="['rememberMe', { initialValue: true, valuePropName: 'checked' }]"
        >自动登录</a-checkbox
      >
    </a-form-item>

    <!-- 确定 -->
    <a-form-item style="margin-top:30px">
      <a-button
        size="large"
        type="primary"
        htmlType="submit"
        class="login-button"
        :loading="loginBtn"
        @click.stop.prevent="handleSubmit"
        :disabled="loginBtn"
        >登录
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script>
import Vue from 'vue'
import JSlider from '@/components/jeecg/JSlider'
import { mapActions } from 'vuex'
import { ACCESS_TOKEN, ENCRYPTED_STRING } from '@/store/mutation-types'
import { timeFix } from '@/utils/util'

export default {
  components: {
    JSlider //滑动
  },
  data() {
    return {
      customActiveKey: 'tab1', //默认显示 张海迷们登录
      loginBtn: false, //默认显示 确定按钮
      slidered: false, //滑动
      slideredMsg: '', //滑动信息
      form: this.$form.createForm(this),
      validatorRules: {
        username: { rules: [{ required: true, message: '请输入用户名!' }, { validator: this.handleUsernameOrEmail }] },
        password: { rules: [{ required: true, message: '请输入密码!', validator: 'click' }] }
      }
    }
  },
  created() {
    Vue.ls.remove(ACCESS_TOKEN)
    this.getRouterData()
  },
  methods: {
    ...mapActions(['Login', 'Logout', 'PhoneLogin']),
    //拿到
    getRouterData() {
      this.$nextTick(() => {
        if (this.$route.params.username) {
          this.form.setFieldsValue({
            username: this.$route.params.username
          })
        }
      })
    },

    /*滑块验证*/
    sliderSuccess() {
      this.slidered = true
      this.slideredMsg = ''
    },

    //“确定” 按钮，验证表单
    handleSubmit() {
      let that = this
      if (!that.slidered) {
        this.slideredMsg = '请拖动滑块！'
      }
      let loginParams = {}
      that.loginBtn = true
      // 使用账户密码登陆
      if (that.customActiveKey === 'tab1') {
        that.form.validateFields(
          ['username', 'password', /*'inputCode',*/ 'rememberMe'],
          { force: true },
          (err, values) => {
            if (!err) {
              loginParams.username = values.username
              loginParams.password = values.password
              loginParams.remember_me = values.rememberMe
              loginParams.captcha = that.inputCodeContent //验证码
              loginParams.slidered = that.slidered
              loginParams.checkKey = that.currdatetime
              console.log('登录参数', loginParams)
              that
                .Login(loginParams)
                .then(res => {
                  this.departConfirm(res)
                })
                .catch(err => {
                  that.requestFailed(err)
                })
            } else {
              that.loginBtn = false
            }
          }
        )
      }
    },

    //邮箱是账户名
    handleUsernameOrEmail(rule, value, callback) {
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        this.loginType = 0
      } else {
        this.loginType = 1
      }
      callback()
    },

    //登录成功
    loginSuccess() {
      this.$router.push({ name: 'dashboard' }) //仪表盘
      this.$notification.success({
        message: '欢迎',
        description: `${timeFix()}，欢迎回来`
      })
    },
    //失败
    cmsFailed(err) {
      this.$notification['error']({
        message: '登录失败',
        description: err,
        duration: 4
      })
    },

    //登录失败的提示
    requestFailed(err) {
      this.$notification['error']({
        message: '登录失败',
        description: ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
      this.loginBtn = false
    },

    //部门确认 todo  为啥要有这个？？？？
    departConfirm(res) {
      if (res.success) {
        let multi_depart = res.result.multi_depart
        //0:无部门 1:一个部门 2:多个部门
        if (multi_depart == 0) {
          this.loginSuccess()
          this.$notification.warn({
            message: '提示',
            description: `您尚未归属部门,请确认账号信息`,
            duration: 3
          })
        } else if (multi_depart == 2) {
          this.departVisible = true
          this.currentUsername = this.form.getFieldValue('username')
          this.departList = res.result.departs
        } else {
          this.loginSuccess()
        }
      } else {
        this.requestFailed(res)
        this.Logout()
      }
    }
  }
}
</script>

<style lang="less" scoped>
#formLogin {
  // 欢迎登录
  h6 {
    text-align: center;
    font-size: 30px;
    font-family: 'Microsoft YaHei';
    color: #00a0e9;
    font-weight: 700;
  }
  .login-button {
    width: 100%;
    background: linear-gradient(-90deg, #67eafd 0%, #3ea4fd 100%);
    border-radius: 8px;
    border: none;
    font-size: 22px;
    font-weight: 700;
  }
  #sliderBox {
    margin-bottom: 20px;
  }
}
</style>
