<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 @click="handleInitiateApproval" type="primary" icon="Check" :loading="submitLoading">
							{{ t('cooperationUnit.initiateApproval') }}
						</el-button>
						<el-button @click="handleSaveDraft" icon="Document">
							{{ t('cooperationUnit.saveDraft') }}
						</el-button>
						<el-button @click="handleLoadTemplate" icon="FolderOpened" :loading="templateLoading">
							{{ t('cooperationUnit.loadTemplate') }}
						</el-button>
						<el-button @click="handleSaveTemplate" icon="FolderAdd">
							{{ t('cooperationUnit.saveTemplate') }}
						</el-button>
					</div>
					<div style="margin-left:auto;">
						<el-button @click="handleViewWorkflow" icon="View" :disabled="!singleSelected">
							{{ t('cooperationUnit.viewWorkflow') }}
						</el-button>
					</div>
				</div>
			</el-row>
			<!-- 标题、描述、上传附件（按图示排列） -->
			<el-row class="mb10">
				<el-form :model="headerForm" label-width="60px" class="w-full" :rules="headerRequiredRule" ref="headerFormRef">
					<el-form-item :label="t('cooperationUnit.formTitle')" prop="title">
						<el-input maxlength="255" v-model="headerForm.title" :placeholder="t('cooperationUnit.inputTitleTip')"/>
					</el-form-item>
					<el-form-item :label="t('cooperationUnit.description')" prop="description">
						<el-input v-model="headerForm.description" maxlength="255"
											:placeholder="t('cooperationUnit.inputDescriptionTip')"/>
					</el-form-item>
					<el-form-item :label="t('cooperationUnit.attachments')">
						<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-row>
			<!-- 居中标题 + 基本信息三列（按图示） -->
			<el-row class="mb10 header-summary">
				<div class="title">{{ isUpdate ? t('cooperationUnit.updateTitle') : t('cooperationUnit.title') }}</div>
			</el-row>
			<el-row class="mb10 header-meta">
				<div class="meta-item">{{ t('cooperationUnit.reporterLabel') + displayReporter }}</div>
				<div class="meta-item">{{ t('cooperationUnit.reportingUnitLabel') + displayUnit }}</div>
				<div class="meta-item">{{ t('cooperationUnit.dateLabel') + displayDate }}</div>
<!--				<div class="meta-item">{{ t('cooperationUnit.serialNumber') + '&#45;&#45;' }}</div>-->
			</el-row>

			<!-- 动态明细表（按图示） -->
			<el-row class="mb10">
				<div style="width: 100%; display: flex; gap: 1px;">
					<el-button type="primary" icon="Plus" @click="handleAddRow">
						{{ t('cooperationUnit.add') }}
					</el-button>
					<el-button icon="DocumentCopy" :disabled="selectedRowIndex === -1" @click="handleCopyRow">
						{{ t('cooperationUnit.copy') }}
					</el-button>
					<el-button type="danger" icon="Delete" :disabled="selectedRowIndex === -1" @click="handleDeleteRow">
						{{ t('cooperationUnit.delete') }}
					</el-button>
					<el-button type="danger" icon="Delete" :disabled="headerForm.entities.length === 0"
										 @click="handleDeleteAll">
						{{ t('cooperationUnit.deleteAll') }}
					</el-button>
					<el-button icon="Upload" @click="triggerImport">
						{{ t('cooperationUnit.import') }}
					</el-button>
				</div>
			</el-row>
			<input ref="fileInputRef" type="file" accept=".xlsx,.xls" style="display: none" @change="onImportChange"/>
			<el-table :data="headerForm.entities" border style="width: 100%;" highlight-current-row
								@current-change="handleCurrentChange">
				<el-table-column width="60" fixed>
					<template #default="scope">
						<el-radio v-model="selectedRowIndex" :label="scope.$index"
											@change="handleRowSelect(scope.$index)">&nbsp;
						</el-radio>
					</template>
				</el-table-column>
				<el-table-column type="index" :label="t('cooperationUnit.index')" width="60" fixed/>
				<el-table-column prop="cooperationName" min-width="200">
					<template #header>
						<span class="required-star">*</span>{{ t('cooperationUnit.cooperationName') }}
					</template>
					<template #default="scope">
						<div style="display:flex; gap:6px; align-items:center;">
							<el-input v-model="scope.row.cooperationName" maxlength="255"
												:placeholder="t('cooperationUnit.inputCooperationNameTip')">
							</el-input>
							<el-button v-if="isUpdate" size="small" icon="OfficeBuilding" @click="openCompanyDialog(scope.$index)">
							</el-button>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="province" min-width="240">
					<template #header>
						<span class="required-star">*</span>{{ t('cooperationUnit.provinceCity') }}
					</template>
					<template #default="scope">
							<el-input v-model="scope.row.areaCode" maxlength="255"
												:placeholder="t('cooperationUnit.inputProvinceCityTip')"/>
						<!-- <ChinaArea v-model="scope.row.areaCode" :type="1"
											 @change="handleAreaChange(scope.$index, $event)"/> -->
					</template>
				</el-table-column>
				<el-table-column prop="cooperationNature" min-width="140">
					<template #header>
						<span class="required-star">*</span>{{
							t('cooperationUnit.cooperationNature')
						}}
					</template>
					<template #default="scope">
						<el-select v-model="scope.row.cooperationNature"
											 :placeholder="t('cooperationUnit.selectCooperationNatureTip')" style="width: 100%">
							<el-option
									v-for="option of cooperationPartnerNatureOptions"
									:key="option.value"
									:label="option.label"
									:value="option.value"
							/>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column prop="cooperationIndustry" min-width="160">
					<template #header>
						<span class="required-star">*</span>{{ t('cooperationUnit.cooperationIndustry') }}
					</template>
					<template #default="scope">
						<el-input v-model="scope.row.cooperationIndustry" maxlength="255"
											:placeholder="t('cooperationUnit.inputCooperationIndustryTip')"/>
					</template>
				</el-table-column>
				<el-table-column prop="proposedBusinessCooperation" min-width="180">
					<template #header>
						<span class="required-star">*</span>{{ t('cooperationUnit.proposedBusinessCooperation') }}
					</template>
					<template #default="scope">
						<el-input v-model="scope.row.proposedBusinessCooperation" maxlength="255"
											:placeholder="t('cooperationUnit.inputProposedBusinessCooperationTip')"/>
					</template>
				</el-table-column>
				<el-table-column prop="cooperationAdvantage" min-width="160">
					<template #header>
						<span class="required-star">*</span>{{ t('cooperationUnit.cooperationAdvantage') }}
					</template>
					<template #default="scope">
						<el-input v-model="scope.row.cooperationAdvantage" maxlength="255"
											:placeholder="t('cooperationUnit.inputCooperationAdvantageTip')"/>
					</template>
				</el-table-column>
				<el-table-column prop="cooperationStatus" min-width="140">
					<template #header>
						<span class="required-star">*</span>{{ t('cooperationUnit.cooperationStatus') }}
					</template>
					<template #default="scope">
						<el-input v-model="scope.row.cooperationStatus" maxlength="255"
											:placeholder="t('cooperationUnit.inputCooperationStatusTip')"/>
					</template>
				</el-table-column>
				<el-table-column prop="startTime" min-width="170">
					<template #header>
						<span class="required-star">*</span>{{ t('cooperationUnit.startTime') }}
					</template>
					<template #default="scope">
						<el-date-picker v-model="scope.row.startTime" type="date" value-format="YYYY-MM-DD"
														:placeholder="t('cooperationUnit.inputStartTimeTip')" style="width: 100%"/>
					</template>
				</el-table-column>
				<el-table-column prop="endTime" min-width="170">
					<template #header>
						<span class="required-star">*</span>{{ t('cooperationUnit.endTime') }}
					</template>
					<template #default="scope">
						<el-date-picker v-model="scope.row.endTime" type="date" value-format="YYYY-MM-DD"
														:placeholder="t('cooperationUnit.inputEndTimeTip')" style="width: 100%"/>
					</template>
				</el-table-column>
				<el-table-column prop="unitAddress" min-width="200">
					<template #header>
						<span class="required-star">*</span>{{ t('cooperationUnit.unitAddress') }}
					</template>
					<template #default="scope">
						<el-input v-model="scope.row.unitAddress" maxlength="255"
											:placeholder="t('cooperationUnit.inputUnitAddressTip')"/>
					</template>
				</el-table-column>
				<el-table-column prop="unitContactPerson" min-width="150">
					<template #header>
						<span class="required-star">*</span>{{ t('cooperationUnit.unitContactPerson') }}
					</template>
					<template #default="scope">
						<el-input v-model="scope.row.unitContactPerson" maxlength="255"
											:placeholder="t('cooperationUnit.inputUnitContactPersonTip')"/>
					</template>
				</el-table-column>
				<el-table-column prop="contactPersonDept" min-width="160">
					<template #header>
						<span class="required-star">*</span>{{ t('cooperationUnit.contactPersonDept') }}
					</template>
					<template #default="scope">
						<el-input v-model="scope.row.contactPersonDept" maxlength="255"
											:placeholder="t('cooperationUnit.inputContactPersonDeptTip')"/>
					</template>
				</el-table-column>
				<el-table-column prop="contactPersonPhone" min-width="160">
					<template #header>
						<span class="required-star">*</span>{{ t('cooperationUnit.contactPersonPhone') }}
					</template>
					<template #default="scope">
						<el-input v-model="scope.row.contactPersonPhone" maxlength="255"
											:placeholder="t('cooperationUnit.inputContactPersonPhoneTip')"/>
					</template>
				</el-table-column>
				<el-table-column prop="potentialCooperation" min-width="180">
					<template #header>
						<span class="required-star">*</span>{{ t('cooperationUnit.potentialCooperation') }}
					</template>
					<template #default="scope">
						<el-input v-model="scope.row.potentialCooperation" maxlength="255"
											:placeholder="t('cooperationUnit.inputPotentialCooperationTip')"/>
					</template>
				</el-table-column>
				<el-table-column prop="businessConnectionCompany" min-width="200">
					<template #header>
						<span class="required-star">*</span>{{ t('cooperationUnit.businessConnectionCompany') }}
					</template>
					<template #default="scope">
						<div style="display:flex; gap:6px; align-items:center;">
							<el-tree-select
									v-model="scope.row.businessConnectionCompany"
									:data="projectMainEntityOptions"
									check-strictly
									node-key="name"
									:props="{
								value: 'name',
								label: 'name',
								children: 'children',
							}"
									:render-after-expand="false"
									@current-change="(e:any) =>handleBusinessConnectionCompanyChange(e, scope.$index)"
							/>
<!--							<el-input v-model="scope.row.businessConnectionCompany"-->
<!--												:placeholder="t('cooperationUnit.selectBusinessConnectionCompanyTip')"/>-->
<!--							<el-button size="small" icon="OfficeBuilding" @click="openCompanyDialog(scope.$index)">-->
<!--							</el-button>-->
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="cooperationController" min-width="160">
					<template #header>
						{{ t('cooperationUnit.actualController') }}
					</template>
					<template #default="scope">
						<el-input v-model="scope.row.cooperationController" maxlength="255"
											:placeholder="t('cooperationUnit.inputActualControllerTip')"/>
					</template>
				</el-table-column>
				<el-table-column prop="shareholdingRatio" min-width="140">
					<template #header>
						{{ t('cooperationUnit.shareholdingRatio') }}
					</template>
					<template #default="scope">
						<el-input v-model="scope.row.shareholdingRatio" maxlength="255"
											:placeholder="t('cooperationUnit.inputShareholdingRatioTip')"/>
					</template>
				</el-table-column>
			</el-table>
			<!-- 选择弹窗组件 -->
			<UnitNameSelectDialog v-model:visible="unitNameDialogVisible" @confirm="onUnitNameSelected"/>
<!--			业务-->
			<SelectCompanyDialog v-model:visible="companyDialogVisible" :options="companyOptions"
													 @confirm="onCompanySelected"/>

		</div>
		<templet-table-comom/>
	</div>
</template>

<script lang="ts" name="bizInvestmentCooperationUnit" setup>
import {reactive, ref, computed, onMounted, watch} from 'vue';
import templetTableComom from '/@/components/templetTableComom/index.vue'
import {
	importCooperationUnitAPI,
	addExternalCooperationUnitAPI,
	updateExternalCooperationUnitAPI,
	viewExternalCooperationUnitAPI, getExternalCooperationUnitsByTemplateId,
} from '/@/api/investment/cooperationUnit';
import UnitNameSelectDialog from '/@/components/investment/UnitNameSelectDialog.vue';
import SelectCompanyDialog from '/@/components/investment/SelectCompanyDialog.vue';
import {useMessage,} from '/@/hooks/message';
import {useI18n} from 'vue-i18n';
import {useUserInfo} from '/@/stores/userInfo';
import {formatDate} from '/@/utils/formatTime';
import {useRoute} from 'vue-router';
import {cooperationPartnerNatureOptions, flowNameOptions} from '/@/hooks/enums'
import {flowFn} from "/@/utils/flowFn";
import {addFlowForm} from '/@/api/flow/flow';
import {getExternalCooperationUnitsUserDeptBelong,addTemplate} from "/@/api/common";
import {templateStore} from "/@/stores/template";
import type {FormInstance, FormRules} from "element-plus";
import { selectTreeCompanyTree} from "/@/api/admin/dept";
const temp = templateStore();
const props = defineProps({
	isUpdate: {
		type: Boolean,
		default: false
	}
})

const {t} = useI18n();
const route = useRoute();
const resolveRouteValue = (value: unknown): string => {
	if (Array.isArray(value)) {
		return (value[0] ?? '') as string;
	}
	return (value as string) ?? '';
};
const routeParams = computed(() => route.params as Record<string, unknown>);
const routeQuery = computed(() => route.query as Record<string, unknown>);
const editId = computed(() => resolveRouteValue(routeParams.value?.id) || resolveRouteValue(routeQuery.value?.id));
const routeMode = computed(() => (resolveRouteValue(routeQuery.value?.mode) || resolveRouteValue(routeParams.value?.mode)).toLowerCase());
const isEditMode = computed(() => Boolean(editId.value) || routeMode.value === 'edit');

// 多选变量
const singleSelected = ref(false);
const submitLoading = ref(false);
const detailLoading = ref(false);
// 顶部基础信息
const headerForm = reactive({
	id: '',
	title: '',
	description: '',
	attachments: [] as any[],
	entities: [] as any[],
});
const headerRequiredRule = ref<FormRules>({
	title: [{ required: true, message: t('该字段必传'), trigger: 'blur' }],
});
const headerFormRef = ref<FormInstance>();
// 头部摘要显示
const userInfoStore = useUserInfo();
const displayReporter = (userInfoStore.userInfos.user?.username || '');
const displayUnit = (userInfoStore.userInfos.user?.deptName || '');
const displayDate = formatDate(new Date(), 'YYYY-mm-dd');
// 明细选择
const selectedRowIndex = ref(-1);
// 导入
const fileInputRef = ref<HTMLInputElement | null>(null);
// 单位名称选择弹窗
const unitNameDialogVisible = ref(false);
const editingUnitNameRowIndex = ref(-1);
const selectedUnitName = ref<string | null>(null);
// 公司选择弹窗
const companyDialogVisible = ref(false);
const editingCompanyRowIndex = ref(-1);
const selectedCompany = ref<string | null>(null);
const companyOptions = ref([
	{label: '公司A', value: 'company_a'},
	{label: '公司B', value: 'company_b'},
	{label: '公司C', value: 'company_c'},
]);

const handleBusinessConnectionCompanyChange = (e:any, index:number) =>{
	headerForm.entities[index].deptId = e.id;
}
/**
 * 顶部按钮事件（按图示）
 */
const toInteger = (val: unknown) => {
	if (val === '' || val === null || val === undefined) return 0;
	const num = parseInt(String(val), 10);
	return Number.isNaN(num) ? 0 : num;
};
const toNumberValue = (val: unknown) => {
	if (val === '' || val === null || val === undefined) return 0;
	const num = Number(val);
	return Number.isNaN(num) ? 0 : num;
};
const toSubmitEntity = (entity: Record<string, any>) => {
	const payload = {...entity};
	// delete payload.areaCode;
	payload.province = toInteger(payload.province);
	payload.city = toInteger(payload.city);
	payload.shareholdingRatio = toNumberValue(payload.shareholdingRatio);
	payload.cooperationStatus = toInteger(payload.cooperationStatus);
	payload.reportingUnit = displayUnit
	return payload;
};

const handleInitiateApproval = async () => {
	const valid = await headerFormRef.value?.validate()
	if (!valid) return
	if (submitLoading.value) return;
	submitLoading.value = true;
	if (!tableListIsInput()) {
		submitLoading.value = false;
		return
	}
	try {
		let flowIdKey;
		const data = await getExternalCooperationUnitsUserDeptBelong()
		if (!props.isUpdate) {
			flowIdKey = 'VITE_FLOWID_9'
		} else {
			if (data.data === 1) {
				flowIdKey = 'VITE_FLOWID_10'
			} else if (data.data === 2) {
				flowIdKey = 'VITE_FLOWID_11'
			} else if (data.data === 3) {
				flowIdKey = 'VITE_FLOWID_12'
			} else {
				flowIdKey = 'VITE_FLOWID_10'
			}
		}
		const {processInstanceId} = await flowFn(flowIdKey, {
			paramMap: {}
		})
		const flowName = props.isUpdate ? 'unitUpdate' : 'unitRegistration'
		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
		})
		const payload = {
			entities: headerForm.entities.map(item => toSubmitEntity(
					{
						...item,
						processInstanceId,
						status:1,
						flowType: flowNameObj.value,
						id:'',
					}))
		};
		await addExternalCooperationUnitAPI(payload);
		useMessage().success('成功');
	} catch (error: any) {
		useMessage().error(error?.msg || error?.message || '操作失败');
	} finally {
		submitLoading.value = false;
	}
};
const handleSaveDraft = async () => {
	const valid = await headerFormRef.value?.validate()
	if (!valid) return
	if (!tableListIsInput()) return;
	const flowName = props.isUpdate ? 'unitUpdate' : 'unitRegistration'
	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
	})
	const payload = {
		entities: headerForm.entities.map(item => toSubmitEntity(
				{
					...item,
					processInstanceId:'',
					status:0,
					flowType: flowNameObj.value,
					id:'',
					temporaryStorage:{
						businessType:flowNameObj.value,
						title:headerForm.title,
					}
				}))
	};
	if (isEditMode.value) {
		await updateExternalCooperationUnitAPI(payload);
	} else {
		await addExternalCooperationUnitAPI(payload);
	}
	useMessage().success('保存代发成功');
}

const tmpId = computed(()=>temp.temp_id);
const templateLoading = ref(false);
const handleLoadTemplate = () => {
	// useMessage().info('调用模板功能待实现');
	const flowName = props.isUpdate ? 'unitUpdate' : 'unitRegistration'
	const flowNameObj = flowNameOptions.filter(item => item.label === flowName)[0]
	temp.changeTempShow(true, flowNameObj.value);
}
watch(()=> tmpId.value,()=>{
	getExternalCooperationUnitsByTemplateId(tmpId.value).then(res=>{
		headerForm.entities = res.data
	})
})
const handleSaveTemplate = async () => {
	const valid = await headerFormRef.value?.validate()
	if (!valid) return
	if (templateLoading.value) return;
	if (!tableListIsInput()) return;
	templateLoading.value = true;
	const flowName = props.isUpdate ? 'unitUpdate' : 'unitRegistration'
	const flowNameObj = flowNameOptions.filter(item => item.label === flowName)[0]
	const {data: tmpId} = await addTemplate({templateName:headerForm.title,templateType:flowNameObj.value})
	const payload = {
		entities: headerForm.entities.map(item => toSubmitEntity(
				{
					...item,
					status:0,
					flowType: flowNameObj.value,
					templateId:tmpId,
				}))
	};
	try {
		await addExternalCooperationUnitAPI(payload);
		useMessage().success( '成功');
	}catch (error: any) {
		useMessage().error(error?.msg || error?.message || '操作失败');
	}finally {
		templateLoading.value = false;
	}
}
const handleViewWorkflow = () => {
	if (!singleSelected.value) return;
	useMessage().info('查看流程功能待实现');
}

const createEmptyEntity = () => ({
	// id: 0,
	cooperationName: '',
	province: 0,
	city: 0,
	areaCode: '',
	cooperationNature: '',
	cooperationIndustry: '',
	proposedBusinessCooperation: '',
	cooperationAdvantage: '',
	cooperationStatus: 0,
	startTime: '',
	endTime: '',
	unitAddress: '',
	unitContactPerson: '',
	contactPersonDept: '',
	contactPersonPhone: '',
	potentialCooperation: '',
	businessConnectionCompany: '',
	shareholdingRatio: 0,
	createBy: '',
	createTime: '',
	updateBy: '',
	updateTime: '',
	delFlag: '',
	processInstanceId: '',
	status: '',
	cooperationController: '',
	reportingUnit:displayUnit,
	deptId:''
});
const normalizeEntity = (entity: Record<string, any> = {}) => {
	const base = createEmptyEntity();
	Object.assign(base, entity);
	// const areaSegments = base.areaCode ? base.areaCode.split(',') : [];
	// const provinceCode = base.province || areaSegments[0] || 0;
	// const cityCode = base.city || areaSegments[1] || 0;
	// base.province = toInteger(provinceCode);
	// base.city = toInteger(cityCode);
	// base.areaCode = [base.province, base.city, areaSegments[2], areaSegments[3]].filter((val) => val !== '' && val !== undefined && val !== null && val !== 0).join(',');
	return base;
};

// 动态表格操作
const handleAddRow = () => {
	headerForm.entities.push(createEmptyEntity());
	selectedRowIndex.value = headerForm.entities.length - 1;
};
const handleCopyRow = () => {
	if (selectedRowIndex.value === -1) return;
	const row = headerForm.entities[selectedRowIndex.value];
	headerForm.entities.push({...row});
	selectedRowIndex.value = headerForm.entities.length - 1;
};
const handleDeleteRow = () => {
	if (selectedRowIndex.value === -1) return;
	headerForm.entities.splice(selectedRowIndex.value, 1);
	selectedRowIndex.value = -1;
};
const handleDeleteAll = () => {
	headerForm.entities = [];
	selectedRowIndex.value = -1;
};
const handleRowSelect = (index: number) => {
	selectedRowIndex.value = index;
};
const handleCurrentChange = (current: any) => {
	if (!current) return;
	selectedRowIndex.value = headerForm.entities.indexOf(current);
};

const handleAreaChange = (index: number, value?: string) => {
	if (index < 0) return;
	const target = headerForm.entities[index];
	const segments = (value || '').split(',');
	const provinceCode = segments[0] ?? 0;
	const cityCode = segments[1] ?? 0;
	target.province = toInteger(provinceCode);
	target.city = toInteger(cityCode);
	target.areaCode = value;
};

// 导入处理
const triggerImport = () => {
	fileInputRef.value && (fileInputRef.value as HTMLInputElement).click();
};
const onImportChange = async (e: Event) => {
	const target = e.target as HTMLInputElement;
	const file = (target.files && target.files[0]) as File;
	if (!file) return;
	try {
		await importCooperationUnitAPI(file);
		useMessage().success(t('common.operatingOkText') || '导入成功');
	} catch (err: any) {
		useMessage().error(err.msg || '导入失败');
	} finally {
		target.value = '';
	}
};

// 业务公司弹窗
const openUnitNameDialog = (rowIndex: number) => {
	editingUnitNameRowIndex.value = rowIndex;
	selectedUnitName.value = headerForm.entities[rowIndex]?.cooperationName || null;
	unitNameDialogVisible.value = true;
};
const onUnitNameSelected = (row: any) => {
	if (editingUnitNameRowIndex.value === -1) return;
	const target = headerForm.entities[editingUnitNameRowIndex.value];
	// 基础字段自动回填（存在则覆盖）
	target.cooperationName = row?.cooperationName ?? target.cooperationName;
	target.province = row?.province ?? row?.provinceCode ?? target.province;
	target.city = row?.city ?? row?.cityCode ?? target.city;
	// target.areaCode = [target.province, target.city].filter(Boolean).join(',');
	// 单位类型映射到“合作方性质”
	if (row?.unitType && !target.cooperationNature) target.cooperationNature = row.unitType;
	target.cooperationIndustry =
			row?.cooperationIndustry ?? row?.industryField ?? target.cooperationIndustry;
	target.proposedBusinessCooperation =
			row?.proposedBusinessCooperation ?? row?.cooperationBusiness ?? target.proposedBusinessCooperation;
	target.cooperationAdvantage = row?.cooperationAdvantage ?? target.cooperationAdvantage;
	target.cooperationStatus = row?.cooperationStatus ?? target.cooperationStatus;
	target.startTime = row?.startTime ?? row?.cooperationStartTime ?? target.startTime;
	target.endTime = row?.endTime ?? row?.cooperationEndTime ?? target.endTime;
	// 非必需：若需要也可在此扩展更多字段映射
};
const openCompanyDialog = (rowIndex: number) => {
	editingCompanyRowIndex.value = rowIndex;
	selectedCompany.value = headerForm.entities[rowIndex]?.businessConnectionCompany || null;
	companyDialogVisible.value = true;
};
const onCompanySelected = (row: any) => {
	if (editingCompanyRowIndex.value === -1) return;
	const target = headerForm.entities[editingCompanyRowIndex.value];

	// 保留原始的行索引相关属性，只更新从选择对话框传入的数据
	Object.assign(target, {
		...row,
		id: target.id, // 保持原ID不变
		shareholdingRatio: row?.shareholdingRatio ?? target.shareholdingRatio,
		parentId: row?.id || undefined
	});
};

const applyDetail = (detail: Record<string, any>) => {
	headerForm.id = detail?.id ?? '';
	headerForm.title = detail?.title ?? '';
	headerForm.description = detail?.description ?? '';
	headerForm.attachments = detail?.attachments ?? [];
	const list = detail?.entities ?? detail?.cooperationUnits ?? [];
	const normalizedList = Array.isArray(list) && list.length ? list.map((item: any) => normalizeEntity(item)) : [createEmptyEntity()];
	headerForm.entities = normalizedList;
};

const loadDetail = async () => {
	if (!editId.value) return;
	detailLoading.value = true;
	try {
		const res = await viewExternalCooperationUnitAPI(editId.value);
		const detail = res?.data ?? res;
		applyDetail(detail);
	} catch (error: any) {
		useMessage().error(error?.msg || error?.message || '获取详情失败');
	} finally {
		detailLoading.value = false;
	}
};
function tableListIsInput(){
	if (!headerForm.entities.length) {
		useMessage().warning('合作方数量至少为1');
		return false;
	}
	for (let i = 0; i < headerForm.entities.length; i++) {
		if (headerForm.entities[i].cooperationName === ''){
			useMessage().warning('合作名称必填');
			return false
		}
		if (headerForm.entities[i].areaCode === ''){
			useMessage().warning('所属省市必填');
			return false
		}
		if (headerForm.entities[i].cooperationNature === ''){
			useMessage().warning('合作性质必填');
			return false
		}
		if (headerForm.entities[i].cooperationIndustry === ''){
			useMessage().warning('所属行业必填');
			return false
		}
		if (headerForm.entities[i].proposedBusinessCooperation === ''){
			useMessage().warning('（拟）合作业务必填');
			return false
		}
		if (headerForm.entities[i].cooperationAdvantage === ''){
			useMessage().warning('合作优势必填');
			return false
		}
		if (headerForm.entities[i].cooperationStatus === ''){
			useMessage().warning('合作状态必填');
			return false
		}
		if (headerForm.entities[i].startTime === ''){
			useMessage().warning('合作开始时间必填');
			return false
		}
		if (headerForm.entities[i].endTime === ''){
			useMessage().warning('合作结束时间必填');
			return false
		}
		if (headerForm.entities[i].unitAddress === ''){
			useMessage().warning('单位地址必填');
			return false
		}
		if (headerForm.entities[i].unitContactPerson === ''){
			useMessage().warning('单位联系人必填');
			return false
		}
		if (headerForm.entities[i].contactPersonDept === ''){
			useMessage().warning('单位联系人部门必填');
			return false
		}
		if (headerForm.entities[i].contactPersonPhone === ''){
			useMessage().warning('单位联系人手机必填');
			return false
		}
		if (headerForm.entities[i].potentialCooperation === ''){
			useMessage().warning('潜在机会必填');
			return false
		}
		if (headerForm.entities[i].businessConnectionCompany === ''){
			useMessage().warning('业务对接公司必填');
			return false
		}
	}
	return true
}
onMounted(() => {
	if (isEditMode.value && editId.value) {
		loadDetail();
	} else if (!headerForm.entities.length) {
		handleAddRow();
	}
});
const projectMainEntityOptions = ref([]);
const getDeptTree = async () => {
	const res = await selectTreeCompanyTree();
	projectMainEntityOptions.value = res.data?.filter((item:any) => item.id !== '-7283586818552608318');
};
getDeptTree()
watch(editId, (id) => {
	if (id) {
		loadDetail();
	}
});
</script>

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

.header-summary .title {
	margin: 0 auto;
	font-size: 18px;
	font-weight: 600;
}

.header-meta {
	display: flex;
	justify-content: space-between;
	align-items: center;
	width: 50%;
	align-self: center;
}

.header-meta .meta-item {
	color: var(--el-text-color-regular);
}

.required-star {
	color: var(--el-color-danger);
	margin-right: 2px;
}

.red-label {
	color: var(--el-color-danger);
}
</style>

<style scoped>
.form-header-actions {
	display: flex;
	justify-content: space-between;
	align-items: center;
}
</style>
