<template>
	<el-dialog v-model="visible" :title="dialogTitle" width="900px" destroy-on-close append-to-body :close-on-click-modal="false">
		<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="状态">
				<el-tag v-if="applyData.status === '1'" type="success">已完成</el-tag>
				<el-tag v-else>{{ applyData.status }}</el-tag>
			</el-descriptions-item>
		</el-descriptions>

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

		<el-form ref="formRef" :model="formData" :rules="formRules" label-width="160px" :disabled="mode === 'view'">
			<el-row :gutter="20">
				<el-col :span="12" class="mb12">
					<el-form-item label="合同编号" prop="contractNo">
						<el-input v-model="formData.contractNo" placeholder="请输入合同编号" />
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb12">
					<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" class="mb12">
					<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" class="mb12">
					<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" class="mb12">
					<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" class="mb12">
					<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" class="mb12">
					<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-divider content-position="left">附件上传</el-divider>

		<el-form label-width="160px">
			<el-form-item label="合同文件" required>
				<upload-file
					v-model="contractFileList"
					:limit="5"
					:file-type="['pdf']"
					:data="{ fileType: CONTRACT_FILE_TYPE, purchaseId: applyId }"
					upload-file-url="/purchase/purchasingfiles/upload"
					:disabled="mode === 'view'"
				/>
				<div class="file-tips">请上传PDF格式的合同文件</div>
			</el-form-item>
			<el-form-item label="合同补充材料">
				<upload-file
					v-model="supplementFileList"
					:limit="10"
					:file-type="['pdf']"
					:data="{ fileType: SUPPLEMENT_FILE_TYPE, purchaseId: applyId }"
					upload-file-url="/purchase/purchasingfiles/upload"
					:disabled="mode === 'view'"
				/>
				<div class="file-tips">请上传PDF格式的合同补充材料</div>
			</el-form-item>
		</el-form>

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

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useMessage } from '/@/hooks/message';
import { getObj } from '/@/api/purchase/purchasingrequisition';
import { getByPurchaseId, tempStore, submit as submitContract } from '/@/api/purchase/purchasingcontract';
import { getApplyFiles } from '/@/api/purchase/purchasingrequisition';

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

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

const visible = ref(false);
const submitting = ref(false);
const applyId = ref('');
const mode = ref<'add' | 'edit' | 'view'>('add');
const applyData = ref<any>({});
const formRef = ref();

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 contractFileList = ref<FileItem[]>([]);
const supplementFileList = ref<FileItem[]>([]);

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

const dialogTitle = computed(() => {
	if (mode.value === 'view') return '查看采购合同';
	if (mode.value === 'edit') return '编辑采购合同';
	return '新增采购合同';
});

const canSubmit = computed(() => {
	return formData.value.contractNo && formData.value.contractName && formData.value.money !== null && contractFileList.value.length > 0;
});

const open = async (id: string, openMode: 'add' | 'edit' | 'view' = 'add') => {
	applyId.value = id || '';
	mode.value = openMode;
	visible.value = true;
	resetForm();

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

		const contractRes = await getByPurchaseId(id);
		const contractData = contractRes?.data;
		if (contractData) {
			formData.value = {
				purchaseId: id,
				contractNo: contractData.contractNo || '',
				contractName: contractData.contractName || '',
				money: contractData.money,
				isBidding: contractData.isBidding || '0',
				isLegalAdviser: contractData.isLegalAdviser || '0',
				legalAdviserOpinion: contractData.legalAdviserOpinion || '',
				isDepts: contractData.isDepts || '0',
				isSchool: contractData.isSchool || '0',
				remarks: contractData.remarks || '',
				contractFileIds: [],
				supplementFileIds: [],
			};

			if (contractData.contractFiles && contractData.contractFiles.length > 0) {
				contractFileList.value = contractData.contractFiles.map((f: any) => ({
					id: f.id,
					name: f.fileTitle || '合同文件',
					url: f.fileUrl,
				}));
			}
			if (contractData.supplementFiles && contractData.supplementFiles.length > 0) {
				supplementFileList.value = contractData.supplementFiles.map((f: any) => ({
					id: f.id,
					name: f.fileTitle || '补充材料',
					url: f.fileUrl,
				}));
			}
		}
	} catch (e) {
		console.error('获取数据失败', e);
		useMessage().error('获取数据失败');
	}
};

const resetForm = () => {
	formData.value = {
		purchaseId: applyId.value,
		contractNo: '',
		contractName: '',
		money: null,
		isBidding: '0',
		isLegalAdviser: '0',
		legalAdviserOpinion: '',
		isDepts: '0',
		isSchool: '0',
		remarks: '',
		contractFileIds: [],
		supplementFileIds: [],
	};
	contractFileList.value = [];
	supplementFileList.value = [];
};

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

	const contractFileIds = contractFileList.value.filter((f) => f.id).map((f) => f.id);
	const supplementFileIds = supplementFileList.value.filter((f) => f.id).map((f) => f.id);

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

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

	if (contractFileList.value.length === 0) {
		useMessage().warning('请上传合同文件');
		return;
	}

	const contractFileIds = contractFileList.value.filter((f) => f.id).map((f) => f.id);
	const supplementFileIds = supplementFileList.value.filter((f) => f.id).map((f) => f.id);

	submitting.value = true;
	try {
		await submitContract({
			...formData.value,
			purchaseId: applyId.value,
			contractFileIds,
			supplementFileIds,
		});
		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">
.apply-info {
	margin-bottom: 16px;
}

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