/**
 * @file PC 端供应商审批页：附件内嵌预览（FilePreview）、上一条/下一条、下载。
 * @desc 与 `FilePreview` 配合；预览地址优先 `pcPreview`，其次 `mobilePreview`。
 */

import { ref, computed, type Ref, type ComputedRef } from 'vue';
import { message } from 'ant-design-vue';
import {
    resolveAttachmentIndexInList,
    type HbFileItem_Intf,
} from '../utils/util';
import { triggerBrowserDownload } from '../utils/triggerBrowserDownload';

export interface FilePreviewDetail {
    // 附件列表
    attachmentInfos: HbFileItem_Intf[];
}

export interface UseFilePreviewResult {
    filePreviewVisible: Ref<boolean>;
    pdfPreviewUrlRef: Ref<string>;
    previewFileNameRef: Ref<string>;
    previewAttachmentIndexRef: Ref<number>;
    hasPrevAttachment: ComputedRef<boolean>;
    hasNextAttachment: ComputedRef<boolean>;
    showAttachmentNavBar: ComputedRef<boolean>;
    handlePreview: (record: HbFileItem_Intf, listIndex?: number) => void;
    handleDownload: (record: HbFileItem_Intf) => void;
    handleClosePreview: () => void;
    goPrevAttachment: () => void;
    goNextAttachment: () => void;
    triggerBrowserDownload: (url: string, filename: string) => Promise<void>;
    /** 顺序触发下载，间隔开以避免浏览器拦截连续多次程序化下载 */
    handleBatchDownloadAttachment: () => Promise<void>;
}

/**
 * @param detailRef 详情 ref，须含 `attachmentInfos`
 */
export function useFilePreview(
    detailRef: Ref<FilePreviewDetail>
): UseFilePreviewResult {
    const filePreviewVisible = ref(false);
    const pdfPreviewUrlRef = ref('');
    const previewFileNameRef = ref('');
    const previewAttachmentIndexRef = ref(-1);

    const getUrl = (row: HbFileItem_Intf) => row.previewUrl;

    const hasPrevAttachment = computed(() => {
        const list = detailRef.value.attachmentInfos;
        const i = previewAttachmentIndexRef.value;
        if (i <= 0) return false;
        for (let j = i - 1; j >= 0; j--) {
            if (getUrl(list[j])) return true;
        }
        return false;
    });

    const hasNextAttachment = computed(() => {
        const list = detailRef.value.attachmentInfos;
        const i = previewAttachmentIndexRef.value;
        if (i < 0 || i >= list.length - 1) return false;
        for (let j = i + 1; j < list.length; j++) {
            if (getUrl(list[j])) return true;
        }
        return false;
    });

    const showAttachmentNavBar = computed(
        () => detailRef.value.attachmentInfos.length > 1
    );

    const applyPreviewAtAttachmentIndex = (idx: number) => {
        const list = detailRef.value.attachmentInfos;
        const record = list[idx];
        if (!record) return;
        const url = getUrl(record);
        if (!url) return;
        previewAttachmentIndexRef.value = idx;
        pdfPreviewUrlRef.value = url;
        previewFileNameRef.value = record.attachmentDesc || '';
        filePreviewVisible.value = true;
    };

    const goPrevAttachment = () => {
        const list = detailRef.value.attachmentInfos;
        const i = previewAttachmentIndexRef.value;
        for (let j = i - 1; j >= 0; j--) {
            if (getUrl(list[j])) {
                applyPreviewAtAttachmentIndex(j);
                return;
            }
        }
    };

    const goNextAttachment = () => {
        const list = detailRef.value.attachmentInfos;
        const i = previewAttachmentIndexRef.value;
        for (let j = i + 1; j < list.length; j++) {
            if (getUrl(list[j])) {
                applyPreviewAtAttachmentIndex(j);
                return;
            }
        }
    };

    const handleClosePreview = () => {
        filePreviewVisible.value = false;
        previewAttachmentIndexRef.value = -1;
        pdfPreviewUrlRef.value = '';
        previewFileNameRef.value = '';
    };

    const handlePreview = (record: HbFileItem_Intf, listIndex?: number) => {
        const url = getUrl(record);
        if (!url) {
            message.warning('暂无预览地址');
            return;
        }
        const list = detailRef.value.attachmentInfos;
        const idx = resolveAttachmentIndexInList(list, record, {
            preferredIndex: listIndex,
        });
        if (idx >= 0) {
            applyPreviewAtAttachmentIndex(idx);
        } else {
            previewAttachmentIndexRef.value = -1;
            pdfPreviewUrlRef.value = url;
            previewFileNameRef.value = record.attachmentDesc || '';
            filePreviewVisible.value = true;
        }
    };

    const handleDownload = (record: HbFileItem_Intf) => {
        const url = record.downloadUrl;
        if (!url) {
            message.warning('暂无下载地址');
            return;
        }
        const name = record.attachmentDesc?.trim() || 'download';
        void triggerBrowserDownload(url, name);
    };

    /** 浏览器会限制同一次交互内连续多次 `a.click()` 下载，需分帧/延时顺序触发 */
    const BATCH_DOWNLOAD_STAGGER_MS = 400;

    const handleBatchDownloadAttachment = async () => {
        const list = detailRef.value.attachmentInfos;
        const items = list.filter((row) => Boolean(row.downloadUrl?.trim()));
        if (items.length === 0) {
            message.warning('暂无可下载附件');
            return;
        }
        for (let i = 0; i < items.length; i++) {
            const row = items[i];
            const name = row.attachmentDesc?.trim() || 'download';
            void triggerBrowserDownload(row.downloadUrl!, name);
            if (i < items.length - 1) {
                await new Promise((r) =>
                    setTimeout(r, BATCH_DOWNLOAD_STAGGER_MS)
                );
            }
        }
    };

    return {
        filePreviewVisible,
        pdfPreviewUrlRef,
        previewFileNameRef,
        previewAttachmentIndexRef,
        hasPrevAttachment,
        hasNextAttachment,
        showAttachmentNavBar,
        handlePreview,
        handleDownload,
        handleClosePreview,
        goPrevAttachment,
        goNextAttachment,
        triggerBrowserDownload,
        handleBatchDownloadAttachment,
    };
}
