<script lang="ts" setup>
import { toTypedSchema } from '@vee-validate/zod'
import { useForm } from 'vee-validate'
import { toast } from 'vue-sonner'
import { z } from 'zod'

const route = useRoute()
const router = useRouter()

const historyStore = useLlmHistories('course-course-outline')
const { conversations } = storeToRefs(historyStore)
const { updateConversation, appendChunkToLast, isConversationExist } =
  historyStore

const activeConversationId = ref<string | null>(null)

watch(activeConversationId, (val) => {
  if (val) {
    router.replace({
      query: {
        fn: route.query.fn,
        conversationId: val,
      },
    })
  } else {
    router.replace({
      query: {
        fn: route.query.fn,
      },
    })
  }
})

onMounted(() => {
  if (route.query.conversationId) {
    if (isConversationExist(route.query.conversationId as string)) {
      activeConversationId.value = route.query.conversationId as string
    } else {
      activeConversationId.value = null
      toast.error('会话不存在')
    }
  }
})

const schema = z.object({
  courseName: z
    .string({ required_error: '请输入课程名称' })
    .describe('课程名称'),
  targetAudience: z
    .string({ required_error: '请输入授课对象' })
    .describe('授课对象'),
  courseObjective: z
    .string({ required_error: '请输入课程目标' })
    .describe('课程目标'),
  otherRequirement: z.string().describe('其他要求').optional(),
})

const form = useForm({
  validationSchema: toTypedSchema(schema),
})

const onSubmit = (values: z.infer<typeof schema>) => {
  http_stream<z.infer<typeof schema>>('/ai/curriculum-outline/stream', values, {
    onStart(id, created_at) {
      activeConversationId.value = id
      updateConversation(id, {
        id,
        created_at,
        title: values.courseName,
        messages: [
          {
            role: 'user',
            content: `*生成一份 ${values.courseName} 的课程大纲*`,
          },
          {
            role: 'assistant',
            content: '',
          },
        ],
      })
    },
    onTextChunk: (chunk) => {
      appendChunkToLast(activeConversationId.value!, chunk)
    },
    onComplete: (id, finished_at) => {
      updateConversation(id!, {
        finished_at,
      })
    },
  })
}
</script>

<template>
  <div>
    <AiConversation
      :form
      :form-schema="schema"
      :form-field-config="{
        courseName: {
          inputProps: {
            placeholder: '请输入课程名称，如：数据结构与算法',
          },
        },
        targetAudience: {
          inputProps: {
            placeholder: '请输入授课对象，如：大一物联网专业学生',
          },
        },
        courseObjective: {
          component: 'textarea',
          inputProps: {
            placeholder:
              '例如：知识目标需掌握和理解的理论知识、概念、原理、理论框架等；技能目标需掌握学科中所需的基本操作技能，如实验操作、计算机操作、语言表达等',
          },
        },
        otherRequirement: {
          inputProps: {
            placeholder: '请输入其他要求，如：需要包含案例分析',
          },
        },
      }"
      :conversations
      :active-conversation-id="activeConversationId"
      disable-user-input
      @submit="onSubmit"
      @update:conversation-id="activeConversationId = $event"
      @delete-conversation="historyStore.removeConversation($event)"
    />
  </div>
</template>

<style scoped></style>
