<script lang="ts" setup>
// sendWorkflow
import type {
  AppListResult,
  ResultItem,
  TempItem,
  WordFlowItem,
} from './typing';

import { onMounted, ref } from 'vue';

import { notification } from 'ant-design-vue';

import {
  getAppListByType,
  getSpiderStatus,
  getWorkflowInfo,
  runSpider,
  runSpiderGz,
  stopSpider,
} from '#/api';

import { SelfWorkView, SpiderListView, WorkflowWorkView } from './components';

const history = ref([]);
const loading = ref(true);
const temp = ref<AppListResult[]>([]);
const itemMessage = ref<ResultItem[]>([]);

//  获取日志
// const getLogs = async (appid: string, limit: number) => {
//   loading.value = true;
//   history.value = await getWorkflowList({
//     appid,
//     limit,
//   });
//   loading.value = false;
// };

const getTemp = async () => {
  const res = await getAppListByType(3);
  if (Array.isArray(res) && res.length > 0) {
    // 提取 id 和 name 并赋值给 temp
    temp.value = res.map(({ id, name, description }) => ({
      id,
      name,
      description,
    }));
  }
};

async function handleClick(item: WordFlowItem) {
  const res = await getWorkflowInfo({
    appid: item.appId,
    workflowRunId: item.workflowRunId,
  });
  itemMessage.value = [];
  if (res.outputs) {
    itemMessage.value.push({
      key: itemMessage.value.length + 1,
      role: 'ai',
      content: res.outputs.result,
    });
  }
}

const currentTemp = ref<TempItem>({
  id: '77c068fd-d5b6-4c33-97d8-db5511a09b26',
  name: '全国公共资源交易平台_信息爬取',
  description: 'https://ygp.gdzwfw.gov.cn/',
});

async function handleClickMode(item: TempItem) {
  notification.success({
    message: `${item.name}`,
    description: '已选取',
    duration: 3,
  });
  currentTemp.value = item;

  // getLogs(item.id, 5);
}

onMounted(() => {
  getTemp();
  // getLogs(spiderList.value[0].id);
});
</script>

<template>
  <div class="layout">
    <div class="lg:w-1/5">
      <SpiderListView
        title="选择模板"
        :temp="temp"
        :items="history"
        :loading="loading"
        @click-mode="handleClickMode"
        @click="handleClick"
      />
    </div>
    <SelfWorkView
      v-if="currentTemp.id === '77c068fd-d5b6-4c33-97d8-db5511a09b26'"
      title="目标网址："
      :item="currentTemp"
      :run-spider="runSpider"
      :stop-spider="stopSpider"
      :get-spider-status="getSpiderStatus"
      :item-message="itemMessage"
    />
    <WorkflowWorkView
      v-else
      title="目标网址："
      :item="currentTemp"
      :run-spider-gz="runSpiderGz"
      :item-message="itemMessage"
    />
  </div>
</template>

<style scoped lang="less">
.layout {
  width: 100%;
  min-width: 1400px;
  height: 100%;
  display: flex;
  background: hsl(216deg 21.74% 95.49%);
  font-family: AlibabaPuHuiTi, v-deep(var(--ant-font-family)), sans-serif;
  border-radius: v-deep(var(--ant-border-radius));
}
</style>
