<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
			:close-on-click-modal="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="申请时间"> {{ dayjs(Date()).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="当前期满时间"> {{ dayjs(state.orderDetail.expiredTime).format('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 label="延期申请数量" prop="timeLimitCount" :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.delayForm.timeLimitCount"
											controls-position="right"
											class="w100"
											@input="computeTime"
											:min="1"
											:max="99"
										></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.delayForm.timeLimitUnit" placeholder="延期申请单位" @change="computeTime">
												<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="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="延期后期满时间"> {{ state.delayForm.endTime }} </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="申请时间"> {{ dayjs(Date()).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="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="申请时间"> {{ dayjs(Date()).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="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>
				<el-form :model="state.circularForm" label-width="110px" ref="circularFormRef" v-if="state.processType === '新增通知'">
					<el-row :gutter="10">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="通知类型" prop="circularObj" :rules="[{ required: true, message: '请选择通知类型型', trigger: 'change' }]">
								<el-select
									v-model="state.circularForm.circularObj"
									placeholder="请选择通知类型型"
									value-key="dicDataValue"
									class="w100"
									@change="
										(e) => {
											state.circularForm.circularTypeId = e.dicDataValue;
											state.circularForm.circularTypeName = e.dicDataName;
										}
									"
								>
									<el-option v-for="item in circularTypeOptions" :value="item" :key="item.dicDataValue" :label="item.dicDataName" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
							<el-form-item label="通知标题" prop="title" :rules="[{ required: true, message: '请输入通知标题', trigger: 'blur' }]">
								<el-input v-model="state.circularForm.title" placeholder="请输入通知标题" clearable show-word-limit maxlength="200"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
							<el-form-item label="必须阅读" prop="isMustRead" :rules="[{ required: true, message: '请选择必须阅读', trigger: 'change' }]">
								<el-radio-group v-model="state.circularForm.isMustRead">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
							<el-form-item label="失效时间" prop="lostEfficacyTime" :rules="[{ required: true, message: '请选择失效时间', trigger: 'change' }]">
								<el-date-picker
									v-model="state.circularForm.lostEfficacyTime"
									type="datetime"
									placeholder="请选择失效时间"
									value-format="YYYY-MM-DD[T]HH:mm:ss"
									class="w100"
								/>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
							<el-form-item label="来源单位" prop="sourceOrgId" :rules="[{ required: true, message: '请选择来源单位', trigger: 'change' }]">
								<el-cascader
									:options="orgsOptions"
									filterable
									:props="{ value: 'id', label: 'name', emitPath: false, checkStrictly: true }"
									placeholder="请选择来源单位"
									class="w100"
									v-model="state.circularForm.sourceOrgId"
									ref="orgRef"
									@change="changeOrg('circularForm')"
								>
								</el-cascader>
							</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' }]">
								<editor v-model:get-html="state.circularForm.content" placeholder="请输入通知内容" height="450px" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
							<el-form-item label="通知对象" prop="circularType" :rules="[{ required: true, message: '请选择通知对象', trigger: 'change' }]">
								<el-select v-model="state.circularForm.circularType" placeholder="请选择通知对象" class="w100">
									<el-option v-for="item in circularTypeEnum" :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" v-if="state.circularForm.circularType === 1">
							<el-divider content-position="left">
								<span>选择通知人</span>
							</el-divider>
							<div class="flex-center-align mb10">
								<el-input v-model="state.searchContent" placeholder="请输入搜索内容" class="w100">
									<template #prefix>
										<SvgIcon name="ele-Search" />
									</template>
								</el-input>
							</div>
							<el-table :data="tables" @selection-change="handleSelectionChange" max-height="500" ref="multipleTableRef" row-key="id">
								<el-table-column type="selection" label="请选择" width="40" :reserve-selection="true" align="center" />
								<el-table-column prop="name" label="姓名" show-overflow-tooltip width="170"></el-table-column>
								<el-table-column prop="userName" label="账号" show-overflow-tooltip width="170"></el-table-column>
								<el-table-column prop="organization.name" label="所属部门" show-overflow-tooltip width="190"></el-table-column>
								<el-table-column prop="staffNo" label="工号" show-overflow-tooltip width="120"></el-table-column>
								<el-table-column prop="organization.orgTypeText" label="部门类别" show-overflow-tooltip></el-table-column>
								<template #empty>
									<Empty />
								</template>
							</el-table>
						</el-col>
						<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="state.circularForm.circularType === 2">
							<el-form-item label="选择部门" prop="org" :rules="[{ required: true, message: '请选择部门', trigger: 'change' }]">
								<el-tree-select
									:props="{ label: 'name' }"
									node-key="id"
									class="w100"
									ref="treeSelectRef"
									v-model="state.circularForm.org"
									:data="circularOrgOptions"
									multiple
									:render-after-expand="false"
									show-checkbox
									check-strictly
									default-expand-all
									filterable
									@check="selectOrg"
									collapse-tags
									collapse-tags-tooltip
									placeholder="请选择部门"
								/>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<el-form :model="state.bulletinForm" label-width="110px" ref="bulletinFormRef" v-if="state.processType === '新增公告'">
					<el-row :gutter="10">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="公告类型" prop="bulletinObj" :rules="[{ required: true, message: '请选择公告类型', trigger: 'change' }]">
								<el-select
									v-model="state.bulletinForm.bulletinObj"
									placeholder="请选择公告类型"
									value-key="dicDataValue"
									class="w100"
									@change="
										(e) => {
											state.bulletinForm.bulletinTypeId = e.dicDataValue;
											state.bulletinForm.bulletinTypeName = e.dicDataName;
										}
									"
								>
									<el-option v-for="item in bulletinTypeOptions" :value="item" :key="item.dicDataValue" :label="item.dicDataName" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
							<el-form-item label="公告标题" prop="title" :rules="[{ required: true, message: '请输入公告标题', trigger: 'blur' }]">
								<el-input v-model="state.bulletinForm.title" placeholder="请输入公告标题" clearable show-word-limit maxlength="200"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
							<el-form-item label="失效时间" prop="loseEfficacyTime" :rules="[{ required: true, message: '请选择失效时间', trigger: 'change' }]">
								<el-date-picker
									v-model="state.bulletinForm.loseEfficacyTime"
									type="datetime"
									placeholder="请选择失效时间"
									value-format="YYYY-MM-DD[T]HH:mm:ss"
									class="w100"
								/>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
							<el-form-item label="来源单位" prop="sourceOrgId" :rules="[{ required: true, message: '请选择来源单位', trigger: 'change' }]">
								<el-cascader
									:options="orgsOptions"
									filterable
									:props="{ value: 'id', label: 'name', emitPath: false, checkStrictly: true }"
									placeholder="请选择来源单位"
									class="w100"
									v-model="state.bulletinForm.sourceOrgId"
									ref="orgRef"
									@change="changeOrg('bulletinForm')"
								>
								</el-cascader>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
							<el-form-item label="公告范围" prop="pushRangesArray" :rules="[{ required: true, message: '请选择公告范围', trigger: 'change' }]">
								<el-checkbox-group v-model="state.bulletinForm.pushRangesArray">
									<el-checkbox :label="item" v-for="item in pushRangesOptions" :key="item.dicDataValue">{{ item.dicDataName }}</el-checkbox>
								</el-checkbox-group>
							</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' }]">
								<editor v-model:get-html="state.bulletinForm.content" placeholder="请输入公告内容" height="450px" />
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
        <el-form :model="state.secondVisitForm" label-width="110px" ref="secondVisitFormRef" 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="申请时间"> {{ dayjs(Date()).format('YYYY-MM-DD HH:mm:ss') }} </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="chooseAdviceSecondVisit"
                    v-model="state.secondVisitForm.visitReason"
                    placeholder="请填写二次回访说明"
                    :loading="state.loading"
                    :commonEnum="commonEnum.ReturnVisit"
                />
              </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>
			</div>

			<el-form :model="state.ruleForm" label-width="110px" ref="ruleFormRef" v-show="activeStep === 1">
				<slot name="header"></slot>
				<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.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: true, message: '请选择处理人', trigger: 'change' }]">
							<el-select
								v-model="state.ruleForm.nextHandlers"
								multiple
								filterable
								placeholder="请选择处理人"
								class="w100"
								@change="selectHandlers"
								value-key="key"
								clearable
								collapse-tags
								collapse-tags-tooltip
							>
								<el-option v-for="item in state.handlerOptions" :key="item.key" :label="item.value" :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.key" :label="item.value" :value="item.key" />
							</el-select>
						</el-form-item>
					</el-col>
          <!-- 工单办理专有参数 -->
					<template v-if="flowDirection">
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :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"
											@input="computeTimeNext"
											:min="1"
											:max="99"
										></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="办理时限单位" @change="computeTimeNext" disabled>
												<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.ruleForm.endTime }}
							</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>
					</template>
					<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="inputRealHandler">
						<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="请填写办理人电话" 请填写经办人电话> </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 ">
                <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">
						<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="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="state.annexName" ref="annexListRef" :businessId="state.orderDetail.id" :classify="state.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="onReject(ruleFormRef)" :loading="state.loading" v-if="activeStep === 1 && canReject">驳 回</el-button>
					<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading" v-if="activeStep === 1">{{
						canReject ? '同意' : '提交'
					}}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="processApproval">
import {computed, defineAsyncComponent, nextTick, reactive, ref, watch, watchEffect} 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 { orderFlowParams, orderStartFlow,orderTimeConfig } from '/@/api/business/order';
import {
	workflowNext,
	workflowNextSteps,
	workflowPrevious,
	workflowRecall,
	workflowRecallParams,
	workflowRedoParams,
	workflowReject,
} from '/@/api/system/workflow';
import { redoApply, redoBaseData } from '/@/api/business/redo';
import { delayApply, delayBaseData, delayCalcEndTime, workflowDelayParams } from '/@/api/business/delay';
import { discernApply, screenBaseData, workflowDiscernParams } from '/@/api/business/discern';
import { debounce } from '/@/utils/tools';
import {
	bulletinAdd,
	bulletinAddBaseData,
	circularAdd,
	circularAddBaseData,
	getAllUsers,
	workflowBulletinParams,
	workflowCircularParams,
} from '/@/api/auxiliary/notice';
import { getCanUseOrg } from '/@/api/system/user';
import {
	KnowledgeAdd,
	KnowledgeAddStartFlowParams,
	KnowledgeDel,
	KnowledgeDeleteStartFlowParams,
	KnowledgeUpdate,
	KnowledgeUpdateStartFlowParams,
} from '/@/api/knowledge';
import dayjs from 'dayjs';
import {secondVisitAdd, secondVisitStart} from "/@/api/business/secondVisit";

// 引入组件
const CommonAdvice = defineAsyncComponent(() => import('/@/components/CommonAdvice/index.vue')); // 常用意见
const AnnexList = defineAsyncComponent(() => import('/@/components/AnnexList/index.vue')); // 附件列表
const Editor = defineAsyncComponent(() => import('/@/components/Editor/index.vue')); // 富文本编辑器
// 定义子组件向父组件传值/事件
const emit = defineEmits(['orderProcessSuccess', 'orderProcessFailed']);
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 弹窗显示隐藏
	ruleForm: {
		//流程表单
		opinion: '', // 意见
		nextStepCode: '', // 下一节点
		nextStepName: '', // 下一节点名称
		backToCountersignEnd: false, // 是否回到会签结束节点
		nextHandlers: [], // 下一节点处理人
		nextMainHandler: '', // 主办人
		isSms: false, // 是否短信通知
		isStartCountersign: false, // 是否发起会签
	},
	delayForm: {
		//延期申请表单
		timeLimitCount: null, // 延期申请数量
		content: '', // 延期申请理由
		timeLimitUnit: '', // 延期申请单位
	},
	discernForm: {
		// 甄别表单
		content: '', // 甄别理由
	},
	redoForm: {
		// 重办表单
		content: '', // 重办理由
	},
	circularForm: {
		// 通知表单
		circularObj: '', // 通知类型
		circularTypeId: '', // 通知类型
		circularTypeName: '', // 通知类型
		title: '', // 通知标题
		isMustRead: false, // 必须阅读
		lostEfficacyTime: '', // 失效时间
		sourceOrgId: '', // 来源单位
		content: '', // 文档内容
		circularType: '', // 通知对象
		sourceOrg: [], // 来源单位
		org: [], // 通知对象 部门
	},
	searchContent: '', // 搜索内容
	bulletinForm: {
		// 公告表单
		bulletinObj: '', // 公告类型
		bulletinType: '', // 公告类型
		bulletinTypeName: '', // 公告类型
		title: '', // 公告标题
		loseEfficacyTime: '', // 失效时间
		sourceOrgId: '', // 来源单位
		pushRangesArray: [], // 公告范围
		content: '', // 文档内容
		sourceOrg: [], // 来源单位
	},
  secondVisitForm: {
    // 二次回访表单
    visitReason: '', // 二次回访说明
  },
	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 showStepsArr = ['延期申请', '甄别申请', '工单重办', '新增通知', '新增公告','二次回访申请']; // 显示步骤条的流程
const handelArr = ['工单办理']; // 处于办理状态的流程 （如果是汇总节点 需要填写处理人等  办理流程才有期满时间）
const returnArr = ['工单退回']; // 退回流程 (退回流程不需要展示其他 只需要填写意见和附件即可)

const timeType = ref<EmptyArrayType>([]); // 延期申请单位
const orderRedoReasonOptions = ref<EmptyArrayType>([]); // 重办理由
const screenTypeOptions = ref<EmptyArrayType>([]); // 甄别类型
const bulletinTypeOptions = ref<EmptyArrayType>([]); // 公告类型
const circularTypeOptions = ref<EmptyArrayType>([]); // 通知类型]
const circularTypeEnum = ref<EmptyArrayType>([]); // 通知对象
const pushRangesOptions = ref<EmptyArrayType>([]); // 公告范围
const orgsOptions = ref<EmptyArrayType>([]); // 来源单位
const circularOrgOptions = ref<EmptyArrayType>([]); // 通知对象 部门
const userTables = ref<EmptyArrayType>([]); // 通知对象 个人
const canReject = ref<boolean>(false); // 是否可以驳回
const timeTypeOptions = ref<EmptyArrayType>([]); // 办理时限单位

const handleResult = (res: any) => {
	state.nextStepOptions = res.result.steps; //处理人选择内容
	canReject.value = res.result.canReject ?? false; // 是否可以驳回

	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].key; // 下一节点code
		state.ruleForm.nextStepName = state.nextStepOptions[0].value; // 下一节点name
		selectNextStep(state.nextStepOptions[0].key); // 查询流程下一节点参数

		state.ruleForm.backToCountersignEnd = state.nextStepOptions[0].backToCountersignEnd ?? false; // 是否回到会签结束节点
	} else {
		state.ruleForm.nextStepCode = '';
		state.ruleForm.nextStepName = '';
	}
};
// 打开弹窗
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, classify } = extra ?? {};
	state.dialogTitle = dialogTitle ?? '提交流程'; // 流程标题
	state.annexName = annexName ?? '办理附件'; // 附件标题
	state.classify = classify ?? '办理上传'; // 附件分类
	state.inputPlaceholder = inputPlaceholder ?? '办理意见'; // 意见提示
	switch (state.processType) {
		case '工单发起': //开始流程
			const [orderStartWorkflowResponse] = await Promise.all([orderFlowParams()]); //获取开启流程参数
			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 [workflowDiscernResponse, responseDiscern] = await Promise.all([workflowDiscernParams(), screenBaseData()]); //获取开启流程参数
			screenTypeOptions.value = responseDiscern.result?.screenType ?? []; // 甄别理由
			handleResult(workflowDiscernResponse);
			break;
		case '工单重办': // 工单重办
			const [workflowRedoResponse, responseRedo] = await Promise.all([workflowRedoParams(state.workflowId), redoBaseData()]); //获取开启流程参数
			orderRedoReasonOptions.value = responseRedo.result?.orderRedoReasonOptions ?? []; // 重办理由
			handleResult(workflowRedoResponse);
			break;
		case '工单退回': // 退回流程
			break;
		case '工单办理': // 工单办理
			const [workflowNextStepsResponse] = await Promise.all([workflowNextSteps(state.workflowId)]); // 获取下一节点和下一节点参数
			handleResult(workflowNextStepsResponse);
			break;
		case '新增通知':
			const [workflowCircularResponse, circularResponse, orgResponse, userResponse] = await Promise.all([
				workflowCircularParams(),
				circularAddBaseData(),
				getCanUseOrg(),
				getAllUsers(),
			]); // 新增通知开启流程参数
			circularTypeOptions.value = circularResponse.result?.circularType ?? [];
			orgsOptions.value = circularResponse.result?.orgsOptions ?? [];
			circularTypeEnum.value = circularResponse.result?.circularTypeEnum ?? [];
			circularOrgOptions.value = orgResponse.result ?? [];
			userTables.value = userResponse.result ?? [];
			handleResult(workflowCircularResponse);
			break;
		case '新增公告':
			const [workflowBulletinResponse, responseAnnounce] = await Promise.all([workflowBulletinParams(), bulletinAddBaseData()]); // 新增公告开启流程参数
			bulletinTypeOptions.value = responseAnnounce.result?.bulletinType ?? [];
			pushRangesOptions.value = responseAnnounce.result?.pushRanges ?? [];
			orgsOptions.value = responseAnnounce.result?.orgsOptions ?? [];
			handleResult(workflowBulletinResponse);
			break;
		case '新增知识':
			const [KnowledgeAddStartFlowResponse] = await Promise.all([KnowledgeAddStartFlowParams()]); // 知识库新增参数
			handleResult(KnowledgeAddStartFlowResponse);
			break;
		case '更新知识':
			const [KnowledgeUpdateResponse] = await Promise.all([KnowledgeUpdateStartFlowParams()]); // 知识库更新参数
			handleResult(KnowledgeUpdateResponse);
			break;
		case '删除知识':
			const [KnowledgeDeleteResponse] = await Promise.all([KnowledgeDeleteStartFlowParams()]); // 知识库删除参数
			handleResult(KnowledgeDeleteResponse);
			break;
    case '二次回访申请':
      const [secondVisitStartResponse] = await Promise.all([secondVisitStart()]); // 二次回访申请参数
      handleResult(secondVisitStartResponse);
      break;
		default: // 默认下一流程 工单办理
			// 获取下一节点和下一节点参数
			const [nextResponse] = await Promise.all([workflowNextSteps(state.workflowId)]);
			handleResult(nextResponse);
			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 circularFormRef = ref<RefType>(); //通知表单组件
const bulletinFormRef = 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;
		case '新增通知':
			circularFormRef.value?.validate((valid: boolean) => {
				if (!valid) return;
				activeStep.value = 1;
			});
			break;
		case '新增公告':
			bulletinFormRef.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 fastStepName = ref(''); // 推荐派单处理者
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 ?? [];

	if (items && items.length) {
		fastStepName.value = items[0].value;
	}
};
// 是否展示处理人 (只有结束节点不展示 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 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);
	// return !!(next?.items && next?.items.length);
	return false;
});
// 快速派单
const fastSendOrder = () => {
	state.ruleForm.nextHandlers = [state.handlerOptions[0]];
};
// 是否展示办理时限 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);
});
// 计算工单期满时间
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,acceptType:state.orderDetail.acceptType}).then((res: any) => {
        state.ruleForm.timeLimit = res.result.count ?? null; // 办理时限
        state.ruleForm.timeLimitUnit = res.result.timeType ?? ''; // 办理时限单位
        computeTimeNext();
      })
    }
  }
);
// 办理计算工单期满时间
const computeTimeNext = debounce(() => {
	if (!state.ruleForm.timeLimit || !state.ruleForm.timeLimitUnit) return;
	let request = {
		delayNum: state.ruleForm.timeLimit,
		delayUnit: state.ruleForm.timeLimitUnit,
		beginTime: state.ruleForm.expiredTime,
	};
	state.loading = true;
	delayCalcEndTime(request)
		.then((res: any) => {
			state.ruleForm.endTime = dayjs(res.result.endTime).format('YYYY-MM-DD HH:mm:ss');
			state.loading = false;
		})
		.catch(() => {
			state.delayForm.endTime = '';
			state.loading = false;
		});
}, 300);

// 选择处理人
const selectHandlers = () => {
	ruleFormRef.value?.resetFields('nextMainHandler');
	if (state.ruleForm.nextHandlers.length > 1) {
		state.ruleForm.nextMainHandler = state.ruleForm.nextHandlers[0].key;
	}
};
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.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 computeTime = debounce(() => {
	if (!state.delayForm.timeLimitCount || !state.delayForm.timeLimitUnit) return;
	let request = {
		delayNum: state.delayForm.timeLimitCount,
		delayUnit: state.delayForm.timeLimitUnit,
		beginTime: state.orderDetail.expiredTime,
	};
	state.loading = true;
	delayCalcEndTime(request)
		.then((res: any) => {
			state.delayForm.endTime = dayjs(res.result.endTime).format('YYYY-MM-DD HH:mm:ss');
			state.loading = false;
		})
		.catch(() => {
			state.delayForm.endTime = '';
			state.loading = false;
		});
}, 300);
// 选择常用意见 填入填写框 甄别
const chooseAdviceDiscern = (item: any) => {
	state.discernForm.content += item.content;
};
// 选择常用意见 填入填写框 重办
const chooseAdviceRedo = (item: any) => {
	state.redoForm.redoOpinion += item.content;
};
const chooseAdviceSecondVisit  = (item:any)=>{
  state.secondVisitForm.visitReason += item.content;
}
const orgRef = ref<RefType>(); //来源单位
const changeOrg = (type: string) => {
	const currentNode = orgRef.value.getCheckedNodes();
	state[type].sourceOrgName = currentNode[0].label;
};
// 选择部门
const treeSelectRef = ref<RefType>();
const selectOrgArray = ref<EmptyArrayType>([]);
const selectOrg = () => {
	selectOrgArray.value = treeSelectRef.value.getCheckedNodes();
};
const tables = computed(() => {
	// 模糊搜索
	if (!state.searchContent) return userTables.value;
	// filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
	// 注意： filter() 不会对空数组进行检测。
	// 注意： filter() 不会改变原始数组。
	return userTables.value.filter((data: any) => {
		// some() 方法用于检测数组中的元素是否满足指定条件;
		// some() 方法会依次执行数组的每个元素：
		// 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
		// 如果没有满足条件的元素，则返回false。
		// 注意： some() 不会对空数组进行检测。
		// 注意： some() 不会改变原始数组。
		return Object.keys(data).some((key) => {
			// indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
			// 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
			return String(data[key]).toLowerCase().indexOf(state.searchContent) > -1;
		});
	});
});
// 选择用户（账号）
const multipleSelection = ref<any[]>([]); // 选中的数据
const multipleTableRef = ref<RefType>(); // 表格ref
const handleSelectionChange = (row: any) => {
	if (row) {
		multipleSelection.value = row;
	}
};
const afterSubmit = (emitType?: 'orderProcessSuccess' | 'orderProcessFailed', showMessage?: boolean) => {
	state.loading = false;
	closeDialog();
	if (showMessage) ElMessage.success('操作成功');
	if (emitType) emit(emitType);
};
const close = () => {
	restForm(ruleFormRef.value);
	restForm(delayFormRef.value);
	restForm(discernFormRef.value);
	restForm(redoFormRef.value);
	restForm(circularFormRef.value);
	restForm(bulletinFormRef.value);
};
// 提交
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		const isAuditText = canReject.value ? '同意' : '提交';
		ElMessageBox.confirm(`确认${isAuditText}?`, '提示', {
			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;
					}
				}
				if (!flowDirection.value) {
					// 需要填写办理时限
					Reflect.deleteProperty(submitObj, 'timeLimit');
          Reflect.deleteProperty(submitObj, 'timeLimitUnit');
          Reflect.deleteProperty(submitObj, 'flowDirection');
				} else {
					submitObj.external = {
						timeLimit: state.ruleForm.timeLimit,
						timeLimitUnit: state.ruleForm.timeLimitUnit,
					};
				}
				submitObj.stepExpiredTime = submitObj.expiredTime; //节点过期时间
				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 '延期申请':
						const requestDelay = {
							data: {
								orderId: state.orderDetail.id,
								delayNum: state.delayForm.timeLimitCount,
								delayUnit: state.delayForm.timeLimitUnit,
								delayReason: state.delayForm.content,
							},
							workflow: submitObj,
						};
						delayApply(requestDelay)
							.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,
							},
							workflow: submitObj,
						};
						discernApply(requestDiscern)
							.then(() => {
								afterSubmit('orderProcessSuccess', true);
							})
							.catch(() => {
								afterSubmit('orderProcessFailed');
							});
						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;
					case '新增通知':
						if (state.circularForm.circularType === 1 && !multipleSelection.value.length) {
							ElMessage.error('请选择通知人');
							return;
						}
						let circularReadGroups: EmptyArrayType;
						if (state.circularForm.circularType === 1) {
							//个人
							circularReadGroups = multipleSelection.value.map((item: any) => {
								return {
									userId: item.id,
									userName: item.name,
								};
							});
						} else if (state.circularForm.circularType === 2) {
							// 部门
							circularReadGroups = selectOrgArray.value.map((item: any) => {
								return {
									orgId: item.id,
									orgName: item.name,
								};
							});
						}
						const circularRequest = {
							data: { ...state.circularForm, circularReadGroups: circularReadGroups },
							workflow: submitObj,
						};
						circularAdd(circularRequest)
							.then(() => {
								afterSubmit('orderProcessSuccess', true);
							})
							.catch(() => {
								afterSubmit('orderProcessFailed');
							});
						break;
					case '新增公告':
						const pushRanges = state.bulletinForm.pushRangesArray.map((item: any) => {
							return {
								key: item.dicDataValue,
								value: item.dicDataName,
							};
						});
						const bulletinRequest = {
							data: { ...state.bulletinForm, pushRanges },
							workflow: submitObj,
						};
						bulletinAdd(bulletinRequest)
							.then(() => {
								afterSubmit('orderProcessSuccess', true);
							})
							.catch(() => {
								afterSubmit('orderProcessFailed');
							});
						break;
					case '新增知识':
						const KnowledgeAddRequest = {
							data: { ...state.orderDetail },
							workflow: submitObj,
						};
						KnowledgeAdd(KnowledgeAddRequest)
							.then(() => {
								afterSubmit('orderProcessSuccess', true);
							})
							.catch(() => {
								afterSubmit('orderProcessFailed');
							});
						break;
					case '更新知识':
						const KnowledgeUpdateRequest = {
							data: { ...state.orderDetail },
							workflow: submitObj,
						};
						KnowledgeUpdate(KnowledgeUpdateRequest)
							.then(() => {
								afterSubmit('orderProcessSuccess', true);
							})
							.catch(() => {
								afterSubmit('orderProcessFailed');
							});
						break;
					case '删除知识':
						const KnowledgeRemoveRequest = {
							data: { ...state.orderDetail },
							workflow: submitObj,
						};
						KnowledgeDel(KnowledgeRemoveRequest)
							.then(() => {
								afterSubmit('orderProcessSuccess', true);
							})
							.catch(() => {
								afterSubmit('orderProcessFailed');
							});
						break;
          case '二次回访申请':
            const secondVisitRequest = {
              data: {
                orderId: state.orderDetail.id,
                visitReason: state.secondVisitForm.visitReason,
              },
              workflow: submitObj,
            };
            secondVisitAdd(secondVisitRequest)
                .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(() => {
				state.loading = true;
				const request = {
					opinion: state.ruleForm.opinion,
					workflowId: state.workflowId,
				};
				workflowReject(request)
					.then(() => {
						afterSubmit('orderProcessSuccess', true);
					})
					.catch(() => {
						afterSubmit('orderProcessFailed');
					});
			})
			.catch(() => {});
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
