<template>
  <div class="login-container">
    <el-card
      class="!border-none !rounded-4% w-100 <sm:w-85"
      style="background-color: #a0a8b2"
    >
      <div class="text-center relative">
        <h2>{{ defaultSettings.title }}</h2>
        <el-tag class="ml-2 absolute-rt">{{ defaultSettings.version }}</el-tag>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginData"
        :rules="loginRules"
        class="login-form"
      >
        <!-- 用户名 -->
        <el-form-item prop="userName">
          <div class="flex-y-center w-full">
            <svg-icon class="mx-2" icon-class="user" />
            <el-input
              ref="username"
              v-model="loginData.userName"
              class="h-[48px]"
              name="userName"
              placeholder="请输入账号"
              size="large"
            />
          </div>
        </el-form-item>

        <!-- 密码 -->
        <el-tooltip
          :content="$t('login.capsLock')"
          :visible="isCapslock"
          placement="right"
        >
          <el-form-item prop="password">
            <div class="flex-y-center w-full">
              <svg-icon class="mx-2" icon-class="lock" />
              <el-input
                v-model="loginData.password"
                :placeholder="$t('login.password')"
                class="h-[48px] pr-2"
                name="password"
                show-password
                size="large"
                type="password"
              />
            </div>
          </el-form-item>
        </el-tooltip>

        <!-- 登录按钮 -->
        <el-button
          :loading="loading"
          class="w-full"
          size="large"
          type="primary"
          @click.prevent="handleLogin"
          >{{ $t("login.login") }}
        </el-button>

        <!-- 账号密码提示 -->
        <!-- <div class="mt-10 text-sm">
          <span>{{ $t("login.username") }}: admin</span>
          <span class="ml-4"> {{ $t("login.password") }}: 123456</span>
        </div> -->
      </el-form>
    </el-card>

    <!-- ICP备案 -->
    <div v-show="icpVisible" class="absolute bottom-1 text-[10px] text-center">
      <p>Copyright © 2022-2025 jgai.com All Rights Reserved.</p>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useSettingsStore, useUserStore } from "@/store";
import { getCaptchaApi } from "@/api/auth";
import { LoginData } from "@/api/auth/types";
import { LocationQuery, LocationQueryValue, useRoute } from "vue-router";
import router from "@/router";
import defaultSettings from "@/settings";
import { ThemeEnum } from "@/enums/ThemeEnum";
// Stores
const userStore = useUserStore();
const settingsStore = useSettingsStore();

// Internationalization
const { t } = useI18n();

// Reactive states
const isDark = ref(settingsStore.theme === ThemeEnum.DARK);
const icpVisible = ref(true);
const orgList = ref([]);
const loading = ref(false); // 按钮loading
const isCapslock = ref(false); // 是否大写锁定
const captchaBase64 = ref(); // 验证码图片Base64字符串
const loginFormRef = ref(ElForm); // 登录表单ref
const { height } = useWindowSize();

const loginData = ref<LoginData>({
  userName: "",
  password: "",
});

const loginRules = computed?.(() => {
  return {
    userName: [
      {
        required: true,
        trigger: "blur",
        message: "请输入账号",
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.password.required"),
      },
      {
        min: 6,
        message: t("login.message.password.min"),
        trigger: "blur",
      },
    ],
  };
});

/**
 * 获取验证码
 */
function getCaptcha() {
  getCaptchaApi().then(({ data }) => {
    loginData.value.captchaKey = data.captchaKey;
    captchaBase64.value = data.captchaBase64;
  });
}

/**
 * 登录
 */
const route = useRoute();

function handleLogin() {
  loginFormRef.value.validate((valid: boolean) => {
    loginData.value.userName = loginData.value.userName.trim();
    if (valid) {
      loading.value = true;
      userStore
        .login(loginData.value)
        .then(async () => {
          const query: LocationQuery = route.query;
          const redirect = (query.redirect as LocationQueryValue) ?? "/";
          const otherQueryParams = Object.keys(query).reduce(
            (acc: any, cur: string) => {
              if (cur !== "redirect") {
                acc[cur] = query[cur];
              }
              return acc;
            },
            {}
          );
          router.push({ path: redirect, query: otherQueryParams });
        })
        .catch(() => {
          // getCaptcha();
          console.log("catch");
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

/**
 * 主题切换
 */

const toggleTheme = () => {
  //const newTheme = settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  //settingsStore.changeTheme(newTheme);
};
/**
 * 根据屏幕宽度切换设备模式
 */

watchEffect?.(() => {
  if (height.value < 600) {
    icpVisible.value = false;
  } else {
    icpVisible.value = true;
  }
});

/**
 * 检查输入大小写
 */
function checkCapslock(e: any) {
  isCapslock.value = e.getModifierState("CapsLock");
}

onMounted?.(() => {
  toggleTheme();
});
</script>

<style lang="scss" scoped>
html.dark .login-container {
  background: url("@/assets/images/login-bg.png") no-repeat center right;
}

.login-container {
  overflow-y: auto;
  background: url("@/assets/images/login-bg.png") no-repeat center right;
  background-size: cover;

  @apply wh-full flex-center;

  .login-form {
    padding: 30px 10px;
  }
}

.el-form-item {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      /* 通过延时渲染背景色变相去除背景颜色 */
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}

:deep(.el-select) {
  .el-select__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      /* 通过延时渲染背景色变相去除背景颜色 */
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}

:deep(.el-select__placeholder) {
  color: rgba(0, 0, 0, 0.9);
}

:deep(.el-select__placeholder.is-transparent) {
  color: rgba(0, 0, 0, 0.3);
}

:deep(.el-input__inner::placeholder) {
  color: rgba(0, 0, 0, 0.3);
}

:deep(.el-input__inner) {
  color: rgba(0, 0, 0, 0.9);
}

:deep(.el-select) {
  .el-select__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      /* 通过延时渲染背景色变相去除背景颜色 */
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}
</style>
