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

<script setup lang="ts">
import { reactive } 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 } 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";
const formDataRef = ref<HTMLFormElement | null>()
const { t } = useI18n();
const message = useMessage();

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),
});
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 valid =	await formDataRef?.value?.validateRef();
		if (!valid) return;
		submitLoading.value = true;
		const folowIdKey = 'VITE_FLOWID_35'
		const attachments = JSON.stringify(headerForm.attachments);
		const {processInstanceId} = await flowFn(folowIdKey,{
			paramMap:{
				// miu0ilc1tfa61_assignee_select: [
				// 	{
				// 		"type": "user",
				// 		"id": "1",
				// 		"name": "admin",
				// 		"avatar": "/admin/sys-file/local/2a14ae08150e483c93e12ac8934173e2.png"
				// 	}
				// ]
			}
		})
		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'));
		}).catch((err:any) => {
			useMessage().error(err.msg);
		}).finally(() => {
			submitLoading.value = false;
		});
	}catch (e) {
		console.log(e);
		submitLoading.value = false;
	}

};

const handleSaveDraft = () => {
    message.info(t('projectExitPlan.messages.saveDraft'));
};

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

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

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>
