<script lang="ts" setup>
import {useUserStore} from "@/store";
import {debounce} from "throttle-debounce";
import {z} from "zod";
import {SmsType} from "@/constant/enums";
import * as R from "ramda";
import Config from "@/config";
import {appUserSetPayPwdPost} from "@/service";

const userStore = useUserStore();
const {t} = useI18n();

const {isSend, getMsgCode} = useGetMsgCode();

const btnLoading = ref(false);

const form = ref({
  areaCode: userStore.userInfo?.areaCode || "",
  phone: userStore.userInfo?.phone || "",
  captcha: "",
  payPwd: "",
  confirmPwd: "",
});

const FormSchema = z
    .object({
      captcha: z
          .string()
          .min(1, {
            message: t(
                "pages-user.pay-password.input-placeholder.enter-verification-code"
            ),
          }),
      payPwd: z
          .string()
          .min(1, {
            message: t(
                "pages-user.pay-password.input-placeholder.enter-new-password"
            ),
          })
          .regex(/^\d{6}$/, {
            message: t("pages-user.pay-password.enter-6-digit-password"),
          }),
      confirmPwd: z
          .string()
          .min(1, {
            message: t(
                "pages-user.pay-password.input-placeholder.enter-new-password-again"
            ),
          }),
    })
    .refine((data) => data.payPwd === data.confirmPwd, {
      path: ["confirmPwd"],
      message: t("pages-user.pay-password.two-passwords-inconsistent"),
    });

function checkForm(): boolean {
  const validateFormFields = FormSchema.safeParse(form.value);
  if (!validateFormFields.success) {
    const errorMessage = validateFormFields.error.flatten().fieldErrors;
    console.log(errorMessage);
    const fieldMessageArr = Object.values(errorMessage);
    console.log("fieldMessageArr", fieldMessageArr);
    if (fieldMessageArr[0].length) {
      uni.showToast({
        title: fieldMessageArr[0][0],
        icon: "none",
      });
    }
  }

  return validateFormFields.success;
}

function handleShowGetCode() {
  if (isSend.value > 0) {
    return;
  }
  getMsgCode({
    type: SmsType.USER_SET_PAYMENT_PASSWORD,
    phone: form.value.phone,
    areaCode: form.value.areaCode,
  });
}

async function submit() {
  try {
    btnLoading.value = true;
    await appUserSetPayPwdPost({
      body: {
        ...form.value
      }
    });
    await uni.showToast({
      title: t("pages-user.pay-password.set-payment-password-successfully"),
      icon: "none",
    });
    await userStore.getUserInfo();
    setTimeout(() => {
      uni.navigateBack();
    }, 1000);
  } finally {
    setTimeout(() => {
      btnLoading.value = true;
    }, 1000);
  }
}

const handleSubmit = R.when(
    checkForm,
    debounce(Config.debounceLongTime, submit, {
      atBegin: true,
    })
);

function navigateTo(url: string) {
  uni.navigateTo({
    url,
  });
}
</script>

<template>
  <navbar :title="t('navbar-set-payment-password')"/>
  <view class="page pt-20rpx">
    <view class="bg-#fff">
      <view class="px-30rpx border-bottom">
        <wd-input
            :modelValue="form.phone"
            custom-input-class="!h-112rpx !text-28rpx !text-primary"
            disabled
            disabledColor="transparent"
            no-border
        >
        </wd-input>
      </view>
      <view class="px-30rpx border-bottom">
        <wd-input
            v-model.trim="form.captcha"
            :cursorSpacing="20"
            :focus-when-clear="false"
            :maxlength="6"
            :placeholder="
            t(
              'pages-user.pay-password.input-placeholder.enter-verification-code'
            )
          "
            clearable
            custom-input-class="!h-112rpx !text-28rpx !text-primary"
            no-border
            placeholderStyle="font-size: 28rpx;line-height: 42rpx;color: #999999;"
        >
          <template #suffix>
            <view class="ml-20rpx">
              <wd-button
                  :disabled="!!isSend"
                  custom-class="!box-border !min-w-auto w-130rpx !h-50rpx !text-28rpx font-bold !bg-#1EB171 !rounded-8rpx"
                  @click="handleShowGetCode"
              >
                {{ isSend ? isSend + "S" : t("common.obtain") }}
              </wd-button>
            </view>
          </template>
        </wd-input>
      </view>
      <view class="px-30rpx border-bottom">
        <wd-input
            v-model.trim="form.payPwd"
            :cursorSpacing="20"
            :focus-when-clear="false"
            :maxlength="6"
            :placeholder="
            t('pages-user.pay-password.input-placeholder.enter-new-password')
          "
            clearable
            custom-input-class="!h-112rpx !text-28rpx !text-primary"
            no-border
            placeholderStyle="font-size: 28rpx;line-height: 42rpx;color: #999999;"
            show-password
        ></wd-input>
      </view>
      <view class="px-30rpx">
        <wd-input
            v-model.trim="form.confirmPwd"
            :cursorSpacing="20"
            :focus-when-clear="false"
            :maxlength="6"
            :placeholder="
            t(
              'pages-user.pay-password.input-placeholder.enter-new-password-again'
            )
          "
            clearable
            custom-input-class="!h-112rpx !text-28rpx !text-primary"
            no-border
            placeholderStyle="font-size: 28rpx;line-height: 42rpx;color: #999999;"
            show-password
        ></wd-input>
      </view>
    </view>
    <view class="m-[128rpx+30rpx+30rpx]">
      <wd-button
          block
          custom-class="!h-108rpx !text-36rpx !rounded-16rpx"
          @click="handleSubmit"
      >
        {{ t("common.confirm") }}
      </wd-button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
:deep(.wd-input) {
  .wd-input__suffix {
    display: flex;
    align-items: center;
  }
}
</style>
