<script setup lang="ts">
const props = defineProps<{
  onSubmit: (data: ZodInfer<typeof schema>) => Promise<void>
}>()

const schema = z.object({
  endPoint: z.string({
    required_error: 'endpoint字段不能为空',
  }),
  accessKey: z.string({
    required_error: 'accesskey字段不能为空',
  }),
  secretKey: z.string({
    required_error: 'secretkey字段不能为空',
  }),
  port: z.number({
    required_error: 'port字段不能为空',
  }).optional(),
  region: z.string().optional(),
  useSSL: z.boolean(),
})

const formValues = {
  endPoint: 'fgws3.jwanfs.ocloud.ihep.ac.cn',
  accessKey: 'NsccczIb9DsAQ7RNMIkv',
  secretKey: 'gBGR9UdhESQntF7wbMqB',
  region: 'us-east-1',
  useSSL: true,
}

const open = ref(false)

async function onSubmit(values: ZodInfer<typeof schema>) {
  open.value = false
  await props.onSubmit(values)
}
</script>

<template>
  <Dialog v-model:open="open">
    <DialogTrigger as-child>
      <Button class="font-bold tracking-wide" size="xs">
        添加资源化技术
      </Button>
    </DialogTrigger>
    <DialogScrollContent class="sm:max-w-[425px]">
      <DialogHeader>
        <DialogTitle>资源化技术信息</DialogTitle>
        <DialogDescription>
          请填写所需要的资源化技术信息等。
        </DialogDescription>
      </DialogHeader>
      <Form class="space-y-4" :schema="schema" :initial-values="formValues" @submit="onSubmit">
        <FormFieldItem v-slot="{ componentField }" label="EndPoint" name="endPoint" required>
          <Input type="text" v-bind="componentField" placeholder="" />
        </FormFieldItem>
        <FormFieldItem v-slot="{ componentField }" label="AccessKey" name="accessKey" required>
          <Input type="text" v-bind="componentField" />
        </FormFieldItem>
        <FormFieldItem v-slot="{ componentField }" label="SecretKey" name="secretKey" required>
          <Input type="text" v-bind="componentField" />
        </FormFieldItem>
        <FormFieldItem v-slot="{ componentField }" label="端口" name="port">
          <Input type="number" v-bind="componentField" />
        </FormFieldItem>
        <FormFieldItem name="useSSL">
          <template #content="{ value, handleChange }">
            <div class="col-span-1" />
            <div class="flex col-span-3 gap-x-3">
              <FormControl>
                <Checkbox :checked="value" @update:checked="handleChange" />
              </FormControl>
              <div class="space-y-1 leading-none">
                <FormLabel>useSSL</FormLabel>
                <FormDescription>
                  是否启用安全（HTTPS）认证
                </FormDescription>
                <FormMessage />
              </div>
            </div>
          </template>
        </FormFieldItem>

        <DialogFooter class="mt-4">
          <Button type="submit" class="font-bold tracking-wide">
            保存
          </Button>
        </DialogFooter>
      </Form>
    </DialogScrollContent>
  </Dialog>
</template>
