<script lang="ts" setup>
import type { WorkflowRunListItem } from '#/api/ai-platform/ai-platform';

import { ref } from 'vue';

import { Page } from '@vben/common-ui';
import { Eye } from '@vben/icons';
import { $t } from '@vben/locales';

import { ElButton, ElTag } from 'element-plus';

import { getAllWorkflowRunsApi } from '#/api/ai-platform/ai-platform';
import { useZqTable } from '#/components/zq-table';
import { useAppContextStore } from '#/store/app-context';

import RunStatusTag from './components/RunStatusTag.vue';
import {
  formatDuration,
  formatTime,
  getTagLabel,
  getTagType,
  getTriggerOptions,
  useSearchFormSchema,
  useZqTableColumns,
} from './data';
import DetailDialog from './modules/detail-dialog.vue';

defineOptions({ name: 'WorkflowRunHistory' });

const appContextStore = useAppContextStore();
const detailRef = ref<InstanceType<typeof DetailDialog>>();
const triggerOptions = getTriggerOptions();

const fetchRunList = async (params: any) => {
  const res = await getAllWorkflowRunsApi({
    page: params.page.currentPage,
    pageSize: params.page.pageSize,
    workflowId: params.form?.workflowId || undefined,
    status: params.form?.status || undefined,
    triggerType: params.form?.triggerType || undefined,
    applicationId: appContextStore.currentApp?.id,
  });
  return {
    items: res.items,
    total: res.total,
  };
};

const [Grid] = useZqTable({
  gridOptions: {
    columns: useZqTableColumns(),
    border: true,
    stripe: true,
    showIndex: true,
    proxyConfig: {
      autoLoad: true,
      ajax: {
        query: fetchRunList,
      },
    },
    pagerConfig: {
      enabled: true,
      pageSize: 20,
    },
    toolbarConfig: {
      search: true,
      refresh: true,
      zoom: true,
      custom: true,
    },
  },
  formOptions: {
    schema: useSearchFormSchema(),
    showCollapseButton: true,
    submitOnChange: true,
  },
});

function openDetail(row: WorkflowRunListItem) {
  detailRef.value?.open(row.id);
}
</script>

<template>
  <Page auto-content-height>
    <DetailDialog ref="detailRef" />

    <Grid>
      <template #cell-status="{ row }">
        <RunStatusTag :status="row.status" />
      </template>

      <template #cell-trigger_type="{ row }">
        <ElTag
          :type="getTagType(row.trigger_type, triggerOptions)"
          size="small"
        >
          {{ getTagLabel(row.trigger_type, triggerOptions) }}
        </ElTag>
      </template>

      <template #cell-elapsed_time="{ row }">
        {{ formatDuration(row.elapsed_time) }}
      </template>

      <template #cell-started_at="{ row }">
        {{ formatTime(row.started_at) }}
      </template>

      <template #cell-actions="{ row }">
        <ElButton link type="primary" :icon="Eye" @click.stop="openDetail(row)">
          {{ $t('common.view') }}
        </ElButton>
      </template>
    </Grid>
  </Page>
</template>
