<style lang="less">
@import "./login.less";
</style>

<template>
  <div class="login" @keydown.enter="handleSubmit" v-if="!isSso">
    <!--<div class="logo"></div>-->
    <!--<div class="login-title"></div>-->
    <p class="copyright">{{$t('module.login.copyright')}}</p>

    <div class="login-con run-login-con">
      <Card :bordered="false">
        <p slot="title">
          <!-- <Icon type="log-in"></Icon> -->
          {{$t('module.login.welcomeLogin')}}
        </p>
        <div class="form-con">
          <Form ref="loginForm" :model="form" :rules="rules">
            <FormItem prop="userCode">
              <Input v-model="form.userCode" :placeholder="$t('module.login.account')" @on-change="checkRemember">
              <span slot="prepend">
                <Icon :size="20" type="md-person"></Icon>
              </span>
              </Input>
            </FormItem>
            <FormItem prop="password">
              <Input type="password" v-model="form.password" :placeholder="$t('module.login.password')">
              <span slot="prepend">
                <Icon :size="17" type="md-lock"></Icon>
              </span>
              </Input>
            </FormItem>
            <FormItem prop="captcha" v-if="hasCaptcha()">
              <div style="display:table;">
                <div class="ivu-col ivu-col-span-15">
                  <Input v-model="form.captcha" :placeholder="$t('module.login.verificationCode')">
                  <span slot="prepend">
                    <Icon :size="17" type="ios-barcode"></Icon>
                  </span>
                  </Input>
                </div>
                <!-- 验证码 -->
                <div class="ivu-col ivu-col-span-9">
                  <div class="run-log-yzm" @click="generateCaptchaUrl">
                    <img :src="captchaUrl">
                  </div>
                </div>
              </div>
            </FormItem>
            <FormItem>
              <Button class="ivu-btn-hr" @click="handleSubmit" :loading="handleSubmitState" type="primary" long>{{$t('module.login.login')}}</Button>
            </FormItem>
            <FormItem>
              <!-- 选中时 addName：checkbox-wrapper-checked -->
              <label class="ivu-checkbox-wrapper ivu-checkbox-group-item">
                <!-- 选中时 addName：ivu-checkbox-checked -->
                <Checkbox v-model="remember" @on-change="toggleRemember">{{$t('module.login.rememberPass')}}</Checkbox>
              </label>

              <a style="float:right;">{{$t('module.login.forgetPass')}}</a>
            </FormItem>
          </Form>
          <p class="login-tip"></p>
        </div>
      </Card>
    </div>
  </div>
</template>

<script>
import CryptoJS from "crypto-js";
import Cookies from "js-cookie";
import Vue from "vue";

// 密码过期
const PASSWORD_OVERDUE = "1";
// 密码不符合规则
const PASSWORD_RULE = "2";

export default {
  data() {
    return {
      form: {
        userCode: "",
        password: "",
        captcha: ""
      },
      rules: {
        userCode: [{ required: true, message: this.$t("module.login.accountEmpty"), trigger: "blur" }],
        password: [{ required: true, message: this.$t("module.login.passEmpty"), trigger: "blur" }],
        captcha: [{ required: true, message: this.$t("module.login.enterVc"), trigger: "blur" }]
      },
      captchaUrl: "",
      remember: false,
      handleSubmitState: false
    };
  },
  computed: {
    isSso() {
      return !!process.env.API.sso;
    }
  },
  created() {
    this.$store.commit("clearOpenedSubmenu");
  },
  mounted() {
    if (!!localStorage.remember && !!localStorage.member) {
      Object.assign(this.form, JSON.parse(localStorage.member));
      this.$nextTick(() => {
        this.remember = true;
      });
    }
    this.generateCaptchaUrl();
  },
  methods: {
    handleSubmit() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.handleSubmitState = true;
          this.form.userCode = this.form.userCode.Trim();
          this.form.password = this.form.password.Trim();
          this.form.captcha = this.form.captcha.Trim();
          $store
            .dispatch("SingnIn", {
              params: this.encrypt(JSON.stringify(this.form))
            })
            .then(res => {
              if (res.statusCode != 0) {
                this.$Message.warning({
                  content: res.msg,
                  duration: 3
                });
                this.generateCaptchaUrl();
                this.handleSubmitState = false;
                return;
              }
              if (!!localStorage.remember) {
                localStorage.member = JSON.stringify({
                  userCode: this.form.userCode,
                  password: this.form.password
                });
              } else {
                localStorage.member = "";
              }
              sessionStorage.crctoken = res.dataResult.crctoken;
              $axios.defaults.headers.crctoken = sessionStorage.crctoken;
              // 如果密码过期或者不符合规则
              if (res.extra && (res.extra.loginStatus == PASSWORD_OVERDUE || res.extra.loginStatus == PASSWORD_RULE)) {
                // 强制修改密码
                this.$router.push({
                  name: "reset-password"
                });
                return;
              }
              let lastPath = this.$route.query.path;
              let lastUserCode = window.localStorage.userCode;
              let route;
              if (lastPath && lastUserCode && lastUserCode === this.form.userCode) {
                route = {
                  path: this.$route.query.path
                };
              } else {
                window.localStorage.userCode = this.form.userCode;
                route = {
                  name: $store.getters.homePage.name
                };
              }

              this.$router.push(route);
            });
        }
      });
    },
    encrypt(data) {
      var key = CryptoJS.enc.Latin1.parse(process.env.API.key.substring(0, 16));
      var iv = CryptoJS.enc.Latin1.parse(process.env.API.key.substring(0, 16));
      return CryptoJS.AES.encrypt(data, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
      }).toString();
    },
    decrypt(word) {
      var key = CryptoJS.enc.Utf8.parse(process.env.API.key.substring(0, 16)); //16位
      var iv = CryptoJS.enc.Utf8.parse(process.env.API.key.substring(0, 16));
      var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
      var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
      var decrypt = CryptoJS.AES.decrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      });
      var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
      return decryptedStr.toString();
    },
    generateCaptchaUrl() {
      this.captchaUrl = `${process.env.API.baseURL}/sys/login/captcha?${Math.random()}`;
    },
    toggleRemember() {
      localStorage.remember = this.remember ? "0" : "";
    },
    checkRemember() {
      if (!!localStorage.member) {
        localStorage.member = "";
        this.remember = false;
        this.form.password = "";
      }
    },
    hasCaptcha() {
      return !!Vue.prototype.$Login ? !!Vue.prototype.$Login.hasCaptcha : false;
    }
  }
};
</script>

<style>
</style>
