<template>
	<el-dialog
		v-model="state.dialogVisible"
		draggable
		:title="state.dialogTitle"
		ref="dialogRef"
		@mouseup="mouseup"
		:style="'transform: ' + state.transform + ';'"
		destroy-on-close
		:close-on-click-modal="false"
		@close="close"
		:modal-class="isOrderAccept ? 'modal_class' : ''"
		:class="isOrderAccept ? 'dialog_class' : ''"
		:append-to-body="!isOrderAccept"
		:modal="!isOrderAccept"
	>
		<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>
<!--		{{ seatTopaidan ? '话务部到派单组' : '' }}
		{{ seatToOrgOne ? '话务部到一级部门' : '' }}
		{{ paidanToOrgOne ? '派单组到一级部门' : '' }}-->
		<div v-show="activeStep === 0" v-loading="state.loading">
			<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(new 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" v-loading="state.loading">
						<el-form-item prop="timeLimitCount" :rules="[{ required: true, message: '请填写延期申请数量', trigger: 'blur' }]" label-width="130px">
							<template #label>
								<div style="height: 34px; display: flex; align-items: center">
									延期申请数量
									<el-tooltip placement="top-start">
										<SvgIcon name="ele-QuestionFilled" size="18px" class="ml3" />
										<template #content> 延期申请数量为1-{{ AppConfigInfo.applyDelayTime }} </template>
									</el-tooltip>
								</div>
							</template>
							<el-row :gutter="10" class="w100">
								<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
									<el-input-number
										placeholder="延期申请数量"
										v-model="state.delayForm.timeLimitCount"
										controls-position="right"
										:min="1"
										:max="AppConfigInfo.applyDelayTime"
										class="w100"
									></el-input-number>
								</el-col>
								<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-loading="state.loading">
									<el-form-item
										label=""
										label-width="0"
										prop="timeLimitUnit"
										:rules="[{ required: true, message: '请选择延期申请单位', trigger: 'change' }]"
									>
										<el-select disabled v-model="state.delayForm.timeLimitUnit" placeholder="延期申请单位">
											<el-option v-for="item in timeType" :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="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="commonOpinionType"
								:maxlength="AppConfigInfo.handleOpinionWordLimit"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="附件">
							<annex-list name="延期附件" v-model:format="handleFilesDelay" :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="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="commonOpinionType"
								:maxlength="AppConfigInfo.handleOpinionWordLimit"
							/>
						</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.id"
								classify="甄别上传"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<el-form :model="state.terminateForm" label-width="110px" ref="terminateFormRef" 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="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="终止理由" prop="content" :rules="[{ required: true, message: '请填写终止申请理由', trigger: 'blur' }]">
							<common-advice
								@chooseAdvice="chooseAdviceTerminate"
								v-model="state.terminateForm.content"
								placeholder="请填写终止申请理由"
								:loading="state.loading"
								:commonEnum="commonOpinionType"
								:maxlength="AppConfigInfo.handleOpinionWordLimit"
							/>
						</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="terminateAnnexListRef"
								v-model:format="handleFilesTerminate"
								:businessId="state.orderDetail.id"
								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">
				<!-- 审批流程 -->
				<template v-if="auditArr.includes(state.processType) && canReject">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="!returnArr.includes(state.processType)">
						<el-form-item label="审批结果" prop="isPass" :rules="[{ required: true, message: '请选择审批结果', trigger: 'change' }]">
							<el-radio-group v-model="state.ruleForm.isPass">
								<el-radio :value="true">同意</el-radio>
								<el-radio :value="false">不同意</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<!-- 审批通过 -->
					<template v-if="state.ruleForm.isPass">
						<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="!returnArr.includes(state.processType) && showHandlers">
							<el-form-item
								label="办理对象"
								prop="nextHandlers"
								:rules="[{ required: nextHandlersRequired, message: '请选择办理对象', trigger: 'change' }]"
								v-if="!returnArr.includes(state.processType) && showHandlers"
							>
								<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>
					</template>
					<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-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="commonOpinionType"
								:maxlength="AppConfigInfo.handleOpinionWordLimit"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="附件" :rules="[{ required: false, message: '请填写诉求内容', trigger: 'change' }]">
							<annex-list :name="state.annexName" :businessId="state.orderDetail.id" :classify="state.classify" v-model:format="handleFiles" />
						</el-form-item>
					</el-col>
				</template>
				<!-- 办理流程 -->
				<template v-else>
					<!-- 非退回流程都需要选择 -->
					<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.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="!returnArr.includes(state.processType) && showHandlers">
						<el-form-item
							label="办理对象"
							prop="nextHandlers"
							:rules="[{ required: nextHandlersRequired, 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>
					<!-- 工单办理专有参数 -->
					<template v-if="flowDirection">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="办理时限" prop="timeLimit" :rules="[{ required: true, message: '请填写办理时限', trigger: 'blur' }]">
								<el-row :gutter="10">
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
										<el-input-number
											placeholder="办理时限"
											v-model="state.ruleForm.timeLimit"
											controls-position="right"
											class="w100"
											:min="1"
											:max="99"
											disabled
										></el-input-number>
									</el-col>
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-loading="state.loading">
										<el-form-item
											label=""
											label-width="0"
											prop="timeLimitUnit"
											:rules="[{ required: true, message: '请选择办理时限单位', trigger: 'change' }]"
										>
											<el-select v-model="state.ruleForm.timeLimitUnit" placeholder="办理时限单位" disabled style="width: 240px">
												<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>
					</template>
					<!-- 话务部到一级部门  派单组到一级部门	-->
					<template v-if="seatToOrgOne || paidanToOrgOne">
						<el-col :span="24">
							<el-form-item label="派单类型" prop="orderAssignMode" :rules="[{ required: true, message: '请选择派单类型', trigger: 'change' }]">
								<el-radio-group v-model="state.ruleForm.orderAssignMode" @change="selectDispatchType">
									<el-radio :value="0">逐级派单</el-radio>
									<el-radio :value="1">跨级派单</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="state.ruleForm.orderAssignMode === 0">
									<el-form-item label="接办部门" prop="nextHandlers" :rules="[{ required: true, message: '请选择接办部门', trigger: 'change' }]">
										<!--										<el-select v-model="state.ruleForm.paidanObj" placeholder="请选择接办部门" class="w100" filterable multiple>
											<el-option v-for="item in state.paidanObjOptions" :key="item.key" :label="item.value" :value="item.key" />
										</el-select>-->
										<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 :span="24" v-if="state.ruleForm.orderAssignMode === 1">
							<el-row class="w100" :gutter="10">
								<el-col>
									<el-form-item label="接办部门" prop="nextHandler" :rules="[{ required: true, message: '请选择接办部门', trigger: 'change' }]">
										<el-select-v2
											v-model="state.ruleForm.nextHandler"
											:options="state.handlerOptions"
											placeholder="请选择接办部门"
											class="w100"
											clearable
											filterable
											value-key="key"
											@change="selectHandlers"
										/>
									</el-form-item>
								</el-col>
								<!-- 二级部门 -->
								<template v-if="showOrgLevelTwo">
									<el-col :span="12">
										<el-form-item label="下一环节" prop="levelTwoStep" :rules="[{ required: false, message: '请选择下一环节', trigger: 'change' }]">
											<el-select-v2
												v-model="state.ruleForm.levelTwoStep"
												:options="levelTwoStepOptions"
												placeholder="请选择下一环节"
												class="w100"
												filterable
												value-key="key"
												clearable
												@change="selectOrgLevelTwo"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item
											label="办理对象"
											prop="levelTwoHandlers"
											:rules="[{ required: false, message: '请选择办理对象', trigger: 'change' }]"
										>
											<el-select-v2
												v-model="state.ruleForm.levelTwoHandlers"
												:options="levelTwoHandleOptions"
												placeholder="请选择办理对象"
												class="w100"
												clearable
												filterable
												value-key="key"
												multiple
												collapse-tags
												collapse-tags-tooltip
												:max-collapse-tags="1"
												@change="selectOrgLevelTwoHandler"
											/>
										</el-form-item>
									</el-col>
								</template>
								<!-- 三级部门 -->
								<template v-if="showOrgLevelThree">
									<el-col :span="12">
										<el-form-item label="下一环节" prop="levelThreeStep" :rules="[{ required: false, message: '请选择下一环节', trigger: 'change' }]">
											<el-select-v2
												v-model="state.ruleForm.levelThreeStep"
												:options="levelThreeStepOptions"
												placeholder="请选择下一环节"
												class="w100"
												filterable
												value-key="key"
												clearable
												@change="selectOrgLevelThree"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item
											label="办理对象"
											prop="levelTwoHandlers"
											:rules="[{ required: false, message: '请选择办理对象', trigger: 'change' }]"
										>
											<el-select-v2
												v-model="state.ruleForm.levelThreeHandlers"
												:options="levelThreeHandleOptions"
												placeholder="请选择办理对象"
												class="w100"
												clearable
												filterable
												value-key="key"
												multiple
												collapse-tags
												collapse-tags-tooltip
												:max-collapse-tags="1"
												@change="selectOrgLevelThreeHandler"
											/>
										</el-form-item>
									</el-col>
								</template>
							</el-row>
						</el-col>
					</template>
					<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>
					<!--  汇总节点需要填写 并且是工单办理 -->
					<template v-if="inputRealHandler">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="经办人" prop="realHandlerName" :rules="[{ required: false, 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: false, message: '请填写经办人电话', trigger: 'blur' }]">
								<el-input v-model="state.ruleForm.realHandlerPhone" placeholder="请填写办理人电话" 请填写经办人电话> </el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="是否与市民沟通" prop="realIsContacted">
								<el-switch v-model="state.ruleForm.realIsContacted" inline-prompt active-text="是" inactive-text="否" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="是否与市民现场沟通" prop="realContactLocale" label-width="150">
								<el-switch v-model="state.ruleForm.realContactLocale" inline-prompt active-text="是" inactive-text="否" />
							</el-form-item>
						</el-col>
					</template>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="isSmsSelectShow">
						<el-form-item label="" prop="isSms">
							<el-checkbox v-model="state.ruleForm.isSms" label="短信通知" />
						</el-form-item>
					</el-col>
					<!--  选择结束节点时并且是工单办理并且不是中心，显示部门处理结果 -->
					<template v-if="showResult">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="处理结果" prop="isResolved" :rules="[{ required: true, message: '请选择处理结果', trigger: 'change' }]">
								<el-radio-group v-model="state.ruleForm.isResolved">
									<el-radio :value="true">已得到解决</el-radio>
									<el-radio :value="false">未得到解决</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</template>
					<!--  选择结束节点时并且是工单办理并且工单来源是110时，显示警情退回 -->
					<template v-if="showPoliceReturn">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="" prop="isPoliceReturn">
								<el-checkbox v-model="state.ruleForm.isPoliceReturn" label="警情退回" />
							</el-form-item>
						</el-col>
					</template>
					<template v-if="!['延期申请', '甄别申请', '终止申请'].includes(state.processType)">
						<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="commonOpinionType"
									:maxlength="AppConfigInfo.handleOpinionWordLimit"
								/>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="showRemarkTextarea">
							<el-form-item label="备注信息" prop="remark" :rules="[{ required: false, message: `请填写备注信息`, trigger: 'blur' }]">
								<el-input v-model="state.ruleForm.remark" :rows="2" type="textarea" placeholder="请填写备注信息" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
							<el-form-item label="附件" :rules="[{ required: false, message: '请填写诉求内容', trigger: 'change' }]">
								<annex-list :name="state.annexName" :businessId="state.orderDetail.id" :classify="state.classify" v-model:format="handleFiles" />
							</el-form-item>
						</el-col>
					</template>
				</template>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-text type="danger" class="mr15" tag="b" v-if="showTempSave">温馨提示：临时保存只保存{{ state.inputPlaceholder }}</el-text>
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="handleTempSave" :loading="state.loading" v-if="showTempSave">临时保存</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-popconfirm
					title="该工单属于超期状态，若符合延期要求，请延期通过后办结，是否继续办理？"
					v-if="isOverdueTips"
					@confirm="onSubmit(ruleFormRef)"
					width="300"
				>
					<template #reference>
						<el-button type="primary" :loading="state.loading">办理</el-button>
					</template>
				</el-popconfirm>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading" v-else-if="!isOverdueTips && activeStep === 1"
					>办理</el-button
				>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="processApproval">
import { computed, defineAsyncComponent, nextTick, reactive, ref, watch, watchEffect } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import other from '@/utils/other';
import { useUserInfo } from '@/stores/userInfo';
import { storeToRefs } from 'pinia';
import { commonEnum } from '@/utils/constants';
import { orderAssignParams, orderFlowParams, orderHandle, orderProcessTempSave, orderStartFlow, orderTimeConfig } from '@/api/business/order';
import {
	orderPrevious,
	workflowNext,
	workflowNextSteps,
	workflowNextStepsByOrder,
	workflowNextStepsByOrderInstead,
	workflowPrevious,
	workflowRecall,
	workflowRecallParams,
	workflowReject,
} from '@/api/system/workflow';
import { delayApply, delayApproveParams, delayBaseData, workflowDelayParams } from '@/api/business/delay';
import { discernApply, discernApproveParams, screenBaseData, workflowDiscernParams } from '@/api/business/discern';
import {
	KnowledgeAdd,
	KnowledgeAddStartFlowParams,
	KnowledgeDel,
	KnowledgeDeleteStartFlowParams,
	KnowledgeOffShelf,
	KnowledgeOffShelfStartFlowParams,
	KnowledgeUpdate,
	KnowledgeUpdateStartFlowParams,
} from '@/api/knowledge';
import { formatDate } from '@/utils/formatTime';
import { useAppConfig } from '@/stores/appConfig';
import { terminateNextFlowParams, terminateStartFlow, terminateStartFlowParams } from '@/api/business/terminate';

// 引入组件
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: {
		isPass: true, // 审批结果
		//流程表单
		opinion: '', // 意见
		nextStepCode: '', // 下一节点
		nextStepName: '', // 下一节点名称
		backToCountersignEnd: false, // 是否回到会签结束节点
		nextHandlers: [], // 下一节点办理对象
		nextMainHandler: '', // 主办人
		isSms: false, // 是否短信通知
		isStartCountersign: false, // 是否发起会签
		stepId: null, // 步骤id
		// isTransferHandle:false, // 是否转办
		orderAssignMode: 0, // 派单类型默认逐级派单
	},
	delayForm: {
		//延期申请表单
		timeLimitCount: null, // 延期申请数量
		content: '', // 延期申请理由
		timeLimitUnit: 2, // 延期申请单位 默认工作日
	},
	discernForm: {
		// 甄别表单
		content: '', // 甄别理由
	},
	redoForm: {
		// 重办表单
		content: '', // 重办理由
	},
	terminateForm: {
		//终止表单
		content: '', // 终止理由
	},
	nextStepOptions: [], // 下一节点
	handlerOptions: [], // 办理对象
	transform: 'translate(0px, 0px)', // 滚动条位置
	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 showStepsArr = ['延期申请', '甄别申请', '终止申请']; // 显示步骤条的流程
const handelArr = ['工单办理']; // 处于办理状态的流程 （如果是汇总节点 需要填写办理对象等  办理流程才有期满时间）
const returnArr = ['工单退回', '甄别退回', '延期退回', '终止退回']; // 退回流程 (退回流程不需要展示其他 只需要填写意见和附件即可)
const auditArr = ['甄别审批', '延期审批', '知识审批', '终止审批']; // 审批流程 (审批流程需要选择是否通过和下一环节)
const appConfigStore = useAppConfig();
const { AppConfigInfo } = storeToRefs(appConfigStore); // 系统配置信息
const showTempSave = computed(() => {
	// 是否显示临时办理
	return ['工单办理', '工单代办', '工单受理'].includes(state.processType);
});
const timeType = ref<EmptyArrayType>([]); // 延期申请单位
const screenTypeOptions = ref<EmptyArrayType>([]); // 甄别类型
const screenType = ref(null); // 甄别类型  自贡甄别特殊需求
// 打开弹窗
const openDialog = async (val: any) => {
	console.log(val);
	selectNext.value = {};
	currentParams.value = {};
	state.ruleForm.nextHandlers = [];
	state.ruleForm.nextHandler = {};
	isSmsSelectShow.value = false;
	state.ruleForm.isSms = false;
	state.loading = true;
	state.dialogVisible = true;
	try {
		const { id, processType, extra, orderDetail } = val;
		state.ruleForm.workflowId = state.workflowId = id ?? ''; // 流程id
		state.processType = processType ?? '办理流程'; // 业务类型
		state.orderDetail = orderDetail ?? {}; // 工单详情
		const { dialogTitle, inputPlaceholder, annexName, classify } = extra ?? {};
		state.dialogTitle = dialogTitle ?? '提交流程'; // 流程标题
		state.annexName = annexName ?? '办理附件'; // 附件标题
		state.classify = classify ?? '办理上传'; // 附件分类
		state.inputPlaceholder = inputPlaceholder ?? '办理意见'; // 意见提示
		screenType.value = extra.screenType;
		switch (state.processType) {
			case '工单受理': //开始流程
				const [orderStartWorkflowResponse] = await Promise.all([orderFlowParams(orderDetail.id)]); //获取开启流程参数
				handleResult(orderStartWorkflowResponse);
				break;
			case '工单撤回': // 撤回流程
				const [workflowRecallResponse] = await Promise.all([workflowRecallParams(state.workflowId)]); //获取开启流程参数
				handleResult(workflowRecallResponse);
				break;
			case '延期申请': // 延期申请
				const [workflowDelayResponse, responseDelay] = await Promise.all([workflowDelayParams(), delayBaseData()]); //获取开启流程参数
				timeType.value = responseDelay.result?.timeType ?? []; // 延期时间单位
				handleResult(workflowDelayResponse);
				break;
			case '延期审批': // 延期审批
				const [nextResponseDelayAudit] = await Promise.all([delayApproveParams(state.workflowId)]); //获取延期审批流程参数
				handleResult(nextResponseDelayAudit);
				break;
			case '甄别申请': // 甄别申请
				const [workflowDiscernResponse, responseDiscern] = await Promise.all([workflowDiscernParams(), screenBaseData()]); //获取开启流程参数
				screenTypeOptions.value = responseDiscern.result?.screenType ?? []; // 甄别理由
				handleResult(workflowDiscernResponse);
				break;
			case '终止申请': // 终止申请
				const [workflowTerminateResponse] = await Promise.all([terminateStartFlowParams()]); //获取开启流程参数
				handleResult(workflowTerminateResponse);
				break;
			case '工单退回': // 退回流程
				break;
			case '甄别退回': // 退回流程
				break;
			case '甄别审批': // 甄别审批
				const [nextResponseDiscernAudit] = await Promise.all([discernApproveParams(state.workflowId)]); //获取甄别审批流程参数
				handleResult(nextResponseDiscernAudit);
				break;
			case '终止审批': // 终止审批
				const [nextResponseTerminateAudit] = await Promise.all([terminateNextFlowParams(state.workflowId)]); //获取终止审批流程参数
				handleResult(nextResponseTerminateAudit);
				break;
			case '延期退回': // 退回流程
				break;
			case '工单办理': // 工单办理
				const [workflowNextStepsResponse] = await Promise.all([workflowNextStepsByOrder(state.orderDetail.id)]); // 获取下一节点和下一节点参数
				handleResult(workflowNextStepsResponse);
				break;
			case '工单代办':
				const [orderHandleInstanceResponse] = await Promise.all([workflowNextStepsByOrderInstead(state.orderDetail.id)]); // 工单代办参数获取
				handleResult(orderHandleInstanceResponse);
				break;
			case '新增知识':
				const [KnowledgeAddStartFlowResponse] = await Promise.all([KnowledgeAddStartFlowParams()]); // 知识库新增参数
				handleResult(KnowledgeAddStartFlowResponse);
				break;
			case '更新知识':
				const [KnowledgeUpdateResponse] = await Promise.all([KnowledgeUpdateStartFlowParams()]); // 知识库更新参数
				handleResult(KnowledgeUpdateResponse);
				break;
			case '更新新增知识':
				const [KnowledgeAddUpdateResponse] = await Promise.all([KnowledgeAddStartFlowParams()]); // 知识库更新参数
				handleResult(KnowledgeAddUpdateResponse);
				break;
			case '删除知识':
				const [KnowledgeDeleteResponse] = await Promise.all([KnowledgeDeleteStartFlowParams()]); // 知识库删除参数
				handleResult(KnowledgeDeleteResponse);
				break;
			case '知识下架':
				const [KnowledgeOffShelfResponse] = await Promise.all([KnowledgeOffShelfStartFlowParams()]); // 知识库下架参数
				handleResult(KnowledgeOffShelfResponse);
				break;
			default: // 默认下一流程 工单办理
				// 获取下一节点和下一节点参数
				const [nextResponse] = await Promise.all([workflowNextSteps(state.workflowId)]);
				handleResult(nextResponse);
				break;
		}
		await nextTick(() => {
			restForm(ruleFormRef.value);
		});
	} finally {
		state.loading = false;
	}
};
const isOrderAccept = computed(() => {
	return state.processType === '工单受理';
});
// 常用意见类型
const commonOpinionType = computed(() => {
	switch (state.processType) {
		case '工单受理':
			return commonEnum.Seat;
		case '工单退回':
			return commonEnum.Return;
		case '工单办理':
			return commonEnum.OrderCirculation;
		case '甄别审批':
		case '甄别申请':
			return commonEnum.Discriminate;
		case '延期审批':
		case '延期申请':
			return commonEnum.Delay;
		case '终止审批':
		case '终止申请':
			return commonEnum.OrderCirculation;
		case '知识审批':
			return commonEnum.KnowledgeL;
		default:
			return commonEnum.OrderCirculation;
	}
});
const canReject = ref<boolean>(false); // 是否可以驳回
const timeTypeOptions = ref<EmptyArrayType>([]); // 办理时限单位
const canStartCountersign = ref<boolean>(false); // 是否可以发起会签
const isMainHandlerShow = ref<boolean>(false); // 是否展示主办人
const currentParams = ref<EmptyObjectType>({}); // 当前获取到的参数（当前节点信息）
const handleResult = (res: any) => {
	currentParams.value = res.result; // 当前获取到的参数（当前节点信息）
	state.nextStepOptions = res.result.steps; //办理对象选择内容
	canReject.value = res.result.canReject ?? false; // 是否可以驳回
	timeTypeOptions.value = res.result.timeTypeOptions ?? []; // 办理时限申请单位
	canStartCountersign.value = res.result.canStartCountersign ?? false; // 是否可以发起会签
	isMainHandlerShow.value = res.result.isMainHandlerShow ?? false; // 是否展示主办人
	if (handelArr.includes(state.processType)) {
		// 办理才有期满时间
		state.ruleForm.expiredTime = res.result.expiredTime ?? null; // 期满时间
	}
	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; // 是否回到会签结束节点
		}, 100);
		selectNextStep(state.nextStepOptions[0].key); // 查询流程下一节点参数
	} else {
		state.ruleForm.nextStepCode = '';
		state.ruleForm.nextStepName = '';
	}
	if (res.result.opinion) {
		// 如果有汇总意见没有临时保存 取汇总意见 临时保存会覆盖汇总意见
		setTimeout(() => {
			state.ruleForm.opinion = res.result.opinion;
		}, 100);
	}
	state.ruleForm.stepId = res.result.stepId;
	state.loading = false;
};
// 上一部
const onPrevious = () => {
	activeStep.value = 0;
};
const delayFormRef = ref<RefType>(); //延期申请表单组件
const discernFormRef = ref<RefType>(); //甄别申请表单组件
const terminateFormRef = 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 '终止申请': // 终止申请
			terminateFormRef.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 fastStepCode = ref(''); // 推荐派单处理对象code
const fastStepName = ref(''); // 推荐派单处理对象
// expiredStatus 超期状态（0正常 1即将超期  2已超期）  工单流转选择“结束”节点，点击“办理”时需验证该工单是否处于已超期状态
const isOverdueTips = computed(() => {
	return state.orderDetail.expiredStatus === 2 && state.ruleForm.nextStepCode === 'end';
});
// 先确定当前环节是那一步
/*
 * currentParams.value.currentStepBusinessType 表示当前节点到哪一步 0坐席 1派单 2部门节点 3部门领导节点
 * */
/*selectNext.value.businessType 表示选择节点到哪一步  0 坐席 1派单  2部门节点  3部门领导节点
 * selectNext.value.orgLevel 表示部门等级 1 一级部门 2 二级部门 3 三级部门 4 四级部门
 * selectNext.value.stepType  0普通节点 3汇总节点
 * */
// 话务部到派单组
const seatTopaidan = computed(() => {
	return currentParams.value.currentStepBusinessType === 0 && selectNext.value.businessType === 1;
});
// 话务部到一级部门
const seatToOrgOne = computed(() => {
	return currentParams.value.currentStepBusinessType === 0 && selectNext.value.businessType === 2 && selectNext.value.orgLevel === 1;
});
// 派单组到一级部门
const paidanToOrgOne = computed(() => {
	return currentParams.value.currentStepBusinessType === 1 && selectNext.value.businessType === 2 && selectNext.value.orgLevel === 1;
});
// 是否展示短信通知选择
const isSmsSelectShow = ref(false);
// 办理对象是否必填  0-角色 1-部门类型 2-部门类型 3-指定用户 4-指定部门
// 2024/10/28 新增甄别申请 延期申请 终止申请选择办理对象非必填 !showStepsArr.includes(state.processType)
const nextHandlersRequired = ref<Boolean>(false);
const selectNext = ref<EmptyObjectType>({}); // 选择的下一个节点
const selectNextStep = (val: any) => {
	ruleFormRef.value?.resetFields('nextHandlers');
	ruleFormRef.value?.resetFields('nextMainHandler');
	state.ruleForm.nextHandlers = [];
	const next = state.nextStepOptions.find((item: any) => item.key === val);
	selectNext.value = next;
	const items = next.items; //获取下一节点
	state.ruleForm.nextStepName = next.value; // 下一节点name
	state.ruleForm.handlerType = next.handlerType;
	state.ruleForm.businessType = next.businessType;
	state.ruleForm.flowDirection = next.flowDirection;
	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
	if (items.length === 1) {
		// 如果办理对象只有一个默认选中
		state.ruleForm.nextHandlers = [items[0]];
	}
	// 办理对象是否必填
	// nextHandlersRequired.value = ![0].includes(next.handlerType) && !showStepsArr.includes(state.processType);
	nextHandlersRequired.value = ![0].includes(next.handlerType);

	// 以下是默认需要吧短信勾上的场景 话务部到一级部门 派单组到一级部门
	state.ruleForm.isSms = seatToOrgOne.value || paidanToOrgOne.value;
	// 是否展示短信通知 (取消坐席流转至“派单组”时的短信通知选项框  )
	isSmsSelectShow.value = !seatTopaidan.value;
};

//  会签是否可用 (配置可以会签 并且选择的是逐级派单，并且是普通节点 并且选择是部门)
const countersignAble = computed(() => {
	return canStartCountersign.value && state.ruleForm.orderAssignMode === 0 && selectNext.value.stepType === 0 && selectNext.value.businessType === 2;
});
// 办理对象是否能够选择多个(可以发起会签可以选择多个，不能发起会签只能选择一个) 加个判断 选择的下一环节必须是部门（会签必须是选择的部门）
const multipleLimit = computed(() => {
	return canStartCountersign.value && selectNext.value.businessType === 2 ? 0 : 1;
});
watch(
	() => state.ruleForm.nextHandlers, // 监听办理对象 多个办理对象自动发起会签
	(val) => {
		state.ruleForm.isStartCountersign = val.length > 1;
	}
);
const countersignDisabled = computed(() => {
	// (选中的办理对象如果是一个) 因为是disabled 所以这里取反
	return !(state.ruleForm.nextHandlers.length === 1);
});
// 是否发起会签
const changeStartCountersign = (val: boolean) => {
/*	if (!val) {
		// 如果不能会签清空办理对象
		state.ruleForm.nextHandlers = [];
		ruleFormRef.value?.resetFields('nextHandlers');
	}*/
};

// 是否展示办理对象 (结束节点不展示: next.stepType===2 表示为结束节点,下一环节为派单组时 next.businessType === 1，办理对象下拉框隐藏:AppConfigInfo.value.isAverageSendOrder= true 表示开启了平均派单 )
const showHandlers = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
	const isAverageSendOrder = AppConfigInfo.value.isAverageSendOrder && next?.businessType === 1; // 开启平均派单并且下一个环节是派单组  !isAverageSendOrder
	if (!next) return true;
	// 话务部到派单 派单组到一级部门 也不需要展示办理对象 如果下一环节是汇总节点与不需要展示办理
	return next?.stepType !== 2 && !(seatToOrgOne.value || paidanToOrgOne.value) && selectNext.value.stepType !== 3;
});
// 是否展示部门处理结果 （ 选择结束节点时并且当前操作人不是中心时，显示部门处理结果 ）
const showResult = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
	return next?.stepType === 2 && !userInfos.value.isCenter;
});
// 是否展示警情退回 (选择结束节点时并且工单来源是110时，显示警情退回)
const showPoliceReturn = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
	return next?.stepType === 2 && state.orderDetail?.source === 200;
});
// 是否是汇总节点（汇总需要填入其他参数）并且是工单办理
const inputRealHandler = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
	return next?.inputRealHandler && handelArr.includes(state.processType);
});
// 是否显示快捷派单
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)) {
		const next = state.handlerOptions.find((item: any) => item.value.key === fastStepCode.value);
		if (next) state.ruleForm.nextHandlers = [...state.ruleForm.nextHandlers, next.value];
	}
};
// 是否展示办理时限 flowDirection 并且是工单办理
const flowDirection = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
	if (!next) return false;
	return [0, 1].includes(next.flowDirection) && handelArr.includes(state.processType);
});
// 是否展示备注输入框
const showRemarkTextarea = computed(() => {
	return ['工单受理', '工单办理'].includes(state.processType);
});
// 计算工单期满时间
watch(
	() => flowDirection.value,
	(val) => {
		if (val) {
			const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
			state.ruleForm.flowDirection = next.flowDirection;
			orderTimeConfig({ flowDirection: next.flowDirection, acceptTypeCode: state.orderDetail.acceptTypeCode }).then((res: any) => {
				state.ruleForm.timeLimit = res.result.count ?? null; // 办理时限
				state.ruleForm.timeLimitUnit = res.result.timeType ?? ''; // 办理时限单位
			});
		}
	}
);

// 是否展示主办
const showMainHandler = computed(() => {
	return state.ruleForm.nextHandlers.length > 1 && isMainHandlerShow.value;
});
// 主办从办理对象中选择
state.handlerMainOptions = computed(() => {
	return state.ruleForm.nextHandlers;
});

// 选择派单类型 需要清空选择的内容
const selectDispatchType = () => {
	ruleFormRef.value.resetFields('nextHandlers');
	ruleFormRef.value.resetFields('nextHandler');
	state.ruleForm.nextHandlers = [];
	state.ruleForm.nextHandler = null;
	state.ruleForm.isStartCountersign = false;
	showOrgLevelTwo.value = false;
	state.ruleForm.levelTwoStep = null;
	levelTwoStepOptions.value = [];
	levelTwoHandleOptions.value = [];
	state.ruleForm.levelTwoHandlers = [];
	showOrgLevelThree.value = false;
	state.ruleForm.levelThreeStep = null;
	state.ruleForm.levelThreeHandlers = [];
	levelThreeStepOptions.value = [];
	levelThreeHandleOptions.value = [];
};

// 选择办理对象
const showOrgLevelTwo = ref(false); // 是否展示二级部门选择
const levelTwoStepOptions = ref<EmptyArrayType>([]); // 二级部门节点
const levelTwoHandleOptions = ref<EmptyArrayType>([]); // 二级部门办理参数
const selectHandlers = () => {
	if (state.ruleForm.nextHandlers && state.ruleForm.nextHandlers.length > 1) {
		// AppConfigInfo.value.noSignOrgCode  对应的办理对象不能参与会签
		const isProvince12345 = state.ruleForm.nextHandlers.find((item: any) => AppConfigInfo.value.noSignOrgCode.includes(item.key));
		if (isProvince12345) {
			// 如果选择了省12345平台或者省12345交办就提示不能参与会签 并且从选择中移除
			ElMessage({
				message: '省12345平台和省12345交办不能参与会签',
				grouping: true,
			});
			state.ruleForm.nextHandlers = state.ruleForm.nextHandlers.filter((item: any) => !AppConfigInfo.value.noSignOrgCode.includes(item.key));
		}
	}
	if (state.ruleForm.nextHandlers && state.ruleForm.nextHandlers.length <= 1) {
		// 如果只有一个办理对象就不需要发起会签
		state.ruleForm.isStartCountersign = false;
	}
	if ((seatToOrgOne.value || paidanToOrgOne.value) && state.ruleForm.orderAssignMode === 1) {
		showOrgLevelTwo.value = false;
		state.ruleForm.levelTwoStep = null;
		levelTwoStepOptions.value = [];
		levelTwoHandleOptions.value = [];
		state.ruleForm.levelTwoHandlers = [];
		showOrgLevelThree.value = false;
		state.ruleForm.levelThreeStep = null;
		state.ruleForm.levelThreeHandlers = [];
		levelThreeStepOptions.value = [];
		levelThreeHandleOptions.value = [];
		state.ruleForm.nextHandlers = [state.ruleForm.nextHandler];
		// 话务部到一级部门 派单组到一级部门 并且是跨级派单 需要查询下一级部门
		const request = {
			WorkflowId: state.ruleForm.workflowId,
			StepCode: selectNext.value.key,
			StepType: selectNext.value.stepType,
			BusinessType: selectNext.value.businessType,
			HandlerType: selectNext.value.handlerType,
			OrgIds: state.ruleForm.nextHandler ? [state.ruleForm.nextHandler.key] : [],
		};
		orderAssignParams(request).then((res: any) => {
			showOrgLevelTwo.value = true;
			levelTwoStepOptions.value = res.result.steps.map((item: any) => {
				return {
					value: {
						...item,
					},
					label: item.value,
				};
			});
			if (res.result.steps.length === 1) {
				state.ruleForm.levelTwoStep = res.result.steps[0];
				levelTwoHandleOptions.value = state.ruleForm.levelTwoStep.items.map((item: any) => {
					return {
						value: {
							...item,
						},
						label: item.value,
					};
				});
			}
		});
	} else {
		showOrgLevelTwo.value = false;
	}
};
// 选择二级部门节点
const selectOrgLevelTwo = (val: any) => {
	if (val) {
		levelTwoHandleOptions.value = state.ruleForm.levelTwoStep.items.map((item: any) => {
			return {
				value: {
					...item,
				},
				label: item.value,
			};
		});
	} else {
		levelTwoHandleOptions.value = [];
		state.ruleForm.levelTwoHandlers = [];
		state.ruleForm.levelThreeHandlers = [];
		levelThreeStepOptions.value = [];
		levelThreeHandleOptions.value = [];
		showOrgLevelThree.value = false;
	}
};
const showOrgLevelThree = ref(false);
const levelThreeStepOptions = ref<EmptyArrayType>([]); // 三级部门节点
const levelThreeHandleOptions = ref<EmptyArrayType>([]); // 三级部门办理参数
// 选择二级部门办理对象 展示三级办理对象和节点
const selectOrgLevelTwoHandler = (val: any) => {
	const ids = val.map((item: any) => item.key);
	if (val && val.length) {
		const request = {
			WorkflowId: state.ruleForm.workflowId,
			StepCode: state.ruleForm.levelTwoStep.key,
			StepType: state.ruleForm.levelTwoStep.stepType,
			BusinessType: state.ruleForm.levelTwoStep.businessType,
			HandlerType: state.ruleForm.levelTwoStep.handlerType,
			OrgIds: ids,
		};
		orderAssignParams(request).then((res: any) => {
			showOrgLevelThree.value = true;
			levelThreeStepOptions.value = res.result.steps.map((item: any) => {
				return {
					value: {
						...item,
					},
					label: item.value,
				};
			});
			if (res.result.steps.length === 1) {
				state.ruleForm.levelThreeStep = res.result.steps[0];
				levelThreeHandleOptions.value = state.ruleForm.levelThreeStep.items.map((item: any) => {
					return {
						value: {
							...item,
						},
						label: item.value,
					};
				});
			}
		});
	} else {
		state.ruleForm.levelThreeHandlers = [];
		levelThreeStepOptions.value = [];
		levelThreeHandleOptions.value = [];
		showOrgLevelThree.value = false;
	}
	/*const request = {
		WorkflowId: state.ruleForm.workflowId,
		StepCode: val.key,
		StepType: val.stepType,
		BusinessType: val.businessType,
		HandlerType: val.handlerType,
		OrgIds: state.ruleForm.nextHandler ? [state.ruleForm.nextHandler.key] : [],
	};
	console.log(request, selectNext.value);
	orderAssignParams(request).then((res: any) => {
		console.log(res);
		showOrgLevelTwo.value = true;
		levelTwoStepOptions.value = res.result.steps.map((item: any) => {
			return {
				value: {
					...item,
				},
				label: item.value,
			};
		});
		if(res.result.steps.length === 1){
			state.ruleForm.levelTwoSteps = [res.result.steps[0]];
		}
	});*/
};
// 选择三级部门节点
const selectOrgLevelThree = (val: any) => {
	if (val) {
		levelThreeHandleOptions.value = state.ruleForm.levelThreeStep.items.map((item: any) => {
			return {
				value: {
					...item,
				},
				label: item.value,
			};
		});
	} else {
		state.ruleForm.levelThreeHandlers = [];
		levelThreeHandleOptions.value = [];
	}
};
const selectOrgLevelThreeHandler = () => {};



// 设置抽屉
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 = '';
	state.delayForm.endTime = '';
	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 chooseAdviceTerminate = (item: any) => {
	state.terminateForm.content += item.content;
};
const afterSubmit = (emitType?: 'orderProcessSuccess' | 'orderProcessFailed', showMessage?: boolean, message?: string) => {
	state.loading = false;
	closeDialog();
	const msg = message ?? '操作成功';
	if (showMessage) ElMessage.success(msg);
	if (emitType) emit(emitType);
};
const close = () => {
	restForm(ruleFormRef.value);
	restForm(delayFormRef.value);
	restForm(discernFormRef.value);
	restForm(terminateFormRef.value);
	restForm(redoFormRef.value);
};
// 办理
const handleFiles = ref<EmptyArrayType>([]); // 流程附件
const handleFilesDelay = ref<EmptyArrayType>([]); // 延期附件
const handleFilesDiscern = ref<EmptyArrayType>([]); // 甄别附件
const handleFilesTerminate = ref<EmptyArrayType>([]); // 终止附件
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;

		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;
			}
		}
		if (!flowDirection.value) {
			// 需要填写办理时限
			Reflect.deleteProperty(submitObj, 'timeLimit');
			Reflect.deleteProperty(submitObj, 'timeLimitUnit');
		} else {
			submitObj.external = {
				timeLimit: state.ruleForm.timeLimit,
				timeLimitUnit: state.ruleForm.timeLimitUnit,
			};
		}
		Reflect.deleteProperty(submitObj, 'isPoliceReturn');
		Reflect.deleteProperty(submitObj, 'isResolved');
		submitObj.external = {
			isPoliceReturn: state.ruleForm.isPoliceReturn,
			isResolved: state.ruleForm.isResolved,
		};

		let crossSteps: EmptyArrayType = [];
		if (state.ruleForm.orderAssignMode === 1) {
			// 如果选中了跨级派单
			const levelOneParams = {
				// 一级部门
				nextStepCode: state.ruleForm.nextStepCode,
				nextStepName: state.ruleForm.nextStepName,
				flowDirection: state.ruleForm.flowDirection,
				handlerType: state.ruleForm.handlerType,
				stepType: state.ruleForm.stepType,
				businessType: state.ruleForm.businessType,
				nextHandlers: state.ruleForm.nextHandlers,
				sort: 1,
			};
			crossSteps.push(levelOneParams);
			if (state.ruleForm.levelTwoHandlers && state.ruleForm.levelTwoHandlers.length) {
				// 二级部门
				const levelTwoParams = {
					nextStepCode: state.ruleForm.levelTwoStep.key,
					nextStepName: state.ruleForm.levelTwoStep.value,
					flowDirection: state.ruleForm.levelTwoStep.flowDirection,
					handlerType: state.ruleForm.levelTwoStep.handlerType,
					stepType: state.ruleForm.levelTwoStep.stepType,
					businessType: state.ruleForm.levelTwoStep.businessType,
					nextHandlers: state.ruleForm.levelTwoHandlers,
					sort: 2,
				};
				crossSteps.push(levelTwoParams);
			}
			if (state.ruleForm.levelThreeHandlers && state.ruleForm.levelThreeHandlers.length) {
				// 三级部门
				const levelThreeParams = {
					nextStepCode: state.ruleForm.levelThreeStep.key,
					nextStepName: state.ruleForm.levelThreeStep.value,
					flowDirection: state.ruleForm.levelThreeStep.flowDirection,
					handlerType: state.ruleForm.levelThreeStep.handlerType,
					stepType: state.ruleForm.levelThreeStep.stepType,
					businessType: state.ruleForm.levelThreeStep.businessType,
					nextHandlers: state.ruleForm.levelThreeHandlers,
					sort: 3,
				};
				crossSteps.push(levelThreeParams);
			}
		}
		// submitObj.stepExpiredTime = submitObj.expiredTime; //节点过期时间
		switch (state.processType) {
			case '工单受理':
				const request = {
					data: { orderId: state.orderDetail.id, ...submitObj,crossSteps },
					workflow: { ...submitObj, files: handleFiles.value,currentTag:currentParams.value.currentTag },
				};
				orderStartFlow(request)
					.then(() => {
						afterSubmit('orderProcessSuccess', true);
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			case '工单撤回':
				workflowRecall({ ...submitObj, files: handleFiles.value })
					.then(() => {
						afterSubmit('orderProcessSuccess', true);
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			case '延期申请':
				const requestDelay = {
					data: {
						orderId: state.orderDetail.id,
						delayNum: state.delayForm.timeLimitCount,
						delayUnit: state.delayForm.timeLimitUnit,
						delayReason: state.delayForm.content,
						files: handleFilesDelay.value,
					},
					workflow: {
						...submitObj,
						opinion: state.delayForm.content,
						files: handleFilesDelay.value,
					},
				};
				delayApply(requestDelay)
					.then(() => {
						afterSubmit('orderProcessSuccess', true, '延期申请成功');
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			case '延期退回':
				workflowPrevious({ ...submitObj, files: handleFiles.value })
					.then(() => {
						afterSubmit('orderProcessSuccess', true);
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			case '延期审批':
				if (state.ruleForm.isPass) {
					// 审批通过 下一步
					workflowNext({ ...submitObj, reviewResult: 1, files: handleFiles.value })
						.then(() => {
							afterSubmit('orderProcessSuccess', true);
						})
						.catch(() => {
							afterSubmit('orderProcessFailed');
						});
				} else {
					// 审批拒绝
					const requestDelayAudit = {
						opinion: state.ruleForm.opinion,
						workflowId: state.workflowId,
						files: handleFiles.value,
						stepId: state.ruleForm.stepId,
					};
					workflowReject(requestDelayAudit)
						.then(() => {
							afterSubmit('orderProcessSuccess', true);
						})
						.catch(() => {
							afterSubmit('orderProcessFailed');
						});
				}
				break;
			case '甄别申请':
				const requestDiscern = {
					data: {
						no: state.orderDetail.no,
						visitId: state.orderDetail.visitId,
						visitDetailId: state.orderDetail.visitDetailId,
						orderId: state.orderDetail.id,
						typeDicId: state.discernForm.type.dicDataValue,
						typeDicName: state.discernForm.type.dicDataName,
						content: state.discernForm.content,
						screenType: screenType.value,
						files: handleFilesDiscern.value,
					},
					workflow: { ...submitObj, files: handleFilesDiscern.value, opinion: state.discernForm.content },
				};
				discernApply(requestDiscern)
					.then(() => {
						afterSubmit('orderProcessSuccess', true, '甄别申请成功');
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			case '甄别退回':
				workflowPrevious({ ...submitObj, files: handleFiles.value })
					.then(() => {
						afterSubmit('orderProcessSuccess', true);
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			case '甄别审批':
				if (state.ruleForm.isPass) {
					// 审批通过 下一步
					workflowNext({ ...submitObj, reviewResult: 1, files: handleFiles.value })
						.then(() => {
							afterSubmit('orderProcessSuccess', true);
						})
						.catch(() => {
							afterSubmit('orderProcessFailed');
						});
				} else {
					// 审批拒绝
					const requestDiscernAudit = {
						opinion: state.ruleForm.opinion,
						workflowId: state.workflowId,
						files: handleFiles.value,
						stepId: state.ruleForm.stepId,
					};
					workflowReject(requestDiscernAudit)
						.then(() => {
							afterSubmit('orderProcessSuccess', true);
						})
						.catch(() => {
							afterSubmit('orderProcessFailed');
						});
				}
				break;
			case '终止申请':
				const requestTerminate = {
					data: {
						no: state.orderDetail.no,
						orderId: state.orderDetail.id,
						content: state.terminateForm.content,
						files: handleFilesTerminate.value,
					},
					workflow: { ...submitObj, files: handleFilesTerminate.value, opinion: state.terminateForm.content },
				};
				terminateStartFlow(requestTerminate)
					.then(() => {
						afterSubmit('orderProcessSuccess', true, '终止申请成功');
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			case '终止审批':
				if (state.ruleForm.isPass) {
					// 审批通过 下一步
					workflowNext({ ...submitObj, reviewResult: 1, files: handleFiles.value })
						.then(() => {
							afterSubmit('orderProcessSuccess', true);
						})
						.catch(() => {
							afterSubmit('orderProcessFailed');
						});
				} else {
					// 审批拒绝
					const requestTerminateAudit = {
						opinion: state.ruleForm.opinion,
						workflowId: state.workflowId,
						files: handleFiles.value,
						stepId: state.ruleForm.stepId,
					};
					workflowReject(requestTerminateAudit)
						.then(() => {
							afterSubmit('orderProcessSuccess', true);
						})
						.catch(() => {
							afterSubmit('orderProcessFailed');
						});
				}
				break;
			case '终止退回':
				workflowPrevious({ ...submitObj, files: handleFiles.value })
					.then(() => {
						afterSubmit('orderProcessSuccess', true);
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			case '工单退回':
				orderPrevious({ ...submitObj, files: handleFiles.value,orderId: state.orderDetail.id })
					.then(() => {
						afterSubmit('orderProcessSuccess', true, '退回申请成功');
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			case '工单办理': // 工单办理流程
			case '工单代办': // 工单代办流程
				const requestHandle = {
					data: { orderId: state.orderDetail.id, ...submitObj, crossSteps },
					workflow: { ...submitObj, files: handleFiles.value,currentTag:currentParams.value.currentTag },
				};
				orderHandle(requestHandle)
					.then(() => {
						afterSubmit('orderProcessSuccess', true);
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			case '新增知识':
				const KnowledgeAddRequest = {
					data: { ...state.orderDetail },
					workflow: { ...submitObj, files: handleFiles.value },
				};
				KnowledgeAdd(KnowledgeAddRequest)
					.then(() => {
						afterSubmit('orderProcessSuccess', true, '新增知识成功');
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			case '知识审批':
				if (state.ruleForm.isPass) {
					// 审批通过 下一步
					workflowNext({ ...submitObj, reviewResult: 1, files: handleFiles.value })
						.then(() => {
							afterSubmit('orderProcessSuccess', true);
						})
						.catch(() => {
							afterSubmit('orderProcessFailed');
						});
				} else {
					// 审批拒绝
					const requestDiscernAudit = {
						opinion: state.ruleForm.opinion,
						workflowId: state.workflowId,
						files: handleFiles.value,
						stepId: state.ruleForm.stepId,
					};
					workflowReject(requestDiscernAudit)
						.then(() => {
							afterSubmit('orderProcessSuccess', true);
						})
						.catch(() => {
							afterSubmit('orderProcessFailed');
						});
				}
				break;
			case '更新新增知识':
				const KnowledgeAddUpdateRequest = {
					data: { ...state.orderDetail },
					workflow: { ...submitObj, files: handleFiles.value },
				};
				KnowledgeUpdate(KnowledgeAddUpdateRequest)
					.then(() => {
						afterSubmit('orderProcessSuccess', true);
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			case '更新知识':
				const KnowledgeUpdateRequest = {
					data: { ...state.orderDetail },
					workflow: { ...submitObj, files: handleFiles.value },
				};
				KnowledgeUpdate(KnowledgeUpdateRequest)
					.then(() => {
						afterSubmit('orderProcessSuccess', true);
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			case '删除知识':
				const KnowledgeRemoveRequest = {
					data: { ...state.orderDetail },
					workflow: { ...submitObj, files: handleFiles.value },
				};
				KnowledgeDel(KnowledgeRemoveRequest)
					.then(() => {
						afterSubmit('orderProcessSuccess', true, '删除知识申请成功');
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			case '知识下架':
				const KnowledgeOffShelfRequest = {
					data: { ...state.orderDetail },
					workflow: { ...submitObj, files: handleFiles.value },
				};
				KnowledgeOffShelf(KnowledgeOffShelfRequest)
					.then(() => {
						afterSubmit('orderProcessSuccess', true, '下架知识申请成功');
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
			default: // 默认工单办理
				const requestDefault = {
					data: { orderId: state.orderDetail.id, ...submitObj, crossSteps },
					workflow: { ...submitObj, files: handleFiles.value,currentTag:currentParams.value.currentTag },
				};
				orderHandle(requestDefault)
					.then(() => {
						afterSubmit('orderProcessSuccess', true);
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
				break;
		}
	});
};
// 临时保存
const handleTempSave = () => {
	ruleFormRef.value
		.validateField('opinion')
		.then(() => {
			state.loading = true;
			orderProcessTempSave({ orderId: state.orderDetail.id, opinion: state.ruleForm.opinion })
				.then(() => {
					state.loading = false;
					ElMessage.success('临时保存成功');
				})
				.catch((err) => {
					state.loading = false;
					console.log(err);
				});
		})
		.catch(() => {});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
<style lang="scss">
.modal_class {
	pointer-events: none;
	height: 100%;
}
.dialog_class {
	pointer-events: auto;
	flex-direction: column;
	margin: 0 !important;
	position: absolute;
	top: 20%;
	left: 25%;
}
</style>
