<template>
  <el-form ref='form' :rules='rules' :model='form' class='login-form' size='small'>
    <el-form-item prop='username'>
      <el-input prefix-icon='el-icon-user' v-model='form.username' placeholder='请输入用户名'></el-input>
    </el-form-item>
    <el-form-item prop='password'>
      <el-input v-model='form.password' :type='inputType' placeholder='请输入密码' prefix-icon='el-icon-lock'>
        <template slot='append'>
          <img style='width: 20px; cursor: pointer' :src="pwdIcon" @click='showPass'
               alt=''></template>
      </el-input>
    </el-form-item>
    <el-form-item prop='multiAccount' v-if='multiAccountShow'>
      <el-select v-model='form.multiAccount' placeholder='请选择' style='width: 100%'>
        <el-option
          v-for='item in multiAccountList'
          :key='item.accId'
          :label="item.accountSen + '(' + item.tenantName + ')'"
          :value='item.accId'
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop='captchaCode'>
      <el-input
        prefix-icon='el-icon-key'
        v-model='form.captchaCode'
        placeholder='图片验证码'
        maxlength='4'
        @keyup.enter.native='toLogin'
      >
        <template slot='suffix'>
          <img class='imageCode' :src='imageCode' alt='图形验证码' @click='fetchDigitCaptcha' />
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop='smsCode'>
      <el-input prefix-icon='el-icon-message' v-model='form.smsCode' maxlength='6' placeholder='短信验证码'>
        <template slot='suffix'>
          <el-button class='smsBtn' type='text' :disabled='smsBtn.disable' @click='sendSmsCodeFn'>
            {{ smsBtn.btnName }}
          </el-button>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
</template>

<script>
import { fetchDigitCaptcha, sendLoginSmsCode, fetchMultiAccount } from '@api/api-login';
import { encryptByAES } from '@utils/util';
import { isUsername, isMobile } from '@utils/validate';

export default {
  name: 'LoginForm',
  data() {
    let validateUsername = (rule, value, callback) => {
      if (!isUsername(value) && !isMobile(value)) {
        return callback(new Error('请输入正确的用户名'));
      } else {
        return callback();
      }
    };
    return {
      multiAccountList: [],
      multiAccountShow: false,
      smsBtn: {
        btnName: '发送验证码',
        disable: false,
        seconds: 60,
        intervalObj: null
      },
      imageCode: '',
      form: {
        username: '',
        password: '',
        captchaKey: '',
        captchaCode: ''
      },
      rules: {
        username: [{ required: true, validator: validateUsername, trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        smsCode: [
          { required: true, message: '请输入短信验证码', trigger: 'blur' },
          { len: 6, message: '长度6个字符', trigger: 'blur' }
        ],
        captchaCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { max: 4, message: '最长4个字符', trigger: 'blur' }
        ]
      },
      showPwd: false,
      inputType: 'password',
      pwdIcon: require('@/assets/icon/biyan.png')
    };
  },
  mounted() {
    this.fetchDigitCaptcha();
  },
  methods: {
    toLogin() {
      let vm = this;
      let pwd = vm.form.password;
      this.$refs.form.validate((valid) => {
        if (valid) {
          let form = {
            username: encryptByAES(vm.form.username),
            password: encryptByAES(vm.form.password),
            smsCode: vm.form.smsCode,
            captchaKey: vm.form.captchaKey,
            captchaCode: vm.form.captchaCode
          };
          if (vm.multiAccountShow) {
            form.multiAccount = vm.form.multiAccount;
          }
          this.$store
            .dispatch('loginByUsername', form)
            .then((res) => {
              if (res.code === 200) {
                vm.$message.success('登陆成功，请稍候...');
                setTimeout(() => {
                  vm.$router.push({ path: '/' });
                }, 500);
              }
            })
            .catch((error) => {
              let username = vm.form.username;
              if (error.data.code === 'C030103') {
                vm.$message.error(`${error.data.msg}, 请于${error.data.data}秒后重试`);
              } else if (error.data.code === 'C030105') {
                vm.$confirm(error.data.msg, '密码过期提示', {
                  type: 'warning',
                  confirmButtonText: '前往修改',
                  dangerouslyUseHTMLString: true
                })
                  .then(() => {
                    // 弹出修改密码的界面
                    vm.$router.push({ path: '/update-pwd', query: { code: error.data.data } });
                  })
                  .catch(() => {
                    let username = vm.form.username;
                    vm.$refs.form.resetFields();
                    vm.form.username = username;
                    vm.fetchDigitCaptcha();
                  });
              } else if (error.data.code === 'C030111') {
                vm.$message.warning(error.data.msg);
                // 查询出多个账号
                setTimeout(() => {
                  fetchMultiAccount({ username: vm.form.username }).then(
                    (res) => {
                      vm.multiAccountList = res.data;
                      vm.multiAccountShow = true;
                      vm.form.password = pwd;
                      vm.form.captchaCode = '';
                      vm.form.username = username;
                      vm.fetchDigitCaptcha();
                    },
                    (error) => {
                      vm.$message.error(error.data.msg);
                    }
                  );
                }, 1000);
              } else {
                vm.$message.error(error.data.data);
                let username = vm.form.username;
                vm.$refs.form.resetFields();
                vm.form.username = username;
                vm.fetchDigitCaptcha();
              }
            });
        }
      });
    },
    fetchDigitCaptcha() {
      let vm = this;
      fetchDigitCaptcha().then(
        (res) => {
          let key = Object.keys(res.data)[0];
          vm.form.captchaKey = key;
          vm.imageCode = res.data[key];
        },
        (error) => {
          vm.$message.error(error.data.msg);
        }
      );
    },
    sendSmsCodeFn() {
      let vm = this;
      let fieldsToValidate = ['username', 'captchaCode'];
      Promise.all(
        fieldsToValidate.map((item) => {
          return new Promise((resolve, reject) => {
            vm.$refs.form.validateField(item, (errorMsg) => {
              resolve(errorMsg);
            });
          });
        })
      ).then((result) => {
        // result返回各个字段的验证信息，如果为空字符串则认为验证通过
        let error = result.find((res) => {
          return res !== '';
        });
        if (!error) {
          vm.smsBtn.disable = true;
          vm.smsBtn.btnName = '已发送';
          let params = {
            username: encryptByAES(vm.form.username),
            password: encryptByAES(vm.form.password),
            captchaKey: vm.form.captchaKey,
            captchaCode: vm.form.captchaCode
          };
          sendLoginSmsCode(params).then(
            (res) => {
              if (res.code === 200) {
                vm.$message.success(res.msg);
              } else {
                vm.$message.error(res.msg);
              }
              vm.smsBtn.intervalObj = window.setInterval(vm.counter, 1000);
            },
            (error) => {
              vm.$message.error(error.data.msg);
              vm.smsBtn.intervalObj = window.setInterval(vm.counter, 1000);
            }
          );
        }
      });
    },
    counter() {
      let vm = this;
      if (vm.smsBtn.seconds === 0) {
        vm.smsBtn.seconds = 60;
        window.clearInterval(vm.smsBtn.intervalObj); // 停止计时器
        vm.smsBtn.disable = false;
        vm.smsBtn.btnName = '重新发送';
      } else {
        vm.smsBtn.seconds--;
        vm.smsBtn.btnName = vm.smsBtn.seconds + '秒';
      }
    },
    showPass() {
      if (!this.showPwd) {
        this.showPwd = true;
        this.inputType = 'input';
        this.pwdIcon = require('@/assets/icon/kaiyanjing.png');
      } else {
        this.showPwd = false;
        this.inputType = 'password';
        this.pwdIcon = require('@/assets/icon/biyan.png');
      }
    }
  }
};
</script>

<style scoped lang='less'>
.login-form {
  .imageCode {
    position: absolute;
    right: -5px;
    top: 0px;
    cursor: pointer;
    height: 100%;
    width: 100px;
  }

  .smsBtn {
    position: absolute;
    cursor: pointer;
    right: 0;
    width: 100px;
    text-align: center;
    height: 100%;
  }
}

/deep/ .el-input--small .el-input__inner {
  height: 40px;
  line-height: 40px;
}

/deep/ .el-form-item--small.el-form-item {
  margin-bottom: 24px;
}
</style>
