<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row class="mb10">
				<div class="form-header-actions" style="width: 100%">
					<div>
						<el-button type="primary" icon="Check" :loading="submitLoading" @click="handleInitiateApproval">
							{{ t('progressReport.actions.initiateApproval') }}
						</el-button>
						<el-button icon="Document" @click="handleSaveDraft" :loading="saveLoading">
							{{ t('progressReport.actions.saveDraft') }}
						</el-button>
						<el-button icon="FolderOpened" @click="handleLoadTemplate" :loading="templateLoading">
							{{ t('progressReport.actions.loadTemplate') }}
						</el-button>
						<el-button icon="FolderAdd" @click="handleSaveTemplate">
							{{ t('progressReport.actions.saveTemplate') }}
						</el-button>
					</div>
					<div style="margin-left: auto">
						<el-button icon="View" @click="handleViewWorkflow">
							{{ t('progressReport.actions.viewWorkflow') }}
						</el-button>
					</div>
				</div>
			</el-row>

			<!-- 标题、描述、上传附件 -->
			<el-row class="mb10">
				<el-form :model="headerForm" :rules="headerFormRules" ref="headerFormRef" label-width="80px"
					class="w-full">
					<el-form-item :label="t('progressReport.headerForm.title')" prop="title" required>
						<el-input v-model="headerForm.title"
							:placeholder="t('progressReport.headerForm.titlePlaceholder')" />
					</el-form-item>
					<el-form-item :label="t('progressReport.headerForm.description')">
						<el-input v-model="headerForm.description"
							:placeholder="t('progressReport.headerForm.descriptionPlaceholder')" />
					</el-form-item>
					<el-form-item :label="t('progressReport.headerForm.attachments')">
						<UploadFile :modelValue="headerForm.attachments" @change="uploadChange" :fileSize="20"
							type="simple" :limit="10" />
					</el-form-item>
				</el-form>
			</el-row>

			<ProjectProgressReportForm v-model="formData" :rules="formDataRef" ref="formRef" />
			<templateTable/>
		</div>
	</div>
</template>

<script setup lang="ts">
import templateTable from "/@/components/templetTableComom/index.vue"
import {computed, reactive, ref, watch} from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';
import ProjectProgressReportForm from '/@/components/investment/common/ProjectProgressReportForm.vue';
import { InvestmentProjectProgress } from '/@/views/invMid/progressReport/interface/type';
import { FormRules } from 'element-plus';
import {
	addInvestmentProjectsProgressAPI, getInvestmentProjectsProgressByTemplateIdAPI,
	getInvestmentProjectsProgressUserDeptBelongAPI
} from '/@/api/investment/progressOfInvestmentProjects';
import UploadFile from "/@/components/Upload/index.vue";
import { flowFn } from "/@/utils/flowFn";
import { addFlowForm } from "/@/api/flow/flow";
import { flowNameOptions } from "/@/hooks/enums";
import {templateStore} from "/@/stores/template"
import {useRouter} from "vue-router";
import {addTemplate} from "/@/api/common";
import {getPropertyRightsByIdAPI} from "/@/api/workbench/miOwLibr/ownershipCreate";

const router = useRouter();
const temp = templateStore();
const { t } = useI18n();
const message = useMessage();

const headerFormRef = ref<any>();
const headerFormRules = {
	title: [{ required: true, message: '标题必填', trigger: ['blur', 'change'] }]
};
const headerForm = reactive<{ title: string; description: string; attachments: any[] | string }>({
	title: '',
	description: '',
	attachments: [],
});
const submitLoading = ref<boolean>(false);
const formRef = ref<HTMLFormElement | null>(null);
const formData = reactive<InvestmentProjectProgress>({
	id: undefined,
	projectName: '',
	projectId: undefined,
	projectStatus: '',
	constructionStage: '',
	implementingBody: '',
	projectTotalAmount: undefined,
	cumulativeInvestmentToDate: undefined,
	completionRate: undefined,
	cumulativePaymentToDate: undefined,
	paymentCompletionRate: undefined,
	annualReport: undefined,
	annualPlannedInvestment: undefined,
	ytdRemainingInvestment: undefined,
	investmentCompletionRate: undefined,
	plannedPayment: undefined,
	actualPayment: undefined,
	investmentPlanCompletionRate: undefined,
	achievements: '',
	coordinationIssues: '',
	nextWorkPlan: '',
	supportingDocuments: '',
	remarks: '',
	isFinalApplication: undefined,
	createBy: '',
	createTime: '',
	updateBy: '',
	updateTime: '',
	delFlag: '',
	processInstanceId: '',
	status: '',
	deptId: '',
});
// 必填规则
const requiredRule = [{ required: true, message: `${t('该字段必填')}` }];
const formDataRef = ref<FormRules<InvestmentProjectProgress>>({
	projectName: requiredRule,
	projectStatus: requiredRule,
	projectTotalAmount: requiredRule,
	cumulativeInvestmentToDate: requiredRule,
	completionRate: requiredRule,
	annualPlannedInvestment: requiredRule,
	ytdRemainingInvestment: requiredRule,
});
const handleInitiateApproval = async () => {
	// message.info(t('progressReport.messages.initiateApproval'));
	try {
		const headerValid = await headerFormRef.value?.validate().catch(() => false);
		if (!headerValid) {
			return;
		}
		const valid = await formRef.value?.validate();
		submitLoading.value = true;
		let flowIdKey = '';
		const data = await getInvestmentProjectsProgressUserDeptBelongAPI();
		switch (data.data) {
			case 1:
				flowIdKey = 'VITE_FLOWID_31';
				break;
			case 2:
				flowIdKey = 'VITE_FLOWID_32';
				break;
			case 3:
				flowIdKey = 'VITE_FLOWID_33';
				break;
			case 4:
				flowIdKey = 'VITE_FLOWID_34';
				break;
			default:
				flowIdKey = 'VITE_FLOWID_31';
		}
		headerForm.attachments = JSON.stringify(headerForm.attachments);
		const flowResult = await flowFn(flowIdKey, {
			paramMap: {
			}
		})
		if (flowResult instanceof Error) {
			throw flowResult;
		}
		const { processInstanceId } = flowResult;
		const flowNameObj = flowNameOptions.filter(item => item.label === 'projectProgressDeclaration')[0]
		await addFlowForm({
			title: headerForm.title,
			description: headerForm.description,
			attachments: headerForm.attachments,
			processInstanceId,
			flowType: flowNameObj.value
		})
		valid.processInstanceId = processInstanceId;
		valid.supportingDocuments = JSON.stringify(valid.supportingDocuments);
		valid.status = 1;
		valid.flowType = flowNameObj.value
		await addInvestmentProjectsProgressAPI(valid).then(() => {
			message.success(t('common.success'));
		}).finally(() => {
			submitLoading.value = false;
		}).catch((err: any) => {
			submitLoading.value = false;
			message.error(err.msg);
		});
	} catch (error) {
		submitLoading.value = false;
	}
};
const saveLoading = ref(false)
const handleSaveDraft = async () => {
	try {
		const headerValid = await headerFormRef.value?.validate().catch(() => false);
		if (!headerValid) {
			return;
		}
		const valid = await formRef.value?.validate();
		submitLoading.value = true;
		headerForm.attachments = JSON.stringify(headerForm.attachments);
		const  processInstanceId  = '';
		const flowNameObj = flowNameOptions.filter(item => item.label === 'projectProgressDeclaration')[0]
		await addFlowForm({
			title: headerForm.title,
			description: headerForm.description,
			attachments: headerForm.attachments,
			processInstanceId,
			flowType: flowNameObj.value
		})
		valid.processInstanceId = processInstanceId;
		valid.supportingDocuments = JSON.stringify(valid.supportingDocuments);
		valid.status = 0;
		valid.flowType = flowNameObj.value
		valid.temporaryStorage={
			businessType:flowNameObj.value,
			title: headerForm.title,
		}
		await addInvestmentProjectsProgressAPI(valid).then(() => {
			message.success(t('common.success'));
		}).finally(() => {
			saveLoading.value = false;
		}).catch((err: any) => {
			saveLoading.value = false;
			message.error(err.msg);
		});
	} catch (error) {
		saveLoading.value = false;
	}
};
const templateLoading = ref(false)
const tempId = computed(()=>temp.temp_id)
const handleLoadTemplate = async () => {
	const flowNameObj = flowNameOptions.filter(item => item.label === 'projectProgressDeclaration')[0]
	temp.changeTempShow(true,flowNameObj.value)
};
watch(()=>tempId.value,()=>{
	getInvestmentProjectsProgressByTemplateIdAPI(tempId.value).then(data => {
		Object.assign(formData, data.data);
	})
})
const handleSaveTemplate = () => async () => {
	try {
		const headerValid = await headerFormRef.value?.validate().catch(() => false);
		if (!headerValid) {
			return;
		}
		const valid = await formRef.value?.validate();
		templateLoading.value = true;
		headerForm.attachments = JSON.stringify(headerForm.attachments);
		const  processInstanceId  = '';
		const flowNameObj = flowNameOptions.filter(item => item.label === 'projectProgressDeclaration')[0]
		await addFlowForm({
			title: headerForm.title,
			description: headerForm.description,
			attachments: headerForm.attachments,
			processInstanceId,
			flowType: flowNameObj.value
		})
		const {data: templateId} = await addTemplate({
			templateName:headerForm.title,
			templateType:flowNameObj.value,
		})
		valid.processInstanceId = processInstanceId;
		valid.supportingDocuments = JSON.stringify(valid.supportingDocuments);
		valid.status = 0;
		valid.flowType = flowNameObj.value
		valid.templateId = templateId
		await addInvestmentProjectsProgressAPI(valid).then(() => {
			message.success(t('common.success'));
		}).finally(() => {
			templateLoading.value = false;
		}).catch((err: any) => {
			templateLoading.value = false;
			message.error(err.msg);
		});
	} catch (error) {
		templateLoading.value = false;
	}
};

const handleViewWorkflow = () => {
	message.info(t('progressReport.messages.viewWorkflow'));
};
const uploadChange = (_: any, data: any[]) => {
	if (!data || Object.prototype.toString.call(data) !== '[object Array]' || data.length === 0) {
		headerForm.attachments = [];
		return;
	}
	headerForm.attachments = data.map((item: any) => {
		return {
			name: item.name,
			url: item.url
		}
	})
}
</script>

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

.form-header-actions {
	display: flex;
	justify-content: space-between;
	align-items: center;
}
</style>
