<template>
	<el-dialog v-model="visible" title="采购合同详情" width="1000px" destroy-on-close append-to-body>
		<el-descriptions :column="2" border class="apply-info">
			<el-descriptions-item label="采购编号">{{ purchaseNo || '-' }}</el-descriptions-item>
			<el-descriptions-item label="采购项目名称">{{ projectName || '-' }}</el-descriptions-item>
		</el-descriptions>

		<el-divider content-position="left">合同信息</el-divider>

		<el-descriptions v-if="contractData" :column="2" border>
			<el-descriptions-item label="合同编号">{{ contractData.contractNo || '-' }}</el-descriptions-item>
			<el-descriptions-item label="合同名称">{{ contractData.contractName || '-' }}</el-descriptions-item>
			<el-descriptions-item label="供应商">{{ contractData.supplierName || '-' }}</el-descriptions-item>
			<el-descriptions-item label="合同金额">{{
				contractData.money ? Number(contractData.money).toLocaleString() + ' 元' : '-'
			}}</el-descriptions-item>
			<el-descriptions-item label="合同状态">
				<el-tag v-if="contractData.flowStatus === '0'" type="warning">运行中</el-tag>
				<el-tag v-else-if="contractData.flowStatus === '1'" type="success">已完成</el-tag>
				<el-tag v-else-if="contractData.flowStatus === '2'" type="info">已作废</el-tag>
				<span v-else>-</span>
			</el-descriptions-item>
			<el-descriptions-item label="是否需要招标">
				<el-tag v-if="contractData.isBidding === '1'" type="success">是</el-tag>
				<el-tag v-else type="info">否</el-tag>
			</el-descriptions-item>
			<el-descriptions-item label="是否需要法律顾问">
				<el-tag v-if="contractData.isLegalAdviser === '1'" type="success">是</el-tag>
				<el-tag v-else type="info">否</el-tag>
			</el-descriptions-item>
			<el-descriptions-item label="是否涉及多个部门">
				<el-tag v-if="contractData.isDepts === '1'" type="success">是</el-tag>
				<el-tag v-else type="info">否</el-tag>
			</el-descriptions-item>
			<el-descriptions-item label="是否全校合同">
				<el-tag v-if="contractData.isSchool === '1'" type="success">是</el-tag>
				<el-tag v-else type="info">否</el-tag>
			</el-descriptions-item>
			<el-descriptions-item v-if="contractData.isLegalAdviser === '1'" label="法律顾问意见" :span="2">
				{{ contractData.legalAdviserOpinion || '-' }}
			</el-descriptions-item>
			<el-descriptions-item label="备注" :span="2">{{ contractData.remarks || '-' }}</el-descriptions-item>
		</el-descriptions>

		<el-empty v-else description="暂无合同信息" />

		<template v-if="contractData">
			<el-divider content-position="left">附件信息</el-divider>

			<el-tabs v-model="activeTab">
				<el-tab-pane label="合同文件" name="contract">
					<el-table :data="contractFiles" border stripe v-if="contractFiles.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-tab-pane>
				<el-tab-pane label="合同补充材料" name="supplement">
					<el-table :data="supplementFiles" border stripe v-if="supplementFiles.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-tab-pane>
			</el-tabs>

			<el-divider content-position="left">审核流程</el-divider>

			<FlowCommentTimeline v-if="flowInstId" :curr-job="{ flowInstId }" />
		</template>

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

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

<script setup lang="ts">
import { ref, defineAsyncComponent } from 'vue';
import { useMessage } from '/@/hooks/message';
import { getDetail } from '/@/api/purchase/purchasingcontract';
import { previewFileById, downloadFileById } from '/@/api/purchase/purchasingrequisition';

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

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

const visible = ref(false);
const loading = ref(false);
const purchaseId = ref('');
const purchaseNo = ref('');
const projectName = ref('');
const contractData = ref<any>(null);
const flowInstId = ref<number | null>(null);
const contractFiles = ref<FileItem[]>([]);
const supplementFiles = ref<FileItem[]>([]);
const activeTab = ref('contract');

const previewVisible = ref(false);
const previewTitle = ref('');
const previewUrl = ref('');

const open = async (id: string) => {
	purchaseId.value = id;
	visible.value = true;
	loading.value = true;
	contractData.value = null;
	contractFiles.value = [];
	supplementFiles.value = [];
	flowInstId.value = null;

	try {
		const res = await getDetail(id);
		const data = res?.data || {};
		purchaseNo.value = data.purchaseNo || '';
		projectName.value = data.projectName || '';
		contractData.value = data.contract || null;

		if (data.contract) {
			flowInstId.value = data.contract.flowInstId || null;

			if (data.contract.contractFiles && data.contract.contractFiles.length > 0) {
				contractFiles.value = data.contract.contractFiles.map((f: any) => ({
					id: f.id,
					name: f.fileTitle || '合同文件',
					url: f.fileUrl,
				}));
			}

			if (data.contract.supplementFiles && data.contract.supplementFiles.length > 0) {
				supplementFiles.value = data.contract.supplementFiles.map((f: any) => ({
					id: f.id,
					name: f.fileTitle || '补充材料',
					url: f.fileUrl,
				}));
			}
		}
	} catch (e) {
		console.error('获取合同详情失败', e);
		useMessage().error('获取合同详情失败');
	} finally {
		loading.value = false;
	}
};

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('下载失败');
	}
};

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

<style scoped lang="scss">
.apply-info {
	margin-bottom: 16px;
}

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

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