<template>
	<div>
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="110px" v-loading="loading" :disabled="operType === 'view'">
			<span style="margin-left: 30px"
				>什么是待跳转参与者？当待跳转参与者为空时，则默认会跳转到该节点下的全部参与者。当待跳转参与者不为空时，则会跳转到该节点下指定的参与者（{{
					userRoleIdText
				}}）</span
			>
			<el-row :gutter="24">
				<el-divider> 参与者设置 </el-divider>
				<el-col :span="24" class="mb20">
					<el-form-item label="跳转参与者类型" prop="jobType">
						<el-tooltip placement="top">
							<template #content>标识【待跳转任务】的【参与者类型】。当待跳转任务存在【参与者】时，可不选择</template>
							<el-radio-group @change="handleRoleType" v-model="form.jobType">
								<el-radio v-for="(item, index) in DIC_PROP.JOB_USER_TYPE" :key="index" :label="item.value">
									{{ item.label }}
								</el-radio>
							</el-radio-group>
						</el-tooltip>
						<el-tooltip placement="top" v-if="form.jobType">
							<template #content>当待跳转任务存在【参与者】时，可不选择</template>
							<el-button text type="primary" icon="delete" @click="clearJobType"> 清空 </el-button>
						</el-tooltip>
					</el-form-item>
				</el-col>
				<el-divider> 任意跳转设置 </el-divider>

				<el-col :span="12" class="mb20">
					<el-form-item :label="t('runReject.flowInstId')" prop="flowInstId">
						<el-input v-model="form.flowInstId" :placeholder="t('runReject.inputFlowInstIdTip')" disabled />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="t('runReject.defFlowId')" prop="defFlowId">
						<el-select v-model="form.defFlowId" :placeholder="t('runReject.inputDefFlowIdTip')" clearable filterable disabled>
							<el-option v-for="(item, index) in cascadeDic.defFlowId" :key="index" :label="item.flowName" :value="item.defFlowId"></el-option>
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item :label="t('runReject.toRunNodeId')" prop="toRunNodeId">
						<el-tooltip placement="top" content="若不选择具体的【待跳转参与者】，则默认会跳转到该节点下的全部参与者">
							<el-select
								v-model="form.toRunNodeId"
								:placeholder="t('runReject.inputToFlowNodeIdTip')"
								clearable
								filterable
								@change="cascadeChange('toRunNodeId', ['anyJumpUserId', 'anyJumpRoleId', 'anyJumpPostId', 'anyJumpDeptId'])"
							>
								<el-option v-for="(item, index) in cascadeDic.toRunNodeId" :key="index" :label="item.nodeName" :value="item.id"></el-option>
							</el-select>
						</el-tooltip>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20" v-if="form.jobType === DIC_PROP.JOB_USER_TYPE[0].value">
					<el-form-item label="指定待跳转人员" prop="handleRoleId">
						<el-tooltip placement="top">
							<template #content>{{ validateNull(cascadeDic.anyJumpUserId) ? roleIdText : roleIdText2 }}</template>
							<el-select
								v-model="form.handleRoleId"
								placeholder="请输入用户名称进行模糊搜索"
								clearable
								filterable
								remote
								:remote-method="methodsRemote.remoteMethodUser"
								:reserve-keyword="false"
							>
								<el-option
									v-for="(item, index) in validateNull(cascadeDic.anyJumpUserId) ? dicData.users : cascadeDic.anyJumpUserId"
									:key="index"
									:label="item.name"
									:value="item.userId"
								></el-option>
							</el-select>
						</el-tooltip>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20" v-if="form.jobType === DIC_PROP.JOB_USER_TYPE[1].value">
					<el-form-item label="指定待跳转角色" prop="handleRoleId">
						<el-tooltip placement="top">
							<template #content>{{ validateNull(cascadeDic.anyJumpRoleId) ? roleIdText : roleIdText2 }}</template>
							<el-select
								v-model="form.handleRoleId"
								placeholder="请输入角色名称进行模糊搜索"
								clearable
								filterable
								remote
								:remote-method="methodsRemote.remoteMethodRole"
								:reserve-keyword="false"
							>
								<el-option
									v-for="(item, index) in validateNull(cascadeDic.anyJumpRoleId) ? dicData.roles : cascadeDic.anyJumpRoleId"
									:key="index"
									:label="item.roleName"
									:value="item.roleId"
								></el-option>
							</el-select>
						</el-tooltip>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20" v-if="form.jobType === DIC_PROP.JOB_USER_TYPE[2].value">
					<el-form-item label="指定待跳转岗位" prop="handleRoleId">
						<el-tooltip placement="top">
							<template #content>{{ validateNull(cascadeDic.anyJumpPostId) ? roleIdText : roleIdText2 }}</template>
							<el-select
								v-model="form.handleRoleId"
								placeholder="请输入岗位名称进行模糊搜索"
								clearable
								filterable
								remote
								:remote-method="methodsRemote.remoteMethodPost"
								:reserve-keyword="false"
							>
								<el-option
									v-for="(item, index) in validateNull(cascadeDic.anyJumpPostId) ? dicData.posts : cascadeDic.anyJumpPostId"
									:key="index"
									:label="item.postName"
									:value="item.postId"
								></el-option>
							</el-select>
						</el-tooltip>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20" v-if="form.jobType === DIC_PROP.JOB_USER_TYPE[3].value">
					<el-form-item label="指定待跳转部门" prop="handleRoleId">
						<el-tooltip placement="top">
							<template #content>{{ validateNull(cascadeDic.anyJumpDeptId) ? roleIdText : roleIdText2 }}</template>
							<el-select
								v-model="form.handleRoleId"
								placeholder="请输入部门名称进行模糊搜索"
								clearable
								filterable
								remote
								:remote-method="methodsRemote.remoteMethodDept"
								:reserve-keyword="false"
							>
								<el-option
									v-for="(item, index) in validateNull(cascadeDic.anyJumpDeptId) ? dicData.depts : cascadeDic.anyJumpDeptId"
									:key="index"
									:label="item.name"
									:value="item.deptId"
								></el-option>
							</el-select>
						</el-tooltip>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<footer class="el-dialog__footer">
			<span class="dialog-footer">
				<el-button type="primary" @click="handleUpdate" :loading="loading">{{ $t('common.confirmButtonText') }}</el-button>
			</span>
		</footer>
	</div>
</template>

<script setup lang="ts" name="RunAnyJumpForm">
import { useI18n } from 'vue-i18n';
import { onCascadeChange, onLoadDicUrl, remoteMethodByKey } from '/@/flow/components/convert-name/convert';
import { validateNull } from '/@/utils/validate';
import { useMessage } from '/@/hooks/message';
import { handleChangeJobType } from '/@/flow';

const { t } = useI18n();
const $message = useMessage();
const $emit = defineEmits(['onAnyJumpJob']);
// 定义变量内容
const dataFormRef = ref();
const loading = ref(false);
const operType = ref(false);

// 定义字典
const dicData = reactive({});
const cascadeDic = reactive({});
const onLoad = onLoadDicUrl();
const onCascade = onCascadeChange(
	cascadeDic,
	{ key: 'flowInstId', cascades: ['defFlowId'] },
	{ prefix: 'runJob', key: 'flowInstId', cascades: ['toRunNodeId'] },
	{ key: 'toRunNodeId', cascades: ['anyJumpUserId', 'anyJumpRoleId', 'anyJumpPostId', 'anyJumpDeptId'] }
);

onMounted(() => {
	// onLoad(dicData);
});

function cascadeChange(key, cascades) {
	cascadeDic.anyJumpUserId = null;
	cascadeDic.anyJumpRoleId = null;
	cascadeDic.anyJumpPostId = null;
	cascadeDic.anyJumpDeptId = null;
	onCascade(form, { key: key, cascades: cascades });
	handleToFlowNodeId(form[key]);
}

// 提交表单数据
const form = reactive({
	defFlowId: '',
	flowInstId: '',
	toRunNodeId: '',
	handleRoleId: '',
	runRejectVO: {},
	jobType: '',
});

// 定义校验规则
const dataRules = ref({
	defFlowId: [{ required: true, message: '流程名称不能为空', trigger: 'blur' }],
	flowInstId: [{ required: true, message: '流程实例ID不能为空', trigger: 'blur' }],
	toRunNodeId: [{ required: true, message: '到达节点名称不能为空', trigger: 'blur' }],
});

const props = defineProps({
	currJob: {
		type: Object,
		default: null,
	},
});

const roleIdText = '注：当前待跳转节点下可候选待跳转参与者为空，请指定待跳转参与者即为其分配参与者';
const roleIdText2 = '注：当待跳转参与者为空时，则默认会跳转到当前节点显示的全部参与者';
const userRoleIdText = '注：当待跳转节点下任务不存在参与者时，请指定待跳转参与者即为其分配参与者';

function handleToFlowNodeId(val) {
	if (!val) return;
	const runNode = cascadeDic.toRunNodeId.find((f) => f.id === val);
	form.runRejectVO.toRunNodeId = runNode.id;
	form.runRejectVO.toFlowNodeId = runNode.flowNodeId;
}

function initJobData() {
	Object.assign(form, props.currJob);
	onCascade(form);
}

function handleRoleType() {
	handleChangeJobType(dicData, form);
	form.handleRoleId = null;
}

function clearJobType() {
	form.jobType = '';
	form.handleRoleId = null;
}

const methodsRemote = {
	remoteMethodUser(query: string) {
		remoteMethodByKey(query, onLoad, dicData, 'userName', 'users');
	},
	remoteMethodRole(query: string) {
		remoteMethodByKey(query, onLoad, dicData, 'roleName', 'roles');
	},
	remoteMethodPost(query: string) {
		remoteMethodByKey(query, onLoad, dicData, 'postName', 'posts');
	},
	remoteMethodDept(query: string) {
		remoteMethodByKey(query, onLoad, dicData, 'deptName', 'depts');
	},
};

async function handleUpdate() {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	let b =
		validateNull(cascadeDic.anyJumpUserId) &&
		validateNull(cascadeDic.anyJumpRoleId) &&
		validateNull(cascadeDic.anyJumpPostId) &&
		validateNull(cascadeDic.anyJumpDeptId) &&
		!form.handleRoleId;

	if (b) {
		$message.warning(roleIdText);
		return;
	}

	// 为空则跳转到显示的全部参与者
	if (form.jobType) {
		form.runRejectVO.handleRoleId = form.handleRoleId;
		form.runRejectVO.jobType = form.jobType;
	}

	props.currJob.runRejectVO = form.runRejectVO;

	loading.value = true;
	try {
		$emit('onAnyJumpJob', props.currJob);
		setTimeout(() => {
			// 异步异常
			loading.value = false;
		}, 3000);
	} catch (e) {
		loading.value = false;
	}
}

// 监听双向绑定
watch(
	() => props.currJob.id,
	(val) => {
		initJobData();
	}
);

onMounted(() => {
	initJobData();
});
</script>

<style lang="scss" scoped>
.el-dialog__footer {
	text-align: center;

	.dialog-footer {
		text-align: center;
	}
}
</style>
