<template>
	<div class="form">
		<el-form :model="form" label-width="130px" ref="ruleFormRef">
			<el-form-item label="节点名称" prop="name" :rules="[{ required: true, message: '请填写节点名称', trigger: 'blur' }]">
				<el-input v-model="form.name" placeholder="请填写节点名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="节点编码" prop="stepType" :rules="[{ required: true, message: '请填写节点编码', trigger: 'blur' }]">
				<el-input v-model="form.code" disabled placeholder="请填写节点编码" clearable></el-input>
			</el-form-item>
			<el-form-item label="节点类型" prop="stepTypeName" :rules="[{ required: true, message: '请选择节点类型', trigger: 'change' }]">
				<el-input v-model="form.stepTypeName" disabled></el-input>
			</el-form-item>
			<el-form-item label="业务类型" prop="businessType" :rules="[{ required: true, message: '请选择业务类型', trigger: 'change' }]">
				<el-select v-model="form.businessType" class="w100" placeholder="请选择业务类型">
					<el-option v-for="item in baseData.businessTypeOptions" :key="item.key" :label="item.value" :value="item.key" />
				</el-select>
			</el-form-item>
			<el-form-item label="办理者类型" prop="handlerType" :rules="[{ required: true, message: '请选择办理者类型', trigger: 'change' }]">
				<el-select v-model="form.handlerType" class="w100" placeholder="请选择办理者类型" @change="changeOptions">
					<el-option v-for="item in baseData.handlerTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
			<!-- 选择其他 -->
			<el-form-item
				v-if="[0, 1, 2].includes(form.handlerType)"
				:label="itemName"
				prop="handlerTypeItemsOrigin"
				:rules="[{ required: true, message: `请选择${itemName}`, trigger: 'change' }]"
			>
				<el-select
					v-model="form.handlerTypeItemsOrigin"
					multiple
					filterable
					class="w100"
					@change="getSelectValue"
					value-key="key"
					collapse-tags
					collapse-tags-tooltip
				>
					<el-option v-for="item in selectList" :key="item.key" :label="item.value" :value="item" />
				</el-select>
			</el-form-item>
			<!-- 选择用户 -->
			<el-form-item
				v-if="[3].includes(form.handlerType)"
				:label="itemName"
				prop="handlerTypeItemsOrigin"
				:rules="[{ required: true, message: `请选择${itemName}`, trigger: 'change' }]"
			>
				<el-select
					v-model="form.handlerTypeItemsOrigin"
					multiple
					filterable
					remote
					class="w100"
					reserve-keyword
					placeholder="请填写用户名称"
					remote-show-suffix
					:remote-method="remoteMethod"
					:loading="loading"
					@change="getSelectValue"
					value-key="id"
					collapse-tags
					collapse-tags-tooltip
				>
					<el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item" />
				</el-select>
			</el-form-item>
			<!-- 部门 -->
			<el-form-item
				v-if="[4].includes(form.handlerType)"
				:label="itemName"
				prop="handlerTypeItemsOrigin"
				:rules="[{ required: true, message: `请选择${itemName}`, trigger: 'change' }]"
			>
				<VTreeDrop
					:data="orgData"
					checkable
					keyField="id"
					titleField="name"
					v-model="form.handlerTypeItemsOrigin"
					@checked-change="selectOrg1"
					dropPlaceholder="指定部门"
					dropdownWidthFixed
					clearable
					searchPlaceholder="指定部门名称"
					checkedButtonText="查看已选"
					:cascade="false"
				/>

<!--				<el-tree-select
					:props="{ label: 'name' }"
					node-key="id"
					class="w100"
					ref="treeSelectRef"
					v-model="form.handlerTypeItemsOrigin"
					:data="orgData"
					multiple
					:render-after-expand="false"
					show-checkbox
					check-strictly
					default-expand-all
					filterable
					@check="selectOrg"
					collapse-tags
					collapse-tags-tooltip
				/>-->
			</el-form-item>
			<el-form-item label="否决按钮" prop="canReject">
				<el-switch v-model="form.canReject" inline-prompt active-text="启用" inactive-text="禁用" />
			</el-form-item>
			<el-form-item label="执行模式" prop="executeMode" :rules="[{ required: true, message: '请选择执行模式', trigger: 'change' }]">
				<el-select v-model="form.executeMode" class="w100" placeholder="请选择执行模式">
					<el-option v-for="item in baseData.executeModeOptions" :key="item.key" :label="item.value" :value="item.key" />
				</el-select>
			</el-form-item>
			<el-form-item label="支持会签" prop="canStartCountersign">
				<el-switch v-model="form.canStartCountersign" inline-prompt active-text="支持" inactive-text="不支持" />
			</el-form-item>
			<el-form-item
				label="会签策略"
				prop="countersignPolicy"
				:rules="[{ required: true, message: '请选择会签策略', trigger: 'change' }]"
				v-if="form.canStartCountersign"
			>
				<el-select v-model="form.countersignPolicy" class="w100" placeholder="请选择会签策略">
					<el-option v-for="item in baseData.dynamicPolicyOptions" :key="item.key" :label="item.value" :value="item.key" />
				</el-select>
			</el-form-item>
			<el-form-item label="实例化模式" prop="instanceMode" :rules="[{ required: true, message: '请选择实例化模式', trigger: 'change' }]">
				<el-select v-model="form.instanceMode" class="w100" placeholder="请选择实例化模式">
					<el-option v-for="item in baseData.instanceModeOptions" :key="item.key" :label="item.value" :value="item.key" />
				</el-select>
			</el-form-item>
			<el-form-item
				label="动态策略"
				prop="instancePolicy"
				:rules="[{ required: true, message: '请选择动态策略', trigger: 'change' }]"
				v-if="form.instanceMode === 1"
			>
				<el-select v-model="form.instancePolicy" class="w100" placeholder="请选择动态策略" @change="selectInstancePolicy">
					<el-option v-for="item in baseData.dynamicPolicyOptions" :key="item.key" :label="item.value" :value="item.key" />
				</el-select>
			</el-form-item>
			<el-form-item
				label="动态终止标识"
				prop="terminalDynamicMark"
				:rules="[{ required: true, message: '请选择动态终止标识', trigger: 'change' }]"
				v-if="form.instanceMode === 1"
			>
				<el-select v-model="form.terminalDynamicMark" class="w100" placeholder="请选择动态终止标识">
					<el-option v-for="item in baseData.dynamicStrategyOptions" :key="item.key" :label="item.value" :value="item.key" />
				</el-select>
			</el-form-item>
			<el-form-item label="标识" prop="tag" :rules="[{ required: false, message: '请填写标识', trigger: 'blur' }]">
				<el-input v-model="form.tag" placeholder="请填写标识" type="textarea" :autosize="{ minRows: 4, maxRows: 8 }"></el-input>
			</el-form-item>
		</el-form>
	</div>
</template>
<script lang="ts" setup name="flowNodeEnd">
import { onMounted, reactive, ref, watch } from 'vue';
import { getSelectList, queryUser } from '@/api/system/workflow';
import { getCanUseOrg } from '@/api/system/user';
import { removeDuplicate } from '@/utils/arrayOperation';
import { VTreeDrop } from '@wsfe/vue-tree';

// 定义属性
const props = defineProps({
	modelValue: {
		type: Object,
		default: () => {},
	},
	baseData: {
		type: Object,
		default: () => {},
	},
});
// 注意:ref不能与model一样，相同的话表单双向绑定将会失效
const form = reactive<Record<string, any>>({
	...props.modelValue, // 传入的数据
	stepTypeName: '结束节点',
	stepType: 2, // 节点类型(开始1 结束2)
	businessType: null, // 业务类型
	handlerType: null, // 办理者类型
	handlerTypeItemsOrigin: [], // 办理者类型
	handlerTypeItems: '[]', // 办理者类型
	canReject: false, // 否决按钮
	executeMode: null, // 执行模式
	canStartCountersign: false, // 支持会签
	countersignPolicy: null, // 会签策略
	instanceMode: null, // 实例化模式
	instancePolicy: null, // 动态策略
	terminalDynamicMark: null, // 动态终止标识
	tag: '', // 标识
});
const emits = defineEmits(['update:modelValue']); // 定义事件
const loading = ref(false); // 加载
watch(
	() => form,
	() => {
		form.stepTypeName = form.name + '节点';
		emits('update:modelValue', Object.assign(props.modelValue, form));
	},
	{ deep: true }
);
// 选择处理人获取数据
// 下拉内容
const selectList = ref<EmptyArrayType>() as any;
// 会签
const itemName = ref<string>('');
const changeOptions = (e: any) => {
	form.handlerTypeItemsOrigin = [];
	form.handlerTypeItems = '[]';
	itemName.value = baseData.handlerTypeOptions[e].label;
	if ([0, 1, 2].includes(e)) {
		getSelectList(e).then((res: any) => {
			selectList.value = res.result ?? [];
		});
	}
	if (e === 4) {
		getOrgListFn();
	}
};
// 远程搜索用户名称
// 指定用户列表
const userList = ref<EmptyArrayType>([]);
const remoteMethod = (query: string) => {
	if (query !== '') {
		loading.value = true;
		queryUser({ name: query }).then((res: any) => {
			loading.value = false;
			const newUsers = res.result.map((item: any) => {
				return {
					...item,
					name: !item.name.includes('-') ? item.name + '-' + item.organization.name : item.name,
				};
			});
			userList.value = removeDuplicate([...newUsers, ...userList.value], 'id');
		});
	}
};

// 获取可用组织
const orgData = ref<EmptyArrayType>([]);
const getOrgListFn = () => {
	getCanUseOrg().then((res: any) => {
		orgData.value = res?.result ?? [];
	});
};
// 获取选择对象
const getSelectValue = (query: any[]) => {
	let arr: EmptyArrayType = [];
	if ([0, 1, 2].includes(form.handlerType)) {
		arr = query;
	} else if ([3].includes(form.handlerType)) {
		arr = query.map((item: any) => ({ key: item.id, value: item.name }));
	}
	// 使用模板字符串
	form.handlerTypeItems = `${JSON.stringify(arr)}`;
};
// 选择部门
const treeSelectRef = ref<RefType>();
const selectOrg = () => {
	const currentNode = treeSelectRef.value.getCheckedNodes();
	let arr = currentNode.map((item: any) => ({ key: item.id, value: item.name }));
	// 使用模板字符串
	form.handlerTypeItems = `${JSON.stringify(arr)}`;
};
const selectOrg1 = (value:any)=>{
	let arr = value.map((item: any) => ({ key: item.id, value: item.name }));
	// 使用模板字符串
	form.handlerTypeItems = `${JSON.stringify(arr)}`;
	form.handlerTypeItemsOrigin = value.map((item: any) => item.id);
	ruleFormRef.value.validateField('handlerTypeItemsOrigin')
}
// 选择动态策略
const ruleFormRef = ref<RefType>();
const selectInstancePolicy = (val: string | number) => {
	let item = baseData.dynamicPolicyOptions.filter((item: any) => item.key === val)[0];
	if (item.items && item.items.length) {
		baseData.dynamicStrategyOptions = item.items;
	}
	ruleFormRef.value.resetFields('terminalDynamicMark');
	form.terminalDynamicMark = null;
};
const baseData = reactive<any>({
	businessTypeOptions: <EmptyArrayType>[], // 业务类型
	countersignMode: <EmptyArrayType>[], // 会签
	handlerTypeOptions: <EmptyArrayType>[], // 办理者类型
	dynamicStrategyOptions: <EmptyArrayType>[], // 动态策略
	executeModeOptions: <EmptyArrayType>[], // 执行模式
	dynamicPolicyOptions: <EmptyArrayType>[], // 会签策略
	instanceModeOptions: <EmptyArrayType>[], // 实例化模式
});
onMounted(async () => {
	const { stepTypeOptions, businessTypeOptions, handlerTypeOptions, countersignMode, dynamicPolicyOptions, executeModeOptions, instanceModeOptions } =
		props.baseData;
	baseData.businessTypeOptions = businessTypeOptions; // 业务类型
	baseData.stepTypeOptions = stepTypeOptions; // 节点类型
	baseData.handlerTypeOptions = handlerTypeOptions.map((item: any) => ({
		// 办理者类型
		value: item.key,
		label: item.value,
	}));
	baseData.executeModeOptions = executeModeOptions; // 执行模式
	baseData.countersignMode = countersignMode; // 支持发起会签
	baseData.dynamicPolicyOptions = dynamicPolicyOptions; // 会签策略
	baseData.instanceModeOptions = instanceModeOptions; // 实例模式

	// 合并表单
	Object.assign(form, props.modelValue);
	if (form.handlerTypeItems.includes('[')) {
		switch (form.handlerType) {
			case 0:
			case 1:
			case 2:
				form.handlerTypeItemsOrigin = JSON.parse(form.handlerTypeItems);
				break;
			case 3:
				const users = JSON.parse(form.handlerTypeItems);
				userList.value = form.handlerTypeItemsOrigin = users.map((item: any) => ({ id: item.key, name: item.value }));
				break;
			case 4:
				form.handlerTypeItemsOrigin = JSON.parse(form.handlerTypeItems).map((v: any) => v.key);
				break;
			default:
				break;
		}
	}
	if ([0, 1, 2].includes(form.handlerType)) {
		const res: any = await getSelectList(form.handlerType);
		selectList.value = res.result ?? [];
		if (baseData.handlerTypeOptions.length) itemName.value = baseData.handlerTypeOptions[form.handlerType].label;
	} else if ([3].includes(form.handlerType)) {
		if (baseData.handlerTypeOptions.length) itemName.value = baseData.handlerTypeOptions[form.handlerType].label;
	} else if ([4].includes(form.handlerType)) {
		if (baseData.handlerTypeOptions.length) itemName.value = baseData.handlerTypeOptions[form.handlerType].label;
		getOrgListFn();
	}
	if (form.instancePolicy || form.instancePolicy === 0) {
		let item = baseData.dynamicPolicyOptions.filter((item: any) => item.key === form.instancePolicy)[0];
		if (item.items && item.items.length) {
			baseData.dynamicStrategyOptions = item.items;
		}
	}
});
// 导入属性及方法给外部调用
defineExpose({
	ruleFormRef,
});
</script>
<style lang="scss">
.vtree-tree-drop__wrapper {
	width: 100%;
}
</style>