<script setup lang="ts">
import type {
  AttachmentsProps,
  BubbleListProps,
  PromptsProps,
} from 'ant-design-x-vue';

import type { DrawerPlacement } from '@vben/common-ui';

import type { Props, ResultItem } from '../typing';

import { computed, h, ref, watch } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';

import { EditOutlined, UserOutlined } from '@ant-design/icons-vue';
import {
  Badge,
  Button,
  Flex,
  Form,
  FormItem,
  Input,
  Modal,
  notification,
  Space,
  Textarea,
  Typography,
} from 'ant-design-vue';
import {
  Attachments,
  Bubble,
  Prompts,
  Sender,
  Welcome,
} from 'ant-design-x-vue';
import markdownIt from 'markdown-it';

import WordPreview from './word-preview.vue';

defineOptions({ name: 'WordWorkView' });

const props = withDefaults(defineProps<Props>(), {
  item: () => {
    return {
      id: '',
      name: '',
    };
  },
  itemMessage: Array,
  paramsData: Array,
  runChatFlow: () => {
    return {
      event: '',
      conversationId: '',
      messageFiles: [],
      messageId: '',
      taskId: '',
      id: '',
      answer: '',
    };
  },
  projectInfo: () => {
    return {
      projectContext: '',
      projectKeyAvoidTechOrKeyword: '',
      projectName: '',
      userInitialInnovationPoint: '',
    };
  },
});

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

// 初始化 markdown 解析器
const md = markdownIt({ html: true, breaks: true });

const renderMarkdown: BubbleListProps['roles'][string]['messageRender'] = (
  content: string,
) => {
  return h(Typography, [
    h('div', {
      innerHTML: content,
      style: {
        // padding: '8px',
        lineHeight: '1.6',
        whiteSpace: 'break-spaces',
      },
    }),
  ]);
};

// const sleep = () => new Promise((resolve) => setTimeout(resolve, 500));

const senderPromptsItems = computed(() => {
  if (typeof props.paramsData !== 'object' || props.paramsData === null)
    return [];

  return Object.keys(props.paramsData).map((key, index) => ({
    key: index,
    description: props.paramsData[key],
  }));
});

const roles: BubbleListProps['roles'] = {
  user: {
    placement: 'end',
    variant: 'shadow',
    typing: false,
    styles: {
      content: {
        background: '#ffffff',
      },
    },
    avatar: { icon: h(UserOutlined), style: { background: '#87d068' } },
  },
  ai: {
    placement: 'start',
    variant: 'shadow',
    typing: false,
    style: {
      maxWidth: 600,
      marginInlineEnd: 44,
    },
    styles: {
      content: {
        background: '#ffffff',
      },
      footer: {
        width: '100%',
      },
    },
    avatar: { icon: h(UserOutlined), style: { background: '#fde3cf' } },
    messageRender: (content) =>
      h(Typography, [
        h('div', {
          innerHTML: md.render(content),
        }),
      ]),
  },
  file: {
    placement: 'start',
    avatar: { icon: h(UserOutlined), style: { visibility: 'hidden' } },
    variant: 'borderless',
    messageRender: (items: any) =>
      h(
        Flex,
        { vertical: true, gap: 'middle' },
        items.map((item: any) =>
          h(Attachments.FileCard, { key: item.uid, item }),
        ),
      ),
  },
};

// ==================== State ====================
const userStore = useUserStore();
const headerOpen = ref(false);
const content = ref('');
// const conversationsItems = ref(defaultConversationsItems);
const attachedFiles = ref<AttachmentsProps['items']>([]);
const agentRequestLoading = ref(false);
const projectInfo = ref({ ...props.projectInfo });
const open = ref(false);
// const inputStatus = ref<string>('');
const fetchStatus = ref('');
const resultItems = ref<ResultItem[]>([]);
const conversationId = ref('');
const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};
// ==================== Runtime ====================

const [PreviewDrawer, previewDrawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: WordPreview,
  // placement: 'left',
});
function openPreviewDrawer(
  placement: DrawerPlacement = 'right',
  filename?: string,
) {
  previewDrawerApi.setState({ placement }).setData(filename).open();
}

// ==================== Event ====================
function extractDocxInfo(
  markdownLink: string,
): null | { filename: string | undefined; url: string } {
  const fileRegex = /\[(.*?)\]/;
  const urlRegex = /\((.*?)\)/;
  const fileMatch = markdownLink.match(fileRegex);
  const urlMatch = markdownLink.match(urlRegex);
  if (fileMatch && urlMatch) {
    const filename = fileMatch[1]; // 提取 [filename] 部分
    const url = urlMatch[1] || ''; // 提取 (url) 部分
    return { filename, url };
  }
  return null;
}

const startFetching = async () => {
  if (projectInfo.value.projectName === '') {
    open.value = true;
    return;
  }
  if (content.value === '') {
    notification.warn({
      message: '请输入项目内容',
      description: '请在输入框中输入项目内容',
    });
    open.value = false;
    return;
  }
  open.value = false;
  agentRequestLoading.value = true;
  fetchStatus.value = 'fetching';
  resultItems.value.push({
    key: resultItems.value.length + 1,
    role: 'user',
    content: content.value,
  });

  try {
    const res = await props.runChatFlow(props.item.id, {
      userId: userStore.userInfo?.userId || '',
      conversationId: conversationId.value,
      files: [],
      inputs: {
        projectName: projectInfo.value.projectName,
        projectContext: projectInfo.value.projectContext,
        keyAvoidTechOrKeyword: projectInfo.value.projectKeyAvoidTechOrKeyword,
        userInitialInnovationPoint:
          projectInfo.value.userInitialInnovationPoint,
      },
      content: content.value || '',
    });
    content.value = '';
    if (conversationId.value === '') {
      emit('history', props.item.id);
    }
    conversationId.value = res.conversationId;
    const docxInfo = extractDocxInfo(res.answer);
    if (docxInfo === null) {
      resultItems.value.push({
        key: resultItems.value.length + 1,
        role: 'ai',
        content: res.answer,
      });
    } else {
      const { filename, url } = docxInfo;
      // const { id, url } = res.messageFiles[0];
      resultItems.value.push({
        key: resultItems.value.length + 1,
        role: 'ai',
        content: '文档已生成',
        footer: h(Flex, null, [
          h(
            Button,
            {
              type: 'primary',
              onClick: () => {
                openPreviewDrawer('right', url);
              },
            },
            '文档预览',
          ),
          h(
            Button,
            {
              type: 'primary',
              style: { marginLeft: '10px' },
              onClick: () => {
                const link = document.createElement('a');
                link.href = url;
                link.download = filename as string;
                document.body.append(link);
                link.click();
                link.remove();
              },
            },
            '文档下载',
          ),
        ]),
      });
    }
  } catch (error) {
    console.error(error);
  }

  agentRequestLoading.value = false;
  fetchStatus.value = 'completed';
};

const onPromptsItemClick: PromptsProps['onItemClick'] = (info) => {
  content.value = info.data.description;
};

// 监听 itemMessage 变化并更新 resultItems
watch(
  () => props.itemMessage,
  (newVal) => {
    resultItems.value = [];
    content.value = '';
    conversationId.value = newVal[1]?.content.conversationId || '';
    if (newVal && newVal.length > 0) {
      newVal.forEach((msg) => {
        if (msg.role === 'user') {
          resultItems.value.push({
            key: resultItems.value.length + 1,
            role: msg.role,
            content: msg.content,
            footer: msg.footer,
          });
        } else {
          if (msg.content.messageFiles.length > 0) {
            const { id, url } = msg.content.messageFiles[0];
            resultItems.value.push({
              key: resultItems.value.length + 1,
              role: msg.role,
              content: '文档已生成',
              footer: h(Flex, null, [
                h(
                  Button,
                  {
                    type: 'primary',
                    onClick: () => {
                      openPreviewDrawer('right', url);
                    },
                  },
                  '文档预览',
                ),
                h(
                  Button,
                  {
                    type: 'primary',
                    style: { marginLeft: '10px' },
                    onClick: () => {
                      const link = document.createElement('a');
                      link.href = url;
                      link.download = id;
                      document.body.append(link);
                      link.click();
                      link.remove();
                    },
                  },
                  '文档下载',
                ),
              ]),
            });
          } else {
            resultItems.value.push({
              key: resultItems.value.length + 1,
              role: msg.role,
              content: msg.content.answer,
            });
          }
        }
      });
    }
  },
  { deep: true },
);

watch(
  () => props.projectInfo,
  (newVal) => {
    projectInfo.value = { ...newVal };
  },
  { deep: true, immediate: true },
);
</script>

<template>
  <div class="layout">
    <PreviewDrawer />
    <Modal v-model:open="open" title="项目信息" :footer="null">
      <Form :model="projectInfo" v-bind="layout" @finish="startFetching">
        <FormItem label="项目名称" name="projectName" required>
          <Input
            v-model:value="projectInfo.projectName"
            placeholder="请输入项目名称"
          />
        </FormItem>
        <FormItem label="项目背景" name="projectContext">
          <Textarea
            v-model:value="projectInfo.projectContext"
            placeholder="请输入项目背景"
          />
        </FormItem>
        <FormItem label="规避关键词" name="projectKeyAvoidTechOrKeyword">
          <Textarea
            v-model:value="projectInfo.projectKeyAvoidTechOrKeyword"
            placeholder="规避关键词"
          />
        </FormItem>
        <FormItem label="创新点" name="userInitialInnovationPoint">
          <Textarea
            v-model:value="projectInfo.userInitialInnovationPoint"
            placeholder="请输入创新点"
          />
        </FormItem>
        <FormItem label="" :wrapper-col="{ span: 14, offset: 8 }">
          <Button type="primary" html-type="submit" style="float: right">
            提交
          </Button>
        </FormItem>
      </Form>
    </Modal>
    <div class="chat">
      <Space
        v-if="resultItems.length === 0"
        direction="vertical"
        size:16
        style="flex: 1; padding-top: 20px"
      >
        <Welcome
          variant="borderless"
          icon="https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*s5sNRo5LjfQAAAAAAAAAAAAADgCCAQ/fmt.webp"
          title="欢迎使用AI申报书WORD生成"
          description="请选择模板列表中需要生成文件的模板，输入参数后开始生成生成内容或文件。"
        />
      </Space>
      <!-- 🌟 消息列表 -->
      <Bubble.List
        v-else
        :items="resultItems"
        :roles="roles"
        style="flex: 1; padding: 10px"
        :message-render="renderMarkdown"
      />

      <!-- 🌟 提示词 -->
      <Prompts
        :items="senderPromptsItems"
        @item-click="onPromptsItemClick"
        :wrap="true"
      />

      <!-- 🌟 输入框 -->
      <Sender
        :value="content"
        class="sender"
        :loading="agentRequestLoading"
        :disabled="agentRequestLoading"
        @submit="startFetching"
        @change="(value) => (content = value)"
      >
        <template #prefix>
          <Badge :dot="attachedFiles.length > 0 && !headerOpen">
            <Button @click="() => (open = !open)">
              <template #icon>
                <EditOutlined />
              </template>
            </Button>
          </Badge>
        </template>
      </Sender>
    </div>
  </div>
</template>

<style scoped lang="less">
.layout {
  width: 100%;
  min-width: 1400px;
  max-height: 100vh;
  display: flex;
  flex-direction: column;
  background: hsl(216deg 21.74% 95.49%);
  font-family: AlibabaPuHuiTi, v-deep(var(--ant-font-family)), sans-serif;
  border-radius: v-deep(var(--ant-border-radius));
}

.chat {
  width: 100%;
  height: 100%;
  max-height: 88vh;
  max-width: 1000px;
  margin: 0 auto;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  padding: 12px;
  gap: 16px;
}

.placeholder {
  padding-top: 32px;
  text-align: left;
  flex: 1;
}

.sender {
  background: #ffffff;
  width: 100%;
  box-shadow: v-deep(var(--ant-box-shadow));
}
</style>
