<template>
  <cwg-popup v-model:visible="visible" type="center" :mask-click="false" :show-footers="true"
    :title="t('signup.form.code')">
    <view class="popup-content">
      <view class="card-handle-dialog-content">
        <uni-forms ref="formRef1" :model="form" :rules="rules" label-position="top" validate-trigger="submit"
          :label-width="200" class="base-info-form">
          <view class="code-input-wrapper">
            <view class="code-input">
              <uni-forms-item :label="t('signup.form.code')" name="emailCode">
                <uni-easyinput type="number" v-model="form.emailCode" :placeholder="t('signup.form.code')" />
              </uni-forms-item>
            </view>
            <view class="get-code-btn">
              <view class="cwg-button ok-button">
                <button type="primary" block :disabled="!canSend || isLoading" @click="handleGetCode">{{
                  getCodeString
                }}</button>
              </view>
            </view>
          </view>
        </uni-forms>
      </view>
    </view>

    <template #footer>
      <button @click="visible = false">{{ t('Btn.Cancel') }}</button>
      <button type="primary" @click="tosubmitConfirm">{{ t('Btn.Confirm') }}</button>
    </template>
  </cwg-popup>
</template>

<script setup lang="ts">
import { ref, computed, onBeforeUnmount } from "vue";
import { showToast } from "@/utils/toast";
import { useI18n } from "vue-i18n";
import { useEmailCountdown } from '@/hooks/useEmailCountdown';
const {
  time,
  text: getCodeString,
  canSend,
  start,
  restore
} = useEmailCountdown({ storageKey: 'emailCodeTimer' })
const { t } = useI18n();
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  email: {
    type: String,
    default: ''
  },
  country: {
    type: String,
    default: ''
  },
  api: {
    type: Function,
    default: () => { }
  }
});


const emit = defineEmits(['update:visible', 'confirm']);

// Watch for changes in visible prop and emit update event
const visible = computed({
  get: () => props.visible,
  set: (value: boolean) => emit('update:visible', value)
});

const formRef1 = ref(null);
const isLoading = ref(false);
const form = ref<{
  emailCode: string;
}>({
  emailCode: "",
});


const rules = computed(() => ({
  emailCode: {
    rules: [
      {
        required: true,
        errorMessage: t('vaildate.code.empty'),
      },
      {
        validateFunction: (rule, value, data, callback) => {
          // 空值处理：直接报格式错误
          if (!value) {
            callback(t('vaildate.code.empty'))
            return false
          }
          if (!/^\d{6}$/.test(value)) {
            callback(t('vaildate.code.empty'))
            return false
          }
          return true
        },
      },
    ],
  },
}))

// 发送邮箱验证码
async function sendEmailCode() {
  try {
    isLoading.value = true;
    const res = await props.api({
      email: props.email || undefined,
      country: props.country || undefined
    });

    if (res.code === 200) {
      showToast(t("Msg.CodeSuccess"));
      start();
      return true;
    } else {
      showToast(t("Msg.CodeFail"));
      return false;
    }
  } catch (error: any) {
    showToast(t("Msg.CodeFail"));
    return false;
  } finally {
    isLoading.value = false;
  }
}

// 获取验证码按钮点击
async function handleGetCode() {
  if (!canSend.value || isLoading.value) {
    return;
  }
  await sendEmailCode();
}

// 确认提交
const tosubmitConfirm = async () => {
  if (formRef1.value) {
    try {
      await formRef1.value.validate();
      visible.value = false;
      console.log(form.value.emailCode, 12121);

      emit('confirm', form.value.emailCode);
    } catch (error) {
      if (error instanceof Array) {
        showToast(error[0].errorMessage);
        return
      } else {
        showToast(t("Msg.CodeFail"));
      }

    }
  }
}

// 组件卸载时恢复倒计时
onBeforeUnmount(() => {
  restore();
});
</script>

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

.popup-content {
  width: 100%;
}

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

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

  .code-input-wrapper {
    position: relative;
    display: flex;
    align-items: flex-end;
    gap: px2rpx(10);
  }

  .code-input {
    flex: 1;
  }

  .get-code-btn {
    min-width: px2rpx(120);
    display: flex;
    align-items: flex-end;
    margin-bottom: px2rpx(16);

    button {
      border-radius: px2rpx(8);
      font-size: px2rpx(14);
      line-height: px2rpx(35);
      height: 100%;
      height: px2rpx(35);
    }
  }

  /* 移动端适配 */
  @media screen and (max-width: 750px) {}

  :deep(.uni-forms-item) {
    margin-bottom: px2rpx(16);
  }

  :deep(.uni-easyinput) {
    border-radius: px2rpx(8);
  }
}
</style>
