<template>
	<div class="contract-audit-container">
		<el-card shadow="never" class="info-card">
			<template #header>
				<div class="card-header">
					<span class="card-title">
						<el-icon><Document /></el-icon>
						采购申请信息
					</span>
					<el-tag v-if="flowStatus === '0'" type="warning">运行中</el-tag>
					<el-tag v-else-if="flowStatus === '1'" type="success">已完成</el-tag>
					<el-tag v-else-if="flowStatus === '2'" type="info">已作废</el-tag>
				</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="申请人">{{ applyData.createName || '-' }}</el-descriptions-item>
				<el-descriptions-item label="申请部门" :span="2">{{ applyData.deptName || '-' }}</el-descriptions-item>
			</el-descriptions>
		</el-card>

		<el-card shadow="never" class="contract-card">
			<template #header>
				<div class="card-header">
					<span class="card-title">
						<el-icon><Tickets /></el-icon>
						合同信息
					</span>
				</div>
			</template>

			<el-form ref="formRef" :model="formData" :rules="formRules" label-width="160px" :disabled="isViewMode">
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="合同编号" prop="contractNo">
							<el-input v-model="formData.contractNo" placeholder="请输入合同编号" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="合同名称" prop="contractName">
							<el-input v-model="formData.contractName" placeholder="请输入合同名称" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="合同金额(元)" prop="money">
							<el-input-number v-model="formData.money" :precision="2" :min="0" :controls="false" style="width: 100%" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="是否需要招标" prop="isBidding">
							<el-radio-group v-model="formData.isBidding">
								<el-radio label="0">否</el-radio>
								<el-radio label="1">是</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="是否需要法律顾问" prop="isLegalAdviser">
							<el-radio-group v-model="formData.isLegalAdviser">
								<el-radio label="0">否</el-radio>
								<el-radio label="1">是</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="是否涉及多个部门" prop="isDepts">
							<el-radio-group v-model="formData.isDepts">
								<el-radio label="0">否</el-radio>
								<el-radio label="1">是</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="是否全校合同" prop="isSchool">
							<el-radio-group v-model="formData.isSchool">
								<el-radio label="0">否</el-radio>
								<el-radio label="1">是</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item v-if="formData.isLegalAdviser === '1'" label="法律顾问意见" prop="legalAdviserOpinion">
					<el-input v-model="formData.legalAdviserOpinion" type="textarea" :rows="3" placeholder="请输入法律顾问意见" />
				</el-form-item>
				<el-form-item label="备注" prop="remarks">
					<el-input v-model="formData.remarks" type="textarea" :rows="2" placeholder="请输入备注" />
				</el-form-item>
			</el-form>
		</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-tabs v-model="activeTab">
				<el-tab-pane label="合同文件" name="contract">
					<el-table v-loading="fileLoading" :data="contractFiles" stripe border v-if="contractFiles.length > 0">
						<el-table-column type="index" label="序号" width="60" align="center" />
						<el-table-column prop="fileTitle" 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 v-loading="fileLoading" :data="supplementFiles" stripe border v-if="supplementFiles.length > 0">
						<el-table-column type="index" label="序号" width="60" align="center" />
						<el-table-column prop="fileTitle" 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-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" name="ContractAudit">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import { Document, Tickets, FolderOpened } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { getObj } from '/@/api/purchase/purchasingrequisition';
import { getByPurchaseId, updateContract } from '/@/api/purchase/purchasingcontract';
import { previewFileById, downloadFileById } from '/@/api/purchase/purchasingrequisition';
import { currElTabIsSave } from '/@/api/order/order-key-vue';

const CONTRACT_FILE_TYPE = '160';
const SUPPLEMENT_FILE_TYPE = '170';

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 fileLoading = ref(false);
const formRef = ref();

const isFlowEmbed = computed(() => !!props.currJob);
const isViewMode = computed(() => {
	if (isFlowEmbed.value && props.currJob) {
		return !!props.currJob.hiJob || props.currElTab?.isFormEdit === '0';
	}
	return route.query.mode === 'view';
});

const applyData = ref<any>({});
const formData = ref({
	purchaseId: '',
	contractNo: '',
	contractName: '',
	money: null as number | null,
	isBidding: '0',
	isLegalAdviser: '0',
	legalAdviserOpinion: '',
	isDepts: '0',
	isSchool: '0',
	remarks: '',
	contractFileIds: [] as string[],
	supplementFileIds: [] as string[],
});

const formRules = {
	contractNo: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
	contractName: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
	money: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
};

const flowStatus = computed(() => formData.value.flowStatus || '0');
const activeTab = ref('contract');
const contractFiles = ref<any[]>([]);
const supplementFiles = ref<any[]>([]);

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

const effectivePurchaseId = computed(() => {
	if (props.currJob?.orderId) {
		return String(props.currJob.orderId);
	}
	return (route.query.id as string) || (route.query.purchaseId as string) || '';
});

const loadApplyData = async () => {
	if (!effectivePurchaseId.value) return;

	try {
		loading.value = true;
		const res = await getObj(effectivePurchaseId.value);
		if (res.code === 0 && res.data) {
			applyData.value = res.data;
		}
	} catch (e: any) {
		ElMessage.error(e?.msg || '加载采购申请失败');
	} finally {
		loading.value = false;
	}
};

const loadContractData = async () => {
	if (!effectivePurchaseId.value) return;

	try {
		fileLoading.value = true;
		const res = await getByPurchaseId(effectivePurchaseId.value);
		if (res.code === 0 && res.data) {
			const data = res.data;
			formData.value = {
				purchaseId: effectivePurchaseId.value,
				contractNo: data.contractNo || '',
				contractName: data.contractName || '',
				money: data.money,
				isBidding: data.isBidding || '0',
				isLegalAdviser: data.isLegalAdviser || '0',
				legalAdviserOpinion: data.legalAdviserOpinion || '',
				isDepts: data.isDepts || '0',
				isSchool: data.isSchool || '0',
				remarks: data.remarks || '',
				contractFileIds: [],
				supplementFileIds: [],
			};
			(formData.value as any).flowStatus = data.flowStatus;

			if (data.contractFiles && data.contractFiles.length > 0) {
				contractFiles.value = data.contractFiles;
			}
			if (data.supplementFiles && data.supplementFiles.length > 0) {
				supplementFiles.value = data.supplementFiles;
			}
		}
	} catch (e: any) {
		ElMessage.error(e?.msg || '加载合同信息失败');
	} finally {
		fileLoading.value = false;
	}
};

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

const handleDownload = async (row: any) => {
	if (!row.id) {
		ElMessage.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.fileTitle || '附件.pdf';
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);
		window.URL.revokeObjectURL(url);
	} catch (e) {
		ElMessage.error('下载失败');
	}
};

const handleFlowSave = async () => {
	try {
		await formRef.value?.validate();

		const contractFileIds = contractFiles.value.filter((f: any) => f.id).map((f: any) => f.id);
		const supplementFileIds = supplementFiles.value.filter((f: any) => f.id).map((f: any) => f.id);

		await updateContract({
			...formData.value,
			purchaseId: effectivePurchaseId.value,
			contractFileIds,
			supplementFileIds,
		});

		if (props.currJob && props.currElTab?.id) {
			currElTabIsSave(props.currJob, props.currElTab.id, true, emit);
		}

		return true;
	} catch (e: any) {
		ElMessage.error(e?.msg || '保存失败');
		return false;
	}
};

const registerFlowCallbacks = () => {
	if (!isFlowEmbed.value) return;

	if (props.currJob?.resolveSaves) {
		props.currJob.resolveSaves.push(handleFlowSave);
	}
};

onMounted(async () => {
	await loadApplyData();
	await loadContractData();
	registerFlowCallbacks();
});

watch(
	() => props.currJob,
	async (newVal) => {
		if (newVal) {
			await loadApplyData();
			await loadContractData();
			registerFlowCallbacks();
		}
	},
	{ immediate: false }
);
</script>

<style scoped lang="scss">
.contract-audit-container {
	padding: 16px;
	min-height: 100%;
	background: var(--el-fill-color-lighter);
}

.info-card,
.contract-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: 600;
	color: var(--el-text-color-primary);
}

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

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