<template>
  <u-modal v-model:show="showDialog" class="card-handle-dialog" :title="t('card.vaildate.v42')"
    :show-confirm-button="false" :show-cancel-button="false" :close-on-click-overlay="false" @closed="handleClose">
    <view class="card-handle-dialog-content">
      <u-form ref="formRef" :model="form" class="payment-form">
        <view class="code-input-label">{{ t("newSignup.item9") }}</view>
        <view class="code-input-wrapper">
          <view class="code-input">
            <cwg-input v-model:value="form.emailCode" fkey="emailCode" type="text" :required="true"
              :placeholder="t('newSignup.item10')" @change="handleChange" />
          </view>
          <view class="get-code-btn">
            <view class="cwg-button ok-button">
              <u-button type="primary" block @click="handleGetCode">{{
                getCodeString
                }}</u-button>
            </view>
          </view>
        </view>
        <cwg-input v-if="cvv" v-model:value="cvv" fkey="cvv" type="text" label="CVV" :readonly="true"
          :disabled="true" />
      </u-form>

      <view class="dialog-footer">
        <view v-if="!cvv" class="cwg-button ok-button">
          <u-button type="primary" block @click="handleConfirm">{{
            t("card.vaildate.v42")
            }}</u-button>
        </view>
        <view v-else class="cwg-button ok-button">
          <u-button type="primary" block @click="cardCopy">{{
            t("card.vaildate.v43")
            }}</u-button>
        </view>
        <view class="cwg-button no-button">
          <u-button type="default" block @click="handleClose">{{
            t("card.Btn.Cancel")
            }}</u-button>
        </view>
      </view>
    </view>
  </u-modal>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onBeforeUnmount } from "vue";
import { showToast } from "@/utils/toast";
import { useI18n } from "vue-i18n";
import { ucardApi } from "@/api/ucard";
import errorIcon from "/static/images/error.png";
import copyIcon from "/static/images/success.png";
import ls from "@/utils/store2";
const { t } = useI18n();
const props = defineProps<{
  dialogInfoTradingAdd: boolean;
  formList: Record<string, any>;
}>();

const emit = defineEmits(["closeAdd"]);

const showDialog = ref(false);
const formRef = ref();
const form = ref<{
  emailCode: string;
  cardNo?: string;
  password?: string;
  country?: string;
  email?: string;
}>({
  emailCode: "",
});
const cvv = ref("");
const timer = ref(59);
const getCodeString = ref("");
const interval = ref<NodeJS.Timeout | null>(null);

const rules = {
  emailCode: [
    {
      required: true,
      message: t("vaildate.code.empty"),
    },
  ],
};

// 监听 props 变化
watch(
  () => props.dialogInfoTradingAdd,
  (newVal) => {
    showDialog.value = newVal;
    if (newVal) {
      initForm();
      initTimer();
    } else {
      handleClose();
    }
  },
  { immediate: true }
);

// 初始化表单
function initForm() {
  if (props.formList) {
    form.value = {
      ...JSON.parse(JSON.stringify(props.formList)),
      emailCode: "",
    };
  }
  cvv.value = "";
  timer.value = 59;
  getCodeString.value = t("newSignup.item11");
  if (interval.value) {
    clearInterval(interval.value);
    interval.value = null;
  }
}

// 初始化定时器
function initTimer() {
  const savedTimer = Number(ls.get("cvvTimer")) || 59;
  if (savedTimer === 59) {
    getCodeString.value = t("newSignup.item11");
  } else {
    timer.value = savedTimer;
    startTimer();
  }
}

// 开始倒计时
function startTimer() {
  if (interval.value) {
    return;
  }
  getCodeString.value = `${t("signup.form.waitCode1")}${timer.value}${t(
    "signup.form.waitCode2"
  )}`;
  interval.value = setInterval(() => {
    timer.value--;
    localStorage.setItem("cvvTimer", timer.value.toString());
    if (timer.value > 0) {
      getCodeString.value = `${t("signup.form.waitCode1")}${timer.value}${t(
        "signup.form.waitCode2"
      )}`;
    } else {
      getCodeString.value = t("newSignup.item11");
      if (interval.value) {
        clearInterval(interval.value);
        interval.value = null;
      }
      timer.value = 59;
      localStorage.setItem("cvvTimer", "59");
    }
  }, 1000);
}

// 发送邮箱验证码
async function sendEmailCode() {
  try {
    if (!form.value.country) {
      showToast(t("vaildate.country.empty"));
      return false;
    }
    if (!form.value.email) {
      showToast(t("vaildate.email.empty"));
      return false;
    }

    const res = await ucardApi.sendEmailCode({
      ...form.value,
    });

    if (res.code === 200) {
      showToast(t("Msg.CodeSuccess"));
      startTimer();
      return true;
    } else {
      showToast(t("Msg.CodeFail"));
      return false;
    }
  } catch (error: any) {
    console.log(error, 12);

    showToast(t("Msg.CodeFail"));
    return false;
  }
}

// 获取验证码按钮点击
async function handleGetCode() {
  if (timer.value > 0 && timer.value < 59) {
    return;
  }
  cvv.value = "";
  await sendEmailCode();
}

// 表单字段变化
function handleChange(value: any) {
  if (value.key === "emailCode") {
    form.value.emailCode = value.value;
  }
}

// 确认获取 CVV
async function handleConfirm() {
  try {
    await formRef.value?.validate();
    if (!form.value.emailCode) {
      // showToast(t('vaildate.code.empty'))
      return;
    }

    const res = await ucardApi.getCvvCode({
      ...form.value,
    } as any);

    if (res.code === 200) {
      cvv.value = res.data;
    } else {
      showToast(res.msg);
      cvv.value = "";
    }
  } catch (error: any) {
    if (Array.isArray(error) && error.length > 0) {
      showToast({
        message: error[0].message,
        icon: errorIcon,
        className: "custom-toast",
      });
    } else {
      showToast({
        message: error?.message,
        icon: errorIcon,
        className: "custom-toast",
      });
    }
  }
}

// 复制 CVV
function cardCopy() {
  let title = t("common.copy2");
  uni.setClipboardData({
    data: cvv.value,
    success: () => {
      uni.showToast({
        title,
      });
    },
  });
}

// 降级复制方案
function fallbackCopy() {
  const textarea = document.createElement("textarea");
  textarea.value = cvv.value;
  textarea.setAttribute("readonly", "");
  textarea.style.position = "absolute";
  textarea.style.left = "-9999px";
  document.body.appendChild(textarea);
  textarea.select();
  try {
    document.execCommand("copy");
    showToast({
      message: t("card.Msg.m8"),
      icon: copyIcon,
      className: "custom-toast",
    });
  } catch (_err) {
    showToast({
      message: t("card.Msg.m9"),
      icon: errorIcon,
      className: "custom-toast",
    });
  }
  document.body.removeChild(textarea);
}

// 关闭对话框
function handleClose() {
  showDialog.value = false;
  emit("closeAdd", false);
  if (interval.value) {
    clearInterval(interval.value);
    interval.value = null;
  }
}

// 组件卸载时清理
onBeforeUnmount(() => {
  if (interval.value) {
    clearInterval(interval.value);
    interval.value = null;
  }
});
</script>

<style scoped lang="scss">
@import "@/uni.scss";

.card-handle-dialog {
  width: 100%;

  :deep(.u-popup__content) {
    width: 90% !important;
  }

  :deep(.u-modal) {
    width: 100% !important;
  }

  .card-handle-dialog-content {
    padding: px2rpx(44) px2rpx(2);

    .no-button {
      width: 100%;
      margin: px2rpx(12) 0;

      .u-button {
        background-color: #ffbdc8 !important;
      }
    }

    .ok-button {
      margin: px2rpx(4) 0;
      /* background-color: #EA002A; */
    }
  }

  .code-input-label {
    font-size: var(--font-size-16);
    line-height: px2rpx(44);
    letter-spacing: px2rpx(1);
    color: #474747;
  }

  .code-input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
  }

  .code-input {
    flex: 1;
  }

  .get-code-btn {
    min-width: px2rpx(100);
    margin-bottom: px2rpx(12);
    margin-left: px2rpx(10);

    .cwg-button .u-button {
      border-radius: px2rpx(8);
    }
  }
}
</style>
