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

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

import type { WordTempItem } 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 WordPreview from './word-preview.vue';

interface WorkflowParams {
  appid: string;
}

interface WorkflowContext {
  userId: string;
  conversationId: string;
  content: string;
  inputs: {
    [key: string]: any;
  };
  files: [];
}

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

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

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

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

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

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

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

  try {
    // const res = await props.runWorkflow(
    //   {
    //     appid: props.item.id,
    //   },
    //   {
    //     userId: '1562',
    //     conversationId: '',
    //     files: [],
    //     inputs: {
    //       declarationDoc: value.value,
    //     },
    //   },
    // );
    // 保存抓取结果 url

    const res = await props.runChatflow(
      {
        appid: 'baca08c1-e92b-4dc9-a445-3584803f54d4',
      },
      {
        userId: '1562',
        conversationId: '',
        files: [],
        inputs: {
          projectName: projectName.value,
        },
        content: value.value || '',
      },
    );
    fetchResult.value = '/static/9e1c421e-991c-411f-8176-6350a97e70f3.docx';
    resultItems.value.push({
      key: resultItems.value.length + 1,
      role: 'ai',
      content: res.answer,
      footer: h(Flex, null, [
        h(
          Button,
          {
            size: 'nomarl',
            type: 'primary',
            onClick: () => {
              openPreviewDrawer('right');
            },
          },
          '文档预览',
        ),
        h(
          Button,
          {
            size: 'nomarl',
            type: 'primary',
            style: {
              marginLeft: '10px',
            },
            onClick: () => {},
          },
          '文档下载',
        ),
      ]),
    });
    // 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 projectName = ref<string>('');
const value = ref('');

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

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

<template>
  <div>
    <PreviewDrawer />
    <a-space class="w-full" direction="vertical">
      <a-input v-model:value="projectName" required placeholder="项目名称" />
    </a-space>
    <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>
