<template>
	<div class="supplement-view-container">
		<el-card shadow="never" class="info-card">
			<template #header>
				<div class="card-header">
					<span class="card-title">
						<el-icon><Document /></el-icon>
						采购申请基本信息
					</span>
				</div>
			</template>
			<el-descriptions :column="2" border>
				<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="采购内容" :span="2">{{ applyData.projectContent || '-' }}</el-descriptions-item>
				<el-descriptions-item label="申请人">{{ applyData.createByName || '-' }}</el-descriptions-item>
				<el-descriptions-item label="申请部门">{{ applyData.deptName || '-' }}</el-descriptions-item>
			</el-descriptions>
		</el-card>

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

		<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>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import { Document, FolderOpened, Download } from '@element-plus/icons-vue';
import { useMessage } from '/@/hooks/message';
import { getDicts } from '/@/api/admin/dict';
import { previewFileById, downloadFileById } from '/@/api/purchase/purchasingrequisition';
import { currElTabIsSave } from '/@/api/order/order-key-vue';
import request from '/@/utils/request';

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

const props = defineProps({
	currJob: { type: Object, default: null },
	currElTab: { type: Object, default: null },
});

const emit = defineEmits(['handleJob']);

const route = useRoute();
const loading = ref(false);
const applyData = ref<any>({});
const fileList = ref<FileInfo[]>([]);
const purchaseTypeLabel = ref('');
const requiredFileTypeName = ref('');
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 loadDictData = async () => {
	try {
		const res = await getDicts('PURCHASE_TYPE_DEPT');
		if (res.data && Array.isArray(res.data)) {
			const list = 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 = list.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 loadData = async () => {
	const flowInstId = route.query.flowInstId as string;
	if (!flowInstId) {
		useMessage().warning('缺少流程实例ID');
		return;
	}

	loading.value = true;
	try {
		const res = await request({
			url: '/purchase/purchasingapply/supplement/getByFlowInstId',
			method: 'get',
			params: { flowInstId },
		});
		applyData.value = res?.data || {};

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

		if (applyData.value.id && fileTypeCode) {
			const filesRes = await request({
				url: '/purchase/purchasingfiles/listByType',
				method: 'get',
				params: { purchaseId: applyData.value.id, fileType: fileTypeCode },
			});
			const files = filesRes?.data || [];
			fileList.value = files.map((f: any) => ({
				id: f.id,
				name: f.fileTitle || f.fileName || '附件',
				url: f.fileUrl,
			}));
		}
	} catch (e) {
		console.error('获取数据失败', e);
		useMessage().error('获取采购申请信息失败');
	} finally {
		loading.value = false;
	}
};

const handlePreview = async (row: FileInfo) => {
	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: FileInfo) => {
	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('下载失败');
	}
};

onMounted(() => {
	loadData();
	if (props.currJob && props.currElTab?.id) {
		currElTabIsSave(props.currJob, props.currElTab.id, true, emit);
	}
});
</script>

<style scoped lang="scss">
.supplement-view-container {
	padding: 16px;
	background-color: #f5f7fa;
	min-height: 100vh;
}

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

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

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

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

.preview-iframe {
	width: 100%;
	height: 100%;
	border: none;
}
</style>