<script lang="ts" setup>
import {
  getStudentInfoBySessionApi,
  getStudentSpecialtyNameListApi,
  loginApi,
} from "@/api/login";
import { DOMAIN, VITE_GIT_REPO_VERSION } from "@/constants/constants";
import { useTimers } from "@/setups/useTimers";
import { store } from "@/store/store";
import { createUserDetailLog } from "@/utils/logger";
import { CloseCircleOutline, LockClosed, Person } from "@vicons/ionicons5";
import { FormItemInst, FormRules } from "naive-ui";
import { onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import GeeTest from "./GeeTest.vue";
import GlobalNotice from "./GlobalNotice.vue";
import { useAppVersion } from "./useAppVersion";
import { getElectronConfig } from "./useElectronConfig";
import { checkExamInProgress } from "./useExamInProgress";
import { getGeeTestConfig } from "./useGeeTestConfig";
import { limitLogin } from "./useLimitLogin";
import { useNewVersion } from "./useNewVersion";

logger({
  cnl: ["console", "local", "server"],
  pgn: "登录页面",
  act: "首次渲染",
});

const { addTimeout } = useTimers();

let isGeeTestEnabled = $ref(false);
onMounted(async () => {
  const conf = await getElectronConfig();
  store.QECSConfig = conf;

  isGeeTestEnabled = await getGeeTestConfig(store.QECSConfig.ROOT_ORG_ID);
});

const QECSConfig = store.QECSConfig;

const logoPath = $computed(() => QECSConfig.LOGO_FILE_URL || "");
const backgroundUrl = $computed(
  () =>
    `url(${
      QECSConfig.STUDENT_CLIENT_BG_PICTURE_URL ||
      "https://cdn.qmth.com.cn/ui/ecs-client-bg.jpg!/progressive/true"
    })`
);
const productName = $computed(
  () => QECSConfig.OE_STUDENT_SYS_NAME || "远程教育网络考试"
);
const allowLoginType = $computed(() => QECSConfig.LOGIN_TYPE ?? []);

const { newVersionAvailable, checkNewVersion } = useNewVersion();
const { disableLoginBtnBecauseAppVersionChecker } =
  useAppVersion(newVersionAvailable);

let disableLoginBtn = $computed(
  () =>
    disableLoginBtnBecauseNotTimeout ||
    (!import.meta.env.DEV &&
      //   (this.disableLoginBtnBecauseRemoteApp ||
      //     this.disableLoginBtnBecauseVCam)) ||
      disableLoginBtnBecauseAppVersionChecker.value)
  // this.disableLoginBtnBecauseRefreshServiceWorker ||
  // this.disableLoginBtnBecauseNotAllowedNative
);

//#region form校验
const domain = DOMAIN;
type FormModel = {
  accountType: "STUDENT_CODE" | "IDENTITY_NUMBER";
  accountValue: string;
  password: string;
  domain: string;
  rootOrgId: string;
};
const formRef: FormItemInst = $ref();
const formValue: FormModel = $ref({
  accountType: "STUDENT_CODE",
  accountValue: "",
  password: "",
  domain,
  rootOrgId: "",
});

const fromRules: FormRules = {
  accountValue: {
    required: true,
    trigger: "blur",
    message: "账号必填",
  },
  password: {
    required: true,
    trigger: "blur",
    message: "密码必填",
  },
};

let errorInfo = $ref("");
watch([formValue], () => (errorInfo = ""));
//#endregion

//#region 极验
type Captcha = {
  appendTo(sel: string): void;
  onReady(cb: () => void): void;
  onError(cb: (error: any) => void): void;
  destroy(): void;
  getValidate(): any;
};
let captchaObj: Captcha = $ref();
let resetGeeTime = $ref(0);
resetGeeTime = Date.now();
// 超过60秒，刷新极验；优化刷新次数，当用户真正想输入时
watch(
  () => [formValue.accountType, formValue.accountValue, formValue.password],
  () => {
    if (isGeeTestEnabled && Date.now() - resetGeeTime > 60 * 1000) {
      captchaObj?.destroy();
      resetGeeTime = Date.now();
    }
  }
);
//#endregion

const router = useRouter();

let loginBtnLoading = $ref(false);
let disableLoginBtnBecauseNotTimeout = $ref(false);
async function loginForuser() {
  if (await checkNewVersion()) return;

  if (await formRef.validate().catch(() => true)) return;

  if (isGeeTestEnabled) {
    if (!captchaObj?.getValidate()) {
      $message.error("请完成验证");
      return;
    }
  }

  loginBtnLoading = true;
  // 登录接口调一次必然间隔10秒以上
  disableLoginBtnBecauseNotTimeout = true;
  addTimeout(() => (disableLoginBtnBecauseNotTimeout = false), 10 * 1000);

  if (await limitLogin()) {
    loginBtnLoading = false;
    return;
  }

  logger({
    pgn: "登录页面",
    cnl: ["local", "server"],
    act: "login clicked",
    ext: { UA: navigator.userAgent },
  });
  errorInfo = "";

  let geeParams = {};
  if (isGeeTestEnabled) {
    // const geeForm = document.querySelector(".geetest_form").children;
    const geeRes = captchaObj.getValidate();
    geeParams = {
      user_id: localStorage.getItem("uuidForEcs"),
      client_type: "Web",
      challenge: geeRes.geetest_challenge, // geeForm[0].value,
      validate: geeRes.geetest_validate, // geeForm[1].value,
      seccode: geeRes.geetest_seccode, // geeForm[2].value,
    };
  }

  try {
    const res = await loginApi(
      formValue.accountType,
      formValue.accountValue,
      formValue.password,
      domain,
      QECSConfig.ROOT_ORG_ID,
      geeParams
    );

    if (res.data.code === "200") {
      errorInfo = "";
      // 准备下面的登录token
      store.user = res.data.content;
    } else {
      errorInfo = res.data.desc;
      captchaObj?.destroy();
      resetGeeTime = Date.now();
      logger({
        pgu: "AUTO",
        act: "点击登录-res-error",
        stk: res.data.code + res.data.desc,
        cnl: ["console", "server"],
      });
      return;
    }

    await afterLogin(res);
  } finally {
    loginBtnLoading = false;
  }
}

/** 登录成功后，取学生信息和跳转 */
async function afterLogin(loginRes: any) {
  try {
    const [{ data: student }, { data: specialty }] = await Promise.all([
      getStudentInfoBySessionApi(),
      getStudentSpecialtyNameListApi(),
    ]);
    const user = {
      ...loginRes.data.content,
      ...student,
      specialty: specialty.join(),
      schoolDomain: domain,
    };

    store.user = user;
    createUserDetailLog();

    // 有断点或者异常，停止后续处理
    if (await checkExamInProgress().catch(() => true)) return;

    void router.push({ name: "ChangePassword" });
  } catch (error) {
    logger({
      cnl: ["local", "server"],
      act: "登录失败",
      dtl: "getStudentInfoBySession/getStudentSpecialtyNameListApi失败",
    });
    $message.error("获取学生信息失败，请重试！", {
      duration: 15,
      closable: true,
    });
  }
}

function closeApp() {
  logger({
    pgu: "AUTO",
    cnl: ["local", "server"],
    key: "退出应用",
    act: "点击关闭按钮",
  });
  window.close();
}
</script>

<template>
  <div class="tw-flex tw-flex-col tw-h-full">
    <header class="header">
      <div class="school-logo-container">
        <img
          v-show="logoPath"
          class="school-logo"
          :src="logoPath"
          alt="school logo"
          style="
            background: linear-gradient(to bottom, #38f6f5 0%, #8efdf4 100%);
          "
        />
        <!-- 加上它，在logo加载失败的时候有用 -->
        <!-- @load="(e: any) => (e.target.style = '')" -->
      </div>
      <a class="close" @click="closeApp">关闭</a>
    </header>

    <div class="center" :style="{ backgroundImage: backgroundUrl }">
      <div class="content">
        <div class="login-types qm-big-text tw-flex tw-overflow-clip">
          <a
            v-if="allowLoginType.includes('STUDENT_CODE')"
            key="STUDENT_CODE"
            :class="{ 'active-type': formValue.accountType === 'STUDENT_CODE' }"
            @click="formValue.accountType = 'STUDENT_CODE'"
          >
            {{ QECSConfig.STUDENT_CODE_LOGIN_ALIAS }}
          </a>
          <a
            v-if="allowLoginType.includes('IDENTITY_NUMBER')"
            key="IDENTITY_NUMBER"
            :class="{
              'active-type': formValue.accountType === 'IDENTITY_NUMBER',
            }"
            @click="formValue.accountType = 'IDENTITY_NUMBER'"
          >
            {{ QECSConfig.IDENTITY_NUMBER_LOGIN_ALIAS }}
          </a>
          <a v-if="allowLoginType.length === 0" key="loading">loading...</a>
        </div>

        <div class="qm-title-text tw-text-center tw-mt-10">
          {{ productName }}
        </div>

        <div class="tw-mx-10">
          <n-form ref="formRef" :model="formValue" :rules="fromRules">
            <n-form-item class="form-item-style" path="accountValue">
              <n-input v-model:value="formValue.accountValue">
                <template #prefix>
                  <n-icon :component="Person" />
                </template>
              </n-input>
            </n-form-item>
            <n-form-item
              prop="password"
              class="form-item-style"
              path="password"
            >
              <n-input
                v-model:value="formValue.password"
                type="password"
                @onEnter="loginForuser"
              >
                <template #prefix>
                  <n-icon :component="LockClosed" />
                </template>
              </n-input>
            </n-form-item>

            <n-form-item
              v-if="isGeeTestEnabled"
              class="form-item-style"
              style="height: 40px; margin-top: 0px"
            >
              <GeeTest
                :reset="resetGeeTime"
                @onLoad="(v) => (captchaObj = v)"
              />
            </n-form-item>

            <div
              v-show="errorInfo"
              class="tw-flex tw-items-center tw-text-red-900"
            >
              <n-icon :component="CloseCircleOutline" size="large" />
              {{ errorInfo }}
            </div>
            <n-form-item class="tw-mb-8">
              <n-button
                type="success"
                size="large"
                style="width: 100%"
                :disabled="disableLoginBtn"
                :loading="loginBtnLoading"
                @click="loginForuser"
              >
                {{ newVersionAvailable ? "点击更新版本" : "登录" }}
              </n-button>
            </n-form-item>
          </n-form>
        </div>
      </div>
    </div>

    <footer class="footer">
      <div style="position: absolute; right: 20px; bottom: 20px">
        版本: {{ VITE_GIT_REPO_VERSION }}
      </div>
    </footer>
    <GlobalNotice />
  </div>
</template>

<style scoped>
.header {
  display: flex;
  align-items: center;
  min-height: 120px;
}
.school-logo-container {
  justify-self: flex-start;
  margin-left: 100px;
}

.school-logo {
  height: 100px;
  width: 400px;
  object-fit: cover;
}

.close {
  position: absolute;
  top: 0;
  right: 0;
  background-color: #eeeeee;
  color: #999999;
  text-align: center;
  width: 80px;
  height: 40px;
  line-height: 40px;
  border-bottom-left-radius: 6px;
}

.close:hover {
  color: #444444;
  cursor: pointer;
}

.center {
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  width: 100vw;
  min-height: 600px;
}

.content {
  margin-top: 100px;
  margin-left: 60%;
  width: 340px;
  border-radius: 6px;
  overflow: hidden;
  background-color: white;
}

/* FIXME: 样式复用候选 */
.qm-big-text {
  font-size: 16px;
  font-weight: normal;
  font-stretch: normal;
  line-height: 22px;
  letter-spacing: 0px;
  color: #999999;
}
.qm-title-text {
  font-size: 18px;
  font-weight: bold;
  font-stretch: normal;
  line-height: 24px;
  letter-spacing: 0px;
  color: #444444;
}

.login-types a {
  flex: 1;
  line-height: 40px;
  background-color: #eeeeee;
  text-align: center;
}
.login-types a.active-type {
  background-color: #ffffff;
}

.form-item-style {
  margin-bottom: 30px;
  height: 42px;
}
</style>
