<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,
  // CloudUploadOutlined,
  // PaperClipOutlined,
  UserOutlined,
} from '@ant-design/icons-vue';
// import type { VNode } from '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: () => null,
  itemMessage: () => null,
  paramsData: () => null,
  runChatflow: () => async () => ({
    data: {
      outputs: {
        result: '',
      },
    },
  }),
});

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

const renderMarkdown: BubbleListProps['roles'][string]['messageRender'] = (
  content,
) => {
  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({
  projectName: '',
  projectContext: '',
  projectKeyAvoidTechOrKeyword: '',
  userInitialInnovationPoint: '',
});
const open = ref(false);
// const inputStatus = ref<string>('');
const fetchStatus = ref('');
const resultItems = ref<ResultItem[]>([]);
const conversationId = ref('');
const fetchResult = 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,
) {
  const fileData = filename.value;
  previewDrawerApi.setState({ placement }).setData(fileData).open();
}

// ==================== Event ====================

// 判断是否是以 .docx 结尾的 URL
function isDocxURL(str: string): boolean {
  return str.endsWith('.docx');
}

// 使用正则提取 /static/ 后面的文件名部分
function extractDocxFilename(url: string): null | string {
  const match = url.match(/\/static\/([a-f0-9-]+\.docx)$/i);
  if (match) {
    return match[1]; // 返回类似：9e1c421e-991c-411f-8176-6350a97e70f3.docx
  }
  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({
      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 = '';
    const { answer } = res;
    conversationId.value = res.conversationId;

    const filename = ref('');

    if (answer && isDocxURL(answer)) {
      filename.value = extractDocxFilename(answer);
      resultItems.value.push({
        key: resultItems.value.length + 1,
        role: 'ai',
        content: '文档已生成',
        footer: h(Flex, null, [
          h(
            Button,
            {
              size: 'nomarl',
              type: 'primary',
              onClick: () => {
                openPreviewDrawer('right', filename);
              },
            },
            '文档预览',
          ),
          h(
            Button,
            {
              size: 'nomarl',
              type: 'primary',
              style: {
                marginLeft: '10px',
              },
              onClick: () => {
                // 创建隐藏的 <a> 标签用于触发下载
                const link = document.createElement('a');
                link.href = answer; // 设置下载链接
                link.download = filename.value; // 设置下载文件名
                document.body.append(link); // 将 <a> 标签添加到页面中
                link.click(); // 触发点击事件开始下载
                link.remove(); // 下载完成后移除 <a> 标签
              },
            },
            '文档下载',
          ),
        ]),
      });
    } else {
      resultItems.value.push({
        key: resultItems.value.length + 1,
        role: 'ai',
        content: res.answer,
      });
    }

    fetchResult.value = `/static/${filename.value}`;
  } 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 = [];
    if (newVal && newVal.length > 0) {
      newVal.forEach((msg) => {
        if (msg.role === 'user') {
          resultItems.value.push({
            key: resultItems.value.length + 1,
            role: msg.role, // 'user' or 'ai'
            content: msg.content,
            footer: msg.footer,
          });
        } else {
          const filename = ref('');

          if (msg.content && isDocxURL(msg.content)) {
            filename.value = extractDocxFilename(msg.content);
            resultItems.value.push({
              key: resultItems.value.length + 1,
              role: msg.role, // 'user' or 'ai'
              content: '文档已生成',
              footer: h(Flex, null, [
                h(
                  Button,
                  {
                    size: 'normal',
                    type: 'primary',
                    onClick: () => {
                      openPreviewDrawer('right', filename);
                    },
                  },
                  '文档预览',
                ),
                h(
                  Button,
                  {
                    size: 'normal',
                    type: 'primary',
                    style: {
                      marginLeft: '10px',
                    },
                    onClick: () => {
                      // 创建隐藏的 <a> 标签用于触发下载
                      const link = document.createElement('a');
                      link.href = msg.content; // 设置下载链接
                      link.download = filename.value; // 设置下载文件名
                      document.body.append(link); // 将 <a> 标签添加到页面中
                      link.click(); // 触发点击事件开始下载
                      link.remove(); // 下载完成后移除 <a> 标签
                    },
                  },
                  '文档下载',
                ),
              ]),
            });
          } else {
            resultItems.value.push({
              key: resultItems.value.length + 1,
              role: msg.role, // 'user' or 'ai'
              content: msg.content,
            });
          }
        }
      });
    }
  },
  { deep: 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"
        :message-render="renderMarkdown"
      />

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

      <!-- 🌟 输入框 -->
      <Sender
        :value="content"
        class="sender"
        :loading="agentRequestLoading"
        @submit="startFetching"
        @change="(value) => (content = value)"
      >
        <template #prefix>
          <Badge :dot="attachedFiles.length > 0 && !headerOpen">
            <Button type="text" @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>
