<template>
  <div class="login">
    <div
      class="login-title"
      :style="{ paddingBottom: loginTabs.length > 1 ? '14px' : '50px' }"
    >
      {{ systemName }}
    </div>
    <div v-if="loginTabs.length > 1" class="login-way">
      <div v-for="item in loginTabs" :key="item.value" class="login-way-item">
        <span
          class="login-way-text"
          :class="activeLoginWay === item.value && 'is-active'"
          @click="() => toggleLoginWay(item.value)"
        >
          {{ item.label }}
        </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
        :style="{
          paddingBottom: activeLoginWay === 'LOGIN_TYPE_SCAN' ? '48px' : 0,
        }"
      >
        <a-input
          id="username"
          ref="username"
          v-model="form.username"
          :auto-focus="activeLoginWay === 'LOGIN_TYPE_SCAN'"
          autocomplete="autocomplete"
          size="large"
          :placeholder="usernamePlaceholder"
        >
          <a-icon slot="prefix" type="user" />
        </a-input>
      </a-form-model-item>
      <a-form-model-item
        v-if="activeLoginWay !== 'LOGIN_TYPE_SCAN'"
        style="margin-bottom: 48px"
      >
        <a-input
          id="password"
          v-model="form.password"
          size="large"
          autocomplete="autocomplete"
          type="password"
          :placeholder="passwordPlaceholder"
        >
          <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: undefined,
        password: undefined,
        tenantId: undefined,
        boundUrl: "",
      },
      activeLoginWay: "LOGIN_TYPE_PWD", // 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";
    },
    loginTabs() {
      const tmp = [];
      if (this.systemConfig?.LOGIN_TYPE_PWD === "Y") {
        tmp.push({
          label: this.$t("ACCOUNT_LOGIN"),
          value: "LOGIN_TYPE_PWD",
        });
      }
      if (this.systemConfig?.LOGIN_TYPE_AD === "Y") {
        tmp.push({
          label: this.$t("DOMAIN_LOGIN"),
          value: "LOGIN_TYPE_AD",
        });
      }
      if (this.systemConfig?.LOGIN_TYPE_SCAN === "Y") {
        tmp.push({
          label: this.$t("SCAN_LOGIN"),
          value: "LOGIN_TYPE_SCAN",
        });
      }
      return tmp;
    },
    usernamePlaceholder() {
      if (this.activeLoginWay === "LOGIN_TYPE_PWD") {
        return this.$t("USER_NAME");
      }
      if (this.activeLoginWay === "LOGIN_TYPE_AD") {
        return this.$t("DOMAIN_NAME");
      }
      if (this.activeLoginWay === "LOGIN_TYPE_SCAN") {
        return this.$t("SCAN_LOGIN");
      }
      return "";
    },
    passwordPlaceholder() {
      if (this.activeLoginWay === "LOGIN_TYPE_PWD") {
        return this.$t("PASSWORD");
      }
      if (this.activeLoginWay === "LOGIN_TYPE_AD") {
        return this.$t("DOMAIN_PASSWORD");
      }
      return "";
    },
    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: {
    "systemConfig.DEFALUT_LOGIN_TYPE": {
      handler(newVal) {
        const val = newVal || this.loginTabs?.[0]?.value || "LOGIN_TYPE_PWD";
        this.toggleLoginWay(val);
      },
      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) {
      if (this.activeLoginWay !== way) {
        this.activeLoginWay = way;
        this.form.username = undefined;
        this.form.password = undefined;
      }

      this.$nextTick(() => {
        if (this.activeLoginWay === "LOGIN_TYPE_SCAN") {
          this.$refs.username.focus();
        }
      });
    },
    // 登录
    onSubmit(e) {
      e && e.preventDefault();
      const params = new URLSearchParams();
      let username, password;
      if (this.activeLoginWay === "LOGIN_TYPE_AD") {
        params.append("type", "AD");
      } else if (this.activeLoginWay === "LOGIN_TYPE_SCAN") {
        params.append("type", "SCAN");

        [username, password] = (this.form.username || "").split(",") || []
        if ([username, password].filter(item => item).length < 2) {
          this.$message.error(this.$t("SCAN_LOGIN_TIP"))
          return;
        }
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.logging = true;
          params.append("username", username || this.form.username);
          params.append(
            "passValue",
            encryption({
              data: {
                password: password || this.form.password
              },
              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");
          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: "",
            };
          }
          const $auth = this.$auth || this.instance?.$auth || null;
          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;
          }
        }
      });
    },
  },
};
</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>
