<script setup lang="ts">
import type { 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 { UserOutlined } from '@ant-design/icons-vue';
import { Button, Flex, Space } 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: () => {
    return {
      id: '',
      name: '',
    };
  },
  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 content = ref('');
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 ====================
// 判断是否是以 .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,
          {
            type: 'primary',
            onClick: () => {
              openPreviewDrawer('right', files.url);
            },
          },
          '文档预览',
        ),
        h(
          Button,
          {
            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,
                {
                  type: 'primary',
                  onClick: () => {
                    openPreviewDrawer('right', msg.content.url);
                  },
                },
                '文档预览',
              ),
              h(
                Button,
                {
                  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">
      <div class="chat-left">
        <!-- 🌟 输入框 -->
        <Sender
          :value="content"
          class="sender"
          placeholder="科研申报文档"
          :auto-size="{ minRows: 6, maxRows: 18 }"
          :loading="agentRequestLoading"
          :disabled="agentRequestLoading"
          @submit="startFetching"
          @change="(value) => (content = value)"
        >
          <template #header>
            <Sender.Header :open="true" :title="props.item?.name || ''" />
          </template>
        </Sender>
      </div>

      <Space
        v-if="resultItems.length === 0"
        direction="vertical"
        size:16
        style="width: 60%; padding: 20px 0 0 12px"
      >
        <Welcome
          variant="borderless"
          icon="https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*s5sNRo5LjfQAAAAAAAAAAAAADgCCAQ/fmt.webp"
          title="欢迎使用PPT自动生成"
          description="请选择模板列表中需要生成文件的模板，输入参数后开始生成生成文件。"
        />
      </Space>
      <!-- 🌟 消息列表 -->
      <Bubble.List
        v-else
        style="width: 60%; padding: 12px"
        variant="shadow"
        :typing="true"
        :items="resultItems"
        :roles="roles"
      />
    </div>
  </div>
</template>

<style scoped lang="less">
.layout {
  width: 100%;
  //min-width: 1400px;
  max-height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 0;
  margin: 0 auto;
  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;
  //margin: 0 auto;
  box-sizing: border-box;
  display: flex;
  //flex-direction: column;
  padding: 0 12px 0 12px;
}
.chat-left {
  width: 40%;
  height: 100%;
  background: #ffffff;
  //margin: 0 auto;
  box-sizing: border-box;
  padding: 12px 12px 0 12px;
}

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

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