<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row class="page-header-row mb10">
				<div class="page-title">{{ t('postInvestmentEvaluationForm.title') }}</div>
				<el-button type="primary" @click="handleSubmit">
					{{ t('postInvestmentEvaluationForm.submitButton') }}
				</el-button>
			</el-row>

			<PostInvestmentEvaluationForm v-model="formData" ref="formDataRef"/>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';
import { useRouter, useRoute } from 'vue-router';
import PostInvestmentEvaluationForm from '/@/components/invBid/common/PostInvestmentEvaluationForm.vue';
import { addInvestmentEvaluation, getInvestmentEvaluationView } from '/@/api/investment/postVoteList';
import { PostInvestmentEvaluation, ProjectInvestmentInfo } from '/@/views/invBid/postInvestmentEvaluation/interface/type';


const { t } = useI18n();
const message = useMessage();
const router = useRouter();
const route = useRoute();
const paramsId = ref();

// 表单数据
const formData = ref<ProjectInvestmentInfo>({} as ProjectInvestmentInfo);

/**
 * 获取投后评价表单数据
 * @param id 项目ID
 */
const getData = async (id: number | string) => {
	try {
		const res = await getInvestmentEvaluationView(id)
		formData.value = res.data;
	} catch (error: any) {
		// 错误处理
		message.error(error.msg);
	}
};
const formDataRef = ref<InstanceType<typeof PostInvestmentEvaluationForm>  | null>();

/**
 * 提交表单数据
 */
const handleSubmit = async () => {
	if (!formDataRef.value) return;

	try {
		// 检查 validate 方法是否存在
		if (typeof formDataRef.value.validateRefFn !== 'function') {
			return;
		}

		const submitFormData:PostInvestmentEvaluation|boolean = await formDataRef.value.validateRefFn();
		// 提交表单数据
		if (submitFormData) {
			submitFormData.attachmentUrl = JSON.stringify(submitFormData.attachmentUrl);
			submitFormData.deptId = formData.value.deptId;
			await addInvestmentEvaluation(submitFormData as PostInvestmentEvaluation);
			message.success(t('成功'));
			router.back();
		}
	} catch (error: any) {
		message.error(error.msg || '失败');
	}
};

onMounted(() => {
	paramsId.value = route.query.id ||  undefined;
	if (paramsId.value){
		getData(paramsId.value);
	}

});

</script>

<style scoped>
.page-header-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.page-title {
	font-size: 20px;
	font-weight: 600;
	color: var(--el-text-color-primary);
}

.layout-container .layout-padding {
	height: auto;
	overflow: auto;
}
</style>