<script setup lang="ts">
import { ref } from "vue";
import type { PaymentData } from "@/interfaces";
import { useMainStore } from "@/stores/main";

const mainStore = useMainStore();
let isLoading = ref(false);
const credit = ref(1);

function increment() {
  credit.value++;
}
function decrement() {
  if (credit.value > 1) {
    credit.value--;
  }
}

const epayment = ref("ecpay");

async function ecpay() {
  isLoading.value = true;
  const data: PaymentData = {
    item: `Credit ${60 *credit.value}`,
    amount: 500 * credit.value,
  };
  if (data.amount <= 0) {
    return;
  }

  const originalHTML = await mainStore.Payment(data, "zh");

  let formHTML = originalHTML?.replace(
    '<script type="text/javascript">document.getElementById("data_set").submit();</scr',
    ""
  );
  formHTML = formHTML?.replace("ipt>", "");
  const payFormElement = document.getElementById("pay-form");
  payFormElement!.innerHTML = formHTML!;
  const ecpayForm: HTMLFormElement = <HTMLFormElement>(
    document.getElementById("data_set")
  );
  ecpayForm.submit();

  setTimeout(() => {
    isLoading.value = false;
  }, 3000);
}
</script>

<template>
  <div class="d-flex align-center flex-wrap">
    <div class="payment-item me-6 mt-3">
      <span>分鐘數：</span>
      <v-btn
        density="compact"
        icon="remove"
        color="grey"
        class="mx-2"
        @click="decrement"
      ></v-btn>
      <span class="px-2">{{ credit }}</span>
      <v-btn
        density="compact"
        icon="add"
        color="grey"
        class="mx-2"
        @click="increment"
      ></v-btn>
      <span class="ms-2">NT＄{{ 500 * credit }}</span>
    </div>

    <v-btn
      @click="ecpay"
      variant="flat"
      color="primary"
      class="px-4 mt-3"
      prepend-icon="add"
      :loading="isLoading"
      >我要加值</v-btn
    >
  </div>

  <div id="pay-form"></div>
</template>

<style lang="scss" scoped>
.payment-item {
  .v-btn {
    border: 1px solid #a6a6a6;
  }
}
</style>
