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

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

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

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

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

import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
  CardTitle,
} from '@vben-core/shadcn-ui';

import { UserOutlined } from '@ant-design/icons-vue';
import { Button, Flex, message, notification, Space } from 'ant-design-vue';
import { Attachments, Bubble, Welcome } from 'ant-design-x-vue';

import SpiderPreview from './spider-preview.vue';

defineOptions({
  name: 'WorkflowWorkView',
});
const props = withDefaults(defineProps<Props>(), {
  itemMessage: () => null,
  item: () => ({
    id: '',
    name: '',
    url: '',
    description: '',
  }),
  runSpiderGz: () => async () => ({
    outputs: {
      result: '',
      files: [],
    },
  }),
});
const userStore = useUserStore();
const resultItems = ref<ResultItem[]>([]);

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

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

const startFetching = async () => {
  // 更新状态为“抓取中”
  isFetching.value = true;
  fetchStatus.value = 'fetching';

  try {
    notification.info({
      message: '正在获取中...',
      duration: 3,
    });
    const res = await props.runSpiderGz(props.item.id, {
      userId: userStore.userInfo?.userId || '',
      conversationId: '',
      files: [],
      inputs: {},
    });
    if (res.data.outputs.files) {
      // 保存抓取结果
      fetchResult.value = res.data.outputs.files[0].url;
      notification.success({
        message: '获取成功',
        duration: 3,
      });

      const fileUrl = ref('');
      fileUrl.value = `/guangzhou${fetchResult.value}`;

      resultItems.value.push({
        key: resultItems.value.length + 1,
        role: 'ai',
        content: '文档已生成，有效时间5分钟，请及时查看或下载',
        footer: h(Flex, null, [
          h(
            Button,
            {
              // size: 'normal',
              type: 'primary',
              onClick: () => {
                openPreviewDrawer('right', fileUrl.value);
              },
            },
            '文档预览',
          ),
          h(
            Button,
            {
              // size: 'normal',
              type: 'primary',
              style: {
                marginLeft: '10px',
              },
              onClick: () => {
                // 创建隐藏的 <a> 标签用于触发下载
                const link = document.createElement('a');
                link.href = fileUrl.value; // 设置下载链接
                link.download = '广州公共资源交易中心数据获取'; // 设置下载文件名
                document.body.append(link); // 将 <a> 标签添加到页面中
                link.click(); // 触发点击事件开始下载
                link.remove(); // 下载完成后移除 <a> 标签
              },
            },
            '文档下载',
          ),
        ]),
      });
      fetchStatus.value = 'completed';
    } else {
      fetchResult.value = '';
      message.error('抓取无结果');
    }
  } catch (error) {
    message.error(`${error}`);
  }
  isFetching.value = false;
};

// 列表角色
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 }),
        ),
      ),
  },
};

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

// 监听 title 变化并更新 resultItems
watch(
  () => props.item,
  () => {
    resultItems.value = [];
  },
);

// 监听 itemMessage 变化并更新 resultItems
watch(
  () => props.itemMessage,
  (newVal) => {
    resultItems.value = [];
    if (newVal.length > 0) {
      newVal.forEach((msg) => {
        // resultItems.value.push({
        //   key: resultItems.value.length + 1,
        //   role: msg.role, // 'user' or 'ai'
        //   content: msg.content,
        //   footer: msg.footer,
        // });
        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: '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 = '广州公共资源交易中心数据获取'; // 设置下载文件名
                    document.body.append(link); // 将 <a> 标签添加到页面中
                    link.click(); // 触发点击事件开始下载
                    link.remove(); // 下载完成后移除 <a> 标签
                  },
                },
                '文档下载',
              ),
            ]),
          });
        }
      });
    }
  },
  { deep: true },
);
</script>

<template>
  <!--  style="flex-direction: column"-->
  <div
    class="flex h-full"
    style="flex-direction: column; width: 70%; padding-top: 20px"
  >
    <PreviewDrawer />
    <!--    <PreviewDrawer />-->
    <Space
      v-if="resultItems.length === 0"
      direction="vertical"
      size:16
      style="flex: 1"
    >
      <Welcome
        variant="borderless"
        icon="https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*s5sNRo5LjfQAAAAAAAAAAAAADgCCAQ/fmt.webp"
        title="欢迎使用AI平台信息获取"
        description="请选择数据信息列表中需要获取信息的链接，选取时间后开始爬取获取信息。"
      />
    </Space>
    <Bubble.List
      v-else
      variant="shadow"
      :typing="true"
      :items="resultItems"
      :roles="roles"
      style="flex: 1"
    />

    <Card class="w-full self-end" v-loading="isFetching">
      <CardHeader class="py-4">
        <CardTitle class="text-lg">{{ title }}</CardTitle>
      </CardHeader>
      <CardContent class="flex flex-wrap pt-0">
        {{ props.item ? props.item.description : '请选择左侧列表' }}
      </CardContent>
      <CardFooter class="flex justify-end">
        <Button :disabled="!item" type="primary" @click="startFetching">
          {{ isFetching ? '抓取中...' : '开始抓取' }}
        </Button>
      </CardFooter>
    </Card>
  </div>
</template>
