<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('projectExitPlan.actions.initiateApproval') }}
						</el-button>
						<el-button icon="Document" @click="handleSaveDraft" :loading="saveLoading">
							{{ t('projectExitPlan.actions.saveDraft') }}
						</el-button>
						<el-button icon="FolderOpened" @click="handleLoadTemplate">
							{{ t('projectExitPlan.actions.loadTemplate') }}
						</el-button>
						<el-button icon="FolderAdd" @click="handleSaveTemplate" :loading="saveTemplateLoading">
							{{ t('projectExitPlan.actions.saveTemplate') }}
						</el-button>
					</div>
					<div style="margin-left:auto;">
						<el-button icon="View" @click="handleViewWorkflow">
							{{ t('projectExitPlan.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('projectExitPlan.headerForm.title')" prop="title" required>
						<el-input v-model="headerForm.title"
							:placeholder="t('projectExitPlan.headerForm.titlePlaceholder')" />
					</el-form-item>
					<el-form-item :label="t('projectExitPlan.headerForm.description')">
						<el-input v-model="headerForm.description"
							:placeholder="t('projectExitPlan.headerForm.descriptionPlaceholder')" />
					</el-form-item>
					<el-form-item :label="t('projectExitPlan.headerForm.attachments')">
						<UploadFile :modelValue="headerForm.attachments" @change="uploadChange" :fileSize="20"
							type="simple" :limit="10" />
					</el-form-item>
				</el-form>
			</el-row>

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

<script setup lang="ts">
import {computed, reactive, ref, watch} from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';

import type { ProjectTask } from '/@/views/invMid/projectExitPlan/interface/type';
import ProjectExitPlanForm from '/@/components/investment/common/ProjectExitPlanForm.vue';
import { FormRules } from 'element-plus';
import {addProjectExitPlan, getProjectExitPlanByTemplateId} from '/@/api/investment/projectExitPlan';
import UploadFile from "/@/components/Upload/index.vue";
import { flowFn } from "/@/utils/flowFn";
import { addFlowForm } from "/@/api/flow/flow";
import { flowNameOptions } from "/@/hooks/enums";
import {addTemplate} from "/@/api/common";
import {getPropertyRightsByIdAPI} from "/@/api/workbench/miOwLibr/ownershipCreate";
const formDataRef = ref<HTMLFormElement | null>()
import templateTable from "/@/components/templetTableComom/index.vue"
import {templateStore} from "/@/stores/template"
import {useRouter} from "vue-router";

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

const temp = templateStore()
const router = useRouter()
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: [] as any[],
});

const formData = ref<ProjectTask>({
	id: undefined,
	projectName: '',
	exitRecommendation: '',
	executionTask: '',
	taskDescription: '',
	executor: '',
	taskStartDate: new Date().toISOString().substring(0, 10),
	taskEndDate: new Date().toISOString().substring(0, 10),
	deptId: ''
});
const requiredRule = [{ required: true, message: `${t('该字段必填')}` }]
const rules = reactive<FormRules<ProjectTask>>({
	projectName: requiredRule,
	exitRecommendation: requiredRule
})
const submitLoading = ref<boolean>(false);
const handleInitiateApproval = async () => {
	try {
		const headerValid = await headerFormRef.value?.validate().catch(() => false);
		if (!headerValid) {
			return;
		}
		const valid = await formDataRef?.value?.validateRef();
		if (!valid) return;
		submitLoading.value = true;
		const folowIdKey = 'VITE_FLOWID_35'
		const attachments = JSON.stringify(headerForm.attachments);
		const flowResult = await flowFn(folowIdKey, {
			paramMap: {
				// miu0ilc1tfa61_assignee_select: [
				// 	{
				// 		"type": "user",
				// 		"id": "1",
				// 		"name": "admin",
				// 		"avatar": "/admin/sys-file/local/2a14ae08150e483c93e12ac8934173e2.png"
				// 	}
				// ]
			}
		})
		if (flowResult instanceof Error) {
			submitLoading.value = false;
			throw flowResult;
		}
		const { processInstanceId } = flowResult;
		const flowNameObj = flowNameOptions.filter(item => item.label === 'exitPlan')[0]
		await addFlowForm({
			title: headerForm.title,
			description: headerForm.description,
			attachments,
			processInstanceId,
			flowType: flowNameObj.value
		})
		formData.value.processInstanceId = processInstanceId;
		addProjectExitPlan(formData.value).then((res: any) => {
			useMessage().success(t('common.success'));
			 router.push('/flow/task/started')
		}).catch((err: any) => {
			useMessage().error(err.msg);
		}).finally(() => {
			submitLoading.value = false;
		});
	} catch (e) {
		console.log(e);
		submitLoading.value = false;
	}

};
const saveLoading = ref<boolean>(false);
const handleSaveDraft = async () => {
	try {
		const headerValid = await headerFormRef.value?.validate().catch(() => false);
		if (!headerValid) {
			return;
		}
		const valid = await formDataRef?.value?.validateRef();
		if (!valid) return;
		saveLoading.value = true;
		const attachments = JSON.stringify(headerForm.attachments);
		const flowNameObj = flowNameOptions.filter(item => item.label === 'exitPlan')[0]
		await addFlowForm({
			title: headerForm.title,
			description: headerForm.description,
			attachments,
			processInstanceId:'',
			flowType: flowNameObj.value
		})
		formData.value.processInstanceId = '';
		Object.assign(formData.value,{status:0,temporaryStorage:{
				businessType:flowNameObj.value,
				title: headerForm.title,
			}})
		addProjectExitPlan(formData.value).then(() => {
			useMessage().success(t('common.success'));
		}).catch((err: any) => {
			useMessage().error(err.msg);
		}).finally(() => {
			saveLoading.value = false;
		});
	} catch (e) {
		console.log(e);
		saveLoading.value = false;
	}

};
const tempId = computed(()=>temp.temp_id)
watch(()=>tempId.value,()=>{
	getProjectExitPlanByTemplateId(tempId.value).then(data => {
		Object.assign(formData, data.data);
	})
})
const handleLoadTemplate = () => {
	const flowNameObj = flowNameOptions.filter(item => item.label === 'exitPlan')[0]
	temp.changeTempShow(true,flowNameObj.value)
};
const saveTemplateLoading = ref<boolean>(false);
const handleSaveTemplate = async () => {
	try {
		const headerValid = await headerFormRef.value?.validate().catch(() => false);
		if (!headerValid) {
			return;
		}
		const valid = await formDataRef?.value?.validateRef();
		if (!valid) return;
		saveTemplateLoading.value = true;
		const attachments = JSON.stringify(headerForm.attachments);
		const flowNameObj = flowNameOptions.filter(item => item.label === 'exitPlan')[0]
		await addFlowForm({
			title: headerForm.title,
			description: headerForm.description,
			attachments,
			processInstanceId:'',
			flowType: flowNameObj.value
		})
		const {data: templateId} = await addTemplate({
			templateName:headerForm.title,
			templateType:flowNameObj.value,
		})
		formData.value.processInstanceId = '';
		Object.assign(formData.value,{status:0,templateId})
		addProjectExitPlan(formData.value).then(() => {
			useMessage().success(t('common.success'));
		}).catch((err: any) => {
			useMessage().error(err.msg);
		}).finally(() => {
			saveTemplateLoading.value = false;
		});
	} catch (e) {
		console.log(e);
		saveTemplateLoading.value = false;
	}

};

const handleViewWorkflow = () => {
	message.info(t('projectExitPlan.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>
