<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-form :model="state.ruleForm" label-width="110px" ref="ruleFormRef" v-loading="state.loading">
			<slot name="header"></slot>
			<el-row :gutter="10">
				<!--								<el-col>
					<el-form-item label="当前选择的流程">
						{{ seatTopaidan ? '话务部到派单组' : '' }}
						{{ seatToOrgOne ? '话务部到一级部门' : '' }}
						{{ paidanToOrgOne ? '派单组到一级部门' : '' }}
						{{ paidanToEnd ? '派单组到归档' : '' }}
						{{ orgOneToEnd ? '一级部门到归档' : '' }}
						{{ orgToOrg ? '部门到部门' : '' }}
						{{ orgToOrgSummary ? '部门到汇总节点' : '' }}
						{{ orgSummaryToOrgSummary ? '部门汇总到部门汇总' : '' }}
						{{ orgSummaryToEnd ? '部门汇总到归档' : '' }}
						{{ orgToOrgLeader ? '部门到部门领导' : '' }}
					</el-form-item>
				</el-col>-->
				<!-- 退回流程  -->
				<template v-if="returnArr.includes(state.processType)">
					<el-col v-if="isShowReturnSms">
						<el-form-item prop="isSms">
							<el-checkbox v-model="state.ruleForm.isSms" label="短信通知" />
						</el-form-item>
					</el-col>
				</template>
				<!-- 办理流程 -->
				<template v-else>
					<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>
						</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"
										></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-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>
					<!-- 非退回流程都需要选择并且如果选择了结束节点就不需要选择办理对象 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="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 :span="24" v-if="isSmsSelectShow || seatTopaidan || seatToOrgOne || paidanToOrgOne || paidanToEnd">
						<el-form-item prop="isSms">
							<el-checkbox v-model="state.ruleForm.isSms" label="短信通知" v-if="isSmsSelectShow" :key="Math.random()" />
							<el-checkbox v-model="state.ruleForm.isForwarded" label="是否转办" v-if="seatTopaidan || seatToOrgOne" :key="Math.random()" />
							<template v-if="paidanToOrgOne || paidanToEnd">
								<el-checkbox v-model="state.ruleForm.isStepUrgent" label="紧急" :key="Math.random()" />
								<el-checkbox v-model="state.ruleForm.isEvasive" label="推诿" :key="Math.random()" />
								<el-checkbox v-model="state.ruleForm.isInactively" label="不积极" :key="Math.random()" />
							</template>
						</el-form-item>
					</el-col>
					<!-- 话务部到一级部门  派单组到一级部门	-->
					<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 :value="2">主协办</el-radio>-->
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="state.ruleForm.orderAssignMode === 0">
							<el-row class="w100">
								<el-col :span="12">
									<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="12" v-if="countersignAble">
									<el-form-item
										label="发起会签"
										prop="isStartCountersign"
										:rules="[{ required: false, message: '请选择发起会签', trigger: 'change' }]"
									>
										<el-switch
											v-model="state.ruleForm.isStartCountersign"
											inline-prompt
											active-text="是"
											inactive-text="否"
											@change="changeStartCountersign"
											:disabled="countersignDisabled"
										/>
									</el-form-item>
								</el-col>
							</el-row>
						</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>
						<el-col :span="24" v-if="state.ruleForm.orderAssignMode === 2">
							<el-form-item label="主办部门" prop="paidanObj" :rules="[{ required: true, message: '请选择主办部门', trigger: 'change' }]">
								<el-row class="w100" :gutter="20">
									<el-col :span="18">
										<el-select v-model="state.ruleForm.paidanObj" placeholder="请选择主办部门" class="w100" filterable>
											<el-option v-for="item in state.paidanObjOptions" :key="item.key" :label="item.value" :value="item.key" />
										</el-select>
									</el-col>
									<el-col :span="6">
										<el-checkbox v-model="state.ruleForm.zhipai">是否直派 </el-checkbox>
									</el-col>
								</el-row>
							</el-form-item>
							<el-row class="w100">
								<el-col :span="12">
									<el-form-item label="协办部门" prop="paidanObj" :rules="[{ required: false, 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-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="抄送部门" prop="paidanObj" :rules="[{ required: false, 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-form-item>
								</el-col>
							</el-row>
						</el-col>
					</template>
					<!-- 部门到部门	-->
					<template v-if="orgToOrg">
						<el-col>
							<el-row class="w100">
								<el-col :span="12">
									<el-form-item label="接办部门" prop="nextHandlers" :rules="[{ required: true, message: '请选择接办部门', trigger: 'change' }]">
										<el-select-v2
											v-model="state.ruleForm.nextHandlers"
											:options="state.handlerOptions"
											placeholder="请选择接办部门"
											class="w100"
											multiple
											clearable
											collapse-tags
											collapse-tags-tooltip
											filterable
											value-key="key"
											@change="selectHandlers"
											:multiple-limit="multipleLimit"
										/>
									</el-form-item>
								</el-col>
								<el-col :span="12" v-if="countersignAble">
									<el-form-item
										label="发起会签"
										prop="isStartCountersign"
										:rules="[{ required: false, message: '请选择发起会签', trigger: 'change' }]"
									>
										<el-switch
											v-model="state.ruleForm.isStartCountersign"
											inline-prompt
											active-text="是"
											inactive-text="否"
											@change="changeStartCountersign"
											:disabled="countersignDisabled"
										/>
									</el-form-item>
								</el-col>
							</el-row>
						</el-col>
					</template>
					<!-- 派单组流转到归档  派单组到一级部门 -->
					<template v-if="paidanToOrgOne || paidanToEnd">
						<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
							<el-form-item label="市州转办" prop="transpond" :rules="[{ required: false, message: '请选择市州转办', trigger: 'change' }]">
								<el-select v-model="state.ruleForm.transpond" placeholder="请选择市州转办" class="w100" @change="changeTransPond">
									<el-option :key="true" label="是" :value="true" />
									<el-option :key="false" label="否" :value="false" />
								</el-select>
							</el-form-item>
						</el-col>
						<!-- 必填，若“是否市州互转”为“是”，则展示选择市州选择框 -->
						<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="state.ruleForm.transpond">
							<el-form-item prop="transpondCityObj" label-width="10px" :rules="[{ required: true, message: '请选择转办市州', trigger: 'change' }]">
								<el-select
									v-model="state.ruleForm.transpondCityObj"
									placeholder="请选择转办市州"
									class="w100"
									value-key="dicDataValue"
									@change="changeTranspondCity"
									clearable
								>
									<el-option v-for="item in transpondCity" :key="item.dicDataValue" :label="item.dicDataName" :value="item" />
								</el-select>
							</el-form-item>
						</el-col>
					</template>
					<!-- 派单组到一级部门  -->
					<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="paidanToOrgOne">
						<el-form-item label="领导短信" prop="leaderSMSKey" :rules="[{ required: false, message: '请选择领导短信', trigger: 'change' }]">
							<el-select v-model="state.ruleForm.leaderSMSKey" placeholder="请选择领导短信" class="w100" filterable clearable>
								<el-option v-for="item in leaderSMS" :key="item.key" :label="item.value" :value="item.key" />
							</el-select>
						</el-form-item>
					</el-col>
					<!--  一级部门流转到归档 或者 部门流转至部门汇总  并且不能是会签-->
					<template v-if="(orgOneToEnd || orgToOrgSummary) && !isCountersign && ['ZiGong'].includes(themeConfig.appScope)">
						<el-col :span="24">
							<el-form-item prop="checkedCities" :rules="[{ required: true, message: '至少选择一项', trigger: 'change' }]">
								<el-checkbox-group v-model="state.ruleForm.checkedCities" @change="changeCheckBox">
									<el-checkbox value="0" label="已与市民电话联系，确认办理结果" />
									<el-checkbox value="1" label="已赴现场处置，将处理结果告知市民" />
									<el-checkbox value="2" label="其他" />
								</el-checkbox-group>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="其他原因" prop="otherRemark" :rules="[{ required: false, message: '请填写其他原因', trigger: 'blur' }]">
								<el-input v-model="state.ruleForm.otherRemark" placeholder="请填写其他原因"> </el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="8" :md="8" :lg="8">
							<el-form-item prop="realHandlerName" :rules="[{ required: true, message: '请填写经办人姓名', trigger: 'blur' }]">
								<el-input v-model="state.ruleForm.realHandlerName" placeholder="经办人姓名" autocomplete="on"> </el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
							<el-form-item prop="realHandlerPhone" label-width="0" :rules="[{ required: true, message: '请填写经办人电话', trigger: 'blur' }]">
								<el-input v-model="state.ruleForm.realHandlerPhone" placeholder="经办人电话" autocomplete="on"> </el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
							<el-form-item
								prop="realCommunicationTime"
								:xl="8"
								label-width="0"
								:rules="[{ required: true, message: '请选择沟通时间', trigger: 'change' }]"
							>
								<el-date-picker
									v-model="state.ruleForm.realCommunicationTime"
									type="datetime"
									placeholder="沟通时间"
									class="w100"
									clearable
									value-format="YYYY-MM-DD[T]HH:mm:ss"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item
								label="沟通地点"
								prop="realCommunicationAddress"
								:rules="[{ required: true, message: '请填写沟通地点', trigger: 'blur' }]"
							>
								<el-input v-model="state.ruleForm.realCommunicationAddress" placeholder="请填写沟通地点"> </el-input>
							</el-form-item>
						</el-col>
					</template>
					<!--  选择结束节点时并且是工单办理并且工单来源是110时，显示警情退回 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="showPoliceReturn">
						<el-form-item label="" prop="isPoliceReturn">
							<el-checkbox v-model="state.ruleForm.isPoliceReturn" label="警情退回" />
						</el-form-item>
					</el-col>
				</template>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item
						:label="state.inputPlaceholder"
						prop="opinion"
						:rules="[
							{ required: true, message: `请填写${state.inputPlaceholder}`, trigger: 'blur' },
							{ required: true, pattern: '[^ \x20]+', trigger: 'blur', message: `${state.inputPlaceholder}不能为空` },
						]"
					>
						<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>
				<!--				<el-col v-if="isOverdueTips" :span="24">
					<el-alert type="warning" show-icon title="注意"> 该工单属于超期状态，若符合延期要求，请延期通过后办结，是否继续办理 </el-alert>
				</el-col>-->
			</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>
				<template v-if="seatTopaidan || seatToOrgOne">
					<el-popconfirm title="确定当前工单为中心直办件？" v-if="!state.ruleForm.isForwarded" @confirm="onSubmit(ruleFormRef)" width="230">
						<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>办理</el-button>
				</template>
				<template v-else>
					<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>办理</el-button>
				</template>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="processApproval">
import { computed, defineAsyncComponent, nextTick, reactive, ref, watch } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import other from '@/utils/other';
import { storeToRefs } from 'pinia';
import { commonEnum } from '@/utils/constants';
import {
	getDepartmentList,
	orderAssignParams,
	orderFlowParams,
	orderHandle,
	orderProcessTempSave,
	orderReturnParams,
	orderStartFlow,
	orderTimeConfig,
} from '@/api/business/order';
import { orderPrevious, workflowNextSteps, workflowNextStepsByOrder, workflowNextStepsByOrderInstead } from '@/api/system/workflow';
import { useAppConfig } from '@/stores/appConfig';
import { useThemeConfig } from '@/stores/themeConfig';

// 引入组件
const CommonAdvice = defineAsyncComponent(() => import('@/components/CommonAdvice/index.vue')); // 常用意见
const AnnexList = defineAsyncComponent(() => import('@/components/AnnexList/index.vue')); // 附件列表
// 定义子组件向父组件传值/事件
const emit = defineEmits(['orderProcessSuccess', 'orderProcessFailed']);
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 弹窗显示隐藏
	ruleForm: {
		opinion: '', // 意见
		nextStepCode: '', // 下一节点
		nextStepName: '', // 下一节点名称
		backToCountersignEnd: false, // 是否回到会签结束节点
		nextHandlers: [], // 下一节点办理对象
		nextHandler: null, // 单选对象
		isSms: false, // 是否短信通知
		isStartCountersign: false, // 是否发起会签
		stepId: null, // 步骤id
		isForwarded: false, // 是否转办
		isStepUrgent: null, // 是否紧急
		isEvasive: null, // 是否推诿
		isInactively: null, // 是否不积极
		leaderSMSKey: null, // 领导短信key
		realHandlerName: null, // 办理人姓名
		realHandlerPhone: null, // 办理人电话
		realCommunicationTime: null, // 沟通时间
		realCommunicationAddress: null, //沟通地点
		realIsContacted: null, //已与市民沟通 已与市民电话联系，确认办理结果
		realContactLocale: null, // 已与市民现场沟通 已赴现场处置，将处理结果告知市民
		isOther: null, // 其它
		otherRemark: null, // 其它原因
		transpond: false, // 市州转办
		transpondCityName: null, // 市州转办信息
		transpondCityId: null, // 市州转办信息id
		transpondCityValue: null, // 市州转办信息
		orderAssignMode: 0, // 派单类型默认逐级派单
		copyToHandlers: [], // 抄送对象
	},
	nextStepOptions: [], // 下一节点
	handlerOptions: [], // 办理对象
	transform: 'translate(0px, 0px)', // 滚动条位置
	loading: false, // 提交按钮loading
	processType: 'next', // 流程状态
	workflowId: '', // 流程id
	handleId: '', // 流程处理ID
	dialogTitle: '', // 弹窗标题
	annexName: '', // 附件标题
	inputPlaceholder: '办理意见', // 意见提示
	orderDetail: {}, // 工单详情
});
const ruleFormRef = ref<RefType>(); //表单组件
const handelArr = ['工单办理', '工单代办', '工单受理']; // 处于办理状态的流程
const returnArr = ['工单退回']; // 退回流程 (退回流程不需要展示其他 只需要填写意见和附件即可)
const appConfigStore = useAppConfig();
const { AppConfigInfo } = storeToRefs(appConfigStore); // 系统配置信息
const showTempSave = computed(() => {
	// 是否显示临时办理
	return ['工单办理', '工单代办', '工单受理'].includes(state.processType);
});
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
// 打开弹窗
const openDialog = async (val: any) => {
	console.log(val);
	selectNext.value = {};
	currentParams.value = {};
	state.ruleForm.nextHandlers = [];
	state.ruleForm.nextHandler = {};
	isSmsSelectShow.value = false;
	isNotShowNextHandlers.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 ?? {}; // 工单详情
		state.ruleForm.isStepUrgent = orderDetail.isStepUrgent; // 是否紧急
		state.ruleForm.isEvasive = orderDetail.isEvasive; // 是否推诿
		state.ruleForm.isInactively = orderDetail.isInactively; // 是否不积极
		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(orderDetail.id)]); //获取开启流程参数
				handleResult(orderStartWorkflowResponse);
				break;
			case '工单退回': // 退回流程
				const workflowReturnResponse = await orderReturnParams(state.orderDetail.id);
				handleResultReturn(workflowReturnResponse);
				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;
			default: // 默认下一流程 工单办理
				// 获取下一节点和下一节点参数
				const [nextResponse] = await Promise.all([workflowNextSteps(state.workflowId)]);
				handleResult(nextResponse);
				break;
		}
		await nextTick(() => {
			restForm(ruleFormRef.value);
		});
	} finally {
		state.loading = false;
	}
};
// 处理退回 currentBusinessType   表示选择节点到哪一步  0 坐席 1派单  2部门节点  3部门领导节点
// targetBusinessType  0 坐席 1派单  2部门节点  3部门领导节点
const isShowReturnSms = ref(false);
const handleResultReturn = (res: any) => {
	// 部门退部门需要默认选中短信
	if (res.result.currentBusinessType === 2 && res.result.targetBusinessType === 2) {
		isShowReturnSms.value = true;
		state.ruleForm.isSms = true;
	} else {
		isShowReturnSms.value = false;
		state.ruleForm.isSms = 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;
		default:
			return commonEnum.OrderCirculation;
	}
});
const timeTypeOptions = ref<EmptyArrayType>([]); // 办理时限单位
const canStartCountersign = ref<boolean>(false); // 是否可以发起会签
const isMainHandlerShow = ref<boolean>(false); // 是否展示主办人
const currentParams = ref<EmptyObjectType>({}); // 当前获取到的参数（当前节点信息）
const leaderSMS = ref<EmptyArrayType>([]); // 领导短信选择
const transpondCity = ref<EmptyArrayType>([]); // 市州互转选择
const handleResult = (res: any) => {
	currentParams.value = res.result;
	state.nextStepOptions = res.result.steps; //办理对象选择内容
	timeTypeOptions.value = res.result.timeTypeOptions ?? []; // 办理时限申请单位
	canStartCountersign.value = res.result.canStartCountersign ?? false; // 是否可以发起会签
	isMainHandlerShow.value = res.result.isMainHandlerShow ?? false; // 是否展示主办人
	leaderSMS.value = res.result.leaderSMS ?? []; // 领导短信选择
	transpondCity.value = res.result.transpondCity ?? []; // 市州互转
	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;
};

// 先确定当前环节是那一步
/*
 * 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 paidanToEnd = computed(() => {
	return currentParams.value.currentStepBusinessType === 1 && selectNext.value.key === 'end';
});
// 一级部门到归档
const orgOneToEnd = computed(() => {
	return (
		currentParams.value.currentStepBusinessType === 2 &&
		currentParams.value.currentStepType !== 3 &&
		currentParams.value.currentOrgLevel === 1 &&
		selectNext.value.key === 'end'
	);
});
// 部门流转到部门
const orgToOrg = computed(() => {
	return currentParams.value.currentStepBusinessType === 2 && selectNext.value.businessType === 2 && selectNext.value.stepType !== 3;
});
// 部门到部门汇总
const orgToOrgSummary = computed(() => {
	return (
		currentParams.value.currentStepBusinessType === 2 &&
		currentParams.value.currentStepType !== 3 &&
		selectNext.value.businessType === 2 &&
		selectNext.value.stepType === 3
	);
});
// 部门流转到部门领导
const orgToOrgLeader = computed(() => {
	return currentParams.value.currentStepBusinessType === 2 && selectNext.value.businessType === 3 && selectNext.value.key !== 'end';
});
// 部门退回部门 当前节点是部门 并且 部门等级大于1 需要展示短信并且默认勾选
const orgReturnOrg = computed(() => {
	return currentParams.value.currentStepBusinessType === 2 && selectNext.value.orgLevel > 1;
});
// 部门汇总到部门汇总
const orgSummaryToOrgSummary = computed(() => {
	return (
		currentParams.value.currentStepBusinessType === 2 &&
		currentParams.value.currentStepType === 3 &&
		selectNext.value.businessType === 2 &&
		selectNext.value.stepType === 3
	);
});
// 部门汇总到归档
const orgSummaryToEnd = computed(() => {
	return (
		currentParams.value.currentStepBusinessType === 2 &&
		currentParams.value.currentStepType === 3 &&
		currentParams.value.currentOrgLevel === 1 &&
		selectNext.value.key === 'end'
	);
});
// 判断当前节点是否在会签中 0中心会签 1部门会签
const isCountersign = computed(() => {
	return currentParams.value.counterSignType !== null;
});
// expiredStatus 超期状态（0正常 1即将超期  2已超期）  工单流转选择“结束”节点，点击“办理”时需验证该工单是否处于已超期状态
const isOverdueTips = computed(() => {
	return state.orderDetail.expiredStatus === 2 && state.ruleForm.nextStepCode === 'end';
});
// 是否展示短信通知选择
const isSmsSelectShow = ref(false);
// 是否不展示办理对象
const isNotShowNextHandlers = ref(false);
// 重置表单内容
const restFormData = () => {
	state.ruleForm.nextHandlers = [];
	state.ruleForm.nextHandler = {};
	/*	state.ruleForm.isStepUrgent = null;
	state.ruleForm.isEvasive = null;
	state.ruleForm.isInactively = null;*/
	state.ruleForm.leaderSMSKey = null;
	state.ruleForm.realHandlerName = null;
	state.ruleForm.realHandlerPhone = null;
	state.ruleForm.realCommunicationTime = null;
	state.ruleForm.realCommunicationAddress = null;
	state.ruleForm.realIsContacted = null;
	state.ruleForm.realContactLocale = null;
	state.ruleForm.isOther = null;
	state.ruleForm.otherRemark = null;
	state.ruleForm.transpond = false;
	state.ruleForm.transpondCityName = null;
	state.ruleForm.transpondCityId = null;
	state.ruleForm.orderAssignMode = 0;
	state.ruleForm.copyToHandlers = [];
	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 nextHandlersRequired = ref<Boolean>(false);
// 流程选择下一环节
const selectNext = ref<EmptyObjectType>({}); // 选择的下一个节点
const selectNextStep = (val: any) => {
	ruleFormRef.value?.resetFields('nextHandlers');
	ruleFormRef.value?.resetFields('nextHandler');
	restFormData();
	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.stepType = next.stepType;
	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,
		};
	});
	if (items.length === 1) {
		// 如果办理对象只有一个默认选中
		state.ruleForm.nextHandlers = [items[0]];
	}
	// 如果是泸州所有流转到派单组节点的都需要必填办理对象
	nextHandlersRequired.value = selectNext.value.businessType === 1;

	// 以下是默认需要吧短信勾上的场景 话务到部门、派单到一级部门、部门到部门、部门到汇总、部门到部门领导  部门退回到部门
	state.ruleForm.isSms =
		seatToOrgOne.value || paidanToOrgOne.value || orgToOrg.value || orgToOrgSummary.value || orgToOrgLeader.value || orgReturnOrg.value;
	// 是否展示短信通知 (话务部到一级部门 派单组到一级部门 部门流转到部门 部门到汇总 部门流转到部门领导 部门退回到部门)
	isSmsSelectShow.value =
		seatToOrgOne.value || paidanToOrgOne.value || orgToOrg.value || orgToOrgSummary.value || orgToOrgLeader.value || orgReturnOrg.value;
	// 是否不展示办理对象  （话务部到一级部门 派单组到一级部门 派单到归档 一级部门到归档 部门到部门 部门到汇总）
	isNotShowNextHandlers.value =
		seatToOrgOne.value ||
		paidanToOrgOne.value ||
		paidanToEnd.value ||
		orgOneToEnd.value ||
		orgToOrg.value ||
		orgToOrgSummary.value ||
		orgSummaryToEnd.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) => {
		if (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');
	}*/
};
// 选择派单类型 需要清空选择的内容
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 = [];
};

// 是否展示办理对象 (办理对象下拉框隐藏:AppConfigInfo.value.isAverageSendOrder= true 表示开启了平均派单 )
// 话务部到一级部门部不展示办理对象  派单组到一级部门不展示办理对象  派单组流转到归档不展示办理对象 一级部门流转到归档不展示办理对象  xx部门流转到xx部门 不展示办理对象 xx部门流转至xx部门汇总；不展示办理对象
const showHandlers = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
	const isAverageSendOrder = AppConfigInfo.value.isAverageSendOrder && next?.businessType === 1; // 开启平均派单
	if (!next) return true;
	// !isAverageSendOrder && 自贡的需求是如果选择了办理对象，则平均派单无效
	return !isNotShowNextHandlers.value;
});
// 是否展示警情退回 (选择结束节点时并且工单来源是110时，显示警情退回)
const showPoliceReturn = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
	return next?.stepType === 2 && state.orderDetail?.source === 200;
});

// 是否展示办理时限 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 secondaryHandlers = ref<EmptyArrayType>([]);
const getNextOrgList = async (orgCode?: string | any) => {
	try {
		const { result } = await getDepartmentList(orgCode);
		secondaryHandlers.value = result;
	} catch (e) {
		console.log(e);
	}
};
// 选择办理对象
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 = () => {};

/*watch(
	() => state.ruleForm.nextStepCode,
	(val) => {
		const next = state.nextStepOptions.find((item: any) => item.key === val);
		if (!next) return true;
		nextHandlersRequired.value = ![0].includes(next.handlerType);
	}
);*/
// 选择多选框
/*	<el-checkbox v-model="state.ruleForm.realIsContacted" label="已与市民电话联系，确认办理结果" />
								<el-checkbox v-model="state.ruleForm.realContactLocale" label="已赴现场处置，将处理结果告知市民" />
								<el-checkbox v-model="state.ruleForm.isOther" label="其他" />*/
const changeCheckBox = (val: any) => {
	state.ruleForm.realIsContacted = val.includes('0');
	state.ruleForm.realContactLocale = val.includes('1');
	state.ruleForm.isOther = val.includes('2');
	console.log(
		`是否已与市民电话联系，确认办理结果:${val.includes('0')},是否已赴现场处置，将处理结果告知市民${val.includes('1')},是否其他${val.includes('2')}`
	);
};
// 设置抽屉
const dialogRef = ref<RefType>();
const mouseup = () => {
	state.transform = dialogRef.value.dialogContentRef.$el.style.transform;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
// 重置表单方法
const restForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	state.ruleForm.opinion = '';
	formEl.resetFields();
	formEl.clearValidate();
};
// 选择常用意见 填入填写框 办理
const chooseAdvice = (item: any) => {
	state.ruleForm.opinion += 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);
};
// 选择是否市州互转
const changeTransPond = (val: any) => {
	if (!val) {
		state.ruleForm.transpondCityValue = null;
		state.ruleForm.transpondCityName = null;
		state.ruleForm.transpondCityId = null;
		state.ruleForm.transpondCityObj = null;
	}
};
// 选择市州互转
const changeTranspondCity = (val: any) => {
	state.ruleForm.transpondCityId = val?.id ?? null;
	state.ruleForm.transpondCityValue = val?.dicDataValue ?? null;
	state.ruleForm.transpondCityName = val?.dicDataName ?? null;
};
// 办理
const handleFiles = 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 (!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);
			}
		}
		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 '工单办理': // 工单办理流程
			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 requestReturn = { ...submitObj, files: handleFiles.value, orderId: state.orderDetail.id };
				orderPrevious(requestReturn)
					.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>
