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

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

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

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

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

import {
  CloudUploadOutlined,
  PaperClipOutlined,
  UserOutlined,
} from '@ant-design/icons-vue';
import { Badge, Button, Flex, Space, Typography } from 'ant-design-vue';
import { Attachments, Bubble, Sender, Welcome } from 'ant-design-x-vue';

import PptPreview from './ppt-preview.vue';

defineOptions({ name: 'PptWorkView' });

const props = withDefaults(defineProps<PropsWork>(), {
  itemMessage: () => null,
  item: () => null,
  runWorkflow: () => async () => ({
    data: {
      outputs: {
        result: '',
      },
    },
  }),
});

const userStore = useUserStore();
const roles: BubbleListProps['roles'] = {
  user: {
    placement: 'end',
    typing: false,
    styles: {
      content: {
        background: '#ffffff',
      },
    },
    avatar: { icon: h(UserOutlined), style: { background: '#87d068' } },
  },
  ai: {
    placement: 'start',
    typing: false,
    style: {
      maxWidth: 600,
      marginInlineEnd: 44,
    },
    styles: {
      content: {
        background: '#ffffff',
      },
      footer: {
        width: '100%',
      },
    },
    avatar: { icon: h(UserOutlined), style: { background: '#fde3cf' } },
  },
  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 headerOpen = ref(false);
const content = ref('');
const attachedFiles = ref<AttachmentsProps['items']>([]);
const agentRequestLoading = ref(false);
const fetchStatus = ref('');
const resultItems = ref<ResultItem[]>([]);
const fetchResult = ref('');

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

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

const handleFileChange: AttachmentsProps['onChange'] = (info) =>
  (attachedFiles.value = info.fileList);

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

const startFetching = async () => {
  resultItems.value = [];
  agentRequestLoading.value = true;
  fetchStatus.value = 'fetching';
  resultItems.value.push({
    key: resultItems.value.length + 1,
    role: 'user',
    content: content.value,
  });

  try {
    const res = await props.runWorkflow(props.item.id, {
      userId: userStore.userInfo?.userId || '',
      conversationId: '',
      files: [],
      inputs: {
        declarationDoc: content.value,
      },
    });
    const files = res.data.outputs.files[0];
    content.value = '';

    // const filename = ref('');

    // if (result && isPptxURL(result)) {
    //   filename.value = extractPptxFilename(result);
    // }

    // 保存抓取结果 url http://47.112.173.8:6802/static/66f3cfd95e364a239d8036390db658ae.pptx
    fetchResult.value = files.url;
    resultItems.value.push({
      key: resultItems.value.length + 1,
      role: 'ai',
      content: '文档已生成',
      footer: h(Flex, null, [
        h(
          Button,
          {
            size: 'nomarl',
            type: 'primary',
            onClick: () => {
              openPreviewDrawer('right', files.url);
            },
          },
          '文档预览',
        ),
        h(
          Button,
          {
            size: 'nomarl',
            type: 'primary',
            style: {
              marginLeft: '10px',
            },
            onClick: () => {
              // 创建隐藏的 <a> 标签用于触发下载
              const link = document.createElement('a');
              link.href = files.url; // 设置下载链接
              link.download = files.filename; // 设置下载文件名
              document.body.append(link); // 将 <a> 标签添加到页面中
              link.click(); // 触发点击事件开始下载
              link.remove(); // 下载完成后移除 <a> 标签
            },
          },
          '文档下载',
        ),
      ]),
    });
  } catch (error) {
    console.error(error);
  }

  // 模拟抓取完成
  agentRequestLoading.value = false;
  fetchStatus.value = 'completed';
};

// ==================== Nodes ====================

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

<template>
  <div class="layout">
    <PreviewDrawer />
    <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="欢迎使用PPT自动生成"
          description="请选择模板列表中需要生成文件的模板，输入参数后开始生成生成文件。"
        />
      </Space>
      <!-- 🌟 消息列表 -->
      <Bubble.List
        v-else
        variant="shadow"
        :typing="true"
        :items="resultItems"
        :roles="roles"
        style="flex: 1; padding: 10px 10px 0"
      />

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

        <template #header>
          <Sender.Header
            title="Attachments"
            :open="headerOpen"
            :styles="{ content: { padding: 0 } }"
            @open-change="(open) => (headerOpen = open)"
          >
            <Attachments
              :before-upload="() => false"
              :items="attachedFiles"
              @change="handleFileChange"
            >
              <template #placeholder="type">
                <Flex
                  v-if="type && type.type === 'inline'"
                  align="center"
                  justify="center"
                  vertical
                  gap="2"
                >
                  <Typography.Text style="font-size: 30px; line-height: 1">
                    <CloudUploadOutlined />
                  </Typography.Text>
                  <Typography.Title
                    :level="5"
                    style="margin: 0; font-size: 14px; line-height: 1.5"
                  >
                    Upload files
                  </Typography.Title>
                  <Typography.Text type="secondary">
                    Click or drag files to this area to upload
                  </Typography.Text>
                </Flex>
                <Typography.Text v-if="type && type.type === 'drop'">
                  Drop file here
                </Typography.Text>
              </template>
            </Attachments>
          </Sender.Header>
        </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>
