<template>
	<div class="property-common">
		<el-form :model="formData" ref="ruleFormRef" label-width="auto">
			<el-tabs>
				<el-tab-pane label="基本信息">
					<el-row :gutter="35">
						<el-col :span="24" class="mb20">
							<el-form-item label="编号">
								<el-input v-model="nodeData.id" readonly />
							</el-form-item>
						</el-col>
						<el-col :span="24" class="mb20">
							<el-form-item label="类型">
								<el-input v-model="nodeData.type" readonly />
							</el-form-item>
						</el-col>
					</el-row>
				</el-tab-pane>

				<!-- 用户任务节点属性 -->
				<el-tab-pane label="审批配置" v-if="isUserTask">
					<el-row :gutter="35">
						<el-col :span="24" class="mb20">
							<el-form-item label="节点名称">
								<el-input v-model="formData.nodeName" placeholder="请输入节点名称" clearable />
							</el-form-item>
						</el-col>
						<el-col :span="24" class="mb20">
							<el-form-item label="审批人类型">
								<el-select v-model="formData.approverType" placeholder="请选择" clearable>
									<el-option label="指定用户" value="SpecificUser" />
									<el-option label="指定角色" value="Role" />
									<el-option label="指定部门" value="Department" />
									<el-option label="部门负责人" value="DepartmentLeader" />
									<el-option label="发起人本人" value="Initiator" />
								</el-select>
							</el-form-item>
						</el-col>

						<!-- 指定用户：远程搜索多选 -->
						<el-col :span="24" class="mb20" v-if="formData.approverType === 'SpecificUser'">
							<el-form-item label="选择用户">
								<el-select
									v-model="selectedUserIds"
									multiple
									filterable
									remote
									reserve-keyword
									:remote-method="searchUsers"
									:loading="userLoading"
									placeholder="输入姓名或账号搜索"
									style="width: 100%"
									@change="onUserChange"
								>
									<el-option
										v-for="u in userOptions"
										:key="u.id"
										:label="`${u.realName}（${u.account}）`"
										:value="u.id"
									/>
								</el-select>
							</el-form-item>
						</el-col>

						<!-- 指定角色：全量下拉多选 -->
						<el-col :span="24" class="mb20" v-if="formData.approverType === 'Role'">
							<el-form-item label="选择角色">
								<el-select
									v-model="selectedRoleIds"
									multiple
									filterable
									placeholder="请选择角色"
									style="width: 100%"
									@change="onRoleChange"
								>
									<el-option
										v-for="r in roleOptions"
										:key="r.id"
										:label="r.name"
										:value="r.id"
									/>
								</el-select>
							</el-form-item>
						</el-col>

						<!-- 指定部门：树形多选 -->
						<el-col :span="24" class="mb20" v-if="formData.approverType === 'Department'">
							<el-form-item label="选择部门">
								<el-tree-select
									v-model="selectedOrgIds"
									:data="orgTreeData"
									multiple
									filterable
									check-strictly
									:render-after-expand="false"
									:props="{ label: 'name', value: 'id', children: 'children' }"
									placeholder="请选择部门"
									style="width: 100%"
									@change="onOrgChange"
								/>
							</el-form-item>
						</el-col>

						<!-- 只读回显已选 -->
						<el-col :span="24" class="mb20" v-if="formData.approverType && formData.approverType !== 'Initiator' && formData.approverNames">
							<el-form-item label="已选">
								<el-tag v-for="name in formData.approverNames.split(',')" :key="name" size="small" style="margin-right: 4px">{{ name }}</el-tag>
							</el-form-item>
						</el-col>

						<el-col :span="24" class="mb20">
							<el-form-item label="审批方式">
								<el-select v-model="formData.multiApproveMode" placeholder="请选择" clearable>
									<el-option label="或签（一人通过即可）" value="Any" />
									<el-option label="会签（所有人通过）" value="All" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="24" class="mb20">
							<el-form-item label="超时(小时)">
								<el-input-number v-model="formData.timeoutHours" :min="0" :max="720" controls-position="right" />
							</el-form-item>
						</el-col>
						<el-col :span="24" class="mb20" v-if="formData.timeoutHours">
							<el-form-item label="超时动作">
								<el-select v-model="formData.timeoutAction" placeholder="请选择">
									<el-option label="自动通知" value="Notify" />
									<el-option label="自动通过" value="AutoApprove" />
									<el-option label="自动拒绝" value="AutoReject" />
									<el-option label="自动升级" value="AutoEscalate" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="24" class="mb20">
							<el-form-item label="允许手动升级">
								<el-switch v-model="formData.enableManualEscalation" />
							</el-form-item>
						</el-col>

						<!-- 升级目标配置 -->
						<template v-if="needEscalationConfig">
							<el-col :span="24"><el-divider content-position="left">升级目标配置</el-divider></el-col>
							<el-col :span="24" class="mb20">
								<el-form-item label="升级目标类型">
									<el-select v-model="formData.escalationApproverType" placeholder="请选择" clearable @change="onEscalationTypeChange">
										<el-option label="指定用户" value="SpecificUser" />
										<el-option label="指定角色" value="Role" />
										<el-option label="指定部门" value="Department" />
										<el-option label="部门负责人" value="DepartmentLeader" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="24" class="mb20" v-if="formData.escalationApproverType === 'SpecificUser'">
								<el-form-item label="升级目标用户">
									<el-select
										v-model="escSelectedUserIds"
										multiple filterable remote reserve-keyword
										:remote-method="searchUsers"
										:loading="userLoading"
										placeholder="输入姓名或账号搜索"
										style="width: 100%"
										@change="onEscUserChange"
									>
										<el-option v-for="u in userOptions" :key="u.id" :label="`${u.realName}（${u.account}）`" :value="u.id" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="24" class="mb20" v-if="formData.escalationApproverType === 'Role'">
								<el-form-item label="升级目标角色">
									<el-select v-model="escSelectedRoleIds" multiple filterable placeholder="请选择角色" style="width: 100%" @change="onEscRoleChange">
										<el-option v-for="r in roleOptions" :key="r.id" :label="r.name" :value="r.id" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="24" class="mb20" v-if="formData.escalationApproverType === 'Department'">
								<el-form-item label="升级目标部门">
									<el-tree-select
										v-model="escSelectedOrgIds"
										:data="orgTreeData" multiple filterable check-strictly :render-after-expand="false"
										:props="{ label: 'name', value: 'id', children: 'children' }"
										placeholder="请选择部门" style="width: 100%" @change="onEscOrgChange"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="24" class="mb20" v-if="formData.escalationApproverNames">
								<el-form-item label="已选升级目标">
									<el-tag v-for="name in formData.escalationApproverNames.split(',')" :key="name" size="small" type="warning" style="margin-right: 4px">{{ name }}</el-tag>
								</el-form-item>
							</el-col>
						</template>
					</el-row>
					<el-row>
						<el-col :span="24" style="text-align: right">
							<el-button type="primary" @click="saveProperties">保存到节点</el-button>
						</el-col>
					</el-row>
				</el-tab-pane>

				<!-- 并行网关说明（无可配置项） -->
				<el-tab-pane label="并行网关" v-if="isParallelGateway">
					<el-alert type="info" :closable="false" show-icon>
						<template #title>并行网关（Parallel Gateway）</template>
						<div style="margin-top: 6px; line-height: 1.6">
							<p style="margin: 0">• <strong>分叉（Fork）</strong>：1 条入边 + ≥2 条出边，到达后同时开启所有后续分支。</p>
							<p style="margin: 0">• <strong>汇合（Join）</strong>：≥2 条入边 + 1 条出边，等待所有前驱分支完成后再继续。</p>
							<p style="margin: 0">• 任一分支被驳回将终止整个流程实例。</p>
							<p style="margin: 0">• 本节点无可配置参数，由图的拓扑结构决定行为。</p>
						</div>
					</el-alert>
				</el-tab-pane>

				<!-- 网关节点属性 -->
				<el-tab-pane label="条件分支" v-if="isGateway">
					<div v-for="(cond, idx) in formData.conditions" :key="idx" style="margin-bottom: 16px; padding: 12px; border: 1px solid #eee; border-radius: 4px">
						<el-row :gutter="12">
							<el-col :span="22">
								<el-form-item :label="'分支 ' + (idx + 1) + ' 目标节点'">
									<el-input v-model="cond.targetNodeId" placeholder="目标节点 Id" clearable />
								</el-form-item>
								<el-form-item label="条件表达式">
									<el-input v-model="cond.expression" placeholder="如 bizData.amount > 100000" clearable />
								</el-form-item>
								<el-form-item label="描述">
									<el-input v-model="cond.label" placeholder="条件描述" clearable />
								</el-form-item>
								<el-checkbox v-model="cond.isDefault">默认分支</el-checkbox>
							</el-col>
							<el-col :span="2" style="display: flex; align-items: center">
								<el-button type="danger" icon="ele-Delete" circle size="small" @click="formData.conditions.splice(idx, 1)" />
							</el-col>
						</el-row>
					</div>
					<el-button type="primary" plain @click="addCondition" style="margin-bottom: 12px">+ 添加分支</el-button>
					<el-row>
						<el-col :span="24" style="text-align: right">
							<el-button type="primary" @click="saveProperties">保存到节点</el-button>
						</el-col>
					</el-row>
				</el-tab-pane>
			</el-tabs>
		</el-form>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, watch } from 'vue';
import { getAPI } from '/@/utils/axios-utils';
import { SysUserApi, SysRoleApi, SysOrgApi } from '/@/api-services/api';

const props = defineProps({
	nodeData: { type: Object, default: () => ({}) },
});
const emit = defineEmits(['setProperties']);

const ruleFormRef = ref();

const isUserTask = computed(() => {
	const t = props.nodeData?.type;
	return t === 'bpmn:userTask' || t === 'user-node' || t === 'task-node';
});

const isGateway = computed(() => {
	const t = props.nodeData?.type;
	return t === 'bpmn:exclusiveGateway';
});

const isParallelGateway = computed(() => {
	const t = props.nodeData?.type;
	return t === 'bpmn:parallelGateway';
});

// ── 用户搜索 ──
const userLoading = ref(false);
const userOptions = ref<Array<{ id: number; account: string; realName: string }>>([]);
const selectedUserIds = ref<number[]>([]);

const searchUsers = async (query: string) => {
	if (!query) return;
	userLoading.value = true;
	try {
		const res = await getAPI(SysUserApi).apiSysUserPagePost({ page: 1, pageSize: 20, realName: query } as any);
		const items = res.data.result?.items ?? [];
		const existing = userOptions.value.filter((o) => selectedUserIds.value.includes(o.id));
		const merged = [...existing];
		for (const u of items) {
			if (u.id && !merged.some((m) => m.id === u.id)) {
				merged.push({ id: u.id, account: u.account ?? '', realName: u.realName ?? '' });
			}
		}
		userOptions.value = merged;
	} finally {
		userLoading.value = false;
	}
};

const onUserChange = () => {
	const selected = userOptions.value.filter((o) => selectedUserIds.value.includes(o.id));
	formData.approverIds = selected.map((s) => s.id).join(',');
	formData.approverNames = selected.map((s) => s.realName || s.account).join(',');
};

// ── 角色列表 ──
const roleOptions = ref<Array<{ id: number; name: string }>>([]);
const selectedRoleIds = ref<number[]>([]);
let roleLoaded = false;

const loadRoles = async () => {
	if (roleLoaded) return;
	const res = await getAPI(SysRoleApi).apiSysRoleListGet();
	roleOptions.value = (res.data.result ?? []).map((r: any) => ({ id: r.id, name: r.name ?? '' }));
	roleLoaded = true;
};

const onRoleChange = () => {
	const selected = roleOptions.value.filter((o) => selectedRoleIds.value.includes(o.id));
	formData.approverIds = selected.map((s) => s.id).join(',');
	formData.approverNames = selected.map((s) => s.name).join(',');
};

// ── 部门树 ──
const orgTreeData = ref<any[]>([]);
const selectedOrgIds = ref<number[]>([]);
let orgLoaded = false;

const loadOrgs = async () => {
	if (orgLoaded) return;
	const res = await getAPI(SysOrgApi).apiSysOrgTreeGet(0);
	orgTreeData.value = res.data.result ?? [];
	orgLoaded = true;
};

const flattenOrg = (nodes: any[]): Array<{ id: number; name: string }> => {
	const result: Array<{ id: number; name: string }> = [];
	for (const n of nodes) {
		result.push({ id: n.id, name: n.name ?? '' });
		if (n.children?.length) result.push(...flattenOrg(n.children));
	}
	return result;
};

const onOrgChange = () => {
	const flat = flattenOrg(orgTreeData.value);
	const selected = flat.filter((o) => selectedOrgIds.value.includes(o.id));
	formData.approverIds = selected.map((s) => s.id).join(',');
	formData.approverNames = selected.map((s) => s.name).join(',');
};

// ── 升级目标选择状态 ──
const escSelectedUserIds = ref<number[]>([]);
const escSelectedRoleIds = ref<number[]>([]);
const escSelectedOrgIds = ref<number[]>([]);

const needEscalationConfig = computed(() =>
	formData.timeoutAction === 'AutoEscalate' || formData.enableManualEscalation,
);

const onEscalationTypeChange = () => {
	formData.escalationApproverIds = '';
	formData.escalationApproverNames = '';
	escSelectedUserIds.value = [];
	escSelectedRoleIds.value = [];
	escSelectedOrgIds.value = [];
	if (formData.escalationApproverType === 'Role') loadRoles();
	if (formData.escalationApproverType === 'Department') loadOrgs();
};

const onEscUserChange = () => {
	const selected = userOptions.value.filter((o) => escSelectedUserIds.value.includes(o.id));
	formData.escalationApproverIds = selected.map((s) => s.id).join(',');
	formData.escalationApproverNames = selected.map((s) => s.realName || s.account).join(',');
};

const onEscRoleChange = () => {
	const selected = roleOptions.value.filter((o) => escSelectedRoleIds.value.includes(o.id));
	formData.escalationApproverIds = selected.map((s) => s.id).join(',');
	formData.escalationApproverNames = selected.map((s) => s.name).join(',');
};

const onEscOrgChange = () => {
	const flat = flattenOrg(orgTreeData.value);
	const selected = flat.filter((o) => escSelectedOrgIds.value.includes(o.id));
	formData.escalationApproverIds = selected.map((s) => s.id).join(',');
	formData.escalationApproverNames = selected.map((s) => s.name).join(',');
};

// ── 表单数据 ──
const formData = reactive({
	nodeName: '',
	approverType: '',
	approverIds: '',
	approverNames: '',
	multiApproveMode: 'Any',
	timeoutHours: undefined as number | undefined,
	timeoutAction: 'Notify',
	enableManualEscalation: false,
	escalationApproverType: '',
	escalationApproverIds: '',
	escalationApproverNames: '',
	conditions: [] as Array<{ targetNodeId: string; expression: string; label: string; isDefault: boolean }>,
});

// 审批人类型切换时清空已选
watch(
	() => formData.approverType,
	(newType, oldType) => {
		if (oldType && newType !== oldType) {
			formData.approverIds = '';
			formData.approverNames = '';
			selectedUserIds.value = [];
			selectedRoleIds.value = [];
			selectedOrgIds.value = [];
		}
		if (newType === 'Role') loadRoles();
		if (newType === 'Department') loadOrgs();
	}
);

// 节点数据变化时回显
const restoreSelection = async () => {
	const ids = formData.approverIds ? formData.approverIds.split(',').map(Number).filter(Boolean) : [];
	const names = formData.approverNames ? formData.approverNames.split(',') : [];

	if (formData.approverType === 'SpecificUser' && ids.length) {
		userOptions.value = ids.map((id, i) => ({ id, account: '', realName: names[i] || String(id) }));
		selectedUserIds.value = ids;
	} else if (formData.approverType === 'Role' && ids.length) {
		await loadRoles();
		selectedRoleIds.value = ids;
	} else if (formData.approverType === 'Department' && ids.length) {
		await loadOrgs();
		selectedOrgIds.value = ids;
	}
};

const restoreEscalationSelection = async () => {
	const ids = formData.escalationApproverIds ? formData.escalationApproverIds.split(',').map(Number).filter(Boolean) : [];
	const names = formData.escalationApproverNames ? formData.escalationApproverNames.split(',') : [];

	if (formData.escalationApproverType === 'SpecificUser' && ids.length) {
		for (const [i, id] of ids.entries()) {
			if (!userOptions.value.some((o) => o.id === id)) {
				userOptions.value.push({ id, account: '', realName: names[i] || String(id) });
			}
		}
		escSelectedUserIds.value = ids;
	} else if (formData.escalationApproverType === 'Role' && ids.length) {
		await loadRoles();
		escSelectedRoleIds.value = ids;
	} else if (formData.escalationApproverType === 'Department' && ids.length) {
		await loadOrgs();
		escSelectedOrgIds.value = ids;
	}
};

watch(
	() => props.nodeData,
	(val) => {
		if (!val?.properties) return;
		const p = val.properties;
		formData.nodeName = p.nodeName || '';
		formData.approverType = p.approverType || '';
		formData.approverIds = p.approverIds || '';
		formData.approverNames = p.approverNames || '';
		formData.multiApproveMode = p.multiApproveMode || 'Any';
		formData.timeoutHours = p.timeoutHours;
		formData.timeoutAction = p.timeoutAction || 'Notify';
		formData.enableManualEscalation = !!p.enableManualEscalation;
		formData.escalationApproverType = p.escalationApproverType || '';
		formData.escalationApproverIds = p.escalationApproverIds || '';
		formData.escalationApproverNames = p.escalationApproverNames || '';
		formData.conditions = Array.isArray(p.conditions) ? [...p.conditions] : [];
		restoreSelection();
		restoreEscalationSelection();
	},
	{ immediate: true, deep: true }
);

const addCondition = () => {
	formData.conditions.push({ targetNodeId: '', expression: '', label: '', isDefault: false });
};

const saveProperties = () => {
	const data: Record<string, any> = {};
	if (isUserTask.value) {
		data.nodeName = formData.nodeName;
		data.approverType = formData.approverType;
		data.approverIds = formData.approverIds;
		data.approverNames = formData.approverNames;
		data.multiApproveMode = formData.multiApproveMode;
		if (formData.timeoutHours) {
			data.timeoutHours = formData.timeoutHours;
			data.timeoutAction = formData.timeoutAction;
		}
		data.enableManualEscalation = formData.enableManualEscalation;
		if (formData.enableManualEscalation || formData.timeoutAction === 'AutoEscalate') {
			data.escalationApproverType = formData.escalationApproverType;
			data.escalationApproverIds = formData.escalationApproverIds;
			data.escalationApproverNames = formData.escalationApproverNames;
		}
	}
	if (isGateway.value) {
		data.conditions = formData.conditions;
	}
	emit('setProperties', data);
};
</script>

<style lang="scss" scoped></style>
