<template>
	<el-dialog
		v-model="state.dialogVisible"
		draggable
		:title="state.dialogTitle"
		ref="dialogRef"
		@mouseup="mouseup"
		:style="'transform: ' + state.transform + ';'"
		append-to-body
		destroy-on-close
		:close-on-click-modal="false"
		@close="close"
	>
		<el-steps :active="activeStep" align-center finish-status="success" class="mb20">
			<el-step title="业务表单" />
			<el-step title="流程表单" />
		</el-steps>

		<div v-show="activeStep === 0" v-loading="state.loading">
			<el-form :model="state.discernForm" label-width="110px" ref="discernFormRef">
				<el-row :gutter="10">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="工单编码"> {{ state.orderDetail.no }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="工单标题"> {{ state.orderDetail.order?.title }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="申请人"> {{ state.orderDetail.creatorName }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="申请部门"> {{ state.orderDetail.creatorOrgName }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="申请时间"> {{ dayjs(state.orderDetail.creationTime).format('YYYY-MM-DD HH:mm:ss') }} </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="申请类型" prop="type" :rules="[{ required: true, message: '请选择申请类型', trigger: 'change' }]">
							<el-select v-model="state.discernForm.type" placeholder="请选择申请类型" class="w100" value-key="dicDataValue">
								<el-option v-for="item in screenTypeOptions" :value="item" :key="item.dicDataValue" :label="item.dicDataName" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="申请理由" prop="content" :rules="[{ required: true, message: '请填写甄别申请理由', trigger: 'blur' }]">
							<common-advice
								@chooseAdvice="chooseAdviceDiscern"
								v-model="state.discernForm.content"
								placeholder="请填写甄别申请理由"
								:loading="state.loading"
								:commonEnum="commonEnum.Discriminate"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="附件">
							<annex-list
								name="甄别附件"
								ref="discernAnnexListRef"
								v-model:format="handleFilesDiscern"
								:businessId="state.orderDetail.orderId"
								v-model="state.ruleForm.files"
								classify="甄别上传"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</div>

		<el-form :model="state.ruleForm" label-width="110px" ref="ruleFormRef" v-show="activeStep === 1" v-loading="state.loading">
			<slot name="header"></slot>
			<el-row :gutter="10">
				<!-- 非退回流程都需要选择 -->
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="下一环节" prop="nextStepCode" :rules="[{ required: true, message: '请选择下一环节', trigger: 'change' }]">
						<el-select v-model="state.ruleForm.nextStepCode" placeholder="请选择下一环节" class="w100" @change="selectNextStep">
							<el-option v-for="item in state.nextStepOptions" :key="item.key" :label="item.value" :value="item.key" />
						</el-select>
						<p class="flex-center-align color-danger" v-if="showFastSendOrder">
							当前推荐派单办理对象：{{ fastStepName }} <el-button type="primary" link class="ml4" @click="fastSendOrder">快捷派单</el-button>
						</p>
					</el-form-item>
				</el-col>
				<!-- 非退回流程都需要选择并且如果选择了结束节点就不需要选择办理对象 -->
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="showHandlers">
					<el-form-item label="办理对象" prop="nextHandlers" :rules="[{ required: true, message: '请选择办理对象', trigger: 'change' }]">
						<el-select-v2
							v-model="state.ruleForm.nextHandlers"
							:options="state.handlerOptions"
							placeholder="请选择办理对象"
							class="w100"
							multiple
							clearable
							collapse-tags
							collapse-tags-tooltip
							filterable
							value-key="key"
							@change="selectHandlers"
							:multiple-limit="multipleLimit"
						/>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="showMainHandler">
					<el-form-item label="主办" prop="nextMainHandler" :rules="[{ required: false, message: '请选择主办', trigger: 'change' }]">
						<el-select v-model="state.ruleForm.nextMainHandler" placeholder="请选择主办" class="w100" filterable>
							<el-option v-for="item in state.handlerMainOptions" :key="item.key" :label="item.value" :value="item.key" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="countersignAble">
					<el-form-item label="发起会签" prop="isStartCountersign" :rules="[{ required: false, message: '请选择发起会签', trigger: 'change' }]">
						<el-switch
							v-model="state.ruleForm.isStartCountersign"
							inline-prompt
							active-text="是"
							inactive-text="否"
							@change="changeStartCountersign"
							:disabled="countersignDisabled"
						/>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="" prop="isSms">
						<el-checkbox v-model="state.ruleForm.isSms" label="短信通知" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button class="default-button" @click="onPrevious" :loading="state.loading" v-if="activeStep === 1">上一步</el-button>
				<el-button class="default-button" @click="onNext" :loading="state.loading" v-if="activeStep === 0">下一步</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading" v-if="activeStep === 1">办理</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="processApproval">
import { computed, defineAsyncComponent, nextTick, reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import other from '@/utils/other';
import { useUserInfo } from '@/stores/userInfo';
import { storeToRefs } from 'pinia';
import { commonEnum } from '@/utils/constants';
import { discernUpdate, screenBaseData, screenDetail, workflowDiscernParams } from '@/api/business/discern';
import { transformFile } from '@/utils/tools';
import dayjs from 'dayjs';

// 引入组件
const CommonAdvice = defineAsyncComponent(() => import('@/components/CommonAdvice/index.vue')); // 常用意见
const AnnexList = defineAsyncComponent(() => import('@/components/AnnexList/index.vue')); // 附件列表
// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList', 'orderProcessFailed']);
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 弹窗显示隐藏
	ruleForm: {
		isPass: true, // 审批结果
		//流程表单
		opinion: '', // 意见
		nextStepCode: '', // 下一节点
		nextStepName: '', // 下一节点名称
		backToCountersignEnd: false, // 是否回到会签结束节点
		nextHandlers: [], // 下一节点办理对象
		nextMainHandler: '', // 主办人
		isSms: false, // 是否短信通知
		isStartCountersign: false, // 是否发起会签
	},
	discernForm: {
		// 甄别表单
		content: '', // 甄别理由
	},
	nextStepOptions: [], // 下一节点
	handlerOptions: [], // 办理对象
	transform: 'translate(0px, 0px)', // 滚动条位置
	loading: false, // 提交按钮loading
	workflowId: '', // 流程id
	handlerClassifies: [], //撤回办理对象
	handlerMainOptions: [], // 主办人
	handleId: '', // 流程处理ID
	dialogTitle: '', // 弹窗标题
	annexName: '', // 附件标题
	inputPlaceholder: '', // 意见提示
	orderDetail: {}, // 工单详情
});
const ruleFormRef = ref<RefType>(); //表单组件
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息
const screenTypeOptions = ref<EmptyArrayType>([]); // 甄别类型

// 打开弹窗
const openDialog = async (val: any) => {
	console.log(val);
	state.loading = true;
	try {
		state.dialogTitle = '甄别申请'; // 流程标题
		activeStep.value = 0;

		const [workflowDiscernResponse, responseDiscern] = await Promise.all([workflowDiscernParams(), screenBaseData()]); //获取开启流程参数
		screenTypeOptions.value = responseDiscern.result?.screenType ?? []; // 甄别理由
		handleResult(workflowDiscernResponse);

		const { result } = await screenDetail(val.id);
		state.discernForm.content = result.content ?? {};
		state.discernForm.type = {
			dicDataValue: result.typeDicId,
			dicDataName: result.typeDicName,
		};
		state.orderDetail = result;
		state.ruleForm.files = transformFile(result.files);
		console.log(result);

		await nextTick(() => {
			restForm(ruleFormRef.value);
		});
    state.dialogVisible = true;
	} finally {
		state.loading = false;
	}
};
const canStartCountersign = ref<boolean>(false); // 是否可以发起会签
const isMainHandlerShow = ref<boolean>(false); // 是否展示主办人
const handleResult = (res: any) => {
	state.nextStepOptions = res.result.steps; //办理对象选择内容
	canStartCountersign.value = res.result.canStartCountersign ?? false; // 是否可以发起会签
	isMainHandlerShow.value = res.result.isMainHandlerShow ?? false; // 是否展示主办人
	if (state.nextStepOptions.length === 1) {
		// 下一节点是否只有一个 默认选中第一个
		setTimeout(() => {
			state.ruleForm.nextStepCode = state.nextStepOptions[0].key; // 下一节点code
			state.ruleForm.nextStepName = state.nextStepOptions[0].value; // 下一节点name
			state.ruleForm.backToCountersignEnd = state.nextStepOptions[0].backToCountersignEnd ?? false; // 是否回到会签结束节点
		}, 0);
		selectNextStep(state.nextStepOptions[0].key); // 查询流程下一节点参数
	} else {
		state.ruleForm.nextStepCode = '';
		state.ruleForm.nextStepName = '';
	}
	state.loading = false;
};
// 上一部
const onPrevious = () => {
	activeStep.value = 0;
};
const discernFormRef = ref<RefType>(); //甄别申请表单组件
// 下一步
const onNext = () => {
	discernFormRef.value?.validate((valid: boolean) => {
		if (!valid) return;
		activeStep.value = 1;
	});
};
const activeStep = ref(0); //步骤条
// 流程选择下一环节
const fastStepName = ref(''); // 推荐派单处理对象
const fastStepCode = ref(''); // 推荐派单处理对象code
const selectNextStep = (val: any) => {
	ruleFormRef.value?.resetFields('nextHandlers');
	ruleFormRef.value?.resetFields('nextMainHandler');
	const next = state.nextStepOptions.find((item: any) => item.key === val);
	const items = next.items; //获取下一节点
	state.ruleForm.nextStepName = next.value; // 下一节点name
	state.ruleForm.backToCountersignEnd = next.backToCountersignEnd ?? false; // 是否回到会签结束节点
	state.handlerOptions = items ?? [];
	state.handlerOptions = state.handlerOptions.map((item: any) => {
		return {
			value: {
				...item,
			},
			label: item.value,
		};
	});
	fastStepName.value = next.recommendOrgName; // 推荐派单处理对象
	fastStepCode.value = next.recommendOrgId; // 推荐派单处理对象code
};
//  会签是否可用 (多个办理对象,并且配置可以会签)
const countersignAble = computed(() => {
	return canStartCountersign.value;
});
// 办理对象是否能够选择多个(可以发起会签可以选择多个，不能发起会签只能选择一个)
const multipleLimit = computed(() => {
	return canStartCountersign.value ? 0 : 1;
});
watch(
	() => state.ruleForm.nextHandlers, // 监听办理对象 多个办理对象自动发起会签
	(val) => {
		state.ruleForm.isStartCountersign = val.length > 1;
	}
);
const countersignDisabled = computed(() => {
	// 是否可以发起会签
	return state.ruleForm.nextHandlers.length <= 1;
});
// 是否发起会签
const changeStartCountersign = (val: boolean) => {
	if (!val) {
		// 如果不能会签清空办理对象
		state.ruleForm.nextHandlers = [];
		ruleFormRef.value?.resetFields('nextHandlers');
	}
};

// 是否展示办理对象 (只有结束节点不展示 next.stepType===2 表示为结束节点)
const showHandlers = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
	if (!next) return true;
	return next.stepType !== 2;
});
// 是否显示快捷派单
const showFastSendOrder = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
	if (!next) return false;
	return next?.recommendOrgName && next?.recommendOrgId;
});
// 快速派单
const fastSendOrder = () => {
	if (!fastStepCode.value) return;
	// 如果办理对象中没有推荐派单的对象就添加
	if (!state.ruleForm.nextHandlers.find((item: any) => item.key === fastStepCode.value)) {
		state.ruleForm.nextHandlers = [...state.ruleForm.nextHandlers, { key: fastStepCode.value, value: fastStepName.value }];
	}
};

// 选择办理对象
const selectHandlers = () => {
	ruleFormRef.value?.resetFields('nextMainHandler');
	if (state.ruleForm.nextHandlers.length > 1) {
		// 多个办理对象 主办
		state.ruleForm.nextMainHandler = state.ruleForm.nextHandlers[0].key;
	}
	if (state.ruleForm.nextHandlers.length <= 1) {
		// 如果只有一个办理对象就不需要发起会签
		state.ruleForm.isStartCountersign = false;
	}
};
// 是否展示主办
const showMainHandler = computed(() => {
	return state.ruleForm.nextHandlers.length > 1 && isMainHandlerShow.value;
});
// 主办从办理对象中选择
state.handlerMainOptions = computed(() => {
	return state.ruleForm.nextHandlers;
});
// 设置抽屉
const dialogRef = ref<RefType>();
const mouseup = () => {
	state.transform = dialogRef.value.dialogContentRef.$el.style.transform;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
// 重置表单方法
const restForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	state.ruleForm.opinion = '';
	formEl.resetFields();
	formEl.clearValidate();
};
// 选择常用意见 填入填写框 甄别
const chooseAdviceDiscern = (item: any) => {
	state.discernForm.content += item.content;
};
const afterSubmit = (emitType?: 'updateList' | 'orderProcessFailed', showMessage?: boolean) => {
	state.loading = false;
	closeDialog();
	if (showMessage) ElMessage.success('操作成功');
	if (emitType) emit(emitType);
};
const close = () => {
	restForm(ruleFormRef.value);
	restForm(discernFormRef.value);
};
// 提交
const handleFilesDiscern = ref<EmptyArrayType>([]); // 甄别附件
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		ElMessageBox.confirm(`确认办理?`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
			draggable: true,
			cancelButtonClass: 'default-button',
			autofocus: false,
		})
			.then(() => {
				state.loading = true;
				let submitObj = other.deepClone(state.ruleForm);
				if (submitObj.nextHandlers && submitObj.nextHandlers.length) {
					if (submitObj.nextHandlers.length === 1) {
						submitObj.nextMainHandler = submitObj.nextHandlers[0].key;
					}
				}
				const requestDiscern = {
					data: {
						id: state.orderDetail.id,
						no: state.orderDetail.no,
						visitId: state.orderDetail.visitId,
						visitDetailId: state.orderDetail.visitDetailId,
						orderId: state.orderDetail.orderId,
						typeDicId: state.discernForm.type.dicDataValue,
						typeDicName: state.discernForm.type.dicDataName,
						content: state.discernForm.content,
						files: handleFilesDiscern.value,
					},
					nextWorkflow: { ...submitObj, files: handleFilesDiscern.value, opinion: state.discernForm.content },
				};
				discernUpdate(requestDiscern)
					.then(() => {
						afterSubmit('updateList', true);
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
			})
			.catch(() => {});
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
