<script lang="ts" setup>
import { DOMAIN } from "@/constants/constants";
import { httpApp } from "@/plugins/axiosApp";
import { store } from "@/store/store";
import { onMounted, onUnmounted } from "vue";
import { showLogout } from "@/utils/utils";

let phoneModal = $ref(false);
let code = $ref("");
let interval = $ref(-1);
let remainTime = $ref(0);
let btnText = "发送验证码";

onMounted(() => {
  if (
    ["cugr.ecs.qmth.com.cn", "test.cugr.qmth.com.cn"].includes(DOMAIN) &&
    !localStorage.getItem("phoneVerified")
  ) {
    phoneModal = true;
  }
});
onUnmounted(() => clearInterval(interval));

async function getCode() {
  logger({
    cnl: ["local", "server"],
    pgn: "PhoneVerifyForDD",
    act: "发送验证码按钮",
  });
  try {
    await httpApp.post("/api/ecs_oe_student/sms/sendSmsCodeToStudent");
  } catch (error) {
    $message.error("发送验证码失败，请重试！", {
      duration: 15,
      closable: true,
    });
    return;
  }

  remainTime = 90;
  interval = window.setInterval(() => {
    if (remainTime > 0) {
      remainTime--;
    } else {
      clearInterval(interval);
    }
  }, 1000);
}
async function verify() {
  if (code.length < 4) {
    $message.warning("请输入正确的验证码");
    return;
  }
  logger({
    cnl: ["local", "server"],
    pgn: "PhoneVerifyForDD",
    act: "点击验证按钮",
  });
  const { phoneNumber } = store.user;
  try {
    await httpApp.post(
      `/api/ecs_oe_student/sms/checkSmsCode?phoneNumber=${phoneNumber}&code=${code}`,
      null,
      { setGlobalMask: true }
    );
    phoneModal = false;
    localStorage.setItem("phoneVerified", "true");
  } catch (error) {
    $message.error("验证手机号接口失败，请重试！", {
      duration: 15,
      closable: true,
    });
    logger({
      cnl: ["local", "server"],
      pgn: "PhoneVerifyForDD",
      dtl: "验证手机号接口失败，请重试！",
    });
  }
}
</script>

<template>
  <!-- 手机号验证。For 地质大学 -->
  <n-modal
    :show="phoneModal"
    preset="dialog"
    title="验证手机号"
    type="info"
    :closable="false"
    negativeText="退出系统"
    positiveText="确认"
    :zIndex="2000"
    @positiveClick="verify"
    @negativeClick="() => showLogout('未确认手机号')"
  >
    <div class="tw-flex">
      <span class="tw-min-w-max tw-mr-2">预留手机号:</span>
      <span>{{ store.user.phoneNumber }}</span>
    </div>
    <div class="tw-flex tw-items-center tw-mt-2">
      <div class="tw-min-w-max tw-mr-2">输入验证码:</div>
      <n-input
        v-model:value="code"
        maxlength="4"
        placeholder="验证码"
        type="text"
        class="tw-mr-2"
      />
      <n-button type="success" :disabled="remainTime > 0" @click="getCode">
        {{ btnText }}{{ remainTime > 0 ? "(" + remainTime + "秒)" : "" }}
      </n-button>
    </div>
  </n-modal>
</template>
