<template>
  <div class="login-page">
    <!-- 右上角语言切换按钮 -->
    <div class="login-lang-switch">
      <i18nSwitch />
    </div>

    <div class="login-wrapper">
      <div class="login-header">{{ $t("login.headerTitle") }}</div>

      <div class="login-card">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          @keyup.enter="submit"
          class="login-form"
        >
          <el-form-item prop="username">
            <el-input
              v-model="form.username"
              :placeholder="$t('login.userName')"
              size="large"
            >
              <template #prefix>
                <SvgIcon name="login-user" :size="28" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="form.password"
              type="password"
              :placeholder="$t('login.passWord')"
              size="large"
            >
              <template #prefix>
                <SvgIcon name="login-password" :size="28" />
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-checkbox v-model="remember">{{
              $t("login.jizhu")
            }}</el-checkbox>
          </el-form-item>

          <el-button
            type="primary"
            class="submit-btn"
            :loading="loading"
            size="large"
            @click="submit"
          >
            {{ $t("login.denglu") }}
          </el-button>
        </el-form>

        <div class="login-footer">
          {{ $t("login.copyright") }} <br />
          {{ $t("login.hotline") }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { adminLogin } from "@/service/modular/login";
import { useUserStore } from "@/stores/api/user";
import SvgIcon from "@/components/SvgIcon/index.vue";
import i18nSwitch from "@/components/i18nSwitch/index.vue";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const HOME_BY_TYPE = {
  Admin: "/admin/orders",
  Hospital: "/hospital/workbench",
};

const formRef = ref();
const loading = ref(false);
const remember = ref(false);

const form = reactive({ username: "", password: "" });

const rules = {
  username: [
    {
      required: true,
      message: () => t("login.pleaseEnterUserName"),
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: () => t("login.pleaseEnterPassWord"),
      trigger: "blur",
    },
  ],
};

const submit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    loading.value = true;
    try {
      const data = await adminLogin({
        username: form.username,
        password: form.password,
      });

      const userType = data?.userType;
      const home = HOME_BY_TYPE[userType];

      if (!home) {
        ElMessage.error(t("login.unknownUserType"));
        return;
      }

      const userInfo = {
        userId: data?.userId,
        userName: data?.userName,
        userType: data?.userType,
        hospitalId: data?.hospitalId,
        hospitalName: data?.hospitalName,
        role: data?.role,
        name: data?.name,
        gender: data?.gender,
      };

      userStore.setToken(data?.token || "");
      userStore.setUserInfo(userInfo);

      if (remember.value) {
        localStorage.setItem("csm_remember_account", form.username);
      } else {
        localStorage.removeItem("csm_remember_account");
      }

      ElMessage.success(t("login.loginSuccess"));
      router.replace(route.query.redirect || home);
    } catch (e) {
      // request 层已经 ElMessage.error
    } finally {
      loading.value = false;
    }
  });
};

onMounted(() => {
  const cached = localStorage.getItem("csm_remember_account");
  if (cached) {
    form.username = cached;
    remember.value = true;
  }
});
</script>

<style scoped lang="scss">
.login-page {
  position: relative;
  width: 100vw;
  height: 100vh;
  background-color: #b3defb;
  background-image: url("@/assets/image/login/bg.gif");
  background-position: bottom center;
  background-size: 100% auto;
  background-repeat: no-repeat;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-lang-switch {
  position: absolute;
  top: 64px;
  right: 64px;
  z-index: 10;
}

.login-wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 24px 24px 24px 24px;
  border: 1px solid #fff;
  padding: 47px 50px 32px;
  --el-color-primary: #2b7afa;
}

.login-header {
  font-weight: bold;
  font-size: 32px;
  color: #2b7afa;
  margin-bottom: 48px;
}

.login-card {
}

.login-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  text-align: center;
  margin-bottom: 20px;
}

:deep(.login-form) {
  .el-form-item {
    margin-bottom: 24px;
    width: 368px;
  }

  .el-input__wrapper {
    height: 56px;
    background: #fafafa;
    border-radius: 12px 12px 12px 12px;
    border: 1px solid #e7e9ed;

    &:hover {
      border: 1px solid #97c2fd;
    }

    input {
      font-weight: 400;
      font-size: 16px;
      caret-color: #2b7afa;
      &::placeholder {
        color: #bbbbbb;
      }
    }
  }
}

.submit-btn {
  width: 368px;
  height: 56px;
  font-weight: bold;
  font-size: 18px;
  color: #ffffff;
  border-radius: 12px 12px 12px 12px;
  background: linear-gradient(to right, #2b7afa, #56d2ff);
  border: none;
  // letter-spacing: 0.8em;

  &:hover {
    background: linear-gradient(to right, #5695fb, #77d9ff);
  }

  &:active {
    background: linear-gradient(to right, #2870e1, #4dbbe5);
  }
}

.login-footer {
  font-size: 14px;
  color: #697589;
  text-align: center;
  margin-top: 50px;
}
</style>
