<template>
  <a-modal
    v-model="visible"
    wrap-class-name="login-modal-toast"
    :mask-closable="false"
  >
    <app-login
      ref="loginModel"
      :on-success="handleSuccess"
      :on-error="handleError"
    />
  </a-modal>
</template>

<script>
import mixin from "@/components/AppLogin/mixin";
import AppLogin from "./index";

export default {
  components: { AppLogin },
  mixins: [mixin],
  data() {
    return {
      visible: false,
    };
  },
  computed: {
    instance() {
      if (window) {
        return window.$nuxt;
      }
      return null;
    },
    prevUserId() {
      return this.$store.state.account.prevUserId;
    },
    userId() {
      return this.$store.state.account.userId;
    },
    tenantId() {
      return this.$store.state.account.tenantId;
    },
    user() {
      return this.$store.state.auth.user?.user || {};
    },
  },
  watch: {
    visible: {
      handler(val) {
        val && this.$store.commit("account/SET_PERV_USER_ID", this.userId);
      },
    },
  },
  methods: {
    goReplacePath() {
      const $router = this.$router || this.instance?.$router || null;
      const $route = this.$route || this.instance?.$route || null;
      $router &&
        $router.replace({
          path: `/redirect${$route.path}`,
          query: $route.query || null,
        });
    },
    handleSuccess() {
      this.visible = false;
      // 当前用户
      this.$store.commit("account/SET_USER_ID", this.user.id);
      if (this.userId !== this.prevUserId) {
        // 清空store中的菜单数据
        this.$store.dispatch("account/getUserMenuInfo");
        // 清空tabsview数据
        this.$store.dispatch("tagsView/delAllViews");
        // 登录判断
        this.handleLogin().then(() => {
          if (this.prevUserId) {
            window.location.href = "/";
          } else {
            this.goReplacePath();
          }
        });
      } else {
        this.goReplacePath();
      }
    },
    handleError(err) {
      const { status, data } = err.response || {};
      // eslint-disable-next-line no-prototype-builtins
      if (status === 421 && this.hasOwnProperty("visible")) {
        this.visible = false;
      }
    },
  },
};
</script>
