<script setup lang="ts">
import type { FormInstance } from 'element-plus';

import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { ArrowLeft, DeleteFilled, MoreFilled } from '@element-plus/icons-vue';
import {
  ElButton,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElTable,
  ElTableColumn,
  ElTag,
} from 'element-plus';

import { api } from '#/api/request';
import PageData from '#/components/page/PageData.vue';
import {
  buildListRouteFullPath,
  mergeListRouteStateQuery,
  parseListRouteState,
  watchListRouteState,
} from '#/composables/useListRouteState';
import { $t } from '#/locales';
import {
  navigateBackToList,
  withListReturnTo,
} from '#/router/list-return-context';
import { useDictStore } from '#/store';

import { workflowExecListRouteSchema } from './workflow-exec-list-route-state';

const router = useRouter();
const $route = useRoute();
const initialListState = parseListRouteState(
  $route.query,
  workflowExecListRouteSchema,
);
onMounted(() => {
  initDict();
});
const formRef = ref<FormInstance>();
const pageDataRef = ref();
const formInline = ref({
  execKey: initialListState.execKey,
});
const appliedExecKey = ref(initialListState.execKey);
const currentPageNumber = ref(initialListState.pageNumber);
const currentPageSize = ref(initialListState.pageSize);
let currentWorkflowId = String($route.query.workflowId || '');
watchListRouteState($route, workflowExecListRouteSchema, (state) => {
  const nextWorkflowId = String($route.query.workflowId || '');
  const workflowChanged = nextWorkflowId !== currentWorkflowId;
  currentWorkflowId = nextWorkflowId;
  formInline.value.execKey = state.execKey;
  appliedExecKey.value = state.execKey;
  currentPageNumber.value = state.pageNumber;
  currentPageSize.value = state.pageSize;
  const restored = pageDataRef.value?.restoreState?.({
    pageNumber: state.pageNumber,
    pageSize: state.pageSize,
    queryParams: { keyword: state.execKey || undefined },
  });
  if (workflowChanged && !restored) pageDataRef.value?.reload?.();
});
const dictStore = useDictStore();
function initDict() {
  dictStore.fetchDictionary('dataStatus');
}
function search(formEl: FormInstance | undefined) {
  formEl?.validate((valid) => {
    if (valid) {
      appliedExecKey.value = formInline.value.execKey;
      pageDataRef.value.setQuery({
        keyword: appliedExecKey.value || undefined,
      });
    }
  });
}
function reset(formEl: FormInstance | undefined) {
  formInline.value.execKey = '';
  appliedExecKey.value = '';
  formEl?.clearValidate();
  pageDataRef.value.setQuery({});
}
function remove(row: any) {
  ElMessageBox.confirm($t('message.deleteAlert'), $t('message.noticeTitle'), {
    confirmButtonText: $t('message.ok'),
    cancelButtonText: $t('message.cancel'),
    type: 'warning',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true;
        api
          .get('/api/v1/workflowExecResult/del', { params: { id: row.id } })
          .then((res) => {
            instance.confirmButtonLoading = false;
            if (res.errorCode === 0) {
              ElMessage.success(res.message);
              pageDataRef.value?.reload?.();
              done();
            }
          })
          .catch(() => {
            instance.confirmButtonLoading = false;
          });
      } else {
        done();
      }
    },
  }).catch(() => {});
}
function toStepPage(row: any) {
  router.push({
    name: 'RecordStep',
    query: {
      recordId: row.id,
      workflowId: $route.query.workflowId,
      ...withListReturnTo(currentListFullPath()),
    },
  });
}
function currentListFullPath() {
  return buildListRouteFullPath(
    router,
    $route.query,
    {
      execKey: appliedExecKey.value,
      pageNumber: currentPageNumber.value,
      pageSize: currentPageSize.value,
    },
    workflowExecListRouteSchema,
  );
}
function handlePageStateChange(state: {
  pageNumber: number;
  pageSize: number;
}) {
  currentPageNumber.value = state.pageNumber;
  currentPageSize.value = state.pageSize;
  const query = mergeListRouteStateQuery(
    $route.query,
    {
      execKey: appliedExecKey.value,
      pageNumber: state.pageNumber,
      pageSize: state.pageSize,
    },
    workflowExecListRouteSchema,
  );
  const target = router.resolve({
    path: workflowExecListRouteSchema.path,
    query,
  });
  if (target.fullPath !== $route.fullPath) void router.replace(target);
}
async function backToWorkflowList() {
  await navigateBackToList(
    router,
    $route.query,
    ['/ai/workflow'],
    '/ai/workflow',
  );
}
function getTagType(row: any) {
  switch (row.status) {
    case 1: {
      return 'primary';
    }
    case 5: {
      return 'warning';
    }
    case 10: {
      return 'danger';
    }
    case 20: {
      return 'success';
    }
    case 21: {
      return 'danger';
    }
    default: {
      return 'info';
    }
  }
}
</script>

<template>
  <div class="page-container border-border border">
    <div class="mb-3">
      <ElButton :icon="ArrowLeft" @click="backToWorkflowList">
        {{ $t('button.back') }}
      </ElButton>
    </div>
    <ElForm ref="formRef" :inline="true" :model="formInline">
      <ElFormItem class="w-full max-w-[300px]" prop="execKey">
        <ElInput
          v-model="formInline.execKey"
          :placeholder="$t('aiWorkflowExecRecord.execKey')"
        />
      </ElFormItem>
      <ElFormItem>
        <ElButton @click="search(formRef)" type="primary">
          {{ $t('button.query') }}
        </ElButton>
        <ElButton @click="reset(formRef)">
          {{ $t('button.reset') }}
        </ElButton>
      </ElFormItem>
    </ElForm>
    <div class="handle-div"></div>
    <PageData
      ref="pageDataRef"
      page-url="/api/v1/workflowExecResult/page"
      :page-size="initialListState.pageSize"
      :initial-page-number="initialListState.pageNumber"
      :initial-query-params="{
        keyword: initialListState.execKey || undefined,
      }"
      :extra-query-params="{
        workflowId: $route.query.workflowId,
      }"
      @state-change="handlePageStateChange"
    >
      <template #default="{ pageList }">
        <ElTable :data="pageList" border>
          <ElTableColumn
            prop="execKey"
            show-overflow-tooltip
            :label="$t('aiWorkflowExecRecord.execKey')"
          >
            <template #default="{ row }">
              {{ row.execKey }}
            </template>
          </ElTableColumn>
          <ElTableColumn prop="title" :label="$t('aiWorkflowExecRecord.title')">
            <template #default="{ row }">
              {{ row.title }}
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="description"
            :label="$t('aiWorkflowExecRecord.description')"
          >
            <template #default="{ row }">
              {{ row.description }}
            </template>
          </ElTableColumn>
          <ElTableColumn
            show-overflow-tooltip
            prop="input"
            :label="$t('aiWorkflowExecRecord.input')"
          >
            <template #default="{ row }">
              {{ row.input }}
            </template>
          </ElTableColumn>
          <ElTableColumn
            show-overflow-tooltip
            prop="output"
            :label="$t('aiWorkflowExecRecord.output')"
          >
            <template #default="{ row }">
              {{ row.output }}
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="startTime"
            :label="$t('aiWorkflowExecRecord.execTime')"
          >
            <template #default="{ row }">
              {{ row.execTime || '-' }} ms
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="status"
            :label="$t('aiWorkflowExecRecord.status')"
          >
            <template #default="{ row }">
              <ElTag :type="getTagType(row)">
                {{ $t(`aiWorkflowExecRecord.status${row.status}`) }}
              </ElTag>
            </template>
          </ElTableColumn>
          <ElTableColumn
            show-overflow-tooltip
            prop="errorInfo"
            :label="$t('aiWorkflowExecRecord.errorInfo')"
          >
            <template #default="{ row }">
              {{ row.errorInfo }}
            </template>
          </ElTableColumn>
          <ElTableColumn :label="$t('common.handle')" width="110" align="right">
            <template #default="{ row }">
              <div class="flex items-center gap-1">
                <ElButton link type="primary" @click="toStepPage(row)">
                  {{ $t('aiWorkflowRecordStep.moduleName') }}
                </ElButton>

                <ElDropdown>
                  <ElButton :icon="MoreFilled" link />

                  <template #dropdown>
                    <ElDropdownMenu>
                      <div v-access:code="'/api/v1/workflow/save'">
                        <ElDropdownItem @click="remove(row)">
                          <ElButton type="danger" :icon="DeleteFilled" link>
                            {{ $t('button.delete') }}
                          </ElButton>
                        </ElDropdownItem>
                      </div>
                    </ElDropdownMenu>
                  </template>
                </ElDropdown>
              </div>
            </template>
          </ElTableColumn>
        </ElTable>
      </template>
    </PageData>
  </div>
</template>

<style scoped></style>
