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

			<div v-show="activeStep === 0">
				<el-form :model="state.delayForm" label-width="110px" ref="delayFormRef" v-if="state.processType === '延期申请'">
					<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.title }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="申请人"> {{ userInfos.name }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="申请部门"> {{ userInfos.orgName }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="申请时间"> {{ formatDate(Date(), '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="当前期满时间"> {{ formatDate(state.orderDetail.expiredTime, 'YYYY-mm-dd HH:MM:SS') }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12">
							<el-form-item label="延期申请数量">
								<el-row :gutter="10">
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
										<el-form-item label="" prop="timeLimitCount" :rules="[{ required: true, message: '请输入延期申请数量', trigger: 'blur' }]">
											<el-input-number
												placeholder="延期申请数量"
												v-model="state.delayForm.timeLimitCount"
												controls-position="right"
												class="w100"
											></el-input-number>
										</el-form-item>
									</el-col>
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
										<el-form-item
											label=""
											label-width="0"
											prop="timeLimitCount"
											:rules="[{ required: true, message: '请选择延期申请单位', trigger: 'change' }]"
										>
											<el-select v-model="state.delayForm.timeLimitCount" placeholder="延期申请单位">
												<el-option v-for="item in timeTypeOptions" :value="item.key" :key="item.key" :label="item.value" />
											</el-select>
										</el-form-item>
									</el-col>
								</el-row>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="延期后期满时间"> {{ state.delayForm.title }} </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="chooseAdviceDelay"
									v-model="state.delayForm.content"
									placeholder="请填写延期申请理由"
									:loading="state.loading"
									:commonEnum="commonEnum.Delay"
								/>
							</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="annexListRef" :businessId="state.orderDetail.id" classify="延期上传" />
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<el-form :model="state.discernForm" label-width="110px" ref="discernFormRef" v-if="state.processType === '甄别申请'">
					<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.title }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="申请人"> {{ userInfos.name }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="申请部门"> {{ userInfos.orgName }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="申请时间"> {{ formatDate(Date(), '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="unit" :rules="[{ required: true, message: '请选择申请类型', trigger: 'change' }]">
								<el-select v-model="state.discernForm.unit" placeholder="请选择申请类型" clearable class="w100">
									<el-option v-for="item in channelOptions" :value="item.key" :key="item.key" :label="item.value" />
								</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="annexListRef" :businessId="state.orderDetail.id" classify="甄别上传" />
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<el-form :model="state.redoForm" label-width="110px" ref="redoFormRef" v-if="state.processType === '工单重办'">
					<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.title }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="申请人"> {{ userInfos.name }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="申请部门"> {{ userInfos.orgName }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="申请时间"> {{ formatDate(Date(), '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="orderRedoReason" :rules="[{ required: true, message: '请选择重办理由', trigger: 'change' }]">
								<el-select v-model="state.redoForm.orderRedoReason" placeholder="请选择重办理由" clearable class="w100">
									<el-option v-for="item in orderRedoReasonOptions" :value="item.key" :key="item.key" :label="item.value" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
							<el-form-item label="重办意见" prop="redoOpinion" :rules="[{ required: true, message: '请填写重办意见', trigger: 'blur' }]">
								<common-advice
									@chooseAdvice="chooseAdviceRedo"
									v-model="state.redoForm.redoOpinion"
									placeholder="请填写重办意见"
									:loading="state.loading"
									:commonEnum="commonEnum.OrderCirculation"
								/>
							</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="annexListRedoRef" :businessId="state.orderDetail.id" classify="重办上传" />
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>

			<el-form :model="state.ruleForm" label-width="100px" ref="ruleFormRef" v-show="activeStep === 1">
				<el-row :gutter="10">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="!returnArr.includes(state.processType)">
						<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.code" :label="item.name" :value="item.code" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="!returnArr.includes(state.processType)">
						<el-form-item label="处理人" prop="nextHandlers" :rules="[{ required: false, message: '请选择处理人', trigger: 'change' }]">
							<el-select
								v-model="state.ruleForm.nextHandlers"
                multiple
								filterable
								placeholder="请选择处理人"
								class="w100"
								@change="selectHandlers"
								value-key="id"
								clearable
                collapse-tags
                collapse-tags-tooltip
							>
								<el-option v-for="item in state.handlerOptions" :key="item.id" :label="item.name" :value="item" />
							</el-select>
						</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.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="['Sms'].includes(<string>formComponents)">
						<el-form-item label="短信通知" prop="isSms">
							<el-checkbox v-model="state.ruleForm.isSms" label="短信通知" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="['ApplyDelayProvince'].includes(<string>formComponents)">
						<el-form-item label="省延期申请" prop="applyDelayProvince">
							<el-checkbox v-model="state.ruleForm.applyDelayProvince" label="省延期申请" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="['Timelimit'].includes(<string>formComponents)">
						<el-form-item label="办理时限">
							<el-row :gutter="10">
								<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
									<el-form-item label="" prop="timeLimitCount" :rules="[{ required: true, message: '请输入办理时限数量', trigger: 'blur' }]">
										<el-input-number
											placeholder="办理时限数量"
											v-model="state.ruleForm.timeLimitCount"
											controls-position="right"
											class="w100"
										></el-input-number>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
									<el-form-item
										label=""
										label-width="0"
										prop="timeLimitUnit"
										:rules="[{ required: true, message: '请选择办理时限单位', trigger: 'change' }]"
									>
										<el-select v-model="state.ruleForm.timeLimitUnit" placeholder="办理时限单位" clearable>
											<el-option v-for="item in channelOptions" :value="item.key" :key="item.key" :label="item.value" />
										</el-select>
									</el-form-item>
								</el-col>
							</el-row>
						</el-form-item>
					</el-col>
					<!--  办理流程展示期满时间  -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="handelArr.includes(state.processType)">
						<el-form-item label="期满时间" prop="expiredTime" :rules="[{ required: true, message: '请选择期满时间', trigger: 'change' }]">
							<el-date-picker
								v-model="state.ruleForm.expiredTime"
								type="datetime"
								placeholder="请选择期满时间"
								value-format="YYYY-MM-DD[T]HH:mm:ss"
								class="w100"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<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="否" :disabled="!showMainHandler"/>
						</el-form-item>
					</el-col>
					<!--  汇总节点需要输入  -->
					<template v-if="isCollect">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="办理人姓名" prop="realHandlerName" :rules="[{ required: true, message: '请填写办理人姓名', trigger: 'blur' }]">
								<el-input v-model="state.ruleForm.realHandlerName" placeholder="请填写办理人姓名" clearable> </el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="办理人电话" prop="realHandlerPhone" :rules="[{ required: true, message: '请填写办理人电话', trigger: 'blur' }]">
								<el-input v-model="state.ruleForm.realHandlerPhone" placeholder="请填写办理人电话" clearable> </el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="沟通方式" prop="realCommunicationMode" :rules="[{ required: true, message: '请选择沟通方式', trigger: 'change' }]">
								<el-select v-model="state.ruleForm.realCommunicationMode" placeholder="请选择沟通方式" class="w100">
									<el-option v-for="item in communicationModeOptions" :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">
							<el-form-item label="沟通时间" prop="realCommunicationTime" :rules="[{ required: true, message: '请选择沟通时间', trigger: 'change' }]">
								<el-date-picker
									v-model="state.ruleForm.realCommunicationTime"
									type="datetime"
									placeholder="请选择沟通时间"
									value-format="YYYY-MM-DD[T]HH:mm:ss"
									class="w100"
								/>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item
								label="沟通地点"
								prop="realCommunicationAddress"
								:rules="[{ required: true, message: '请填写沟通地点', trigger: 'blur' }]"
							>
								<el-input v-model="state.ruleForm.realCommunicationAddress" placeholder="请填写沟通地点" clearable> </el-input>
							</el-form-item>
						</el-col>
					</template>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item
							:label="state.inputPlaceholder"
							prop="opinion"
							:rules="[{ required: true, message: `请填写${state.inputPlaceholder}`, trigger: 'blur' }]"
						>
							<common-advice
								@chooseAdvice="chooseAdvice"
								v-model="state.ruleForm.opinion"
								:placeholder="'请填写' + state.inputPlaceholder"
								:loading="state.loading"
								:commonEnum="commonEnum.OrderCirculation"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="附件" prop="additions" :rules="[{ required: false, message: '请填写诉求内容', trigger: 'change' }]">
							<annex-list name="办理附件" ref="annexListRef" :businessId="state.orderDetail.id" classify="办理上传" />
						</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 && showStepsArr.includes(state.processType)">上一步</el-button>
					<el-button class="default-button" @click="onNext" :loading="state.loading" v-if="activeStep === 0 && showStepsArr.includes(state.processType)">下一步</el-button>
					<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading" v-if="activeStep === 1">提 交</el-button>
					<el-button
						type="primary"
						@click="onReject(ruleFormRef)"
						:loading="state.loading"
						v-if="activeStep === 1 && ['Reject'].includes(<string>formComponents)"
						>驳 回</el-button
					>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="processApproval">
import { defineAsyncComponent, reactive, ref, computed, watchEffect, nextTick } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import other from '/@/utils/other';
import { formatDate } from '/@/utils/formatTime';
import { useUserInfo } from '/@/stores/userInfo';
import { storeToRefs } from 'pinia';
import { commonEnum } from '/@/utils/constants';
import { OrderFlowParams, orderStartFlow } from '/@/api/business/order';
import {
	workflowNextSteps,
	workflowNext,
	workflowRecall,
	workflowPrevious,
	workflowRecallParams,
	workflowStepOptions,
	workflowRedoParams,
} from '/@/api/system/workflow';
import { redoBaseData,redoApply } from '/@/api/business/redo';

// 引入组件
const CommonAdvice = defineAsyncComponent(() => import('/@/components/CommonAdvice/index.vue')); // 常用意见
const AnnexList = defineAsyncComponent(() => import('/@/components/AnnexList/index.vue')); // 附件列表
// 定义子组件向父组件传值/事件
const emit = defineEmits(['orderProcessSuccess', 'orderProcessFailed']);
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 弹窗显示隐藏
	ruleForm: {
		//流程表单
		opinion: '', // 意见
		nextHandlers: [], // 下一节点处理人
		nextMainHandler: '', // 主办人
	},
	delayForm: {
		//延期申请表单
		timeLimitCount: 0, // 延期申请数量
		content: '', // 延期申请理由
		timeLimitUnit: '', // 延期申请单位
	},
	discernForm: {
		// 甄别表单
		content: '', // 甄别理由
	},
	redoForm: {
		// 重办表单
		content: '', // 重办理由
	},
	nextStepOptions: [], // 下一节点
	handlerOptions: [], // 处理人
	transform: 'translate(0px, 0px)', // 滚动条位置
	fileList: [], // 附件列表
	loading: false, // 提交按钮loading
	processType: 'next', // 流程状态
	workflowId: '', // 流程id
	handlerClassifies: [], //撤回处理人
	handlerMainOptions: [], // 主办人
	handleId: '', // 流程处理ID
	dialogTitle: '', // 弹窗标题
	annexName: '', // 附件标题
	inputPlaceholder: '', // 意见提示
	orderDetail: {}, // 工单详情
});
const ruleFormRef = ref<RefType>(); //表单组件
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息
const channelOptions = [
	{
		key: '天',
		value: '天',
	},
	{
		key: '小时',
		value: '小时',
	},
	{
		key: '分钟',
		value: '分钟',
	},
]; // 延期申请单位
const showStepsArr = ['延期申请', '甄别申请', '工单重办']; // 显示步骤条的流程
const handelArr = ['工单办理']; // 处于办理状态的流程 （如果是汇总节点 需要填写处理人等  办理流程才有期满时间）
const returnArr = ['工单退回']; // 退回流程 (退回流程不需要展示其他 只需要填写意见和附件即可)
const formComponents = ref<string>(); // 表单组件
const communicationModeOptions = ref<EmptyArrayType>([]); // 沟通方式
const timeTypeOptions = ref<EmptyArrayType>([]); // 延期申请单位
const orderRedoReasonOptions = ref<EmptyArrayType>([]); // 重办理由
const handleResult = (res: any) => {
	state.nextStepOptions = res.result.steps; //处理人选择内容
	state.handleId = res.result.id; //流程ID
	formComponents.value = res.result.components ?? []; // 表单组件
	communicationModeOptions.value = res.result.communicationModeOptions ?? []; // 沟通方式
	timeTypeOptions.value = res.result.timeTypeOptions ?? []; // 时间单位
	if (handelArr.includes(state.processType)) {
		// 办理才有期满时间
		state.ruleForm.expiredTime = res.result.expiredTime ?? null; // 期满时间
	}
	if (state.nextStepOptions.length === 1) {
		// 下一节点是否只有一个 默认选中第一个
		state.ruleForm.nextStepCode = state.nextStepOptions[0].code; // 下一节点
		getNextStepOption(res.result.id, state.nextStepOptions[0].code); // 查询流程下一节点参数
		isCollect.value = state.nextStepOptions[0].stepType === 3 && handelArr.includes(state.processType); // 是否是汇总节点（汇总需要填入其他参数）
	} else {
		state.ruleForm.nextStepCode = '';
		isCollect.value = false;
	}
};
// 打开弹窗
const openDialog = async (val: any) => {
	console.log(val);
	const { id, processType, extra, orderDetail } = val;
	state.ruleForm.workflowId = state.workflowId = id ?? ''; // 流程id
	state.processType = processType ?? '办理流程'; // 业务类型
	state.orderDetail = orderDetail ?? {}; // 工单详情
	const { dialogTitle, inputPlaceholder, annexName } = extra ?? {};
	state.dialogTitle = dialogTitle ?? '提交流程'; // 流程标题
	state.annexName = annexName ?? '办理附件'; // 附件标题
	state.inputPlaceholder = inputPlaceholder ?? '办理意见'; // 意见提示
	let res: any = {};
	switch (state.processType) {
		case '工单发起': //开始流程
			res = await OrderFlowParams(); //获取开启流程参数
			handleResult(res);
			break;
		case '工单撤回': // 撤回流程
			res = await workflowRecallParams(state.workflowId); //撤回参数
			handleResult(res);
			break;
		case '延期申请': // 延期申请
			res = await OrderFlowParams(); //获取开启流程参数
			handleResult(res);
			break;
		case '甄别申请': // 甄别申请
			res = await OrderFlowParams(); //获取开启流程参数
			handleResult(res);
			break;
		case '工单重办': // 工单重办
			res = await workflowRedoParams(state.workflowId); //获取开启流程参数
      const response = await redoBaseData();// 重办基础数据
      orderRedoReasonOptions.value = response.result?.orderRedoReasonOptions ?? [];
			handleResult(res);
			break;
		case '工单退回': // 退回流程
			break;
		case '工单办理': // 工单办理
			res = await workflowNextSteps(state.workflowId);
			handleResult(res);
			break;
		default: // 默认下一流程 工单办理
			res = await workflowNextSteps(state.workflowId);
			handleResult(res);
			break;
	}
	state.dialogVisible = true;
	await nextTick(() => {
		restForm(ruleFormRef.value);
	});
};
// 上一部
const onPrevious = () => {
	activeStep.value = 0;
};
const delayFormRef = ref<RefType>(); //延期申请表单组件
const discernFormRef = ref<RefType>(); //甄别申请表单组件
const redoFormRef = ref<RefType>(); //重办表单组件
// 下一步
const onNext = () => {
	switch (state.processType) {
		case '延期申请':
			delayFormRef.value?.validate((valid: boolean) => {
				if (!valid) return;
				activeStep.value = 1;
			});
			break;
		case '甄别申请': // 甄别申请
			discernFormRef.value?.validate((valid: boolean) => {
				if (!valid) return;
				activeStep.value = 1;
			});
			break;
		case '工单重办':
			redoFormRef.value?.validate((valid: boolean) => {
				if (!valid) return;
				activeStep.value = 1;
			});
			break;
		default: // 默认下一流程
			activeStep.value = 1;
			break;
	}
};
const activeStep = ref(0); //步骤条
watchEffect(() => {
	if (state.dialogVisible) {
		activeStep.value = showStepsArr.includes(state.processType) ? 0 : 1;
	}
});
// 流程选择下一环节
const isCollect = ref(false); // 是否是汇总节点（汇总需要填入其他参数）
const selectNextStep = (val: any) => {
	ruleFormRef.value.resetFields('nextHandlers');
	ruleFormRef.value.resetFields('nextMainHandler');
	let next: any;
	next = state.nextStepOptions.find((item: any) => item.code === val);
	getNextStepOption(state.handleId, next.code);
	isCollect.value = next.stepType === 3 && handelArr.includes(state.processType); // 是否是汇总节点（汇总需要填入其他参数）
};
// 查询流程下一节点参数
const getNextStepOption = async (DefineId: string, Code: string) => {
	try {
		const res: any = await workflowStepOptions({ DefineId, Code });
		state.handlerOptions = res.result.handlers ?? [];
	} catch (error) {
		console.log(error);
	}
};
// 选择处理人
const selectHandlers = () => {
	ruleFormRef.value?.resetFields('nextMainHandler');
	if (state.ruleForm.nextHandlers.length > 1) {
		state.ruleForm.nextMainHandler = state.ruleForm.nextHandlers[0].id;
	}
};
const showMainHandler = computed(() => {
	return state.ruleForm.nextHandlers.length > 1;
});
// 主办从处理人中选择
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.handlerOptions = [];
  state.ruleForm.nextHandlers =  []
  state.ruleForm.opinion = '';
	delayFormRef.value?.clearValidate();
	delayFormRef.value?.resetFields();
	discernFormRef.value?.clearValidate();
	discernFormRef.value?.resetFields();
	formEl.resetFields();
	formEl.clearValidate();
};
// 选择常用意见 填入填写框 办理
const chooseAdvice = (item: any) => {
	state.ruleForm.opinion += item.content;
};
// 选择常用意见 填入填写框 延期
const chooseAdviceDelay = (item: any) => {
	state.delayForm.content += item.content;
};
// 选择常用意见 填入填写框 甄别
const chooseAdviceDiscern = (item: any) => {
	state.discernForm.content += item.content;
};
// 选择常用意见 填入填写框 重办
const chooseAdviceRedo = (item: any) => {
	state.redoForm.redoOpinion += item.content;
};
const afterSubmit = (emitType?: 'orderProcessSuccess' | 'orderProcessFailed', showMessage?: boolean) => {

	state.loading = false;
	closeDialog();
	if (showMessage) ElMessage.success('操作成功');
	if (emitType) emit(emitType);
};
const close = () => {
  restForm(ruleFormRef.value);
};
// 提交
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].id;
					}
				}
				submitObj.extension = {
					applyDelayProvince: submitObj.applyDelayProvince,
					isSms: submitObj.isSms,
					timeLimitCount: submitObj.timeLimitCount,
					timeLimitUnit: submitObj.timeLimitUnit,
				};
				Reflect.deleteProperty(submitObj, 'applyDelayProvince');
				Reflect.deleteProperty(submitObj, 'isSms');
				Reflect.deleteProperty(submitObj, 'timeLimitCount');
				Reflect.deleteProperty(submitObj, 'timeLimitUnit');

				switch (state.processType) {
					case '工单发起': //开始流程
            const request = {
              data: { ...state.orderDetail },
              workflow: submitObj,
            };
						orderStartFlow(request)
							.then(() => {
								afterSubmit('orderProcessSuccess', true);
							})
							.catch(() => {
								afterSubmit('orderProcessFailed');
							});
						break;
					case '工单撤回': // 撤回流程
						workflowRecall(submitObj)
							.then(() => {
								afterSubmit('orderProcessSuccess', true);
							})
							.catch(() => {
								afterSubmit('orderProcessFailed');
							});
						break;
					case '工单延期': // 撤回流程
						break;
					case '工单甄别': // 撤回流程
						break;
					case '工单重办': // 撤回流程
            const requestRedo = {
              data: {
                orderId:state.orderDetail.id,
                orderRedoReason:state.redoForm.orderRedoReason,
                redoOpinion:state.redoForm.redoOpinion,
               },
              workflow: submitObj,
            };
            redoApply(requestRedo).then(() => {
              afterSubmit('orderProcessSuccess', true);
            })
                .catch(() => {
                  afterSubmit('orderProcessFailed');
                });
						break;
					case '工单退回': // 退回流程
						workflowPrevious(submitObj)
							.then(() => {
								afterSubmit('orderProcessSuccess', true);
							})
							.catch(() => {
								afterSubmit('orderProcessFailed');
							});
						break;
					case '工单办理': // 工单办理流程
						workflowNext(submitObj)
							.then(() => {
								afterSubmit('orderProcessSuccess', true);
							})
							.catch(() => {
								afterSubmit('orderProcessFailed');
							});
						break;
					default: // 默认工单办理
						workflowNext(submitObj)
							.then(() => {
								afterSubmit('orderProcessSuccess', true);
							})
							.catch(() => {
								afterSubmit('orderProcessFailed');
							});
						break;
				}
			})
			.catch(() => {});
	});
};
// 否决
const onReject = (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(() => {})
			.catch(() => {});
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
