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

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


const btnLoading = ref(false)


const form = ref({
  oldLoginPwd: '',
  newLoginPwd: '',
  confirmPwd: '',
})


const FormSchema = z.object({
  oldLoginPwd: z.string()
      .min(1, {message: t('pages-user.pay-password.input-placeholder.enter-old-password')}),
  newLoginPwd: 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.newLoginPwd === 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;

}

async function submit() {
  try {
    btnLoading.value = true
    await appUserEditLoginPwdPost({
      body: {
        ...form.value
      }
    })
    await uni.showToast({title: t('pages-user.password.change-password-successfully'), icon: 'none'})
    // await userStore.getUserInfo()
    setTimeout(() => {
      userStore.clear();
      uni.navigateTo({
        url: Config.loginPath
      })
    }, 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-change-password')"/>
  <view class="page pt-20rpx">
    <view class="bg-#fff">

      <view class="px-30rpx border-bottom">
        <wd-input
            no-border
            show-password
            clearable
            :focus-when-clear="false"
            :cursorSpacing="20"
            :maxlength="20"
            v-model.trim="form.oldLoginPwd"
            :placeholder="t('pages-user.pay-password.input-placeholder.enter-old-password')"
            placeholderStyle="font-size: 28rpx;line-height: 42rpx;color: #999999;"
            custom-input-class="!h-112rpx !text-28rpx !text-primary"
        ></wd-input>
      </view>
      <view class="px-30rpx border-bottom">
        <wd-input
            no-border
            show-password
            clearable
            :focus-when-clear="false"
            :cursorSpacing="20"
            :maxlength="20"
            v-model.trim="form.newLoginPwd"
            :placeholder="t('pages-user.pay-password.input-placeholder.enter-new-password')"
            placeholderStyle="font-size: 28rpx;line-height: 42rpx;color: #999999;"
            custom-input-class="!h-112rpx !text-28rpx !text-primary"
        ></wd-input>
      </view>
      <view class="px-30rpx border-bottom">
        <wd-input
            no-border
            show-password
            clearable
            :focus-when-clear="false"
            :cursorSpacing="20"
            :maxlength="20"
            v-model.trim="form.confirmPwd"
            :placeholder="t('pages-user.pay-password.input-placeholder.enter-new-password-again')"
            placeholderStyle="font-size: 28rpx;line-height: 42rpx;color: #999999;"
            custom-input-class="!h-112rpx !text-28rpx !text-primary"
        ></wd-input>
      </view>
    </view>
    <view class="p-[62rpx+30rpx+2rpx] flex justify-end text-right">
      <text class="text-28rpx lh-42rpx text-#FF7002 underline"
            @click="navigateTo('/pages-user/pages/password/forget/index')">
            {{ t('navbar-forget-password') }}?
      </text>
    </view>
    <view class="mt-97rpx px-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>
