<script lang="ts" setup>
import { uuidv4 } from "@uniiem/uuid";
import type { IWorkflowResponse, LocalMessage, VisitorRole } from "~/types";

const gstate = useGState();
const runtimeConfig = useRuntimeConfig();

const getPopularInquiriesByRole = () => {
  return {
    stu: [
      {
        label: "新生入学",
        inquiries: [
          {
            question: "新生报到时间",
          },
          {
            question: "新生报到流程",
          },
          {
            question: "如何到达学院",
          },
          {
            question: "如何办理户口迁移",
          },
          {
            question: "学院 VPN 使用方法",
          },
        ],
      },
      {
        label: "学校概况",
      },
      {
        label: "学术学习",
      },
      {
        label: "生活服务",
      },
      {
        label: "就业辅导",
      },
    ],
    tea: [
      {
        label: "教学管理",
      },
      {
        label: "科研管理",
      },
      {
        label: "学生管理",
      },
      {
        label: "教学资源",
      },
      {
        label: "教学评价",
      },
    ],
    fans: [
      {
        label: "校园风光",
      },
      {
        label: "校园活动",
      },
      {
        label: "校园新闻",
      },
      {
        label: "校园文化",
      },
      {
        label: "校园历史",
      },
    ],
  } as Record<
    VisitorRole,
    { label: string; inquiries?: Array<{ question: string }> }[]
  >;
};

const scrollArea = ref<HTMLDivElement | null>(null);
// 滤除 details 标签正则
const regex = /(?<=<\/details>\n\n)[\s\S]*/gm;

// 常见问题
const inquiries = computed(
  () => getPopularInquiriesByRole()[gstate.currentRole]
);

const responding = ref(false);
const inquiryInput = ref("");
const onInquirySubmit = async () => {
  if (inquiryInput.value) {
    gstate.insertOrUpdateMessage({
      id: uuidv4(),
      role: "user",
      message: inquiryInput.value,
    });
    responding.value = true;

    scrollLastMessageIntoView();

    let botMessageId = uuidv4();
    gstate.insertOrUpdateMessage({
      id: botMessageId,
      role: "bot",
    });

    try {
      const resp = await useFetch<IWorkflowResponse>(
        `${runtimeConfig.public.DifyBaseURL}/workflows/run`,
        {
          method: "post",
          headers: {
            Authorization: `Bearer ${runtimeConfig.public.DifyApiKey}`,
          },
          body: JSON.stringify({
            inputs: {
              question: inquiryInput.value,
              role: gstate.currentRole,
            },
            response_mode: "blocking",
            user: "abc-123",
          }),
        }
      );
      gstate.insertOrUpdateMessage({
        id: botMessageId,
        role: "bot",
        message:
          resp.data.value?.data.outputs.message.match(regex)?.[0] ||
          "网络繁忙，请稍后再试",
      });
    } catch (error) {
      gstate.insertOrUpdateMessage({
        id: botMessageId,
        role: "bot",
        message: "网络繁忙，请稍后再试",
      });
    }
    inquiryInput.value = "";

    responding.value = false;
    scrollLastMessageIntoView();
  }
};

const scrollLastMessageIntoView = () => {
  nextTick(() => {
    scrollArea.value?.scrollTo({
      top: scrollArea.value?.scrollHeight,
      behavior: "smooth",
    });
  });
};
</script>

<template>
  <div ref="scrollArea" class="h-full overflow-auto overflow-x-hidden mb-20">
    <div class="p-4 h-full flex flex-col gap-4">
      <PopularInquiries
        :inquiries-list="inquiries"
        @select-inquiry="
          (inquiry) => {
            if (responding) return;
            inquiryInput = inquiry;
            onInquirySubmit();
          }
        "
      />

      <ChatMessage
        v-for="message in gstate.messages"
        :name="gstate.botName"
        :key="message.id"
        :message="message"
      />
    </div>
    <div
      class="fixed inset-x-0 bottom-0 p-4 bg-white/90 rounded-t-2xl shadow-2xl dark:bg-neutral-800/90 backdrop-blur-2xl"
    >
      <img
        src="~/assets/image/pattern/ai_glow.png"
        class="absolute top-0 inset-x-0 opacity-50 pointer-events-none"
      />
      <div class="w-full flex justify-between items-center gap-2">
        <UInput
          placeholder="请输入问题"
          class="flex-1"
          size="xl"
          v-model="inquiryInput"
        />
        <UButton
          color="primary"
          variant="solid"
          size="xl"
          trailing
          trailing-icon="tabler:send-2"
          :loading="responding"
          loading-icon="svg-spinners:tadpole"
          @click="onInquirySubmit"
          >提问</UButton
        >
      </div>
    </div>
  </div>
</template>

<style scoped></style>
