<script lang="ts" setup>
import {appAutomaticCookingMachineRegistrationPost} from "@/service";
import {useConfigStore} from "@/store";
import {z} from 'zod';

const {t} = useI18n();

const configStore = useConfigStore();

const emit = defineEmits(['submit']);

const formData = ref({
  name: '',
  phone: '',
})

// Zod 校验 schema
const formSchema = z.object({
  name: z.string().min(1, t('common.placeholder.pleaseEnterName')),
  phone: z.string().min(1, t('common.placeholder.pleaseEnterPhone'))
})

const show = ref(false);

function onOpen() {
  show.value = true;
}

function handleClose() {
  show.value = false;
}

function handleSubmit() {
  // Zod 表单校验
  const result = formSchema.safeParse(formData.value)
  if (!result.success) {
    const firstError = result.error.errors[0]
    uni.showToast({
      title: firstError.message,
      icon: 'none'
    })
    return
  }

  // 校验通过，提交表单
  appAutomaticCookingMachineRegistrationPost({
    body: {
      ...formData.value
    }
  }).then(res => {
    uni.showToast({
      title: t('toast.submitSuccess'),
      icon: 'none'
    })
    handleClose()
    emit('submit')
  })
}

defineExpose({
  onOpen,
});
</script>

<template>
  <wd-popup
      v-model="show"
      position="bottom"
      @close="handleClose"
  >
    <view class="px-30rpx pt-52rpx">
      <view class="text-40rpx lh-40rpx font-500 text-#333 text-center mb-52rpx">{{ t('common.inquiry') }}</view>
      <view class="h-98rpx rounded-16rpx px-28rpx flex items-center bg-#F2F2F2 mb-40rpx">
        <wd-input
            v-model="formData.name"
            :focus-when-clear="false"
            :placeholder="t('common.placeholder.pleaseEnterName')"
            clearable
            custom-class="flex items-center !text-30rpx !bg-transparent flex-1"
            maxlength="20"
            no-border
            placeholderStyle="font-size: 30rpx;color: #999;"
        ></wd-input>
      </view>
      <view class="h-98rpx rounded-16rpx px-28rpx flex items-center bg-#F2F2F2">
        <wd-input
            v-model="formData.phone"
            :focus-when-clear="false"
            :placeholder="t('common.placeholder.pleaseEnterPhone')"
            clearable
            custom-class="flex items-center !text-30rpx !bg-transparent flex-1"
            maxlength="20"
            no-border
            placeholderStyle="font-size: 30rpx;color: #999;"
            type="number"
        ></wd-input>
      </view>
      <wd-button block class="!h-108rpx !rounded-16rpx !text-36rpx text-#fff font-500 mt-68rpx" @click="handleSubmit">
        {{ t('common.submit') }}
      </wd-button>
      <view :style="[configStore.iosSafeBottomPlaceholder]"></view>
    </view>
  </wd-popup>
</template>

<style lang="scss" scoped>
:deep(.wd-input__clear) {
  background-color: transparent !important;
}
</style>