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

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

import { Page } from '@vben/common-ui';
import {
  Copy,
  Download,
  Edit,
  MoreVertical,
  Play,
  Plus,
  Trash2,
  Upload,
  Workflow,
} from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElCard,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElEmpty,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElPagination,
  ElSelect,
  ElSwitch,
  ElTag,
  ElTooltip,
} from 'element-plus';

import {
  copyWorkflowApi,
  createWorkflowApi,
  deleteWorkflowApi,
  exportWorkflowConfigApi,
  getWorkflowDetailApi,
  getWorkflowListApi,
  publishWorkflowApi,
  updateWorkflowApi,
} from '#/api/ai-platform/ai-platform';
import { ZqDialog } from '#/components/zq-dialog';
import { useAppContextStore } from '#/store/app-context';

import RunDialog from '../workflow/editor/components/RunDialog.vue';
import ImportDialog from './modules/import-dialog.vue';

const router = useRouter();
const appContextStore = useAppContextStore();

// 工作流类型选项
const workflowTypeOptions = computed(() => [
  { label: $t('ai-platform.workflow.type.general'), value: 'general' },
  { label: $t('ai-platform.workflow.type.application'), value: 'application' },
  { label: $t('ai-platform.workflow.type.form'), value: 'form' },
  { label: $t('ai-platform.workflow.type.report'), value: 'report' },
  { label: $t('ai-platform.workflow.type.dataProcess'), value: 'data_process' },
  { label: $t('ai-platform.workflow.type.automation'), value: 'automation' },
]);

// 弹窗表单数据
const createForm = reactive({
  id: '',
  name: '',
  code: '',
  description: '',
  workflow_type: 'general' as WorkflowType,
  is_global: false,
});

// 是否在主应用下（只有主应用才显示“子应用可见”开关）
const isMainApp = !appContextStore.currentApp?.id;
const formRef = ref();
const isEditMode = ref(false);
const formLoading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref($t('ai-platform.workflow.create'));
const runDialogVisible = ref(false);
const runWorkflowTarget = ref<any>(null);
const runWorkflowNodes = ref<any[]>([]);
const showImportDialog = ref(false);

async function handleConfirm() {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      formLoading.value = true;
      try {
        if (isEditMode.value) {
          // 编辑模式
          await updateWorkflowApi(createForm.id, {
            name: createForm.name,
            code: createForm.code,
            description: createForm.description,
            workflow_type: createForm.workflow_type,
            is_global: createForm.is_global,
          });
          ElMessage.success($t('ai-platform.workflow.saveSuccess'));
          dialogVisible.value = false;
          fetchList();
        } else {
          // 创建模式
          const res = await createWorkflowApi({
            application_id: appContextStore.currentApp?.id,
            is_global: createForm.is_global,
            name: createForm.name,
            code: createForm.code,
            description: createForm.description,
            workflow_type: createForm.workflow_type,
          });
          ElMessage.success($t('ai-platform.workflow.createSuccess'));
          dialogVisible.value = false;
          fetchList();
          // 直接跳转到编辑器（支持子应用模式）
          router.push(
            appContextStore.getContextPath(
              `/ai-platform/workflow/editor/${res.id}`,
            ),
          );
        }
      } catch {
        // error handled by request interceptor
      } finally {
        formLoading.value = false;
      }
    }
  });
}

// 搜索关键词
const searchKeyword = ref('');

// 列表数据
const loading = ref(false);
const workflowList = ref<WorkflowListItem[]>([]);

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 12,
  total: 0,
});

// 获取列表
async function fetchList() {
  loading.value = true;
  try {
    const res = await getWorkflowListApi({
      page: pagination.current,
      pageSize: pagination.pageSize,
      name: searchKeyword.value || undefined,
      applicationId: appContextStore.currentApp?.id,
    });
    workflowList.value = res.items;
    pagination.total = res.total;
  } catch (error) {
    console.error('获取工作流列表失败:', error);
  } finally {
    loading.value = false;
  }
}

// 搜索
function handleSearch() {
  pagination.current = 1;
  fetchList();
}

// 分页变化
function handlePageChange(page: number) {
  pagination.current = page;
  fetchList();
}

// 每页条数变化
function handleSizeChange(size: number) {
  pagination.pageSize = size;
  pagination.current = 1;
  fetchList();
}

const handleCreate = () => {
  isEditMode.value = false;
  createForm.id = '';
  createForm.name = '';
  createForm.code = '';
  createForm.description = '';
  createForm.workflow_type = 'general';
  createForm.is_global = false;
  dialogTitle.value = $t('ai-platform.workflow.create');
  dialogVisible.value = true;
};

const handleEditInfo = (row: WorkflowListItem) => {
  isEditMode.value = true;
  createForm.id = row.id;
  createForm.name = row.name;
  createForm.code = row.code;
  createForm.description = row.description || '';
  createForm.workflow_type = row.workflow_type || 'general';
  createForm.is_global = row.is_global || false;
  dialogTitle.value = $t('ai-platform.workflow.editWorkflow');
  dialogVisible.value = true;
};

const handleQuickRun = async (row: WorkflowListItem) => {
  try {
    const detail = await getWorkflowDetailApi(row.id);
    const definition = detail.definition || {};
    runWorkflowNodes.value = definition.nodes || [];
    runWorkflowTarget.value = row;
    runDialogVisible.value = true;
  } catch (error) {
    console.error('获取工作流详情失败:', error);
    ElMessage.error($t('ai-platform.workflow.editor.loadFailed'));
  }
};

const handleEdit = (row: WorkflowListItem) => {
  router.push(
    appContextStore.getContextPath(`/ai-platform/workflow/editor/${row.id}`),
  );
};

const handleDelete = async (row: WorkflowListItem) => {
  try {
    await ElMessageBox.confirm(
      $t('ai-platform.workflow.deleteConfirmSimple'),
      $t('ai-platform.workflow.deleteTitle'),
      {
        type: 'warning',
        confirmButtonText: $t('ai-platform.workflow.deleteButton'),
        cancelButtonText: $t('ai-platform.workflow.cancelButton'),
      },
    );
    await deleteWorkflowApi(row.id);
    ElMessage.success($t('ai-platform.workflow.deleteSuccess'));
    fetchList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error);
    }
  }
};

const handlePublish = async (row: WorkflowListItem) => {
  try {
    await publishWorkflowApi(row.id);
    ElMessage.success($t('ai-platform.workflow.publishSuccess'));
    fetchList();
  } catch (error) {
    console.error(error);
  }
};

function downloadBlob(blob: Blob, filename: string) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.append(a);
  a.click();
  a.remove();
  URL.revokeObjectURL(url);
}

async function handleExport(row: WorkflowListItem) {
  try {
    const blob = await exportWorkflowConfigApi(row.id);
    downloadBlob(blob, `${row.code}.json`);
    ElMessage.success($t('ai-platform.workflow.importExport.exportSuccess'));
  } catch {
    ElMessage.error($t('ai-platform.workflow.importExport.exportFailed'));
  }
}

function handleImported() {
  fetchList();
}

const handleCopy = async (row: WorkflowListItem) => {
  try {
    await ElMessageBox.confirm(
      $t('ai-platform.workflow.copyConfirm', { name: row.name }),
      $t('ai-platform.workflow.copyTitle'),
      {
        type: 'info',
        confirmButtonText: $t('ai-platform.workflow.copyButton'),
        cancelButtonText: $t('ai-platform.workflow.cancelButton'),
      },
    );
    const res = await copyWorkflowApi(row.id);
    ElMessage.success($t('ai-platform.workflow.copySuccess'));
    fetchList();
    // 跳转到新工作流的编辑器
    router.push(
      appContextStore.getContextPath(`/ai-platform/workflow/editor/${res.id}`),
    );
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error);
    }
  }
};

const handleCommand = (command: string, row: WorkflowListItem) => {
  switch (command) {
    case 'export': {
      handleExport(row);
      break;
    }
    case 'run': {
      handleQuickRun(row);
      break;
    }
    case 'copy': {
      handleCopy(row);
      break;
    }
    case 'edit': {
      handleEditInfo(row);
      break;
    }
    case 'publish': {
      handlePublish(row);
      break;
    }
  }
};

const getWorkflowTypeText = (type: string) => {
  const item = workflowTypeOptions.value.find(
    (o: { label: string; value: string }) => o.value === type,
  );
  return item?.label || type;
};

const getStatusType = (status: string) => {
  const map: Record<string, string> = {
    published: 'success',
    draft: 'info',
    disabled: 'danger',
  };
  return map[status] || 'info';
};

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    published: $t('ai-platform.workflow.status.published'),
    draft: $t('ai-platform.workflow.status.draft'),
    disabled: $t('ai-platform.workflow.status.disabled'),
  };
  return map[status] || status;
};

onMounted(() => {
  fetchList();
});
</script>

<template>
  <div class="ai-workflow-list-page">
    <Page auto-content-height v-loading="loading">
      <template #title>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-4">
            <ElInput
              v-model="searchKeyword"
              :placeholder="$t('ai-platform.workflow.searchPlaceholder')"
              clearable
              class="w-64"
              @keyup.enter="handleSearch"
            />
            <ElButton @click="handleSearch">
              {{ $t('ai-platform.workflow.search') }}
            </ElButton>
          </div>
          <div class="flex items-center gap-2">
            <ElButton @click="showImportDialog = true">
              <Upload class="mr-1 h-4 w-4" />
              {{ $t('ai-platform.workflow.importExport.import') }}
            </ElButton>
            <ElButton type="primary" @click="handleCreate">
              <Plus class="mr-1 h-4 w-4" />
              {{ $t('ai-platform.workflow.create') }}
            </ElButton>
          </div>
        </div>
      </template>

      <!-- 工作流卡片列表 -->
      <div
        v-if="workflowList.length > 0"
        class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5"
      >
        <ElCard
          v-for="item in workflowList"
          :key="item.id"
          class="ai-workflow-card cursor-pointer transition-shadow"
          shadow="hover"
          :body-style="{ padding: '0' }"
          style="border: none"
          @click="handleEdit(item)"
        >
          <div class="p-4">
            <!-- 头部：图标 + 右侧信息区 -->
            <div class="mb-4 flex gap-3">
              <div
                class="bg-primary/10 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg"
              >
                <Workflow class="text-primary h-5 w-5" />
              </div>
              <div class="min-w-0 flex-1">
                <!-- name + 操作 -->
                <div class="flex items-center justify-between">
                  <div class="min-w-0 flex-1 truncate text-sm font-medium">
                    {{ item.name }}
                  </div>
                  <div
                    class="flex flex-shrink-0 items-center -space-x-1"
                    @click.stop
                  >
                    <ElTooltip
                      :content="$t('ai-platform.workflow.design')"
                      placement="top"
                    >
                      <ElButton text size="small" @click="handleEdit(item)">
                        <Edit class="h-3.5 w-3.5" />
                      </ElButton>
                    </ElTooltip>
                    <ElTooltip
                      :content="$t('ai-platform.workflow.delete')"
                      placement="top"
                    >
                      <ElButton text size="small" @click="handleDelete(item)">
                        <Trash2 class="h-3.5 w-3.5" />
                      </ElButton>
                    </ElTooltip>
                    <ElDropdown
                      trigger="click"
                      @command="(cmd: string) => handleCommand(cmd, item)"
                    >
                      <ElButton text size="small">
                        <MoreVertical class="h-3.5 w-3.5" />
                      </ElButton>
                      <template #dropdown>
                        <ElDropdownMenu>
                          <ElDropdownItem command="edit">
                            <Edit class="mr-2 h-4 w-4" />
                            {{ $t('ai-platform.workflow.editInfo') }}
                          </ElDropdownItem>
                          <ElDropdownItem
                            v-if="item.status !== 'published'"
                            command="publish"
                          >
                            <Play class="mr-2 h-4 w-4" />
                            {{ $t('ai-platform.workflow.publish') }}
                          </ElDropdownItem>
                          <ElDropdownItem
                            v-if="
                              item.status === 'published' &&
                              (item.workflow_type === 'data_process' ||
                                item.workflow_type === 'automation')
                            "
                            command="run"
                          >
                            <Play class="mr-2 h-4 w-4" />
                            {{ $t('ai-platform.workflow.run') }}
                          </ElDropdownItem>
                          <ElDropdownItem command="export">
                            <Download class="mr-2 h-4 w-4" />
                            {{ $t('ai-platform.workflow.importExport.export') }}
                          </ElDropdownItem>
                          <ElDropdownItem command="copy">
                            <Copy class="mr-2 h-4 w-4" />
                            {{ $t('ai-platform.workflow.copy') }}
                          </ElDropdownItem>
                        </ElDropdownMenu>
                      </template>
                    </ElDropdown>
                  </div>
                </div>
                <!-- code -->
                <div class="text-muted-foreground font-mono text-xs">
                  {{ item.code }}
                </div>
              </div>
            </div>
            <!-- 描述 -->
            <div
              class="text-muted-foreground mb-4 line-clamp-1 min-h-[18px] text-xs"
            >
              {{ item.description || $t('ai-platform.workflow.noDescription') }}
            </div>
            <!-- 标签 -->
            <div class="mb-4 flex items-center justify-between">
              <div class="flex gap-1">
                <ElTag size="small" :type="getStatusType(item.status) as any">
                  {{ getStatusText(item.status) }}
                </ElTag>
                <ElTag size="small">
                  {{ getWorkflowTypeText(item.workflow_type) }}
                </ElTag>
              </div>
            </div>
            <!-- 应用名称 + 创建时间 -->
            <div class="flex items-center justify-between">
              <div class="text-muted-foreground text-xs">
                <span v-if="item.application_name">{{
                  item.application_name
                }}</span>
                <span v-else>{{ $t('ai-platform.workflow.mainApp') }}</span>
              </div>
              <span class="text-muted-foreground text-xs">
                {{ item.sys_create_datetime }}
              </span>
            </div>
          </div>
        </ElCard>
      </div>

      <!-- 空状态 -->
      <ElEmpty v-else :description="$t('common.noData')" />

      <!-- 分页 -->
      <template #footer>
        <div class="flex w-full items-center justify-end">
          <ElPagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[12, 24, 36, 48]"
            :pager-count="7"
            layout="total, sizes, prev, pager, next, jumper"
            background
            size="small"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </div>
      </template>
    </Page>

    <!-- 创建/编辑弹窗 -->
    <ZqDialog
      v-model="dialogVisible"
      :title="dialogTitle"
      :confirm-loading="formLoading"
      @confirm="handleConfirm"
      width="500px"
    >
      <ElForm
        ref="formRef"
        :model="createForm"
        label-position="top"
        :rules="{
          name: [
            {
              required: true,
              message: $t('ai-platform.workflow.form.nameRequired'),
              trigger: 'blur',
            },
          ],
          code: [
            {
              required: true,
              message: $t('ai-platform.workflow.form.codeRequired'),
              trigger: 'blur',
            },
            {
              pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
              message: $t('ai-platform.workflow.form.codeFormat'),
              trigger: 'blur',
            },
          ],
        }"
      >
        <ElFormItem :label="$t('ai-platform.workflow.form.name')" prop="name">
          <ElInput
            v-model="createForm.name"
            :placeholder="$t('ai-platform.workflow.form.namePlaceholder')"
          />
        </ElFormItem>
        <ElFormItem :label="$t('ai-platform.workflow.form.code')" prop="code">
          <ElInput
            v-model="createForm.code"
            :placeholder="$t('ai-platform.workflow.form.codePlaceholder')"
          />
        </ElFormItem>
        <ElFormItem
          :label="$t('ai-platform.workflow.form.type')"
          prop="workflow_type"
        >
          <ElSelect v-model="createForm.workflow_type" style="width: 100%">
            <ElOption
              v-for="opt in workflowTypeOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem
          :label="$t('ai-platform.workflow.form.description')"
          prop="description"
        >
          <ElInput
            v-model="createForm.description"
            type="textarea"
            :placeholder="
              $t('ai-platform.workflow.form.descriptionPlaceholder')
            "
            :rows="3"
          />
        </ElFormItem>
        <ElFormItem
          v-if="isMainApp"
          :label="$t('ai-platform.workflow.form.globalVisible')"
        >
          <ElSwitch v-model="createForm.is_global" />
        </ElFormItem>
      </ElForm>
    </ZqDialog>

    <!-- 快速运行弹窗（数据处理/自动化工作流） -->
    <RunDialog
      v-model:visible="runDialogVisible"
      :workflow-id="runWorkflowTarget?.id || ''"
      :nodes="runWorkflowNodes"
      :workflow-name="runWorkflowTarget?.name"
      :auto-run="true"
    />

    <ImportDialog v-model="showImportDialog" @imported="handleImported" />
  </div>
</template>
