<template>
  <div>
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      autocomplete="on"
      label-position="left"
      label-width="80px"
    >
      <el-form-item prop="username" :label="$t('login.username')">
        <el-input
          ref="username"
          v-model="loginForm.username"
          :placeholder="$t('login.username')"
          name="username"
          type="text"
          tabindex="1"
        />
      </el-form-item>

      <el-form-item prop="password" :label="$t('login.password')">
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          :placeholder="$t('login.password')"
          name="password"
          tabindex="2"
          autocomplete="on"
          @keyup.native="checkCapslock"
          @blur="capsTooltip = false"
          @keyup.enter.native="handleLogin"
        />
      </el-form-item>

      <div style="display: flex; justify-content: flex-end; margin-top: 20px">
        <el-link
          style="color: #5ba8dc"
          :underline="false"
          href="/ucenter/#/reset-password"
          >{{ $t("login.forget") }}</el-link
        >
      </div>
      <div style="width: 100%; text-align: center; margin-top: 50px">
        <el-button
          :loading="loading"
          type="primary"
          round
          style="width: 70%"
          @click.native.prevent="handleLogin"
          >{{ $t("login.logIn") }}</el-button
        >
      </div>
    </el-form>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import { getInfo } from "@/api/user";
export default {
  name: "UserLogin",
  components: {},
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error("Please enter the correct user name"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("The password can not be less than 6 digits"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          {
            required: true,
            message: this.$t("login.nameRules"),
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: this.$t("login.passwordRules"),
            trigger: "blur",
            validator: validatePassword,
          },
        ],
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      redirect: undefined,
      otherQuery: {},
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    getInfos() {
      getInfo().then((r) => {
        this.loading = false;
        if (r.data.city) {
          this.$router.push({
            path: this.redirect || "/jiedao/jd-profile",
            query: this.otherQuery,
          });
        } else {
          this.$router.push({
            path: "/myInfo",
            query: this.otherQuery,
          });
        }
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          await this.$store.dispatch("user/login", this.loginForm);
          await this.getInfos();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
  },
};
</script>

<style lang="scss" scoped></style>
