<template>
	<el-dialog v-model="visible" title="补充材料详情" width="90%" top="5vh" destroy-on-close append-to-body>
		<template #header>
			<div class="dialog-header">
				<span class="dialog-title">
					<el-icon><FolderOpened /></el-icon>
					补充材料详情 - {{ applyData.purchaseNo || applyId }}
				</span>
			</div>
		</template>

		<el-row :gutter="16">
			<el-col :span="8">
				<el-card shadow="never" class="info-card">
					<template #header>
						<div class="card-header">
							<span class="card-title">采购申请信息</span>
						</div>
					</template>
					<el-descriptions :column="1" border size="small">
						<el-descriptions-item label="采购编号">{{ applyData.purchaseNo || '-' }}</el-descriptions-item>
						<el-descriptions-item label="项目名称">{{ applyData.projectName || '-' }}</el-descriptions-item>
						<el-descriptions-item label="采购金额">{{
							applyData.budget ? Number(applyData.budget).toLocaleString() + ' 元' : '-'
						}}</el-descriptions-item>
						<el-descriptions-item label="采购方式">{{ purchaseTypeLabel || '-' }}</el-descriptions-item>
						<el-descriptions-item label="补充状态">
							<el-tag v-if="applyData.supplementFlowStatus === '1'" type="success">已完成</el-tag>
							<el-tag v-else-if="applyData.supplementFlowStatus === '0'" type="warning">审批中</el-tag>
							<el-tag v-else-if="applyData.supplementFlowStatus === '-1'" type="info">已暂存</el-tag>
							<el-tag v-else type="danger">未补充</el-tag>
						</el-descriptions-item>
					</el-descriptions>
				</el-card>

				<el-card shadow="never" class="file-card">
					<template #header>
						<div class="card-header">
							<span class="card-title">补充材料文件</span>
						</div>
					</template>
					<el-alert v-if="requiredFileTypeName" type="info" :closable="false" style="margin-bottom: 12px">
						<template #title>
							<span>{{ requiredFileTypeName }}</span>
						</template>
					</el-alert>
					<el-table :data="fileList" border stripe size="small" v-if="fileList.length > 0" max-height="300">
						<el-table-column type="index" label="序号" width="50" />
						<el-table-column prop="name" label="文件名称" show-overflow-tooltip />
						<el-table-column label="操作" width="120" align="center">
							<template #default="scope">
								<el-button type="primary" link size="small" icon="View" @click="handlePreview(scope.row)">预览</el-button>
								<el-button type="success" link size="small" icon="Download" @click="handleDownload(scope.row)">下载</el-button>
							</template>
						</el-table-column>
					</el-table>
					<el-empty v-else description="暂无补充材料文件" :image-size="60" />
				</el-card>
			</el-col>

			<el-col :span="16">
				<el-card shadow="never" class="flow-card">
					<template #header>
						<div class="card-header">
							<span class="card-title">审批流程</span>
						</div>
					</template>
					<template v-if="applyData.supplementFlowInstId">
						<FlowCommentTimeline :key="String(applyData.supplementFlowInstId) + 'supplement'" :curr-job="supplementFlowJob" />
					</template>
					<el-empty v-else description="暂未发起审批流程" :image-size="80" />
				</el-card>
			</el-col>
		</el-row>

		<template #footer>
			<el-button @click="visible = false">关闭</el-button>
		</template>

		<el-dialog v-model="previewVisible" :title="previewTitle" width="80%" top="5vh" destroy-on-close append-to-body>
			<div class="preview-container">
				<iframe v-if="previewUrl" :src="previewUrl" class="preview-iframe" />
			</div>
		</el-dialog>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { FolderOpened } from '@element-plus/icons-vue';
import { useMessage } from '/@/hooks/message';
import { getObj, getSupplementFileType, getApplyFiles, previewFileById, downloadFileById } from '/@/api/purchase/purchasingrequisition';
import { getDicts } from '/@/api/admin/dict';

const FlowCommentTimeline = defineAsyncComponent(() => import('/@/views/jsonflow/comment/timeline.vue'));

interface FileItem {
	id: string;
	name: string;
	url: string;
}

const visible = ref(false);
const applyId = ref('');
const applyData = ref<any>({});
const fileList = ref<FileItem[]>([]);
const purchaseTypeLabel = ref('');
const requiredFileTypeName = ref('');
const purchaseTypeDeptList = ref<any[]>([]);
const previewVisible = ref(false);
const previewTitle = ref('');
const previewUrl = ref('');

const PURCHASE_TYPE_DEPT_MAP: Record<string, string> = {
	'1': '网上商城',
	'2': '市场采购',
	'3': '商务洽谈',
	'5': '询价',
};

const FILE_TYPE_MAP: Record<string, string> = {
	'10': '商务洽谈纪要',
	'20': '市场采购纪要',
	'30': '网上商城采购材料',
	'150': '部门采购询价表',
};

const supplementFlowJob = computed(() => {
	if (!applyData.value.supplementFlowInstId) return null;
	return {
		id: applyData.value.id,
		flowInstId: applyData.value.supplementFlowInstId,
	};
});

const loadDictData = async () => {
	try {
		const res = await getDicts('PURCHASE_TYPE_DEPT');
		if (res.data && Array.isArray(res.data)) {
			purchaseTypeDeptList.value = res.data.map((item: any) => ({
				label: item.label || item.dictLabel || item.name,
				value: item.value || item.dictValue || item.code,
			}));
			if (applyData.value.purchaseType) {
				const found = purchaseTypeDeptList.value.find((item: any) => item.value === applyData.value.purchaseType);
				if (found) {
					purchaseTypeLabel.value = found.label;
				}
			}
		}
	} catch (e) {
		console.error('加载字典数据失败', e);
	}
};

const getPurchaseTypeLabel = () => {
	if (applyData.value.purchaseType) {
		purchaseTypeLabel.value = PURCHASE_TYPE_DEPT_MAP[applyData.value.purchaseType] || applyData.value.purchaseType;
	}
};

const getRequiredFileTypeName = () => {
	const purchaseType = applyData.value.purchaseType;
	let fileTypeCode = '';
	if (purchaseType === '3') {
		fileTypeCode = '10';
	} else if (purchaseType === '2') {
		fileTypeCode = '20';
	} else if (purchaseType === '1') {
		fileTypeCode = '30';
	} else if (purchaseType === '5') {
		fileTypeCode = '150';
	}
	if (fileTypeCode) {
		requiredFileTypeName.value = FILE_TYPE_MAP[fileTypeCode] || '补充材料';
	}
	return fileTypeCode;
};

const open = async (id: string, row?: any) => {
	applyId.value = id || '';
	visible.value = true;
	fileList.value = [];
	applyData.value = row || {};
	purchaseTypeLabel.value = '';
	requiredFileTypeName.value = '';

	if (!row || !row.purchaseType) {
		try {
			const res = await getObj(id);
			applyData.value = res?.data || {};
		} catch (e) {
			console.error('获取采购申请详情失败', e);
			useMessage().error('获取采购申请详情失败');
			return;
		}
	}

	await loadDictData();
	getPurchaseTypeLabel();
	const fileTypeCode = getRequiredFileTypeName();

	if (applyData.value.id && fileTypeCode) {
		try {
			const filesRes = await getApplyFiles(applyData.value.id);
			const files = filesRes?.data || [];
			const matchingFiles = files.filter((f: any) => String(f.fileType) === fileTypeCode);
			if (matchingFiles.length > 0) {
				fileList.value = matchingFiles.map((f: any) => ({
					id: f.id,
					name: f.fileTitle || f.fileName || '附件',
					url: f.fileUrl,
				}));
			}
		} catch (e) {
			console.error('获取文件列表失败', e);
		}
	}
};

const handlePreview = async (row: FileItem) => {
	if (!row.id) {
		useMessage().warning('文件ID不存在');
		return;
	}
	try {
		const blob = await previewFileById(row.id);
		previewUrl.value = window.URL.createObjectURL(blob);
		previewTitle.value = row.name || '文件预览';
		previewVisible.value = true;
	} catch (e) {
		console.error('预览失败', e);
		useMessage().error('预览失败');
	}
};

const handleDownload = async (row: FileItem) => {
	if (!row.id) {
		useMessage().warning('文件ID不存在');
		return;
	}
	try {
		const blob = await downloadFileById(row.id);
		const url = window.URL.createObjectURL(blob);
		const link = document.createElement('a');
		link.href = url;
		link.download = row.name || '附件.pdf';
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);
		window.URL.revokeObjectURL(url);
	} catch (e) {
		console.error('下载失败', e);
		useMessage().error('下载失败');
	}
};

const emit = defineEmits<{
	(e: 'refresh'): void;
}>();

defineExpose({
	open,
});
</script>

<style scoped lang="scss">
.dialog-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	width: 100%;
}

.dialog-title {
	display: flex;
	align-items: center;
	gap: 8px;
	font-size: 16px;
	font-weight: 500;
}

.info-card,
.file-card,
.flow-card {
	margin-bottom: 16px;
}

.card-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.card-title {
	font-size: 14px;
	font-weight: 500;
}

.preview-container {
	width: 100%;
	height: 75vh;
}

.preview-iframe {
	width: 100%;
	height: 100%;
	border: none;
}

:deep(.el-card__header) {
	padding: 12px 16px;
}

:deep(.el-card__body) {
	padding: 12px 16px;
}
</style>
