<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 VerificationCode from "../../components/verification-code.vue";
import {appUserRegisterPost} from "@/service";
import {useConfigStore, useUserStore} from "@/store";

const {t} = useI18n()

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

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

const isAgreed = ref(false)

const EmailRegisterSchema = z.object({
  firstName: z.string().min(1, {message: t('pages-login.index.prompt.first-name')}),
  surname: z.string().min(1, {message: t('pages-login.index.prompt.last-name')}),
  email: z.string().min(1, {message: t('pages-login.index.prompt.email-address-verify')}).email({message: t('pages-login.index.prompt.email-address-verify')}),
  confirmEmail: z.string().min(1, {message: t('pages-login.index.prompt.email-address-verify')}).email({message: t('pages-login.index.prompt.email-address-verify')}),
  loginPwd: z.string().min(1, {message: t('pages-login.index.prompt.password')}),
  confirmLoginPwd: z.string().min(1, {message: t('pages-login.index.prompt.password')}),
})
  .refine((data) => data.email === data.confirmEmail, {
    path: ['confirmEmail'],
    message: t('pages-login.index.prompt.confirm-email-verify')
  })
  .refine((data) => data.loginPwd === data.confirmLoginPwd, {
    path: ['confirmLoginPwd'],
    message: t('pages-login.index.prompt.confirm-password-verify')
  })

const PhoneRegisterSchema = z.object({
  firstName: z.string().min(1, {message: t('pages-login.index.prompt.first-name')}),
  surname: z.string().min(1, {message: t('pages-login.index.prompt.last-name')}),
  phone: z.string().min(1, {message: t('pages-login.index.prompt.phone-number')}).regex(/^\d{6,11}$/, {message: t('pages-login.index.prompt.phone-number-verify')}),
  loginPwd: z.string().min(1, {message: t('pages-login.index.prompt.password')}),
  confirmLoginPwd: z.string().min(1, {message: t('pages-login.index.prompt.password')}),
}).refine((data) => data.loginPwd === data.confirmLoginPwd, {
  path: ['confirmLoginPwd'],
  message: t('pages-login.index.prompt.confirm-password-verify')
})

function checkForm(): boolean {
  const type = logicStore.registerForm.type
  const schema = type === 'phone' ? PhoneRegisterSchema : EmailRegisterSchema
  const validateFormField = schema.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() {
  btnLoading.value = true
  // console.log(data)
  const {
    confirmEmail,
    confirmLoginPwd,
    ...rest
  } = logicStore.registerForm as any
  appUserRegisterPost({
    body: {
      ...rest,
      // 后端接收“确认密码”字段名为 newPwd
      newPwd: confirmLoginPwd,
      areaCode: areaCode.value,
      // captcha: data.code,
      // uuid: data.uuid,
      userPort: Config.userPort, // 登录端口2 商户端
    } as any
  }).then((res) => {
    userStore.token = res.data.token;
    logicStore.reset()
    uni.showToast({
      title: t('pages-login.sign-up.register-success'),
      icon: 'none',
    })
    nextTick(() => {
      userStore.getUserInfo();
      uni.navigateTo({
        url: Config.guidePath
      })
      // uni.redirectTo({
      //   url: '/pages-login/pages/guide-page/location'
      // })
      // const pages = getCurrentPages()
      // if(configStore.isShowedGuidePage) {
      //   if(pages.length > 2) {
      //     uni.navigateBack({delta: 2})
      //   } else {
      //     uni.switchTab({
      //       url: Config.indexPath
      //     })
      //   }
      // } else {
      //   uni.navigateTo({
      //     url: Config.guidePath
      //   })
      // }
    })
  }).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)
onMounted(() => {
  const {email, confirmEmail, phone, type} = logicStore.registerForm
  if (type === 'phone') {
    phoneIsReadonly.value = !!phone
    emailIsReadonly.value = false
  }
  if (type === 'email') {
    emailIsReadonly.value = !!(email || confirmEmail)
    phoneIsReadonly.value = false
    if (!logicStore.registerForm.email && logicStore.registerForm.confirmEmail) {
      logicStore.registerForm.email = logicStore.registerForm.confirmEmail
    }
  }
})
</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="logicStore.registerForm.type !== 'phone'" 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="logicStore.registerForm.type !== 'phone'" 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="20"
                :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.confirmLoginPwd"
                :cursorSpacing="20"
                :focus-when-clear="false"
                :maxlength="20"
                :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="logicStore.registerForm.type !== 'email'" 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 px-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 block custom-class="!h-108rpx !text-36rpx text-#fff font-bold !rounded-16rpx"
                     @click="handleSubmit" :loading="btnLoading" loading-color="#000">
            {{ 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>
