<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';

import { message, RangePicker } from 'ant-design-vue';
import dayjs from 'dayjs';

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 selectedDateRange = ref<string[]>([]);

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

  let publish_start_time = ''; // 默认值
  let publish_end_time = ''; // 默认值

  if (selectedDateRange.value && selectedDateRange.value.length === 2) {
    publish_start_time =
      dayjs(selectedDateRange.value[0]).format('YYYYMMDDhhmmss') || '';
    publish_end_time =
      dayjs(selectedDateRange.value[1]).format('YYYYMMDDhhmmss') || '';
  }

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

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

// 下载文件逻辑
const downloadFile = () => {
  if (!fetchResult.value || !fetchResult.value.startsWith('http')) {
    message.error('无效的文件链接');
    return;
  }

  const fileUrl = fetchResult.value;
  const fileName = decodeURIComponent(
    fileUrl.slice(Math.max(0, fileUrl.lastIndexOf('/') + 1)),
  );

  const link = document.createElement('a');
  link.href = fileUrl;
  link.download = fileName;
  link.click();
};

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">
        <RangePicker
          class="mx-2"
          v-model:value="selectedDateRange"
          format="YYYY/MM/DD"
        />
        <Button
          :disabled="!item || selectedDateRange.length < 2"
          @click="startFetching"
        >
          {{ isFetching ? '抓取中...' : '开始抓取' }}
        </Button>
        <Button
          class="mx-2"
          :disabled="fetchStatus !== 'completed'"
          @click="downloadFile"
        >
          下载文件
        </Button>
      </CardFooter>
    </Card>
  </div>
</template>
