<script lang="ts" setup>
import * as R from 'ramda'
import {z} from "zod";
import {useLogicStore} from "@/pages-login/store/module/logic";
import {Agreement} from "@/constant/enums";
import {debounce} from "throttle-debounce";
import Config from "@/config";
import {appUserRegisterPost} from "@/service";
import {useUserStore} from "@/store";

const areaCode = ref<string>('+1');
const columns = ref<string[]>(Config.phoneCodeList);

const {t} = useI18n()

const userStore = useUserStore();
const logicStore = useLogicStore()

const isAgreed = ref(false)


function getFormSchema(type: string) {
  const base = z.object({
    firstName: z.string().min(1, {message: t('pages-login.prompt.first-name')}),
    surname: z.string().min(1, {message: t('pages-login.prompt.last-name')}),
    loginPwd: z.string().min(1, {message: t('pages-login.prompt.password')}),
    newPwd: z.string().min(1, {message: t('pages-login.prompt.confirm-password')}),
  })

  if (type === 'phone') {
    return base.extend({
      phone: z.string().min(1, {message: t('pages-login.prompt.phone-number')}).regex(/^\d{6,11}$/, {message: t('pages-login.prompt.phone-number-verify')}),
    })
      .refine((v: any) => v.loginPwd === v.newPwd, {
        message: t('pages-login.prompt.two-passwords-inconsistent'),
        path: ['newPwd'],
      })
  }

  return base.extend({
    email: z.string().email({message: t('pages-login.prompt.email-verify')}),
    confirmEmail: z.string().email({message: t('pages-login.prompt.email-verify')}),
  }).refine((v) => v.email === v.confirmEmail, {
    message: t('pages-login.prompt.confirm-email'),
    path: ['confirmEmail'],
  })
    .refine((v: any) => v.loginPwd === v.newPwd, {
      message: t('pages-login.prompt.two-passwords-inconsistent'),
      path: ['newPwd'],
    })
}

function checkForm(): boolean {
  const validateFormField = getFormSchema(logicStore.registerForm.type).safeParse(logicStore.registerForm)
  if (!validateFormField.success) {
    const fieldErrorMessage = validateFormField.error.flatten().fieldErrors
    const errorMessage: string | undefined = R.path([0, 0], R.values(fieldErrorMessage))
    errorMessage &&
    uni.showToast({
      title: errorMessage,
      icon: 'none',
    })
  } else if (!isAgreed.value) {
    uni.showToast({
      title: `${t('common.prompt.please-carefully-read-and-agree')} ${t('agreement.user-terms-conditions')}${t('pages-login.and')}${t('agreement.privacy-policy')}`,
      icon: 'none'
    })
  }
  return validateFormField.success && isAgreed.value
}

const verificationCodeRef = ref()
const submit = () => {
  // verificationCodeRef.value.onOpen()
  codeSubmit()
}

const btnLoading = ref(false)

function codeSubmit() {
  // console.log(data)
  btnLoading.value = true
  const body: Record<string, any> = {
    ...logicStore.registerForm,
    phone: logicStore.registerForm.phone,
    areaCode: areaCode.value,
    // captcha: data.code,
    // uuid: data.uuid,
    userPort: 2, // 登录端口2 商户端
  }
  if (!body.email) {
    delete body.email
    delete body.confirmEmail
  }
  if (logicStore.registerForm.type === 'email' && !String(body.phone ?? '').trim()) {
    delete body.phone
    delete body.areaCode
  }
  appUserRegisterPost({
    body
  }).then((res) => {
    ;(userStore as any).token = (res as any).data?.token;
    logicStore.reset()
    uni.showToast({
      title: t('pages-login.sign-up.register-success'),
      icon: 'none',
    })
    nextTick(() => {
      userStore.getUserInfo();
      uni.redirectTo({
        url: '/pages-login/pages/guide-page/welcome'
      })
    })
  }).finally(() => {
    btnLoading.value = false
  })
}

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


function navigateTo(url: string) {
  uni.navigateTo({url});
}

const emailIsReadonly = ref(false)
const phoneIsReadonly = ref(false)
const showEmail = computed(() => logicStore.registerForm.type !== 'phone')
const showPhone = computed(() => logicStore.registerForm.type === 'phone')

onLoad((options: any) => {
  const type = options?.type
  if (type === 'phone' || type === 'email') {
    logicStore.registerForm.type = type
  }
})
onMounted(() => {
  const {email, type} = logicStore.registerForm
  if (type === 'phone') {
    // phoneIsReadonly.value = true
  }
  if (type === 'email') {
    // emailIsReadonly.value = true
  }
})
</script>

<template>
  <view>
    <navbar/>
    <view class="pt-60rpx px-27rpx pb-80rpx">
      <view class="mb-60rpx text-50rpx leading-50rpx font-bold text-#14181B">
        {{ t('pages-login.sign-up.title') }}
      </view>
      <view class="">
        <!-- 邮箱 -->
        <view v-if="showEmail" class="">
          <view class="text-32rpx leading-32rpx text-#14181B mb-24rpx">{{ t("common.email") }}</view>
          <view class="border-color px-30rpx flex items-center bg-#EFEFEF">
            <wd-input
                v-model.trim="logicStore.registerForm.email"
                :cursorSpacing="20"
                :focus-when-clear="false"
                :maxlength="40"
                :placeholder="t('common.enter')"
                :readonly="emailIsReadonly"
                clearable
                custom-class="flex-1 !bg-transparent"
                no-border
                placeholderClass="!text-#999 !text-32rpx"
            >
            </wd-input>
          </view>
        </view>
        <!-- Confirm email -->
        <view v-if="showEmail" class="mt-36rpx">
          <view class="text-32rpx leading-32rpx text-#14181B mb-24rpx">{{
              t("pages-login.sign-up.confirm-email")
            }}
          </view>
          <view class="border-color px-30rpx flex items-center bg-#EFEFEF">
            <wd-input
                v-model.trim="logicStore.registerForm.confirmEmail"
                :cursorSpacing="20"
                :focus-when-clear="false"
                :maxlength="40"
                :placeholder="t('common.enter')"
                :readonly="emailIsReadonly"
                clearable
                custom-class="flex-1 !bg-transparent"
                no-border
                placeholderClass="!text-#999 !text-32rpx"
            >
            </wd-input>
          </view>
        </view>
        <!-- Password -->
        <view class="mt-36rpx ">
          <view class="text-32rpx leading-32rpx text-#14181B mb-24rpx">{{ t("pages-login.sign-up.password") }}</view>
          <view class="border-color px-30rpx flex items-center  bg-#EFEFEF">
            <wd-input
                v-model.trim="logicStore.registerForm.loginPwd"
                :cursorSpacing="20"
                :focus-when-clear="false"
                :maxlength="40"
                :placeholder="t('common.enterPassword')"
                clearable
                custom-class="flex-1 !bg-transparent"
                no-border
                placeholderClass="!text-#999 !text-32rpx"
                showPassword
            >
            </wd-input>
          </view>
        </view>
        <!-- Confirm Password -->
        <view class="mt-36rpx ">
          <view class="text-32rpx leading-32rpx text-#14181B mb-24rpx">{{ t("pages-login.sign-up.confirm-password") }}</view>
          <view class="border-color px-30rpx flex items-center  bg-#EFEFEF">
            <wd-input
                v-model.trim="logicStore.registerForm.newPwd"
                :cursorSpacing="20"
                :focus-when-clear="false"
                :maxlength="40"
                :placeholder="t('common.enterPassword')"
                clearable
                custom-class="flex-1 !bg-transparent"
                no-border
                placeholderClass="!text-#999 !text-32rpx"
                showPassword
            >
            </wd-input>
          </view>
        </view>
        <!-- First name -->
        <view class="mt-36rpx ">
          <view class="text-32rpx leading-32rpx text-#14181B mb-24rpx">{{ t("pages-login.sign-up.first-name") }}</view>
          <view class="border-color px-30rpx flex items-center  bg-#EFEFEF">
            <wd-input
                v-model.trim="logicStore.registerForm.firstName"
                :cursorSpacing="20"
                :focus-when-clear="false"
                :maxlength="40"
                :placeholder="t('common.enter')"
                clearable
                custom-class="flex-1 !bg-transparent"
                no-border
                placeholderClass="!text-#999 !text-32rpx"
            >
            </wd-input>
          </view>
        </view>
        <!-- Last name -->
        <view class="mt-36rpx ">
          <view class="text-32rpx leading-32rpx text-#14181B mb-24rpx">{{ t("pages-login.sign-up.last-name") }}</view>
          <view class="border-color px-30rpx flex items-center  bg-#EFEFEF">
            <wd-input
                v-model.trim="logicStore.registerForm.surname"
                :cursorSpacing="20"
                :focus-when-clear="false"
                :maxlength="40"
                :placeholder="t('common.enter')"
                clearable
                custom-class="flex-1 !bg-transparent"
                no-border
                placeholderClass="!text-#999 !text-32rpx"
            >
            </wd-input>
          </view>
        </view>
        <!-- Phone number -->
        <view v-if="showPhone" class="mt-36rpx ">
          <view class="text-32rpx leading-32rpx text-#14181B mb-24rpx">{{
              t("pages-login.sign-up.phone-number")
            }}
          </view>
          <view class="border-color pr-30rpx flex items-center  bg-#EFEFEF">
            <view class="pr-14rpx text-28rpx">
              <wd-picker v-model="areaCode" :columns="columns"/>
            </view>
            <wd-input
                v-model.trim="logicStore.registerForm.phone"
                :cursorSpacing="20"
                :focus-when-clear="false"
                :maxlength="40"
                :placeholder="t('common.enter')"
                :readonly="phoneIsReadonly"
                clearable
                custom-class="flex-1 !bg-transparent"
                no-border
                placeholderClass="!text-#999 !text-32rpx"
            >
            </wd-input>
          </view>
        </view>
        <view class="mt-54rpx">
          <wd-button :loading="btnLoading" block
                     custom-class="!h-108rpx !text-36rpx text-#fff font-bold !rounded-16rpx" loading-color="#000" @click="handleSubmit">
            {{ t('pages-login.sign-up.title') }}
          </wd-button>
        </view>
        <view class="mt-36rpx flex items-start text-28rpx text-primary lh-42rpx" @click="isAgreed = !isAgreed">
          <view class="shrink-0 center py-5rpx px-10rpx">
            <image v-show="isAgreed" class=" w-28rpx h-28rpx"
                   src="@img-login/101.png"></image>
            <image v-show="!isAgreed" class=" w-28rpx h-28rpx"
                   src="@img-login/100.png"></image>
          </view>
          <view class="">
            <text class="">{{ t('pages-login.continuing-agree') }}</text>
            <text class="text-#00A76D"
                  @click.stop="navigateTo(`/pages/agreement/index?code=${Agreement.USER_AGREEMENT}`)">
              {{ t('agreement.user-terms-conditions') }}、
            </text>
            <text class="text-#00A76D"
                  @click.stop="navigateTo(`/pages/agreement/index?code=${Agreement.PRIVACY_POLICY}`)">
              {{ t('agreement.privacy-policy') }}
            </text>
          </view>
        </view>
      </view>
    </view>


    <verification-code ref="verificationCodeRef" @submit="codeSubmit"/>
  </view>
</template>

<style lang="scss">
page {
  background-color: #fff;
}

.border-color {
  height: 98rpx;
  border-radius: 16rpx;
  border: 2rpx solid #D4D4D4;
}

:deep(.wd-input__clear) {
  background-color: transparent !important;
}

:deep(.wd-input__icon) {
  background-color: transparent !important;
}

:deep(.wd-picker__cell) {
  background-color: transparent !important;

  .wd-picker__value {
    margin-right: 8rpx !important;
  }
}

:deep(.wd-picker-view-column__item) {
  line-height: 94rpx !important;
}

:deep(.uni-picker-view-indicator) {
  height: 94rpx !important;
}
</style>
