<script lang="ts" setup>
import {
  getStudentInfoBySessionApi,
  getStudentSpecialtyNameListApi,
  loginApi,
} from "@/api/login";
import {
  DOMAIN,
  FACE_API_MODEL_PATH,
  VITE_GIT_REPO_VERSION,
} from "@/constants/constants";
import { useTimers } from "@/setups/useTimers";
import { resetStore, store } from "@/store/store";
import { createEncryptLog, createUserDetailLog } from "@/utils/logger";
import { MD5 } from "@/utils/md5";
import { getScreenShot, isElectron } from "@/utils/nativeMethods";
import ua from "@/utils/ua";
import { decryptLogin, preloadResource } from "@/utils/utils";
import { CloseCircleOutline, LockClosed, Person } from "@vicons/ionicons5";
import { FormItemInst, FormRules, useDialog } from "naive-ui";
import { onMounted, onUnmounted, watch, h } 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 { useExamShellStats } from "./useExamShellStats";
import { getGeeTestConfig } from "./useGeeTestConfig";
import { limitLogin } from "./useLimitLogin";
import { useNewVersion } from "./useNewVersion";
import { useRemoteAppChecker } from "./useRemoteAppChecker";
import { useVCamChecker } from "./useVCamChecker";
import copy from "copy-to-clipboard";

const dialog = useDialog();

const { addTimeout, addInterval } = useTimers();

resetStore();

//#region 登录日志处理
// @ts-expect-error
// eslint-disable-next-line no-undef
const portableFile = window.proceess?.env?.PORTABLE_EXECUTABLE_FILE;
logger({
  cnl: ["console", "local", "server"],
  pgn: "登录页面",
  act: "首次渲染",
});

if (isElectron()) {
  logger({
    cnl: ["server"],
    pgn: "登录页面",
    act: "versonstats",
    ext: {
      packageVersion: "ua-" + ua.getBrowser().version,
      file: portableFile,
      uaGood: "uagood-" + (portableFile ? 1 : 0),
    },
  });
}

// @ts-expect-error rtt不应该存在chrome 61以下，此处是陷阱代码
if (navigator.connection && navigator.connection.rtt) {
  logger({
    cnl: ["local", "server"],
    pgn: "登录页面",
    // 故意用特殊的空格字符
    act: "page　created",
    ext: { UA: navigator.userAgent },
  });
}

// 上传本机加密日志
addInterval(createEncryptLog, 5 * 1000);

useExamShellStats();
//#endregion

//#region cache faceapi json
{
  const faceapiUrls = [
    FACE_API_MODEL_PATH + "tiny_face_detector_model-weights_manifest.json",
    FACE_API_MODEL_PATH + "face_landmark_68_model-weights_manifest.json",
    FACE_API_MODEL_PATH + "face_expression_model-weights_manifest.json",
  ];

  for (const u of faceapiUrls) {
    preloadResource(u);
  }
}
//#endregion

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

  if (store.QECSConfig && !store.QECSConfig.LOGIN_SUPPORT.includes("NATIVE")) {
    dialog.warning({
      title: "提醒",
      content: () => {
        return h("div", [
          h("div", [
            "当前版本已禁用，请根据学校通知下载新版考生端程序进行考试！",
          ]),
          h(
            "div",
            {
              style: {
                "user-select": "text",
              },
            },
            [
              h("span", [
                "下载地址: https://cdn.exam-cloud.cn/oe-student-client/setup/setup_ynou_V1.0.0.exe",
              ]),
            ]
          ),
        ]);
      },
      positiveText: "复制并退出",
      maskClosable: false,
      closeOnEsc: false,
      closable: false,
      onPositiveClick: () => {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-call
        copy(
          "https://cdn.exam-cloud.cn/oe-student-client/setup/setup_ynou_V1.0.0.exe"
        );
        closeApp("notSupport");
      },
    });
  }

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

const QECSConfig = $computed(() => 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);
const { disableLoginBtnBecauseVCam } = useVCamChecker();
const { disableLoginBtnBecauseRemoteApp } = useRemoteAppChecker();

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

addTimeout(() => {
  if (disableLoginBtn)
    logger({
      cnl: ["server", "local"],
      // FIXME: change to debug when go prod
      lvl: "log",
      dtl: "disabler",
      ext: {
        notTimeout: disableLoginBtnBecauseNotTimeout,
        remoteApp: disableLoginBtnBecauseRemoteApp.value,
        vcam: disableLoginBtnBecauseVCam.value,
        appVersionChecker: disableLoginBtnBecauseAppVersionChecker.value,
      },
    });
}, 15 * 1000);

//#region form校验
const domain = DOMAIN;
if (!domain?.includes(".ecs.qmth.com.cn")) {
  $message.warning("学校域名不正确", { duration: 5 * 60 * 1000 });
}
type FormModel = {
  accountType: "STUDENT_CODE" | "STUDENT_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(
  () => allowLoginType,
  (v) => {
    let defaultAccountType = formValue.accountType || "STUDENT_CODE";
    const allowStudentCode = v.includes("STUDENT_CODE");
    const allowIdentityNumber = v.includes("IDENTITY_NUMBER");
    if (!allowStudentCode && allowIdentityNumber) {
      defaultAccountType = "STUDENT_IDENTITY_NUMBER";
    }
    formValue.accountType = defaultAccountType;
  }
);
watch([formValue], () => (errorInfo = ""));
watch(
  () => formValue.accountType,
  () => {
    formValue.accountValue = localStorage.getItem(formValue.accountType) || "";
  },
  { immediate: true }
);
//#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

//#region 登录处理
const router = useRouter();
let loginBtnLoading = $ref(false);
let disableLoginBtnBecauseNotTimeout = $ref(false);
async function loginForuser() {
  if (await checkNewVersion()) return;
  if (disableLoginBtn) 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 timestamp = Date.now();
    const res = await loginApi(
      formValue.accountType,
      formValue.accountValue,
      formValue.password,
      domain,
      QECSConfig.ROOT_ORG_ID,
      geeParams,
      timestamp
    );

    const key = MD5(
      "accountValue=" +
        formValue.accountValue +
        "&" +
        "password=" +
        formValue.password +
        "&" +
        "timestamp=" +
        timestamp
    );

    logger({
      cnl: ["server"],
      pgu: "AUTO",
      act: "login api success",
      ext: {
        accountType: formValue.accountType,
        accountValue: formValue.accountValue,
        domain,
        ...geeParams,
      },
    });

    if (res.data.code === "200") {
      errorInfo = "";
      // FIXME: 插入多余代码？
      const str = decryptLogin(res.data.content as string, key);
      res.data.content = JSON.parse(str);
      console.log(res.data.content);
      // setSalt(res.data.content.salt as string);
      // delete res.data.content.salt;
      // 准备下面的登录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) {
  // 存储登录成功的用户名
  localStorage.setItem(formValue.accountType, formValue.accountValue);
  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();

    getScreenShot({ cause: "ss-login" }).catch((e) => {
      logger({
        pgu: "AUTO",
        cnl: ["server"],
        dtl: "桌面抓拍失败-electron问题",
        ejn: JSON.stringify(e),
      });
    });

    let userIds: number[] = JSON.parse(localStorage.getItem("userIds") || "[]");
    userIds = [...new Set(userIds).add(store.user.id)];
    localStorage.setItem("userIds", JSON.stringify(userIds));

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

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

function closeApp(type: "exit" | "notSupport" = "exit") {
  const isNotSupport = type === "notSupport";
  logger({
    pgu: "AUTO",
    cnl: ["local", "server"],
    key: isNotSupport ? "学生端登录禁用" : "退出应用",
    act: isNotSupport ? "学生端登录禁用,点击确定按钮" : "点击关闭按钮",
  });
  window.close();
}

// 登录页会收到很多消息，离开登录页时，都应该销毁掉
onUnmounted(() => $message.destroyAll());
</script>

<template>
  <div class="tw-absolute tw-left-0 tw-right-0">
    <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%);
          "
          @load="(e) => ((e.target as HTMLImageElement).style.backgroundImage = 'none')"
        />
        <!-- 加上它，在logo加载失败的时候有用 -->
      </div>
      <a class="close" @click="closeApp()">关闭</a>
    </header>
  </div>

  <div class="tw-flex tw-items-center tw-min-h-screen">
    <div class="center-bg" :style="{ backgroundImage: backgroundUrl }">
      <div class="login-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 === 'STUDENT_IDENTITY_NUMBER',
            }"
            @click="formValue.accountType = 'STUDENT_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"
                @keypress.enter="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>
  </div>

  <footer class="tw-absolute tw-right-5 tw-bottom-5">
    版本: {{ VITE_GIT_REPO_VERSION }}
  </footer>
  <GlobalNotice />
</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-bg {
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  width: 100%;
  min-height: 400px;
  height: calc(100vh - 240px);
  max-height: 700px;
  display: flex;
  align-items: center;
}

.login-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;
  cursor: pointer;
}
.login-types a.active-type {
  background-color: #ffffff;
}

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