<script setup lang="ts">
import type { SpiderItem } from './typing';

import { ref } from 'vue';

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

interface SpiderParams {
  appid: string;
}

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

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

interface Props {
  item?: SpiderItem;
  title: string;
  runSpider?: (
    params: SpiderParams,
    context: SpiderContext,
  ) => Promise<SpiderResult>;
}

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

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

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

  try {
    const res = await props.runSpider(
      {
        appid: props.item.id,
      },
      {
        userId: '1562',
        conversationId: '',
        files: [],
        inputs: {},
      },
    );
    // 保存抓取结果
    fetchResult.value = res.data.outputs.result;
  } catch (error) {
    console.error(error);
  }

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

// 下载文件逻辑
const downloadFile = () => {
  if (!fetchResult.value) return;

  // 使用抓取结果作为文件内容
  const fileName = `${props.item.name}.txt`;
  const fileContent = fetchResult.value;

  // 创建 Blob 对象
  const blob = new Blob([fileContent], { type: 'text/plain' });

  // 创建下载链接
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = fileName;

  // 触发下载
  link.click();

  // 释放 URL 对象
  URL.revokeObjectURL(link.href);
};

const isFetching = ref(false);
const fetchResult = ref('');
const fetchStatus = ref('');
</script>

<template>
  <div class="flex h-full">
    <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">
        {{ item ? item.name : '请选择右侧爬虫' }}
      </CardContent>
      <CardFooter class="flex justify-end">
        <Button :disabled="!item" @click="startFetching">
          {{ isFetching ? '抓取中...' : '开始抓取' }}
        </Button>
        <Button
          class="mx-2"
          :disabled="fetchStatus !== 'completed'"
          @click="downloadFile"
        >
          下载文件
        </Button>
      </CardFooter>
    </Card>
  </div>
</template>
