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

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

import type { PPTTempItem } from './typing';

import { h, ref } from 'vue';

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

import { Card } from '@vben-core/shadcn-ui';

import { UserOutlined } from '@ant-design/icons-vue';
import { Button, Flex } from 'ant-design-vue';
import { Attachments, BubbleList, Sender } from 'ant-design-x-vue';

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

interface WorkflowParams {
  appid: string;
}

interface WorkflowContext {
  userId: string;
  conversationId: string;
  files: unknown[];
  inputs: Record<string, unknown>;
}

interface WorkflowResult {
  data: {
    outputs: {
      result: string;
    };
  };
}

interface Props {
  item?: PPTTempItem;
  runWorkflow?: (
    params: WorkflowParams,
    context: WorkflowContext,
  ) => Promise<WorkflowResult>;
}

defineOptions({
  name: 'SpiderWorkView',
});

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

const [PreviewDrawer, previewDrawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: PptPreview,
  // placement: 'left',
});

function openPreviewDrawer(placement: DrawerPlacement = 'right') {
  previewDrawerApi.setState({ placement }).open();
}

const startFetching = async () => {
  isFetching.value = true;
  fetchStatus.value = 'fetching';

  try {
    // const res = await props.runWorkflow(
    //   {
    //     appid: props.item.id,
    //   },
    //   {
    //     userId: '1562',
    //     conversationId: '',
    //     files: [],
    //     inputs: {
    //       declarationDoc: value.value,
    //     },
    //   },
    // );
    // 保存抓取结果 url http://47.112.173.8:6802/static/66f3cfd95e364a239d8036390db658ae.pptx
    fetchResult.value = '/static/66f3cfd95e364a239d8036390db658ae.pptx';
    resultItems.value.push({
      key: resultItems.value.length + 1,
      role: 'ai',
      content: '文档已生成',
      footer: h(Flex, null, [
        h(
          Button,
          {
            size: 'nomarl',
            type: 'primary',
            onClick: () => {
              openPreviewDrawer('right');
            },
          },
          '文档预览',
        ),
        h(
          Button,
          {
            size: 'nomarl',
            type: 'primary',
            style: {
              marginLeft: '10px',
            },
            onClick: () => {},
          },
          '文档下载',
        ),
      ]),
    });
  } catch (error) {
    console.error(error);
  }

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

const roles: BubbleListProps['roles'] = {
  user: {
    placement: 'end',
    typing: false,
    avatar: { icon: h(UserOutlined), style: { background: '#87d068' } },
  },
  ai: {
    placement: 'start',
    typing: false,
    style: {
      maxWidth: 600,
      marginInlineEnd: 44,
    },
    styles: {
      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 }),
        ),
      ),
  },
};

const isFetching = ref(false);
const fetchResult = ref('');
const fetchStatus = ref('');
const value = ref('');

interface ResultItem {
  key: number;
  role: 'ai' | 'user';
  content: string;
  footer?: any;
}

const resultItems = ref<ResultItem[]>([]);
</script>

<template>
  <div>
    <PreviewDrawer />
    <div style="height: calc(67vh - 120px); margin: 20px; overflow-y: auto">
      <BubbleList :roles="roles" :items="resultItems" />
    </div>
    <Card class="w-full">
      <Sender
        v-model:value="value"
        :loading="isFetching"
        :auto-size="{ minRows: 6, maxRows: 12 }"
        @submit="startFetching"
      />
    </Card>
  </div>
</template>
