<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="code" :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="handlerType" :rules="[{ required: true, message: '请选择处理人', trigger: 'change' }]">
				<el-select v-model="form.handlerType" class="w100" placeholder="请选择处理人" @change="changeOptions">
					<el-option v-for="item in 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="handlerClassifiesOrgin"
				:rules="[{ required: true, message: `请选择${itemName}`, trigger: 'change' }]"
			>
				<el-select v-model="form.handlerClassifiesOrgin" multiple filterable class="w100" @change="getSelectValue" value-key="id">
					<el-option v-for="item in selectList" :key="item.id" :label="item.name" :value="item" />
				</el-select>
			</el-form-item>
			<!-- 选择用户 -->
			<el-form-item
				v-if="[3].includes(form.handlerType)"
				:label="itemName"
				prop="handlerClassifiesOrgin"
				:rules="[{ required: true, message: `请选择${itemName}`, trigger: 'change' }]"
			>
				<el-select
					v-model="form.handlerClassifiesOrgin"
					multiple
					filterable
					remote
					class="w100"
					reserve-keyword
					placeholder="请输入用户名称"
					remote-show-suffix
					:remote-method="remoteMethod"
					:loading="loading"
					@change="getSelectValue"
					value-key="id"
				>
					<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="handlerClassifiesOrgin"
				:rules="[{ required: true, message: `请选择${itemName}`, trigger: 'change' }]"
			>
				<el-tree-select
					:props="{ label: 'orgName' }"
					node-key="id"
					class="w100"
					ref="treeSelectRef"
					v-model="form.handlerClassifiesOrgin"
					:data="orgData"
					multiple
					:render-after-expand="false"
					show-checkbox
					@check-change="checkChange"
					check-strictly
					default-expand-all
					filterable
				/>
			</el-form-item>
      <el-form-item label="节点属性" prop="businessProperty" :rules="[{ required: true, message: '请选择节点属性', trigger: 'change' }]">
        <el-select v-model="form.businessProperty" class="w100" placeholder="请选择节点属性">
          <el-option v-for="item in businessPropertyOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="会签" prop="countersignMode" :rules="[{ required: true, message: '请选择会签', trigger: 'change' }]">
        <el-select v-model="form.countersignMode" class="w100" placeholder="请选择会签">
          <el-option v-for="item in countersignModeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
			<el-form-item label="节点过滤策略" prop="pathPolicy" :rules="[{ required: true, message: '请选择节点过滤策略', trigger: 'change' }]">
				<el-select v-model="form.pathPolicy" class="w100" placeholder="请选择节点过滤策略">
					<el-option v-for="item in pathPolicyOptions" :key="item.key" :label="item.value" :value="item.key" />
				</el-select>
			</el-form-item>
			<el-form-item label="会签发起节点" prop="countersignStartStepCode" :rules="[{ required: false, message: '请选择会签发起节点', trigger: 'change' }]">
				<el-select v-model="form.countersignStartStepCode" class="w100" placeholder="请选择会签发起节点" @change="chanStartCode">
					<el-option v-for="item in nodesOptions" :key="item.id" :label="item.text.value" :value="item.id" />
				</el-select>
			</el-form-item>
      <el-form-item label="组件配置" prop="componentsOrigin" :rules="[{ required: false, message: '请选择组件配置', trigger: 'change' }]">
        <el-checkbox-group v-model="form.componentsOrigin" @change="selectComponent">
          <el-checkbox :label="item.dicDataValue" v-for="item in stepPropertiesOptions" :key="item.id">{{item.dicDataName}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
		</el-form>
	</div>
</template>
<script lang="ts" setup name="flowNode">
import { reactive, watch, onMounted, ref } from 'vue';
import { ElMessageBox } from 'element-plus';
import { removeDuplicate } from '/@/utils/arrayOperation';
import { baseData, getSelectList,queryUser } from '/@/api/system/workflow';
import { getCanUseOrg } from '/@/api/system/user';
const ruleFormRef = ref<RefType>();
// 定义属性
const props = defineProps<{
	modelValue: any;
}>();
// 注意:ref不能与model一样，相同的话表单双向绑定将会失效
const form = reactive<Record<string, any>>({
  ...props.modelValue,  // 传入的数据
  handlerClassifiesOrgin: [], // 选择的数据
  handlerClassifies: [],  // 选择的数据
  handlerType: '',  // 处理人类型
  businessProperty: '', // 节点属性
  countersignMode: '',  // 会签
  countersignStartStepCode: '', // 会签发起节点
  countersignEndStepCode: '',  // 会签结束节点
  pathPolicy: null, // 节点过滤策略
  componentsOrigin:[],
  components:[], //组件配置
});
const emits = defineEmits(['update:modelValue', 'countersignStartStepCode']); // 定义事件

//
const loading = ref(false); // 加载
const nodesOptions = ref([] as any);  // 节点
watch(
	() => form,
	() => {
		emits('update:modelValue', Object.assign(props.modelValue, form));
	},
	{ deep: true }
);
// 选择处理人获取数据
// 处理人
const handlerTypeOptions = ref<EmptyArrayType>() as any;
// 下拉内容
const selectList = ref<EmptyArrayType>() as any;
// 会签
const itemName = ref<string>('');
const changeOptions = (e: any) => {
	form.handlerClassifiesOrgin = [];
	form.handlerClassifies = '[]';
	itemName.value = handlerTypeOptions.value[e].label;
	if ([0, 1, 2].includes(e)) {
		getSelectList(e).then((res: any) => {
			selectList.value = res.result ?? [];
			selectList.value = selectList.value.map((item: any) => ({
				id: item.key,
				name: item.value,
			}));
		});
	}
	if (e === 4) {
		getOrgListFn();
	}
};
// 获取可用组织
const getOrgListFn = () => {
		getCanUseOrg().then((res: any) => {
			orgData.value = res?.result ?? [];
		});
};
const treeSelectRef = ref<RefType>();
// 选择部门
const checkChange = () => {
	const data = treeSelectRef.value.getCheckedNodes();
	let arr: EmptyArrayType;
	arr = data.map((v: any) => {
		return {
			id: v.orgCode,
			name: v.orgName,
		};
	});
	// 使用模板字符串
	form.handlerClassifies = `${JSON.stringify(arr)}`;
};
// 远程搜索用户名称
// 指定用户列表
const userList = ref<any>();
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.orgName : item.name
				};
			});
			userList.value = removeDuplicate([ ...newUsers,...userList.value], 'id');
		});
	}
};
// 获取选择对象
const getSelectValue = (query: any) => {
	let arr: EmptyArrayType;
	arr = query.map((item: any) => ({ name: item.name, id: item.id }));
	// 使用模板字符串
	form.handlerClassifies = `${JSON.stringify(arr)}`;
};
const selectComponent = (val: any) => {
  form.components = JSON.stringify(val);
};
// 选择会签发起节点
const chanStartCode = (val: string) => {
	form.countersignEndStepCode = form.code;
	const currentItem = form.nodes.find((v: any) => v.id === val); //拿到当前选中的节点
	if (currentItem) {
		if (currentItem.properties?.countersignStartStepCode) {
			// 如果选中的会签发起节点有关联其他汇总节点
			ElMessageBox.alert(`该节点已关联其他汇总节点，覆盖当前配置`, '提示', {
				confirmButtonText: '确认',
				type: 'warning',
				draggable: true,
				cancelButtonClass: 'default-button',
				showClose: false,
				autofocus: false,
			}).then(() => {
				const beforeChangeItem = form.nodes.find((v: any) => v.properties?.countersignEndStepCode === form.countersignEndStepCode);
				// 先找到修改前关联的流程节点并清空
        beforeChangeItem.properties.countersignStartStepCode = '';
        beforeChangeItem.properties.countersignEndStepCode = '';
        beforeChangeItem.properties.type = beforeChangeItem.type.replace('hotline:', '');
        beforeChangeItem.properties.id = beforeChangeItem.id;
				emits('countersignStartStepCode', beforeChangeItem.properties);

				// 再找到修改前的汇总节点并清空
				const afterChangeItem = form.summaryNodes.find((v: any) => v.id === currentItem.properties.countersignEndStepCode);
				afterChangeItem.properties.countersignStartStepCode = '';
				afterChangeItem.properties.countersignEndStepCode = '';
				afterChangeItem.properties.type = afterChangeItem.type.replace('hotline:', '');
				afterChangeItem.properties.id = afterChangeItem.id;
				emits('countersignStartStepCode', afterChangeItem.properties);

				// 再重新赋值 当前节点
				currentItem.properties.countersignStartStepCode = val;
				currentItem.properties.countersignEndStepCode = form.code;
				currentItem.properties.type = currentItem.type.replace('hotline:', '');
				currentItem.properties.id = currentItem.id;
				emits('countersignStartStepCode', currentItem.properties);
			});
		} else {
			currentItem.properties.countersignStartStepCode = val;
			currentItem.properties.countersignEndStepCode = form.code;
			currentItem.properties.type = currentItem.type.replace('hotline:', '');
			currentItem.properties.id = currentItem.id;
			emits('countersignStartStepCode', currentItem.properties);
		}
	}
};
// 会签
const countersignModeList = ref<EmptyArrayType>() as any;
// 节点属性
const businessPropertyOptions = ref<EmptyArrayType>() as any;
// 部门
const orgData = ref<EmptyArrayType>() as any;
// 组件
const stepPropertiesOptions = ref<EmptyArrayType>() as any;
//
const pathPolicyOptions = ref<EmptyArrayType>() as any;
onMounted(async () => {
	// 获取页面基础数据
	const res: any = await baseData();
	handlerTypeOptions.value = res.result?.handlerTypeOptions ?? [];
	handlerTypeOptions.value = handlerTypeOptions.value.map((item: any) => ({
		value: item.key,
		label: item.value,
	}));
	countersignModeList.value = res.result?.countersignMode ?? [];
	countersignModeList.value = countersignModeList.value.map((item: any) => ({
		value: item.key,
		label: item.value,
	}));
  businessPropertyOptions.value = res.result?.businessPropertyOptions ?? [];
  businessPropertyOptions.value = businessPropertyOptions.value.map((item: any) => ({
    value: item.key,
    label: item.value,
  }));
  pathPolicyOptions.value = res.result?.pathPolicyOptions ?? [];
  stepPropertiesOptions.value = res.result?.stepPropertiesOptions ?? [];
	// 合并表单
	Object.assign(form, props.modelValue);
  if(form.components.includes('[')){
    form.componentsOrigin = JSON.parse(form.components);
  }
	if (form.handlerClassifies.includes('[')) {
		switch (form.handlerType) {
			case 0:
			case 1:
			case 2:
				form.handlerClassifiesOrgin = JSON.parse(form.handlerClassifies);
				break;
			case 3:
				userList.value = form.handlerClassifiesOrgin = JSON.parse(form.handlerClassifies);
				break;
			case 4:
				form.handlerClassifiesOrgin = JSON.parse(form.handlerClassifies).map((v: any) => v.id);
				break;
			default:
				break;
		}
	}
	if ([0, 1, 2].includes(form.handlerType)) {
		const res: any = await getSelectList(form.handlerType);
		selectList.value = res.result ?? [];
		selectList.value = selectList.value.map((item: any) => ({
			id: item.key,
			name: item.value,
		}));
		if (handlerTypeOptions.value.length) itemName.value = handlerTypeOptions.value[form.handlerType].label;
	} else if ([3].includes(form.handlerType)) {
		if (handlerTypeOptions.value.length) itemName.value = handlerTypeOptions.value[form.handlerType].label;
	} else if ([4].includes(form.handlerType)) {
		if (handlerTypeOptions.value.length) itemName.value = handlerTypeOptions.value[form.handlerType].label;
		getOrgListFn();
	}
	nodesOptions.value = form.nodes ?? [];
});
// 导入属性及方法给外部调用
defineExpose({
	ruleFormRef,
});
</script>
