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

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

import { useAccessStore } from '@easyflow/stores';

import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTabPane,
  ElTabs,
  ElTag,
} from 'element-plus';

import { api } from '#/api/request';
import { hasPermission } from '#/api/common/hasPermission';
import ListPageShell from '#/components/page/ListPageShell.vue';
import PageData from '#/components/page/PageData.vue';
import { $t } from '#/locales';
import { router } from '#/router';

import ApprovalFlowModal from './ApprovalFlowModal.vue';

type ApprovalTabName = 'flow' | 'initiated' | 'pending' | 'processed';

const RESOURCE_OPTIONS = [
  { label: $t('approval.resource.bot'), value: 'BOT' },
  { label: $t('approval.resource.workflow'), value: 'WORKFLOW' },
  { label: $t('approval.resource.knowledge'), value: 'KNOWLEDGE' },
];

const ACTION_OPTIONS = [
  { label: $t('approval.action.publish'), value: 'PUBLISH' },
  { label: $t('approval.action.offline'), value: 'OFFLINE' },
  { label: $t('approval.action.delete'), value: 'DELETE' },
];

const FLOW_STATUS_OPTIONS = [
  { label: $t('approval.status.enabled'), value: 'ENABLED' },
  { label: $t('approval.status.disabled'), value: 'DISABLED' },
];

const PROCESSED_STATUS_OPTIONS = [
  { label: $t('approval.status.processing'), value: 'PROCESSING' },
  { label: $t('approval.status.approved'), value: 'APPROVED' },
  { label: $t('approval.status.rejected'), value: 'REJECTED' },
];

const INITIATED_STATUS_OPTIONS = [
  { label: $t('approval.status.pending'), value: 'PENDING' },
  { label: $t('approval.status.processing'), value: 'PROCESSING' },
  { label: $t('approval.status.approved'), value: 'APPROVED' },
  { label: $t('approval.status.rejected'), value: 'REJECTED' },
  { label: $t('approval.status.revoked'), value: 'REVOKED' },
];
const TAB_CONFIG = [
  {
    label: $t('approval.tab.flow'),
    name: 'flow',
    path: '/sys/approval/flow',
    permission: '/page/approval/flow',
  },
  {
    label: $t('approval.tab.pending'),
    name: 'pending',
    path: '/sys/approval/pending',
    permission: '/page/approval/pending',
  },
  {
    label: $t('approval.tab.processed'),
    name: 'processed',
    path: '/sys/approval/processed',
    permission: '/page/approval/processed',
  },
  {
    label: $t('approval.tab.initiated'),
    name: 'initiated',
    path: '/sys/approval/initiated',
    permission: '/page/approval/initiated',
  },
] as const;

const accessStore = useAccessStore();
const route = useRoute();
const flowQueryRef = ref<FormInstance>();
const instanceQueryRef = ref<FormInstance>();
const activeTab = ref<ApprovalTabName>('flow');
const flowModalRef = ref();
const flowPageRef = ref();
const pendingPageRef = ref();
const processedPageRef = ref();
const initiatedPageRef = ref();
const pendingBadgeCount = ref(0);

const flowQuery = ref({
  actionType: '',
  name: '',
  resourceType: '',
  status: '',
});

const instanceQuery = ref({
  actionType: '',
  keyword: '',
  resourceType: '',
  status: '',
});
const pendingBadgeText = computed(() =>
  pendingBadgeCount.value > 99 ? '99+' : String(pendingBadgeCount.value),
);
const hasApprovalRootMenu = computed(
  () => !!accessStore.getMenuByPath('/sys/approval'),
);
const hasLegacyTabMenus = computed(() =>
  TAB_CONFIG.some((item) => !!accessStore.getMenuByPath(item.path)),
);
const hasButtonTabPermissions = computed(() =>
  TAB_CONFIG.some((item) => hasPermission([item.permission])),
);
const visibleTabs = computed(() => {
  if (!hasApprovalRootMenu.value) {
    return [];
  }
  if (hasButtonTabPermissions.value) {
    return TAB_CONFIG.filter((item) => hasPermission([item.permission]));
  }
  if (hasLegacyTabMenus.value) {
    return TAB_CONFIG.filter((item) => accessStore.getMenuByPath(item.path));
  }
  return [];
});
const visibleTabNames = computed(() =>
  visibleTabs.value.map((item) => item.name),
);

const instanceStatusOptions = computed(() => {
  if (activeTab.value === 'processed') {
    return PROCESSED_STATUS_OPTIONS;
  }
  if (activeTab.value === 'initiated') {
    return INITIATED_STATUS_OPTIONS;
  }
  return [];
});

onMounted(() => {
  void syncRouteTab();
});

watch(activeTab, () => {
  if (
    instanceQuery.value.status &&
    !instanceStatusOptions.value.some(
      (item) => item.value === instanceQuery.value.status,
    )
  ) {
    instanceQuery.value.status = '';
  }
});
watch(
  [() => route.fullPath, visibleTabNames],
  async () => {
    await syncRouteTab();
  },
  { immediate: true },
);

function hasTab(name: ApprovalTabName) {
  return visibleTabNames.value.includes(name);
}

function resolveTabNameByPath(path: string): ApprovalTabName {
  if (path.endsWith('/pending')) {
    return 'pending';
  }
  if (path.endsWith('/processed')) {
    return 'processed';
  }
  if (path.endsWith('/initiated')) {
    return 'initiated';
  }
  return 'flow';
}

function resolveTabNameByRoute() {
  const queryTab = String(route.query.tab || '');
  if (
    queryTab === 'flow' ||
    queryTab === 'pending' ||
    queryTab === 'processed' ||
    queryTab === 'initiated'
  ) {
    return queryTab as ApprovalTabName;
  }
  return resolveTabNameByPath(route.path);
}

async function syncRouteTab() {
  if (visibleTabs.value.length === 0) {
    activeTab.value = 'flow';
    pendingBadgeCount.value = 0;
    return;
  }
  const fallbackTab = visibleTabs.value[0];
  const queryTab = String(route.query.tab || '');

  // 进入审批管理根路径时，默认落到当前可见页签中排序第一个的页签。
  if (route.path === '/sys/approval' && !queryTab && fallbackTab) {
    activeTab.value = fallbackTab.name;
    if (fallbackTab.name !== 'flow') {
      await router.replace({
        path: '/sys/approval',
        query: { tab: fallbackTab.name },
      });
      return;
    }
  }

  const expectedTab = resolveTabNameByRoute();
  if (visibleTabNames.value.includes(expectedTab)) {
    activeTab.value = expectedTab;
  } else {
    const fallbackQuery =
      fallbackTab?.name === 'flow' ? {} : { tab: fallbackTab?.name };
    const currentQueryTab = String(route.query.tab || '');
    if (
      fallbackTab &&
      (route.path !== '/sys/approval' || currentQueryTab !== String(fallbackTab.name))
    ) {
      await router.replace({
        path: '/sys/approval',
        query: fallbackQuery,
      });
      return;
    }
    activeTab.value = fallbackTab?.name || 'flow';
  }
  if (hasTab('pending')) {
    await refreshPendingBadgeCount();
  } else {
    pendingBadgeCount.value = 0;
  }
}

function handleTabChange(name: number | string) {
  if (typeof name !== 'string') {
    return;
  }
  const target = visibleTabs.value.find((item) => item.name === name);
  const nextQuery = name === 'flow' ? {} : { tab: name };
  const currentQueryTab = String(route.query.tab || '');
  const currentTab = currentQueryTab || 'flow';
  if (!target || currentTab === name) {
    return;
  }
  router.replace({
    path: '/sys/approval',
    query: nextQuery,
  });
}

function reloadCurrentTab() {
  if (activeTab.value === 'flow') {
    flowPageRef.value?.reload();
    return;
  }
  if (activeTab.value === 'pending') {
    pendingPageRef.value?.reload();
    return;
  }
  if (activeTab.value === 'processed') {
    processedPageRef.value?.reload();
    return;
  }
  initiatedPageRef.value?.reload();
}

async function refreshPendingBadgeCount() {
  if (!hasTab('pending')) {
    pendingBadgeCount.value = 0;
    return;
  }
  const res = await api.get('/api/v1/approvalInstance/pendingPage', {
    params: {
      pageNumber: 1,
      pageSize: 1,
    },
  });
  pendingBadgeCount.value = Number(res?.data?.totalRow || 0);
}

function searchFlow(formEl?: FormInstance) {
  formEl?.validate((valid) => {
    if (valid) {
      flowPageRef.value?.setQuery(flowQuery.value);
    }
  });
}

function resetFlow(formEl?: FormInstance) {
  formEl?.resetFields();
  flowPageRef.value?.setQuery({});
}

function searchInstance(formEl?: FormInstance) {
  if (!formEl) {
    currentInstancePageRef()?.setQuery(instanceQuery.value);
    return;
  }
  formEl?.validate((valid) => {
    if (valid) {
      currentInstancePageRef()?.setQuery(instanceQuery.value);
    }
  });
}

function resetInstance(formEl?: FormInstance) {
  if (!formEl) {
    instanceQuery.value = {
      actionType: '',
      keyword: '',
      resourceType: '',
      status: '',
    };
    currentInstancePageRef()?.setQuery({});
    return;
  }
  formEl?.resetFields();
  currentInstancePageRef()?.setQuery({});
}

function currentInstancePageRef() {
  if (activeTab.value === 'pending') {
    return pendingPageRef.value;
  }
  if (activeTab.value === 'processed') {
    return processedPageRef.value;
  }
  return initiatedPageRef.value;
}

function openFlowModal(row?: any) {
  flowModalRef.value?.openDialog(row);
}

async function toggleFlowStatus(row: any, nextStatus: 'DISABLED' | 'ENABLED') {
  const title =
    nextStatus === 'ENABLED'
      ? $t('approval.action.enableFlow')
      : $t('approval.action.disableFlow');
  await ElMessageBox.confirm(
    $t('approval.message.confirmFlowStatus', { title }),
    title,
    { type: 'warning' },
  );
  const url =
    nextStatus === 'ENABLED'
      ? '/api/v1/approvalFlow/enable'
      : '/api/v1/approvalFlow/disable';
  const res = await api.post(url, { id: row.id });
  if (res.errorCode !== 0) {
    return;
  }
  ElMessage.success($t('approval.message.statusUpdated'));
  flowPageRef.value?.reload();
}

async function removeFlow(row: any) {
  await ElMessageBox.confirm(
    $t('approval.message.confirmDeleteFlow'),
    $t('button.delete'),
    { type: 'warning' },
  );
  const res = await api.post('/api/v1/approvalFlow/remove', {
    id: row.id,
  });
  if (res.errorCode !== 0) {
    return;
  }
  ElMessage.success($t('approval.message.deleteSuccess'));
  flowPageRef.value?.reload();
}

async function submitApprovalAction(
  action: 'approve' | 'reject' | 'revoke',
  row: any,
) {
  const titleMap = {
    approve: $t('approval.action.approve'),
    reject: $t('approval.action.reject'),
    revoke: $t('approval.action.revoke'),
  };
  const { value } = await ElMessageBox.prompt(
    $t('approval.placeholder.actionComment'),
    titleMap[action],
    {
      inputValue: '',
      inputType: 'textarea',
    },
  );
  const res = await api.post(`/api/v1/approvalInstance/${action}`, {
    comment: value || '',
    instanceId: row.id,
  });
  if (res.errorCode !== 0) {
    return;
  }
  ElMessage.success($t('approval.message.actionSuccess'));
  pendingPageRef.value?.reload();
  processedPageRef.value?.reload();
  initiatedPageRef.value?.reload();
  refreshPendingBadgeCount();
}

function openInstanceDetail(row: any) {
  router.push(`/sys/approval/detail/${row.id}`);
}

function getFlowStatusType(status: string) {
  return status === 'ENABLED' ? 'success' : 'info';
}

function getInstanceStatusType(status: string) {
  const map: Record<string, any> = {
    APPROVED: 'success',
    PENDING: 'warning',
    PROCESSING: 'primary',
    REJECTED: 'danger',
    REVOKED: 'info',
  };
  return map[status] || 'info';
}

function getInstanceStatusLabel(status: string) {
  return $t(`approval.status.${String(status || '').toLowerCase()}`);
}

function getResourceLabel(value: string) {
  return (
    RESOURCE_OPTIONS.find((item) => item.value === value)?.label || value || '-'
  );
}

function getActionLabel(value: string) {
  return (
    ACTION_OPTIONS.find((item) => item.value === value)?.label || value || '-'
  );
}
</script>

<template>
  <div class="flex h-full flex-col gap-4 p-6">
    <ElTabs
      :model-value="activeTab"
      class="approval-manage__tabs"
      @tab-change="handleTabChange"
    >
      <ElTabPane
        v-if="hasTab('flow')"
        :label="$t('approval.tab.flow')"
        name="flow"
      >
        <ListPageShell>
          <template #filters>
            <ElForm ref="flowQueryRef" inline :model="flowQuery">
              <ElFormItem prop="name" class="!mr-3">
                <ElInput
                  v-model="flowQuery.name"
                  :placeholder="$t('approval.placeholder.flowName')"
                />
              </ElFormItem>
              <ElFormItem prop="resourceType" class="!mr-3">
                <ElSelect
                  v-model="flowQuery.resourceType"
                  class="approval-manage__select"
                  clearable
                  :placeholder="$t('approval.placeholder.resourceType')"
                >
                  <ElOption
                    v-for="item in RESOURCE_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </ElSelect>
              </ElFormItem>
              <ElFormItem prop="actionType" class="!mr-3">
                <ElSelect
                  v-model="flowQuery.actionType"
                  class="approval-manage__select"
                  clearable
                  :placeholder="$t('approval.placeholder.actionType')"
                >
                  <ElOption
                    v-for="item in ACTION_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </ElSelect>
              </ElFormItem>
              <ElFormItem prop="status" class="!mr-3">
                <ElSelect
                  v-model="flowQuery.status"
                  class="approval-manage__select"
                  clearable
                  :placeholder="$t('approval.placeholder.flowStatus')"
                >
                  <ElOption
                    v-for="item in FLOW_STATUS_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </ElSelect>
              </ElFormItem>
              <ElFormItem>
                <ElButton type="primary" @click="searchFlow(flowQueryRef)">
                  {{ $t('button.query') }}
                </ElButton>
                <ElButton @click="resetFlow(flowQueryRef)">
                  {{ $t('button.reset') }}
                </ElButton>
              </ElFormItem>
            </ElForm>
          </template>

          <template #actions>
            <ElButton type="primary" @click="openFlowModal()">
              {{ $t('approval.action.addFlow') }}
            </ElButton>
          </template>

          <PageData
            ref="flowPageRef"
            page-url="/api/v1/approvalFlow/page"
            :page-size="10"
          >
            <template #default="{ pageList }">
              <ElTable
                :data="pageList"
                class="approval-manage__table"
                show-overflow-tooltip
              >
                <ElTableColumn
                  prop="name"
                  :label="$t('approval.fields.flowName')"
                  min-width="180"
                />
                <ElTableColumn
                  :label="$t('approval.fields.resourceType')"
                  width="120"
                >
                  <template #default="{ row }">
                    {{ getResourceLabel(row.resourceType) }}
                  </template>
                </ElTableColumn>
                <ElTableColumn
                  :label="$t('approval.fields.actionType')"
                  width="120"
                >
                  <template #default="{ row }">
                    {{ getActionLabel(row.actionType) }}
                  </template>
                </ElTableColumn>
                <ElTableColumn
                  prop="priority"
                  :label="$t('approval.fields.priority')"
                  width="100"
                />
                <ElTableColumn
                  prop="scopeSummary"
                  :label="$t('approval.fields.scopeSummary')"
                  min-width="160"
                />
                <ElTableColumn
                  prop="stepCount"
                  :label="$t('approval.fields.stepCount')"
                  width="100"
                />
                <ElTableColumn
                  prop="version"
                  :label="$t('approval.fields.version')"
                  width="100"
                />
                <ElTableColumn
                  :label="$t('approval.fields.status')"
                  width="110"
                >
                  <template #default="{ row }">
                    <ElTag :type="getFlowStatusType(row.status)">
                      {{
                        row.status === 'ENABLED'
                          ? $t('approval.status.enabled')
                          : $t('approval.status.disabled')
                      }}
                    </ElTag>
                  </template>
                </ElTableColumn>
                <ElTableColumn
                  :label="$t('common.handle')"
                  min-width="260"
                  align="center"
                >
                  <template #default="{ row }">
                    <div class="flex items-center justify-center gap-3">
                      <ElButton link type="primary" @click="openFlowModal(row)">
                        {{ $t('button.edit') }}
                      </ElButton>
                      <ElButton
                        v-if="row.status === 'DISABLED'"
                        link
                        type="success"
                        @click="toggleFlowStatus(row, 'ENABLED')"
                      >
                        {{ $t('approval.action.enableFlow') }}
                      </ElButton>
                      <ElButton
                        v-else
                        link
                        @click="toggleFlowStatus(row, 'DISABLED')"
                      >
                        {{ $t('approval.action.disableFlow') }}
                      </ElButton>
                      <ElButton
                        link
                        type="danger"
                        :disabled="row.pendingInstanceCount > 0"
                        @click="removeFlow(row)"
                      >
                        {{ $t('button.delete') }}
                      </ElButton>
                    </div>
                  </template>
                </ElTableColumn>
              </ElTable>
            </template>
          </PageData>
        </ListPageShell>
      </ElTabPane>

      <ElTabPane v-if="hasTab('pending')" name="pending">
        <template #label>
          <span class="approval-manage__tab-label">
            <span>{{ $t('approval.tab.pending') }}</span>
            <span
              v-if="pendingBadgeCount > 0"
              class="approval-manage__tab-badge"
              :aria-label="$t('approval.tab.pending')"
            >
              {{ pendingBadgeText }}
            </span>
          </span>
        </template>
        <ListPageShell>
          <template #filters>
            <ElForm ref="instanceQueryRef" inline :model="instanceQuery">
              <ElFormItem prop="resourceType" class="!mr-3">
                <ElSelect
                  v-model="instanceQuery.resourceType"
                  class="approval-manage__select"
                  clearable
                  :placeholder="$t('approval.placeholder.resourceType')"
                >
                  <ElOption
                    v-for="item in RESOURCE_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </ElSelect>
              </ElFormItem>
              <ElFormItem prop="actionType" class="!mr-3">
                <ElSelect
                  v-model="instanceQuery.actionType"
                  class="approval-manage__select"
                  clearable
                  :placeholder="$t('approval.placeholder.actionType')"
                >
                  <ElOption
                    v-for="item in ACTION_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </ElSelect>
              </ElFormItem>
              <ElFormItem prop="keyword" class="!mr-3">
                <ElInput
                  v-model="instanceQuery.keyword"
                  :placeholder="$t('approval.placeholder.keyword')"
                />
              </ElFormItem>
              <ElFormItem>
                <ElButton
                  type="primary"
                  @click="searchInstance(instanceQueryRef)"
                >
                  {{ $t('button.query') }}
                </ElButton>
                <ElButton @click="resetInstance(instanceQueryRef)">
                  {{ $t('button.reset') }}
                </ElButton>
              </ElFormItem>
            </ElForm>
          </template>

          <PageData
            ref="pendingPageRef"
            page-url="/api/v1/approvalInstance/pendingPage"
            :page-size="10"
          >
            <template #default="{ pageList }">
              <ElTable
                :data="pageList"
                class="approval-manage__table"
                show-overflow-tooltip
              >
                <ElTableColumn
                  prop="summary"
                  :label="$t('approval.fields.summary')"
                  min-width="220"
                />
                <ElTableColumn
                  :label="$t('approval.fields.resourceType')"
                  width="120"
                >
                  <template #default="{ row }">
                    {{ getResourceLabel(row.resourceType) }}
                  </template>
                </ElTableColumn>
                <ElTableColumn
                  :label="$t('approval.fields.actionType')"
                  width="120"
                >
                  <template #default="{ row }">
                    {{ getActionLabel(row.actionType) }}
                  </template>
                </ElTableColumn>
                <ElTableColumn
                  prop="currentStepName"
                  :label="$t('approval.fields.currentStep')"
                  min-width="140"
                />
                <ElTableColumn
                  prop="submittedAt"
                  :label="$t('approval.fields.submittedAt')"
                  width="180"
                />
                <ElTableColumn
                  :label="$t('approval.fields.status')"
                  width="110"
                >
                  <template #default="{ row }">
                    <ElTag :type="getInstanceStatusType(row.status)">
                      {{ getInstanceStatusLabel(row.status) }}
                    </ElTag>
                  </template>
                </ElTableColumn>
                <ElTableColumn
                  :label="$t('common.handle')"
                  min-width="290"
                  align="center"
                >
                  <template #default="{ row }">
                    <div class="flex items-center justify-center gap-3">
                      <ElButton
                        link
                        type="primary"
                        @click="openInstanceDetail(row)"
                      >
                        {{ $t('button.view') }}
                      </ElButton>
                      <ElButton
                        v-if="row.canApprove"
                        link
                        type="success"
                        @click="submitApprovalAction('approve', row)"
                      >
                        {{ $t('approval.action.approve') }}
                      </ElButton>
                      <ElButton
                        v-if="row.canReject"
                        link
                        type="danger"
                        @click="submitApprovalAction('reject', row)"
                      >
                        {{ $t('approval.action.reject') }}
                      </ElButton>
                    </div>
                  </template>
                </ElTableColumn>
              </ElTable>
            </template>
          </PageData>
        </ListPageShell>
      </ElTabPane>

      <ElTabPane
        v-if="hasTab('processed')"
        :label="$t('approval.tab.processed')"
        name="processed"
      >
        <ListPageShell>
          <template #filters>
            <ElForm inline :model="instanceQuery">
              <ElFormItem prop="resourceType" class="!mr-3">
                <ElSelect
                  v-model="instanceQuery.resourceType"
                  class="approval-manage__select"
                  clearable
                  :placeholder="$t('approval.placeholder.resourceType')"
                >
                  <ElOption
                    v-for="item in RESOURCE_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </ElSelect>
              </ElFormItem>
              <ElFormItem prop="actionType" class="!mr-3">
                <ElSelect
                  v-model="instanceQuery.actionType"
                  class="approval-manage__select"
                  clearable
                  :placeholder="$t('approval.placeholder.actionType')"
                >
                  <ElOption
                    v-for="item in ACTION_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </ElSelect>
              </ElFormItem>
              <ElFormItem prop="keyword" class="!mr-3">
                <ElInput
                  v-model="instanceQuery.keyword"
                  :placeholder="$t('approval.placeholder.keyword')"
                />
              </ElFormItem>
              <ElFormItem prop="status" class="!mr-3">
                <ElSelect
                  v-model="instanceQuery.status"
                  class="approval-manage__select approval-manage__status-select"
                  clearable
                  popper-class="approval-manage__status-select-dropdown"
                  :placeholder="$t('approval.placeholder.instanceStatus')"
                >
                  <ElOption
                    v-for="item in instanceStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <ElTag
                      class="approval-manage__status-option"
                      :type="getInstanceStatusType(item.value)"
                    >
                      {{ getInstanceStatusLabel(item.value) }}
                    </ElTag>
                  </ElOption>
                </ElSelect>
              </ElFormItem>
              <ElFormItem>
                <ElButton
                  type="primary"
                  @click="searchInstance(instanceQueryRef)"
                >
                  {{ $t('button.query') }}
                </ElButton>
                <ElButton @click="resetInstance(instanceQueryRef)">
                  {{ $t('button.reset') }}
                </ElButton>
              </ElFormItem>
            </ElForm>
          </template>

          <PageData
            ref="processedPageRef"
            page-url="/api/v1/approvalInstance/processedPage"
            :page-size="10"
          >
            <template #default="{ pageList }">
              <ElTable
                :data="pageList"
                class="approval-manage__table"
                show-overflow-tooltip
              >
                <ElTableColumn
                  prop="summary"
                  :label="$t('approval.fields.summary')"
                  min-width="220"
                />
                <ElTableColumn
                  :label="$t('approval.fields.resourceType')"
                  width="120"
                >
                  <template #default="{ row }">
                    {{ getResourceLabel(row.resourceType) }}
                  </template>
                </ElTableColumn>
                <ElTableColumn
                  :label="$t('approval.fields.actionType')"
                  width="120"
                >
                  <template #default="{ row }">
                    {{ getActionLabel(row.actionType) }}
                  </template>
                </ElTableColumn>
                <ElTableColumn
                  prop="finishedAt"
                  :label="$t('approval.fields.finishedAt')"
                  width="180"
                />
                <ElTableColumn
                  :label="$t('approval.fields.status')"
                  width="110"
                >
                  <template #default="{ row }">
                    <ElTag :type="getInstanceStatusType(row.status)">
                      {{ getInstanceStatusLabel(row.status) }}
                    </ElTag>
                  </template>
                </ElTableColumn>
                <ElTableColumn
                  :label="$t('common.handle')"
                  width="100"
                  align="center"
                >
                  <template #default="{ row }">
                    <ElButton
                      link
                      type="primary"
                      @click="openInstanceDetail(row)"
                    >
                      {{ $t('button.view') }}
                    </ElButton>
                  </template>
                </ElTableColumn>
              </ElTable>
            </template>
          </PageData>
        </ListPageShell>
      </ElTabPane>

      <ElTabPane
        v-if="hasTab('initiated')"
        :label="$t('approval.tab.initiated')"
        name="initiated"
      >
        <ListPageShell>
          <template #filters>
            <ElForm inline :model="instanceQuery">
              <ElFormItem prop="resourceType" class="!mr-3">
                <ElSelect
                  v-model="instanceQuery.resourceType"
                  class="approval-manage__select"
                  clearable
                  :placeholder="$t('approval.placeholder.resourceType')"
                >
                  <ElOption
                    v-for="item in RESOURCE_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </ElSelect>
              </ElFormItem>
              <ElFormItem prop="actionType" class="!mr-3">
                <ElSelect
                  v-model="instanceQuery.actionType"
                  class="approval-manage__select"
                  clearable
                  :placeholder="$t('approval.placeholder.actionType')"
                >
                  <ElOption
                    v-for="item in ACTION_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </ElSelect>
              </ElFormItem>
              <ElFormItem prop="keyword" class="!mr-3">
                <ElInput
                  v-model="instanceQuery.keyword"
                  :placeholder="$t('approval.placeholder.keyword')"
                />
              </ElFormItem>
              <ElFormItem prop="status" class="!mr-3">
                <ElSelect
                  v-model="instanceQuery.status"
                  class="approval-manage__select approval-manage__status-select"
                  clearable
                  popper-class="approval-manage__status-select-dropdown"
                  :placeholder="$t('approval.placeholder.instanceStatus')"
                >
                  <ElOption
                    v-for="item in instanceStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <ElTag
                      class="approval-manage__status-option"
                      :type="getInstanceStatusType(item.value)"
                    >
                      {{ getInstanceStatusLabel(item.value) }}
                    </ElTag>
                  </ElOption>
                </ElSelect>
              </ElFormItem>
              <ElFormItem>
                <ElButton
                  type="primary"
                  @click="searchInstance(instanceQueryRef)"
                >
                  {{ $t('button.query') }}
                </ElButton>
                <ElButton @click="resetInstance(instanceQueryRef)">
                  {{ $t('button.reset') }}
                </ElButton>
              </ElFormItem>
            </ElForm>
          </template>

          <PageData
            ref="initiatedPageRef"
            page-url="/api/v1/approvalInstance/initiatedPage"
            :page-size="10"
          >
            <template #default="{ pageList }">
              <ElTable
                :data="pageList"
                class="approval-manage__table"
                show-overflow-tooltip
              >
                <ElTableColumn
                  prop="summary"
                  :label="$t('approval.fields.summary')"
                  min-width="220"
                />
                <ElTableColumn
                  :label="$t('approval.fields.resourceType')"
                  width="120"
                >
                  <template #default="{ row }">
                    {{ getResourceLabel(row.resourceType) }}
                  </template>
                </ElTableColumn>
                <ElTableColumn
                  :label="$t('approval.fields.actionType')"
                  width="120"
                >
                  <template #default="{ row }">
                    {{ getActionLabel(row.actionType) }}
                  </template>
                </ElTableColumn>
                <ElTableColumn
                  prop="submittedAt"
                  :label="$t('approval.fields.submittedAt')"
                  width="180"
                />
                <ElTableColumn
                  :label="$t('approval.fields.status')"
                  width="110"
                >
                  <template #default="{ row }">
                    <ElTag :type="getInstanceStatusType(row.status)">
                      {{ getInstanceStatusLabel(row.status) }}
                    </ElTag>
                  </template>
                </ElTableColumn>
                <ElTableColumn
                  :label="$t('common.handle')"
                  min-width="180"
                  align="center"
                >
                  <template #default="{ row }">
                    <div class="flex items-center justify-center gap-3">
                      <ElButton
                        link
                        type="primary"
                        @click="openInstanceDetail(row)"
                      >
                        {{ $t('button.view') }}
                      </ElButton>
                      <ElButton
                        v-if="row.canRevoke"
                        link
                        @click="submitApprovalAction('revoke', row)"
                      >
                        {{ $t('approval.action.revoke') }}
                      </ElButton>
                    </div>
                  </template>
                </ElTableColumn>
              </ElTable>
            </template>
          </PageData>
        </ListPageShell>
      </ElTabPane>
    </ElTabs>

    <ApprovalFlowModal ref="flowModalRef" @reload="reloadCurrentTab" />
  </div>
</template>

<style scoped>
.approval-manage__tabs {
  display: flex;
  flex: 1;
  flex-direction: column;
  min-height: 0;
}

.approval-manage__tab-label {
  display: inline-flex;
  gap: 6px;
  align-items: center;
}

.approval-manage__tab-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 18px;
  height: 18px;
  padding: 0 5px;
  font-size: 11px;
  font-weight: 600;
  line-height: 1;
  color: #fff;
  background: hsl(var(--destructive));
  border-radius: 999px;
  box-shadow: 0 6px 16px -12px hsl(var(--destructive) / 68%);
}

.approval-manage__tabs :deep(.el-tabs__content) {
  flex: 1;
  min-height: 0;
}

.approval-manage__tabs :deep(.el-tab-pane) {
  display: flex;
  height: 100%;
  min-height: 0;
  flex-direction: column;
}

.approval-manage__select {
  min-width: 136px;
}

.approval-manage__status-select {
  min-width: 118px;
}

.approval-manage__status-option {
  min-width: 0;
  padding-inline: 12px;
  justify-content: center;
}

.approval-manage__tabs
  :deep(.approval-manage__status-select-dropdown .el-select-dropdown__item) {
  display: flex;
  justify-content: center;
  padding: 8px 12px;
}

.approval-manage__table :deep(.el-table__header-wrapper th .cell) {
  text-align: center;
}

.approval-manage__table :deep(.el-table__body-wrapper td .cell) {
  text-align: center;
}
</style>
