<template>
  <div class="main" style="margin-top: 20%">
    <a-form id="formLogin" style="margin-top: 10px" class="user-layout-login" ref="formLogin" :form="form">
      <a-alert v-if="isLoginError" type="error" showIcon style="margin-bottom: 24px" message="账户或密码错误" />
      <a-form-item>
        <j-input
          style="height: 50px"
          :size="size"
          type="text"
          placeholder="账户"
          v-decorator="[
            'username',
            {
              rules: [{ required: true, message: '请输入帐户名或邮箱地址' }, { validator: handleUsernameOrEmail }],
              validateTrigger: 'change',
            },
          ]"
          :hasIcon="true"
          :iconType="userIcon"
        >
        </j-input>
      </a-form-item>
      <a-form-item>
        <a-input
          style="height: 50px"
          size="large"
          type="password"
          autocomplete="false"
          placeholder="密码"
          v-decorator="['password', { rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur' }]"
        >
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
        </a-input>
      </a-form-item>
      <a-form-item style="margin-top: 24px">
        <a-button
          size="large"
          type="primary"
          @click="handleSubmit"
          class="login-button"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
        >登录</a-button
        >
      </a-form-item>
    </a-form>
    <a-row style="font-size: 16px; line-height: 27px; color: #ffffff">
      <a-col
        :span="24"
        style="text-align: right; cursor: pointer"
        @click="register"
      >还没有账号 <a-icon type="question-circle" style="padding: 0 4px" />立即注册</a-col
      >
    </a-row>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { timeFix } from '../../../packages/utils/util'
import { ctos3Api } from '../../../packages/api/manage'
import Vue from 'vue'
import { Base64 } from 'js-base64'
import moment from 'moment'
export default {
  data () {
    return {
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 1,
      uname: Vue.ls.get('uname', 'ADMIN'),
      rememberName: Vue.ls.get('rememberName'),
      isLoginError: false,
      form: this.$form.createForm(this),
      size: 'large',
      userIcon: 'user',
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 1
      },
      visible: false,
      confirmLoading: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      companyLst: []
    }
  },
  mounted () {
    // this.requiredTwoStepCaptcha = true
    Object.keys(localStorage).forEach((item) =>
      item.indexOf('requestTime') !== -1 ? localStorage.removeItem(item) : ''
    )
    if (this.rememberName) {
      const userName = Vue.ls.get('uname', '')
      this.form.setFieldsValue({
        username: userName
      })
      this.loadData(userName)
    }
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    // handler
    handleUsernameOrEmail (rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleTabClick (key) {
      this.customActiveKey = key
    },
    handleSubmit () {
      Vue.ls.clear()
      //  e.preventDefault()
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login
      } = this
      state.loginBtn = true
      const validateFieldsKey = customActiveKey === ['username', 'password']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          const loginParams = { ...values }
          delete loginParams.username
          loginParams.username = values.username
          // Base64加密三次
          loginParams.password = Base64.encode(loginParams.password)
          loginParams.password = Base64.encode(loginParams.password)
          loginParams.password = Base64.encode(loginParams.password)
          // loginParams.password = Base64.decode(loginParams.password)
          const parameter = {}
          parameter.serviceName = 'userService'
          parameter.methodName = 'login'
          parameter.rpcParams = [loginParams.username, loginParams.password]
          Object.keys(localStorage).forEach((item) =>
            item.indexOf('requestTime') !== -1 ? localStorage.removeItem(item) : ''
          )
          Login(parameter)
            .then((res) => {
              this.loginSuccess(res)
            })
            .catch((err) => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
              Vue.ls.set('rememberName', values.rememberName)
              if (values.rememberName) {
                Vue.ls.set('uname', values.username)
              } else {
                Vue.ls.set('uname', '')
              }
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    loginSuccess (res) {
      // console.log(res)
      const time = moment().format('YYYY-MM-DD HH:mm:ss')
      const tailInfos = res.responseData.resultData.tailInfos

      localStorage.setItem('requestTime', time)
      localStorage.setItem('loginTime', moment().format('YYYY-MM-DD HH:mm:ss'))
      localStorage.setItem('isForcePW', tailInfos.isForcePW)
      localStorage.setItem('isFirstLogin', tailInfos.isFirstLogin)
      localStorage.setItem('isInitialPassword', tailInfos.isInitialPassword)
      localStorage.setItem('userName', res.responseData.resultData.userid)
      localStorage.setItem('realname', res.responseData.resultData.username)
      localStorage.setItem('userid', res.responseData.resultData.id)
      localStorage.setItem('companyId', res.responseData.resultData.companyId)
      localStorage.setItem('userType', res.responseData.resultData.userType)
      this.$router.push({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
      this.isLoginError = false
    },
    requestFailed (err) {
      this.isLoginError = true
    },
    register () {
      this.$refs.register.visible = true
    }
  }
}
</script>

<style lang="less" scoped>
.ant-tabs2 /deep/ .ant-tabs-ink-bar {
  background-color: white;
}

//.ant-tabs2{
//  /deep/.ant-tabs-tab{
//    background:red;
//  }
//}

.user-layout-login {
  label {
    font-size: 12px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 12px;
  }

  button.login-button {
    background: #e83820;
    border-color: #e83820;
    padding: 0 15px;
    font-size: 16px !important;
    height: 55px;
    color: #fff;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
  /deep/ .ant-select {
    height: 50px;
    font-size: 15px !important;
    .ant-select-selection {
      height: 100%;
    }
    .ant-select-selection__rendered {
      height: 100%;
      line-height: 48px;
    }
  }
}
</style>
