<template>
  <div class="login">
    <div
      class="login-title"
      :style="{ paddingBottom: showDomainLogin ? '14px' : '50px' }"
    >
      {{ systemName }}
    </div>
    <div v-if="showDomainLogin" class="login-way">
      <div class="login-way-item">
        <span
          class="login-way-text"
          :class="baseLogin && 'is-active'"
          @click="() => toggleLoginWay('base')"
        >
          {{ $t("ACCOUNT_LOGIN") }}
        </span>
      </div>
      <div class="login-way-item">
        <span
          class="login-way-text"
          :class="!baseLogin && 'is-active'"
          @click="() => toggleLoginWay('domain')"
        >
          {{ $t("DOMAIN_LOGIN") }}
        </span>
      </div>
    </div>
    <a-form-model ref="form" :model="form" :rules="rules" @submit="onSubmit">
      <a-form-model-item v-if="tenantOpen && tenantDropDown">
        <a-select
          v-model="form.tenantId"
          show-search
          allow-clear
          :placeholder="$t('TENANT')"
          :filter-option="false"
          :default-active-first-option="false"
          @search="handSearch"
        >
          <a-select-option
            v-for="item in tenantIdList"
            :key="item.id"
            :value="item.id"
          >
            {{ item.tenantName }}
          </a-select-option>
        </a-select>
        <a-icon class="tenantIcon" type="team" />
      </a-form-model-item>
      <a-form-model-item v-if="tenantOpen && tenantDropDown === false">
        <a-input
          v-model="form.tenantId"
          :placeholder="$t('TENANT')"
          onkeyup="value=value.replace(/[@#\$%\^&\*]/g, '')"
          @blur="handBlur"
        >
          <a-icon slot="prefix" type="team" />
        </a-input>
      </a-form-model-item>
      <a-form-model-item>
        <a-input
          id="username"
          v-model="form.username"
          autocomplete="autocomplete"
          size="large"
          :placeholder="baseLogin ? $t('USER_NAME') : $t('DOMAIN_NAME')"
        >
          <a-icon slot="prefix" type="user" />
        </a-input>
      </a-form-model-item>
      <a-form-model-item style="margin-bottom: 48px">
        <a-input
          id="password"
          v-model="form.password"
          size="large"
          autocomplete="autocomplete"
          type="password"
          :placeholder="baseLogin ? $t('PASSWORD') : $t('DOMAIN_PASSWORD')"
        >
          <a-icon slot="prefix" type="lock" />
        </a-input>
      </a-form-model-item>
      <a-form-model-item style="margin-bottom: 0">
        <a-button
          :loading="logging"
          block
          size="large"
          html-type="submit"
          type="primary"
        >
          {{ $t("LOGIN") }}
        </a-button>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>

<script>
import { encryption } from "@mega-apps/utils";
import Settings from "@/config/settings";
import ApiConstant from "@/api/ApiConstant";

export default {
  props: {
    // eslint-disable-next-line vue/require-default-prop
    onSuccess: Function,
    onError: Function,
  },
  data() {
    return {
      logging: false,
      tenantIdList: [],
      form: {
        username: "",
        password: "",
        tenantId: undefined,
        boundUrl: "",
      },
      activeLoginWay: "base", // base domain
    };
  },
  computed: {
    instance() {
      if (window) {
        return window.$nuxt;
      }
      return null;
    },
    systemConfig() {
      return this.$store.state.app.systemConfig;
    },
    i18nReady() {
      return this.$store.state.app.i18nReady;
    },
    systemName() {
      return this.systemConfig?.SYSTEM_TITLE || Settings.title;
    },
    tenantOpen() {
      return this.systemConfig?.TENANT_OPEN === "true";
    },
    tenantDropDown() {
      return this.systemConfig?.TENANT_LOGIN_SELECT === "true";
    },
    showDomainLogin() {
      return [1, "1"].includes(this.systemConfig.DOMAIN_LOGIN_FLAG);
    },
    baseLogin() {
      return this.activeLoginWay === "base";
    },
    rules() {
      return {
        username: [
          {
            required: true,
            trigger: "blur",
            message: this.$t("ENTER_USER_NAME"),
          },
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            message: this.$t("PLEASE_INPUT_PASSWORD"),
          },
        ],
        tenantId: [
          {
            required: true,
            trigger: "blur",
            message: this.$t("PLEASE_INPUT_PASSWORD"),
          },
        ],
      };
    },
  },
  watch: {
    showDomainLogin: {
      handler(val) {
        this.activeLoginWay = val ? "domain" : "base";
      },
      immediate: true,
    },
    "form.tenantId": {
      handler(val) {
        if (val === undefined) {
          this.handSearch("");
        }
      },
    },
  },
  mounted() {
    // 清空动态路由
    const $axios = this.$axios || this.instance?.$axios || null;
    $axios &&
      $axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/tenant/list-open`)
        .then((res) => {
          this.tenantIdList = res.data.data;
        });
  },
  methods: {
    handBlur() {
      // eslint-disable-next-line no-useless-escape
      this.form.tenantId = this.form.tenantId.replace(/[@#\$%\^&\*]/g, "");
      if (this.form.tenantId !== undefined && this.form.tenantId) {
        const $axios = this.$axios || this.instance?.$axios || null;
        $axios &&
          $axios
            .get(
              `${ApiConstant.PREFIX_CORE}/api/sys/tenant/get-id-by-name?tenantName=${this.form.tenantId}`
            )
            .then((res) => {
              this.$store.commit("account/SET_TENANT_ID", res.data.data);
            })
            .catch(() => {
              this.form.tenantId = undefined;
            });
      }
    },
    handSearch(val) {
      /* eslint-disable */
      val = val.replace(/[@#\$%\^&\*]/g, "");
      const $axios = this.$axios || this.instance?.$axios || null;
      $axios &&
        $axios
          .get(`${ApiConstant.PREFIX_CORE}/api/sys/tenant/list-open?key=${val}`)
          .then((res) => {
            this.tenantIdList = res.data.data;
          });
    },
    toggleLoginWay(way) {
      this.activeLoginWay = way;
    },
    // 登录
    onSubmit(e) {
      e && e.preventDefault();
      if (this.baseLogin) {
        this.handleBaseLogin();
      } else {
        this.handleDomainLogin();
      }
    },
    handleBaseLogin() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.logging = true;
          const params = new URLSearchParams();
          params.append("username", this.form.username);
          params.append(
            "passValue",
            encryption({
              data: this.form,
              key: "1234567887654321",
              param: ["password"],
            }).password
          );
          params.append("grant_type", "password");
          params.append("scop", "all");
          params.append("client_id", "client_core");
          params.append("client_secret", "123456");
          const $auth = this.$auth || this.instance?.$auth || null;
          let headers = {};
          if (
            this.tenantOpen &&
            this.form.tenantId !== undefined &&
            this.form.tenantId !== "" &&
            this.tenantDropDown === true &&
            this.form.tenantId
          ) {
            headers = {
              "Content-type": "application/x-www-form-urlencoded",
              Authorization: "",
              tenantId:
                this.form.tenantId !== undefined &&
                this.form.tenantId &&
                this.form.tenantId !== ""
                  ? this.form.tenantId
                  : undefined,
            };
            this.$store.commit("account/SET_TENANT_ID", this.form.tenantId);
          } else {
            headers = {
              "Content-type": "application/x-www-form-urlencoded",
              Authorization: "",
            };
          }
          if ($auth) {
            $auth
              .login({
                headers,
                data: params,
              })
              .then((res) => {
                this.logging = false;
                // 登录框已显示 不重复展示
                this.$store.commit("account/SET_IS_INVALID", false);
                typeof this.onSuccess === "function" &&
                  this.onSuccess(res.data);
              })
              .catch((err) => {
                this.logging = false;
                // 登录失败跳转授权页处理
                typeof this.onError === "function" && this.onError(err);
              });
          } else {
            this.logging = false;
          }
        }
      });
    },
    handleDomainLogin() {
      this.$emit("loginSuccess");
    },
  },
};
</script>

<style lang="less" scoped>
@import (optional, once) "../../theme/index.less";

.login {
  width: 412px;
  padding: 56px 32px;
  border-radius: 6px;
  background-color: #fff;
  box-shadow: 0 0 5px @base-bg-color;
  .login-title {
    text-align: center;
    font-size: 20px;
    font-weight: bold;
  }
  .login-way {
    display: flex;
    margin-bottom: 24px;
    &-item {
      position: relative;
      flex: 1;
      text-align: center;
      color: @text-color-second;
      font-weight: 500;
    }
    &-text {
      position: relative;
      display: inline-block;
      padding: 0 12px;
      line-height: 40px;
      cursor: pointer;
      &::after {
        content: "";
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 2px;
        border-radius: 1px;
        background-color: transparent;
      }
      &.is-active {
        color: @primary-color;
        &::after {
          background-color: @primary-color;
        }
      }
    }
  }
  /deep/ .ant-select-selection__rendered {
    margin-left: 27px;
    position: relative;
  }
  .tenantIcon {
    position: absolute;
    left: 10px;
    top: 3px;
    font-size: 14px;
  }
}
</style>
