<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="orgCode"
					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: false, 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="countersignEndStepCode" v-if="form.countersignEndStepCode">
				<el-select v-model="form.countersignEndStepCode" class="w100" disabled>
					<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="components" :rules="[{ required: false, message: '请选择组件配置', trigger: 'change' }]">
        <el-checkbox-group v-model="form.components">
          <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 { baseData, getSelectList,queryUser } from '/@/api/system/workflow';
import { getCanUseOrg } from '/@/api/system/user';
import { removeDuplicate } from '/@/utils/arrayOperation';
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: '', // 节点过滤策略
});
const emits = defineEmits(['update:modelValue']); // 定义事件
const loading = ref(false); // 加载
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 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 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 getSelectValue = (query: any[]) => {
	let arr:EmptyArrayType;
	arr = query.map((item: any) => ({ name: item.name, id: item.id }));
	// 使用模板字符串
	form.handlerClassifies = `${JSON.stringify(arr)}`;
};
// 会签
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;
// 会签结束节点
const nodesOptions = ref([] 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,
  }));
  stepPropertiesOptions.value = res.result?.stepPropertiesOptions ?? [];
  pathPolicyOptions.value = res.result?.pathPolicyOptions ?? [];
	// 合并表单
	Object.assign(form, props.modelValue);
	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.summaryNodes ?? [];
});
// 导入属性及方法给外部调用
defineExpose({
	ruleFormRef,
});
</script>
