<template>
  <UModal v-model:open="open" title="撰写新闻" description="在数据库中添加一篇新闻" fullscreen :ui="{
    body: 'overflow-y-auto p-6', // 防止溢出 + 内边距
    footer: 'justify-end'
  }">
    <UButton label="撰写新闻" icon="mdi:newspaper-plus" />

    <template #body>
      <UForm ref="form" :schema="newsSchema" :state="newsState" @submit="onSubmit" class="space-y-4">
        <UFormField label="新闻标题" name="title">
          <UInput v-model="newsState.title" placeholder="请输入新闻标题" class="w-full" />
        </UFormField>
        <UFormField label="新闻内容" name="contents">
          <ClientOnly>
            <MdEditor v-model="newsState.content" />
          </ClientOnly>
        </UFormField>
      </UForm>
    </template>

    <template #footer>
      <UButton label="Cancel" color="neutral" variant="subtle" @click="open = false" />
      <UButton label="Create" color="primary" variant="solid" @click="form.submit()" />
    </template>
  </UModal>
</template>

<script lang="ts" setup>
import type { FormSubmitEvent } from '@nuxt/ui';
import { MdEditor } from 'md-editor-v3';
import * as z from 'zod'

const form = ref();
const open = ref(false);

const newsSchema = z.object({
  title: z.string().min(2, '标题太短了容易产生歧义，请写长一些').max(15, '标题太长了影响阅读体验，请简短一些'),
  content: z.string()
})

type NewsSchema = z.output<typeof newsSchema>

const newsState = reactive<Partial<NewsSchema>>({
  title: undefined,
  content: undefined
})

const toast = useToast();
const onSubmit = async (event: FormSubmitEvent<NewsSchema>) => {
  toast.add({
    title: "成功",
    description: `${event.data.title} 新闻稿已经撰写完毕`,
    color: 'success'
  })
  open.value = false
}
</script>

<style></style>