<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">
							{{ t('progressReport.actions.saveDraft') }}
						</el-button>
						<el-button icon="FolderOpened" @click="handleLoadTemplate">
							{{ 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" label-width="80px" class="w-full">
					<el-form-item :label="t('progressReport.headerForm.title')">
						<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" />
		</div>
	</div>
</template>

<script setup lang="ts">
import { reactive } 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,
	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";

const { t } = useI18n();
const message = useMessage();

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: '',
});
// 必填规则
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 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 {processInstanceId} = await flowFn(flowIdKey,{
			paramMap:{
			}
		})
		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 handleSaveDraft = () => {
	message.info(t('progressReport.messages.saveDraft'));
};

const handleLoadTemplate = () => {
	message.info(t('progressReport.messages.loadTemplate'));
};

const handleSaveTemplate = () => {
	message.info(t('progressReport.messages.saveTemplate'));
};

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>
