<template>
  <div class="login-container">
    <!-- 顶部工具栏 -->
    <div class="top-bar">
      <el-switch
        v-model="isDark"
        inline-prompt
        active-icon="Moon"
        inactive-icon="Sunny"
        @change="toggleTheme"
      />
      <lang-select class="ml-2 cursor-pointer" />
    </div>
    <!-- 登录表单 -->
    <el-card class="login-card">
      <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="phone">
          <div class="input-wrapper">
            <i-ep-phone class="mx-2" />
            <el-input
              ref="phone"
              v-model="loginData.phone"
              :placeholder="$t('login.phone')"
              name="phone"
              size="large"
              class="h-[48px]"
            />
          </div>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="code">
          <div class="input-wrapper">
            <i-ep-key class="mx-2" />
            <el-input
              v-model="loginData.code"
              :placeholder="$t('login.code')"
              name="code"
              @keyup.enter="handleLoginSubmit"
              size="large"
              class="h-[48px] pr-2"
              type="password"
            >
              <!-- <template #suffix>
                <el-text
                  v-if="seconds === 0"
                  class="mx-1 cursor-pointer"
                  type="primary"
                  @click="getCode"
                >
                  获取验证码
                </el-text>
                <el-text v-else class="mx-1 cursor-pointer" type="primary">
                  {{ seconds }}s后重新发送
                </el-text>
              </template> -->
            </el-input>
          </div>
        </el-form-item>

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

    <!-- ICP备案 -->
    <!-- <div class="icp-info" v-show="icpVisible">
      <p>
        Copyright © 2021 - 2024 youlai.tech All Rights Reserved. 有来技术
        版权所有
      </p>
      <p>皖ICP备20006496号-3</p>
    </div> -->
  </div>
</template>

<script setup lang="ts">
// 外部库和依赖
import { LocationQuery, useRoute } from "vue-router";

// 内部依赖
import { useSettingsStore, useUserStore, usePermissionStore } from "@/store";
import AuthAPI, { LoginData } from "@/api/auth";
import router from "@/router";
import defaultSettings from "@/settings";
import { ThemeEnum } from "@/enums/ThemeEnum";

// 类型定义
import type { FormInstance } from "element-plus";

// 导入 login.scss 文件
import "@/styles/login.scss";

import { CODE_KEY, CODE_NAME } from "@/enums/CacheEnum";

// 使用导入的依赖和库
const userStore = useUserStore();
const settingsStore = useSettingsStore();
const permissionStore = usePermissionStore();
const route = useRoute();
// 窗口高度
const { height } = useWindowSize();
// 国际化 Internationalization
const { t } = useI18n();

// 是否暗黑模式
const isDark = ref(settingsStore.theme === ThemeEnum.DARK);
// 是否显示 ICP 备案信息
const icpVisible = ref(true);
// 按钮 loading 状态
const loading = ref(false);
// 验证码图片Base64字符串
const captchaBase64 = ref();
// 登录表单ref
const loginFormRef = ref<FormInstance>();

const loginData = ref<LoginData>({
  phone: "",
  code: "",
} as LoginData);

const seconds = ref(0);

const loginRules = computed(() => {
  return {
    phone: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.phone.required"),
      },
    ],
    code: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.code.required"),
      },
      {
        min: 4,
        message: t("login.message.code.min"),
        trigger: "blur",
      },
    ],
  };
});

/** 获取验证码之前先判断手机号对应的货场信息 */
const getCode = () => {
  if (loginData.value.phone) {
    AuthAPI.getCommonDbPhone({ phone: loginData.value.phone }).then((res) => {
      if (res.length > 0) {
        localStorage.setItem(CODE_KEY, res[0].mechanismCode);
        localStorage.setItem(CODE_NAME, res[0].mechanismName);

        // 需存储mechanismCode信息保存到header中
        AuthAPI.getCaptcha({ phone: loginData.value.phone }).then((res) => {
          if (res) {
            ElNotification({
              title: "提示",
              message: "验证码已发送",
              type: "success",
            });
            seconds.value = 60;
            let countDownTimer = setInterval(() => {
              if (seconds.value > 0) {
                --seconds.value;
              } else {
                clearInterval(countDownTimer);
              }
            }, 1000);
          }
        });
      } else {
        ElNotification({
          title: "提示",
          message: "当前号码未加入货场",
          type: "error",
        });
      }
    });
  } else {
    ElNotification({
      title: "提示",
      message: "请先输入手机号",
      type: "error",
    });
  }
};
/** 登录表单提交 */
function handleLoginSubmit() {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      router.push({ path: "/" });
      loading.value = true;
      userStore
        .login(loginData.value)
        .then(() => {
          router.push({ path: "/" });
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

/** 解析 redirect 字符串 为 path 和  queryParams */
function parseRedirect(): {
  path: string;
  queryParams: Record<string, string>;
} {
  const query: LocationQuery = route.query;
  const redirect = (query.redirect as string) ?? "/";

  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams: Record<string, string> = {};

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });

  return { path, queryParams };
}

/** 主题切换 */
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;
  }
});

onMounted(() => {});
</script>

<style lang="scss" scoped></style>
