<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" :loading="submitLoading" icon="Check" @click="handleInitiateApproval">
							{{ t('planApply.actions.initiateApproval') }}
						</el-button>
						<el-button icon="Document" @click="handleSaveDraft" :loading="saveLoading">
							{{ t('planApply.actions.saveDraft') }}
						</el-button>
						<el-button icon="FolderOpened" @click="handleLoadTemplate">
							{{ t('planApply.actions.loadTemplate') }}
						</el-button>
						<el-button icon="FolderAdd" @click="handleSaveTemplate">
							{{ t('planApply.actions.saveTemplate') }}
						</el-button>
					</div>
					<div style="margin-left: auto">
						<el-button icon="View" @click="handleViewWorkflow">
							{{ t('planApply.actions.viewWorkflow') }}
						</el-button>
					</div>
				</div>
			</el-row>

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

			<ProjectPlanApplyForm v-model="formData" :rules="formDataRules" ref="formDataRef" :is-update="props.isUpdate"/>
		</div>
	</div>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue';
import {useI18n} from 'vue-i18n';
import {useMessage} from '/@/hooks/message';
import {
	investmentProjectsPlanAdd, investmentProjectsPlanGetById,
	investmentProjectsPlanUserDeptBelong
} from '/@/api/investment/investmentManagement';
import ProjectPlanApplyForm from '/@/components/investment/common/ProjectPlanApplyForm.vue';
import type {ProjectPlanApplyFormData} from '/@/components/investment/interface/types';
import type {FormInstance, FormRules} from 'element-plus';
import UploadFile from '/@/components/Upload/index.vue';
import {useRoute} from 'vue-router';
import {flowFn} from "/@/utils/flowFn";
import {addFlowForm} from "/@/api/flow/flow";
import {flowNameOptions} from "/@/hooks/enums";

const props = defineProps({
	isUpdate: {
		type: Boolean,
		default: false
	}
})
const {t} = useI18n();
const message = useMessage();
const route = useRoute();
const submitLoading = ref(false);
const headerForm = reactive<{ title: string, description: string, attachments: any[] | string }>({
	title: '',
	description: '',
	attachments: [] as any[],
});
const requiredRule = [{required: true, message: `${t('该字段必填')}`}];
const headerRequiredRule = ref<FormRules<{ title: string, description: string, attachments: any[] | string }>>({
	title: requiredRule,
});
const headerFormRef = ref<FormInstance>()
const formDataRef = ref<HTMLFormElement | undefined>();
const formData = ref<ProjectPlanApplyFormData>({
	entity: {
		id: null,
		projectName: '',
		projectNature: '',
		groupCompany: '',
		projectOwnerUnit: '',
		projectMainEntity: '',
		projectDepartment: '',
		investmentCategory: '',
		investmentArea: '',
		projectAddress: '',
		projectAddressDetail: '',
		projectInvestmentDirection: '',
		totalInvestment: '',
		investmentDirectionSegmentation: '',
		projectBackground: '',
		constructionNature: '',
		constructionStage: '',
		keyProject: '',
		isMainBusiness: '',
		mainBusinessTypes: '',
		mainBusinessCode: '',
		isManufacturingIndustry: '',
		isStuckIndustry: '',
		urbanStrategy: '',
		projectSource: '',
		majorInvestmentProjects: '',
		isStrategicEmergingIndustries: '',
		projectStartTime: '',
		projectEndTime: '',
		projectConstructionContent: '',
		planInvestmentYear: '',
		annualPlanTotal: '',
		annualPlanInvestment: '',
		planPaymentLimit: '',
		plannedImageAmount: '',
		ownedFunds: '',
		financialFunds: '',
		externalFunding: '',
		externalRaisedCapital: '',
		otherFunds: '',
		governmentFundSourceDesc: '',
		otherFundSourceDesc: '',
		projectTotalAmount: '',
		lastYearCompleted: '',
		ourInvestmentTotalAmount: '',
		ourLastYearCompleted: '',
		projectDesc: '',
		promotionPlan: '',
		projectPreliminaryPlan: '',
		projectPreliminaryPlanAttachment: '',
		attachments: [],
		remark: '',
		decisionType: '',
		isProjectApprovalCompleted: '',
		isDecisionProcedureCompleted: '',
		projectApprovalFileNo: '',
		projectApprovalFileInfo: '',
		decisionProcedureFileNo: '',
		decisionFileInfo: '',
		submitUnitOpinion: '',
		groupInvestmentDeptOpinion: '',
		submitUnitLeadershipOpinion: '',
		submitUnitMainLeadershipOpinion: '',
		planImageQuota: '',
		status:1,
		processInstanceId:'',
		deptId:0,
	},
	investmentProjects: [],
});
const formDataRules = ref<FormRules<ProjectPlanApplyFormData>>({
	'entity.projectName': requiredRule,
	'entity.groupCompany': requiredRule,
	'entity.projectMainEntity': requiredRule,
	'entity.investmentCategory': requiredRule,
	'entity.investmentArea': requiredRule,
	'entity.projectAddress': requiredRule,
	'entity.projectAddressDetail': requiredRule,
	'entity.projectInvestmentDirection': requiredRule,
	'entity.investmentDirectionSegmentation': requiredRule,
	'entity.externalRaisedCapital': requiredRule,
	'entity.otherFunds': requiredRule,
	'entity.projectDesc': requiredRule,
	'entity.projectTotalAmount': requiredRule,
	'entity.lastYearCompleted': requiredRule,
	'entity.ourInvestmentTotalAmount': requiredRule,
	'entity.ourLastYearCompleted': requiredRule,
	'entity.isProjectApprovalCompleted': requiredRule,
	'entity.isDecisionProcedureCompleted': requiredRule,
	'entity.projectSource': requiredRule,
	'entity.constructionNature': requiredRule,
	'entity.majorInvestmentProjects': requiredRule,
	'entity.keyProject': requiredRule,
	'entity.isMainBusiness': requiredRule,
	'entity.mainBusinessTypes': [
		{
			validator: (rule: any, value: any, callback: any) => {
				if (formData.value.entity.isMainBusiness === t('planApply.common.yes')) {
					if (!value) {
						callback(new Error(`${t('该字段必填')}`));
						return;
					}
				}
				callback();
			},
		},
	],
	'entity.mainBusinessCode': requiredRule,
	'entity.isManufacturingIndustry': requiredRule,
	'entity.isStrategicEmergingIndustries': requiredRule,
	'entity.urbanStrategy': requiredRule,
	'entity.projectStartTime': requiredRule,
	'entity.projectEndTime': requiredRule,
	'entity.ownedFunds': requiredRule,
	'entity.financialFunds': requiredRule,
	'entity.planImageQuota': requiredRule,
	'entity.planPaymentLimit': requiredRule,
	'entity.projectApprovalFileNo':[{validator:(rule: any, value: any, callback: any) =>{
		if (formData.value.entity.isProjectApprovalCompleted === '1' && !value){
			callback(new Error(`${t('该字段必填')}`));
		}else {
			callback();
		}
		},required:true,trigger: ['blur', 'change']}],
	'entity.projectApprovalFileInfo':[{validator:(rule: any, value: any, callback: any) =>{
		if (formData.value.entity.isProjectApprovalCompleted === '1' && !value){
			callback(new Error(`${t('该字段必填')}`));
		}else {
			callback();
		}
		},required: true,trigger: ['blur', 'change']}],
	'entity.decisionProcedureFileNo':[{validator:(rule: any, value: any, callback: any) =>{
		if (formData.value.entity.isDecisionProcedureCompleted === '1' && !value){
			callback(new Error(`${t('该字段必填')}`));
		}else {
			callback();
		}
		},required:true,trigger: ['blur', 'change']}],
	'entity.decisionFileInfo':[{validator:(rule: any, value: any, callback: any) =>{
		if (formData.value.entity.isDecisionProcedureCompleted === '1' && !value){
			callback(new Error(`${t('该字段必填')}`));
		}else {
			callback();
		}
		},required: true,trigger: ['blur', 'change']}],
});
const handleInitiateApproval = async () => {
	try {
		const headerValid = await headerFormRef.value?.validate();
		const valid = await formDataRef.value?.validateForm();
		if (!valid && !headerValid) return;
		submitLoading.value = true;
		let flowIdKey = ''
		const data = await investmentProjectsPlanUserDeptBelong()
		switch (data.data) {
			case 1:
				flowIdKey = props.isUpdate ? 'VITE_FLOWID_27' : 'VITE_FLOWID_23';
				break;
			case 2:
				flowIdKey = props.isUpdate ? 'VITE_FLOWID_28' : 'VITE_FLOWID_24';
				break;
			case 3:
				flowIdKey = props.isUpdate ? 'VITE_FLOWID_29' : 'VITE_FLOWID_25';
				break;
			case 4:
				flowIdKey = props.isUpdate ? 'VITE_FLOWID_30' : 'VITE_FLOWID_26';
				break;
			default:
				flowIdKey = props.isUpdate ? 'VITE_FLOWID_27' : 'VITE_FLOWID_23';
		}
		const {processInstanceId} = await flowFn(flowIdKey, {
			paramMap: {}
		})
		const flowName = props.isUpdate ? 'investmentPlanUpdates' : 'investmentPlanRegistration';
		const flowNameObj = flowNameOptions.filter(item => item.label === flowName)[0]
		await addFlowForm({
			title: headerForm.title,
			description: headerForm.description,
			attachments: headerForm.attachments ? JSON.stringify(headerForm.attachments) : '',
			processInstanceId,
			flowType: flowNameObj.value
		})
		formData.value.entity.processInstanceId = processInstanceId;
		formData.value.entity.projectPreliminaryPlanAttachment = JSON.stringify(formData.value.entity.projectPreliminaryPlanAttachment);
		formData.value.entity.status = 1
		Object.assign(formData.value.entity,{flowType:flowNameObj.value})
		const params = {
			...formData.value,
			entity: {
				...formData.value.entity,
				attachments: formData.value.entity.attachments ? JSON.stringify(formData.value.entity.attachments) : '',
				projectPreliminaryPlanAttachment: formData.value.entity.projectPreliminaryPlanAttachment ? JSON.stringify(formData.value.entity.projectPreliminaryPlanAttachment) : ''
			}
		}
		investmentProjectsPlanAdd(params)
				.then(() => {
					submitLoading.value = false;
					message.success(t('planApply.messages.initiateApproval'));
				})
				.catch((err: any) => {
					submitLoading.value = false;
					message.error(err.msg);
				});
	} catch (error) {
		console.log(error, 'error');
	}
};

const saveLoading = ref<boolean>(false);
const handleSaveDraft = async () => {
	const headerValid = await headerFormRef.value?.validate();
	const valid = await formDataRef.value?.validateForm();
	if (!valid && !headerValid) return;
	saveLoading.value = true;
	const flowName = props.isUpdate ? 'investmentPlanUpdates' : 'investmentPlanRegistration';
	const flowNameObj = flowNameOptions.filter(item => item.label === flowName)[0]
	formData.value.entity.projectPreliminaryPlanAttachment = JSON.stringify(formData.value.entity.projectPreliminaryPlanAttachment);
	formData.value.entity.status = 1
	Object.assign(formData.value.entity,{flowType:flowNameObj.value})
	const params = {
		...formData.value,
		entity: {
			...formData.value.entity,
			attachments: formData.value.entity.attachments ? JSON.stringify(formData.value.entity.attachments) : '',
			projectPreliminaryPlanAttachment: formData.value.entity.projectPreliminaryPlanAttachment ? JSON.stringify(formData.value.entity.projectPreliminaryPlanAttachment) : ''
		},
		temporaryStorage:{
			title: headerForm.title,
			businessType: flowNameObj.value,
		}
	}
	investmentProjectsPlanAdd(params)
			.then(() => {
				saveLoading.value = false;
				message.success('保存代发成功');
			})
			.catch((err: any) => {
				saveLoading.value = false;
				message.error(err.msg);
			});
};

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

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

const handleViewWorkflow = () => {
	message.info(t('planApply.messages.viewWorkflow'));
};
/**
 * 处理查看详情事件
 * 根据指定行数据获取详细信息并显示在抽屉中
 */
const getData = (id: string) => {
	investmentProjectsPlanGetById(id).then((res: any) => {
		Object.assign(formData.value.entity, res.data);
		Object.assign(formData.value.investmentProjects, res.data.projectInvestmentEntities);
	});
};
onMounted(() => {
	if (route.query.id) {
		getData(<string>route.query.id);
	}
});
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>
