<template>
	<el-dialog v-model="visible" title="补充材料" width="900px" destroy-on-close append-to-body :close-on-click-modal="false">
		<template #header>
			<div class="dialog-header">
				<span class="dialog-title">
					<el-icon><Upload /></el-icon>
					补充材料 - {{ applyData.purchaseNo || applyId }}
				</span>
			</div>
		</template>

		<el-descriptions :column="2" border class="apply-info">
			<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="采购方式">{{ purchaseTypeLabelComputed || '-' }}</el-descriptions-item>
			<el-descriptions-item label="采购内容" :span="2">{{ applyData.projectContent || '-' }}</el-descriptions-item>
		</el-descriptions>

		<el-divider content-position="left">采购相关文件补充上传</el-divider>

		<el-alert :type="fileTypeAlertType" :closable="false" style="margin-bottom: 16px">
			<template #title>
				<span v-if="requiredFileType">{{ requiredFileTypeName }}必传</span>
				<span v-else>当前采购方式无需补充材料</span>
			</template>
		</el-alert>

		<el-form v-if="requiredFileType" label-width="140px">
			<el-form-item :label="requiredFileTypeName" required>
				<upload-file
					v-model="fileList"
					:limit="1"
					:file-type="['pdf']"
					:data="{ fileType: requiredFileType, purchaseId: applyId }"
					upload-file-url="/purchase/purchasingfiles/upload"
				/>
				<div class="file-tips">{{ fileTips }}</div>
			</el-form-item>
		</el-form>

		<el-empty v-else description="当前采购方式无需补充材料" />

		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" :loading="submitting" :disabled="!requiredFileType" @click="handleTempStore">暂存</el-button>
			<el-button type="success" :loading="submitting" :disabled="!canSubmit" @click="handleSubmit">提交</el-button>
		</template>
	</el-dialog>
</template>

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

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

const visible = ref(false);
const submitting = ref(false);
const applyId = ref('');
const applyData = ref<any>({});
const requiredFileType = ref('');
const fileList = ref<FileItem[]>([]);
const purchaseTypeDeptList = ref<any[]>([]);

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

const purchaseTypeLabelComputed = computed(() => {
	if (applyData.value.purchaseTypeLabel) {
		return applyData.value.purchaseTypeLabel;
	}
	if (applyData.value.purchaseType) {
		const found = purchaseTypeDeptList.value.find((item: any) => item.value === applyData.value.purchaseType);
		if (found) {
			return found.label;
		}
		return PURCHASE_TYPE_DEPT_MAP[applyData.value.purchaseType] || applyData.value.purchaseType;
	}
	return '';
});

const fileTypeMap: Record<string, { name: string; tips: string }> = {
	'10': { name: '商务洽谈纪要', tips: '请上传商务洽谈相关纪要文件（PDF格式）' },
	'20': { name: '市场采购纪要', tips: '请上传市场采购相关纪要文件（PDF格式）' },
	'30': { name: '网上商城采购材料', tips: '请上传网上商城采购相关材料（PDF格式）' },
	'150': { name: '部门采购询价表', tips: '请上传部门采购询价表（PDF格式）' },
};

const requiredFileTypeName = computed(() => {
	if (!requiredFileType.value) return '';
	return fileTypeMap[requiredFileType.value]?.name || '补充材料';
});

const fileTips = computed(() => {
	if (!requiredFileType.value) return '';
	return fileTypeMap[requiredFileType.value]?.tips || '请上传PDF格式文件';
});

const fileTypeAlertType = computed(() => {
	return requiredFileType.value ? 'warning' : 'info';
});

const canSubmit = computed(() => {
	return requiredFileType.value && fileList.value.length > 0;
});

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,
			}));
		}
	} catch (e) {
		console.error('加载字典数据失败', e);
	}
};

const open = async (id: string) => {
	applyId.value = id || '';
	visible.value = true;
	fileList.value = [];
	requiredFileType.value = '';
	applyData.value = {};

	await loadDictData();

	try {
		const res = await getObj(id);
		const data = res?.data || {};
		applyData.value = data;

		if (data.purchaseType) {
			const fileTypeRes = await getSupplementFileType(data.purchaseType);
			requiredFileType.value = fileTypeRes?.data || '';
		}

		if (requiredFileType.value) {
			const filesRes = await getApplyFiles(id);
			const files = filesRes?.data || [];
			const matchingFiles = files.filter((f: any) => String(f.fileType) === requiredFileType.value);
			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);
		useMessage().error('获取采购申请详情失败');
	}
};

const handleTempStore = async () => {
	if (!applyId.value) {
		useMessage().warning('无法获取采购申请ID');
		return;
	}

	const fileIds = fileList.value.filter((f) => f.id).map((f) => f.id);
	if (fileIds.length === 0) {
		useMessage().warning('请先上传补充材料');
		return;
	}

	submitting.value = true;
	try {
		await tempStoreSupplement(applyId.value, fileIds);
		useMessage().success('暂存成功');
	} catch (err: any) {
		useMessage().error(err?.msg || '暂存失败');
	} finally {
		submitting.value = false;
	}
};

const handleSubmit = async () => {
	if (!applyId.value) {
		useMessage().warning('无法获取采购申请ID');
		return;
	}

	submitting.value = true;
	try {
		await submitSupplement(applyId.value);
		useMessage().success('提交成功，流程已启动');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err?.msg || '提交失败');
	} finally {
		submitting.value = false;
	}
};

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;
}

.apply-info {
	margin-bottom: 16px;
}

.file-tips {
	font-size: 12px;
	color: #909399;
}
</style>
