<template>
	<div class="layout-padding mixed-register-page">
		<div class="layout-padding-auto layout-padding-view">
			<el-card shadow="never" class="action-card">
				<div class="form-header-actions">
					<div class="left-buttons">
						<el-button type="primary" icon="Check" @click="handleSubmit" :loading="submitLoading">
							{{ t('mixedRegister.actions.submit') }}
						</el-button>
						<el-button icon="Finished" @click="handleSaveDraft" :loading="saveLoading">
							{{ t('mixedRegister.actions.saveDraft') }}
						</el-button>
						<el-button icon="Document" @click="handleLoadTemplate">
							{{ t('mixedRegister.actions.loadTemplate') }}
						</el-button>
						<el-button icon="FolderAdd" @click="handleSaveTemplate" :loading="saveTemplateLoading">
							{{ t('mixedRegister.actions.saveTemplate') }}
						</el-button>
					</div>
					<el-button icon="View" @click="handleViewWorkflow">
						{{ t('mixedRegister.actions.viewWorkflow') }}
					</el-button>
				</div>
			</el-card>

			<el-card shadow="never" class="header-card">
				<el-form :model="headerForm" label-width="90px" class="header-form" :rules="headerRequiredRule" ref="headerFormRef">
					<el-form-item :label="t('mixedRegister.header.title')" prop="title">
						<el-input maxlength="255" v-model="headerForm.title"
											:placeholder="t('mixedRegister.header.titlePlaceholder')"/>
					</el-form-item>
					<el-form-item :label="t('mixedRegister.header.description')">
						<el-input maxlength="255" v-model="headerForm.description"
											:placeholder="t('mixedRegister.header.descriptionPlaceholder')"/>
					</el-form-item>
					<el-form-item :label="t('mixedRegister.header.attachments')" class="upload-item">
						<UploadFile :modelValue="headerForm.attachments" :fileSize="20" type="simple" :limit="10"
												@change="(url: string, files: any[]) => (headerForm.attachments = files?.map((item: any) => ({ name: item.name, url: item.url })) || [])"/>
					</el-form-item>
				</el-form>
			</el-card>

			<div class="page-title">{{ isUpdate ? t('mixedRegister.updateTitle') : t('mixedRegister.title') }}</div>

			<MixedRegisterSections ref="formRef" :instruction-title="t('mixedRegister.sections.instruction')"
														 :basic-info-title="t('mixedRegister.sections.basic')"
														 :instruction-fields="instructionFields"
														 :instruction-form="instructionForm" :basic-info-fields="basicInfoFields"
														 :basic-info-form="basicInfoForm" :is-update="isUpdate"/>
		</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 {addMixedReformAPI,getMixedReformByTemplateIdAPI, type MixedReformPayload} from '/@/api/investment/mixedReform';
import MixedRegisterSections from '/@/components/investment/mixedReform/MixedRegisterSections.vue';
import templateTable from "/@/components/templetTableComom/index.vue"
import {
	cooperationPartnerNatureOptions,
	flowNameOptions,
	industryChainCategoryOptions,
	mixedCompanyCategoryOptions,
	mixedCompanyFieldOptions,
	mixedCompanyIndustryOptions,
	mixedReformMethodOptions,
	mixedReformTypeOptions, recommended, yesOrNo
} from '/@/hooks/enums'
import {flowFn} from "/@/utils/flowFn";
import {addFlowForm} from '/@/api/flow/flow';
import {addTemplate, getMixedReformUserBelong} from "/@/api/common";
import type {FormInstance, FormRules} from "element-plus";
import {templateStore} from "/@/stores/template";
const temp = templateStore();

const props = defineProps({
	isUpdate: {
		type: Boolean,
		default: false
	}
})

const {t} = useI18n();
const message = useMessage();
const submitLoading = ref(false);
const formRef = ref<any>(null)

const headerForm = reactive({
	title: '',
	description: '',
	attachments: [] as any[],
});
const headerRequiredRule = ref<FormRules>({
	title: [{ required: true, message: t('该字段必传'), trigger: 'blur' }],
});
const headerFormRef = ref<FormInstance>();
const initInstructionForm = {
	reportingUnit: '',
	contactPerson: '',
	contactPhone: '',
}
const instructionForm = reactive({...initInstructionForm});

const initBasicInfoForm = {
	groupBelonging: '',
	projectYear: '',
	projectName: '',
	implementEnterprise: '',
	enterpriseCreditCode: '',
	partnerNature: '',
	partnerName: '',
	progressStatus: '',
	estimatedCompletionTime: '',
	mixedReformMethod: '',
	isIndustryLeader: '',
	mixedReformType: '',
	projectStartTime: '',
	actualCompletionTime: '',
	reformProgress: '',
	mixedCompanyCategory: '',
	mixedCompanyIndustry: '',
	mixedCompanyField: '',
	industryChainCategory: ''
}
const basicInfoForm = reactive({...initBasicInfoForm});

type InstructionFieldKey = keyof typeof instructionForm;
type BasicFieldKey = keyof typeof basicInfoForm;

const instructionFields = computed<Array<{ key: InstructionFieldKey; label: string }>>(() => [
	{key: 'reportingUnit', label: t('mixedRegister.instructionFields.reportUnit')},
	{key: 'contactPerson', label: t('mixedRegister.instructionFields.contact')},
	{key: 'contactPhone', label: t('mixedRegister.instructionFields.contactMethod')},
]);

const basicInfoFields = computed<Array<{ key: BasicFieldKey; label: string }>>(() => [
	{key: 'groupBelonging', label: t('mixedRegister.basicFields.groupName')},
	{key: 'projectYear', label: t('mixedRegister.basicFields.year'),type:'number',length:4},
	{key: 'projectName', label: t('mixedRegister.basicFields.projectName')},
	{key: 'implementEnterprise', label: t('mixedRegister.basicFields.companyFullName')},
	{key: 'enterpriseCreditCode', label: t('mixedRegister.basicFields.creditCode')},
	{
		key: 'partnerNature',
		label: t('mixedRegister.basicFields.partnerNature'),
		type: 'select',
		fieldProps: {options: cooperationPartnerNatureOptions}
	},
	{key: 'partnerName', label: t('mixedRegister.basicFields.partnerName')},
	{key: 'progressStatus', label: t('mixedRegister.basicFields.progressStatus'),type: 'select',fieldProps: {options: recommended}},
	{
		key: 'estimatedCompletionTime',
		label: t('mixedRegister.basicFields.expectedFinishTime'),
		type: 'date',
		fieldProps: {valueFormat: 'YYYY-MM-DD'}
	},
	{
		key: 'mixedReformMethod',
		label: t('mixedRegister.basicFields.mixedMode'),
		type: 'select',
		fieldProps: {options: mixedReformMethodOptions}
	},
	{key: 'isIndustryLeader', label: t('mixedRegister.basicFields.isIndustryBenchmark'),type: 'select',fieldProps: {options: yesOrNo}},
	{
		key: 'mixedReformType',
		label: t('mixedRegister.basicFields.mixedType'),
		type: 'select',
		fieldProps: {options: mixedReformTypeOptions}
	},
	{
		key: 'projectStartTime',
		label: t('mixedRegister.basicFields.projectStartTime'),
		type: 'date',
		fieldProps: {valueFormat: 'YYYY-MM-DD'}
	},
	{
		key: 'actualCompletionTime',
		label: t('mixedRegister.basicFields.completionTime'),
		type: 'date',
		fieldProps: {valueFormat: 'YYYY-MM-DD'}
	},
	{key: 'reformProgress', label: t('mixedRegister.basicFields.reformProgress'), span: 24,type: 'number',length: 20},
	{
		key: 'mixedCompanyCategory',
		label: t('mixedRegister.basicFields.mixedCompanyCategory'),
		type: 'select',
		fieldProps: {options: mixedCompanyCategoryOptions}
	},
	{
		key: 'mixedCompanyIndustry',
		label: t('mixedRegister.basicFields.mixedCompanyIndustry'),
		type: 'select',
		fieldProps: {options: mixedCompanyIndustryOptions, filterable: true}
	},
	{
		key: 'mixedCompanyField',
		label: t('mixedRegister.basicFields.mixedCompanyField'),
		type: 'select',
		fieldProps: {options: mixedCompanyFieldOptions}
	},
	{
		key: 'industryChainCategory',
		label: t('mixedRegister.basicFields.industryChainCategory'),
		type: 'select',
		fieldProps: {options: industryChainCategoryOptions, filterable: true}
	}
]);

const handleSubmit = async () => {
	// 校验表单数据
	const formData = await formRef.value?.validate()
	const valid = await headerFormRef.value?.validate()
	if (!formData && !valid) return
	// 提交
	if (submitLoading.value) return;
	submitLoading.value = true;
	try {
		const data = await getMixedReformUserBelong()
		const isUpdate = props.isUpdate;
		let flowIdKey;
		if (isUpdate) {
			if (data.data === 1) {
				flowIdKey = 'VITE_FLOWID_17'
			} else {
				flowIdKey = 'VITE_FLOWID_18'
			}
		} else {
			if (data.data === 1) {
				flowIdKey = 'VITE_FLOWID_15'
			} else {
				flowIdKey = 'VITE_FLOWID_16'
			}
		}
		const {processInstanceId} = await flowFn(flowIdKey, {
			paramMap: {},
		})
		const flowName = isUpdate ? 'mixedReformUpdate' : 'mixedReformRegistration'
		const flowNameObj = flowNameOptions.filter(item => item.label === flowName)[0]
		await addFlowForm({
			title: headerForm.title,
			description: headerForm.description,
			attachments: JSON.stringify(headerForm.attachments),
			processInstanceId,
			flowType: flowNameObj.value,
		})
		Object.assign(formData, {processInstanceId,status:1})
		await addMixedReformAPI(formData);
		message.success(t('mixedRegister.messages.submitSuccess'));
		// 重置表单
		// Object.assign(instructionForm, {...initInstructionForm})
		// Object.assign(basicInfoForm, {...initBasicInfoForm})
	} catch (error: any) {
		message.error(error?.msg || error?.message || t('common.fail'));
	} finally {
		submitLoading.value = false;
	}
};
const saveLoading = ref(false);
const handleSaveDraft = async () => {
	// 校验表单数据
	const formData = await formRef.value?.validate()
	const valid = await headerFormRef.value?.validate()
	if (!formData && !valid) return
	// 提交
	if (saveLoading.value) return;
	const isUpdate = props.isUpdate;
	saveLoading.value = true;
	try {
		const flowName = isUpdate ? 'mixedReformUpdate' : 'mixedReformRegistration'
		const flowNameObj = flowNameOptions.filter(item => item.label === flowName)[0]
		await addFlowForm({
			title: headerForm.title,
			description: headerForm.description,
			attachments: JSON.stringify(headerForm.attachments),
			processInstanceId:'',
			flowType: flowNameObj.value
		})
		Object.assign(formData, {status:0,temporaryStorage:{
				businessType:flowNameObj.value,
				title:headerForm.title,
			}})
		await addMixedReformAPI(formData);
		message.success(t('mixedRegister.messages.submitSuccess') || '提交成功');
	}catch (error: any){
		message.error(error?.msg || error?.message || t('common.fail') || '提交失败');
	}finally {
		saveLoading.value = false;
	}
};

const tempId = computed(() => temp.temp_id)
const handleLoadTemplate = () => {
	const isUpdate = props.isUpdate;
	const flowName = isUpdate ? 'mixedReformUpdate' : 'mixedReformRegistration'
	const flowNameObj = flowNameOptions.filter(item => item.label === flowName)[0]
	temp.changeTempShow(true,flowNameObj.value)
};
const saveTemplateLoading = ref(false);
const handleSaveTemplate = async () => {
	// addTemplate

	const formData = await formRef.value?.validate()
	const valid = await headerFormRef.value?.validate()
	if (!formData && !valid) return
	if (saveTemplateLoading.value) return;
	saveTemplateLoading.value = true;
	try {
		const isUpdate = props.isUpdate;
		const flowName = isUpdate ? 'mixedReformUpdate' : 'mixedReformRegistration'
		const flowNameObj = flowNameOptions.filter(item => item.label === flowName)[0]
		const {data: templateId}= await addTemplate({templateName:headerForm.title,templateType:flowNameObj.value})
		Object.assign(formData, {status:0,templateId})
		await addMixedReformAPI(formData);
		message.success(t('mixedRegister.messages.submitSuccess'));
	}catch (error: any) {
		message.error(error?.msg || error?.message || t('common.fail'));
	}finally {
		saveTemplateLoading.value = false;
	}
};

const handleViewWorkflow = () => {
	message.info(t('mixedRegister.messages.viewWorkflow'));
};
watch(() => tempId.value,()=>{
	getMixedReformByTemplateIdAPI(tempId.value).then(data => {
		Object.assign(basicInfoForm, data.data);
		Object.assign(instructionForm, {
			reportingUnit: data.data.reportingUnit,
			contactPerson: data.data.contactPerson,
			contactPhone: data.data.contactPhone,
			instruction: data.data.instruction,
		});
	})
})
</script>

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

.mixed-register-page {
	background-color: #f5f7fb;
}

.action-card,
.header-card,
.section-card {
	margin-bottom: 16px;
}

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

.left-buttons {
	display: flex;
	gap: 12px;
}

.page-title {
	text-align: center;
	font-size: 20px;
	font-weight: 600;
	margin-bottom: 12px;
}

.header-form :deep(.upload-item .el-form-item__content) {
	align-items: flex-start;
	flex-direction: column;
	gap: 6px;
}
</style>
