<template>
  <div class="login-tab">
    <div class="login-tabs">
      <div :class="active === 'msg'? 'tab-active': ''" class="login-tab-pane" @click="active = 'msg'">短信登录</div>
      <div class="tab-line"/>
      <div :class="active === 'password'? 'tab-active': ''" class="login-tab-pane" @click="active = 'password'">账号登录</div>
    </div>
    <!-- 验证码登录 -->
    <div v-show="active === 'msg'">
      <MsgValidate ref="msgValidateRef" />
      <el-button :loading="loading" type="primary" class="btn-login" @click.native.prevent="handleLogin">立即登录</el-button>
    </div>

    <!-- 密码登录 -->
    <el-form v-show="active === 'password'" ref="loginPassForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="off" label-position="left">
      <el-form-item prop="userName">
        <el-input v-model="loginForm.userName" placeholder="请输入用户名" autocomplete="off" type="text" auto-complete="on" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" placeholder="请输入密码" autocomplete="off" type="password" auto-complete="on" />
      </el-form-item>
      <el-form-item prop="captchaCode">
        <div class="phone-captcha">
          <el-input v-model="loginForm.captchaCode" placeholder="图形验证码" autocomplete="off" type="text" maxlength="6" auto-complete="on">
            <img slot="suffix" :src="captchaImg" class="captch-img" alt="验证码" @click="fetchVerifyGraphic">
          </el-input>
        </div>
      </el-form-item>
      <div class="forget-password">
        <el-button type="text" @click="forgetPassword">忘记密码</el-button>
      </div>
      <el-button :loading="loading" type="primary" class="btn-login" @click.native.prevent="handleLogin">立即登录</el-button>
    </el-form>

  </div>
</template>

<script>
import SvgIcon from '@/components/SvgIcon'
import { getToken } from '@/utils/auth'
import cloneDeep from 'lodash/cloneDeep'
import MsgValidate from './MsgValidate.vue'
import { getLoginSecretKey, getGraphic } from '@/api/user'
import { getJMJqueryParams } from '@/utils/sm4'

export default {
  name: 'LoginTab',
  components: { SvgIcon, MsgValidate },
  data() {
    return {
      active: 'msg',
      loginForm: {
        userName: '',
        password: '',
        requestId: '', // 登录密码加密的请求id
        platformSource: 'Web',
        captchaCode: ''
      },
      loginRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        captchaCode: [
          { required: true, message: '请输入图片验证码', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      captchaImg: '',
      loading: false,
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted() {
    this.fetchVerifyGraphic()
  },
  methods: {
    /**
     * 查询图片验证码
     */
    async fetchVerifyGraphic() {
      // 获取图片验证码
      const { captchaImg, requestId } = await getGraphic({ platformSource: 'Web' })
      // 记录当前图片验证码
      this.captchaImg = captchaImg
      // 请求id
      this.loginForm.captchaId = requestId
    },

    /**
     * 点击登录方法
     */
    handleLogin() {
      let params
      if (this.active === 'msg') {
        params = this.$refs.msgValidateRef.getData()
        this.logIn(params)
      } else if (this.active === 'password') {
        this.$refs.loginPassForm.validate(async valid => {
          if (valid) {
            params = cloneDeep(this.loginForm)
            // 获取随机请求id-登录密码加密
            await this.getSecretKey(params)
            this.logIn(params)
          } else {
            params = false
          }
        })
      }
    },
    // 登录
    logIn(params) {
      if (params) {
        params = { ...params, ...{ type: this.active }}
        this.loading = true
        this.$store.dispatch('user/login', params)
          .then(() => {
            if (getToken()) {
              location.href = this.redirect || process.env.VUE_APP_ROUTER
            }
            this.loading = false
          })
          .catch(() => {
            // 失败，清空验证码们，并重新获取图形验证码
            this.$refs.msgValidateRef && this.$refs.msgValidateRef.clearInit()
            this.fetchVerifyGraphic()
            this.loading = false
          })
      }
    },
    // 获取随机请求id-登录密码加密
    async getSecretKey(params) {
      const { requestId, secretKey } = await getLoginSecretKey()
      params.requestId = requestId
      params.password = getJMJqueryParams(params.password, secretKey)
    },
    // 忘记密码
    forgetPassword() {
      this.$emit('forgetPassword')
    }
  }
}
</script>

<style lang="scss">
  .login-tab{
    .login-tabs {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      .login-tab-pane {
        font-size: 20px;
        font-weight: 600;
        color: #212026;
        line-height: 28px;
        cursor: pointer;
        // &:first-child {
        //   padding-right: 62px;
        //   border-right: 1px dashed #ccc;
        // }
      }
      .tab-line {
        width: 1px;
        height: 34px;
        background: url(../../../assets/img/login-line.svg) no-repeat 0 0;
        background-size: 100% 100%;
      }
      .tab-active {
        padding-bottom: 8px;
        border-bottom: 2px solid #2A68FF;
        color: #2A68FF;
      }
    }
    .login-form {
      width: 100%;

      .btn-send-sms {
        background-color: #ffffff;
        border-color: #2A68FF;
        color: #2A68FF;
        height: 36px;
        padding: 0;
        width: 120px;
      }

      .phone-captcha {
        display: flex;
        .captcha-img-wrap {
          align-items: center;
          display: flex;
          margin-top: 1px;
          .captch-img {
            flex-shrink: 0;
            width: 90px;
            height: 40px;
          }
          .refresh-captcha {
            cursor: pointer;
            font-size: 20px;
            width: 20px;
            height: 20px;
            margin-left: 4px;
          }
        }
        .el-button {
          margin-left: 10px;
          flex: none;
          width: 120px;
        }
        .captch-img {
          width: 90px;
          height: 40px;
          margin-top: -6px;
        }
      }
      .input-wrap {
        display: flex;
      }
      .forget-password {
        display: flex;
        justify-content: flex-end;
        .el-button {
          padding: 24px 0 0;
        }
      }
    }
    .btn-login {
        background: #3269FF;
        border-radius: 4px;
        font-size: 16px;
        width: 100%;
        height: 48px;
        margin-top: 46px;
      }
  }

</style>
