<script lang="ts" setup>
/**
 * 布局级站内信动作宿主
 * - 消息详情走自定义 NoticeSceneHost（非 VbenModal）
 * - 业务审核表单仍复用列表页 Vben Modal（仓品完整审核 / 提现审核等）
 */
import { onMounted, onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { useVbenModal } from '@vben/common-ui';

import WithdrawalAudit from '#/views/finance/withdrawal-audit/components/WithdrawalAudit.vue';
import WarehouseAuditModal from '#/views/system/delivery-warehouse-product-audit/components/audit-modal.vue';
import { readApi } from '#/views/notice/api';
import NoticeSceneHost from '#/views/notice/scenes/NoticeSceneHost.vue';

import { emitNoticeRefresh, registerNoticeActionHandler } from './bus';
import { NOTICE_ACTION, type NoticeItemLike } from './types';

const router = useRouter();

const sceneOpen = ref(false);
const sceneNotice = ref<Record<string, any> | null>(null);

const [WithdrawAuditModal, withdrawAuditApi] = useVbenModal({
  connectedComponent: WithdrawalAudit,
});
const [WarehouseModal, warehouseModalApi] = useVbenModal({
  connectedComponent: WarehouseAuditModal,
});

const readSentIds = new Set<number>();

async function markRead(item: NoticeItemLike) {
  if (!item?.id) return;
  const id = Number(item.id);
  item.status = 1;
  if (readSentIds.has(id)) return;
  readSentIds.add(id);
  try {
    await readApi(id);
    emitNoticeRefresh();
  } catch {
    readSentIds.delete(id);
  }
}

function openWithdrawAudit(bizId: number, modalType: number) {
  if (!bizId) return;
  withdrawAuditApi.setData({
    id: bizId,
    modalType,
    gridApi: { reload: emitNoticeRefresh, query: emitNoticeRefresh },
  });
  withdrawAuditApi.open();
}

function openWarehouseAudit(bizId: number) {
  warehouseModalApi.setData({
    id: bizId,
    values: { id: bizId },
    gridApi: { query: emitNoticeRefresh, reload: emitNoticeRefresh },
  });
  warehouseModalApi.open();
}

/** 打开消息专属场景弹层 */
function openScene(item: NoticeItemLike) {
  sceneNotice.value = { ...item };
  sceneOpen.value = true;
}

async function handleAction(item: NoticeItemLike) {
  void markRead(item);
  const action = String(item.action_type || '');
  const typeCode = String(item.type_code || '');
  const payload = (item.action_payload || {}) as Record<string, any>;

  if (
    action === NOTICE_ACTION.OPEN_ROUTE &&
    typeCode !== 'queue_failure' &&
    typeCode !== 'invoice_todo'
  ) {
    const route = String(payload.route || '');
    if (route) {
      router.push(route);
      return;
    }
  }

  // 全部消息类型统一走自定义场景弹层（含队列失败详情+重试）
  openScene(item);
}

function onWithdrawAudit(payload: { bizId: number; modalType: number }) {
  openWithdrawAudit(payload.bizId, payload.modalType);
}

function onOpenBizAudit(payload: { typeCode: string; bizId: number }) {
  if (payload.typeCode === 'warehouse_product_audit') {
    openWarehouseAudit(payload.bizId);
  }
}

onMounted(() => {
  registerNoticeActionHandler(handleAction);
});
onUnmounted(() => {
  registerNoticeActionHandler(null);
});
</script>

<template>
  <NoticeSceneHost
    v-model:open="sceneOpen"
    :notice="sceneNotice"
    :on-withdraw-audit="onWithdrawAudit"
    :on-open-biz-audit="onOpenBizAudit"
  />
  <WithdrawAuditModal />
  <WarehouseModal />
</template>
